Skip to content

Instantly share code, notes, and snippets.

@onjin
Created October 21, 2020 09:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onjin/1ca2cd8486c68c58959b3097387d0298 to your computer and use it in GitHub Desktop.
Save onjin/1ca2cd8486c68c58959b3097387d0298 to your computer and use it in GitHub Desktop.
python typing decorators
from typing import Any, Callable, TypeVar, cast
F = TypeVar('F', bound=Callable[..., Any])
# A decorator that preserves the signature.
def my_decorator(func: F) -> F:
def wrapper(*args, **kwargs):
print("Calling", func)
return func(*args, **kwargs)
return cast(F, wrapper)
# A decorator that not preservers the signature.
def dumb_decorator(func):
def wrapper(*args, **kwargs):
print("Calling", func)
return func(*args, **kwargs)
return wrapper
# A decorated functions
@my_decorator
def foo(a: int) -> str:
return str(a)
@dumb_decorator
def dumb_foo(a: int) -> str:
return str(a)
if __name__ == "__main__":
a = foo(12)
reveal_type(a) # str
foo('x') # Type check error
a = dumb_foo(12)
reveal_type(a) # unknown
dumb_foo('x') # No type error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment