Skip to content

Instantly share code, notes, and snippets.

@flipbit03
Last active November 17, 2023 00:14
Show Gist options
  • Select an option

  • Save flipbit03/ba98cace41296b32536292bd1acd8818 to your computer and use it in GitHub Desktop.

Select an option

Save flipbit03/ba98cace41296b32536292bd1acd8818 to your computer and use it in GitHub Desktop.
Type-aware Python Decorator
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