Created
October 21, 2020 09:25
-
-
Save onjin/1ca2cd8486c68c58959b3097387d0298 to your computer and use it in GitHub Desktop.
python typing decorators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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