Last active
November 17, 2023 00:14
-
-
Save flipbit03/ba98cace41296b32536292bd1acd8818 to your computer and use it in GitHub Desktop.
Type-aware Python Decorator
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
| P = ParamSpec("P") | |
| RT = TypeVar("RT") | |
| # By using ParamSpec, you are able to capture the original function's args and kwargs and forward | |
| # them through the decorator in a way that static analyzes like MyPy, and also ide's like PyCharm | |
| # will be happy ;-) | |
| def your_decorator(f: Callable[P, RT]) -> Callable[P, RT]: | |
| @wraps(f) | |
| def decorated_function(*args: P.args, **kwargs: P.kwargs) -> RT: | |
| # Do the stuff you need the decorator for | |
| # Run the original function | |
| return f(*args, **kwargs) | |
| return decorated_function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment