Created
April 17, 2021 18:50
-
-
Save jdoiwork/653381c447f294371bbf5aac0ca7534a to your computer and use it in GitHub Desktop.
python decorator typing hint
This file contains hidden or 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, Tuple, cast | |
| F = TypeVar('F', bound=Callable[..., Any]) | |
| # A decorator that preserves the signature. | |
| def my_decorator(func: F) -> F: | |
| def wrapper(*args, **kwds): | |
| print("Calling", func) | |
| return func(*args, **kwds) | |
| return cast(F, wrapper) | |
| def my_decorator2(x: Any) -> Callable[[F], F]: | |
| def decorator(func: F) -> F: | |
| def wrapper(*args, **kwds): | |
| print(x) | |
| print("Calling", func) | |
| return func(*args, **kwds) | |
| return wrapper | |
| return cast(Callable[[F], F], decorator) | |
| # A decorated function. | |
| @my_decorator | |
| def foo(a: int) -> str: | |
| return str(a) | |
| a = foo(12) | |
| @my_decorator2(30) | |
| def baa(a: int) -> str: | |
| return str(a) | |
| foo('x') # Type check error: incompatible type "str"; expected "int" | |
| baa('y') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment