Created
September 15, 2023 14:02
-
-
Save david-andrew/8210781c56f772c1a5167c87d1208769 to your computer and use it in GitHub Desktop.
Python: How to Forward Type Hints in Decorated Functions
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 TypeVar | |
| from typing_extensions import ParamSpec | |
| _R_co = TypeVar("_R_co", covariant=True) | |
| _P = ParamSpec("_P") | |
| # decorated functions will mantain identical typing to their original form | |
| def myDecorator(func: Callable[_P, _R_co]) -> Callable[_P, _R_co]: | |
| def wrapper(*args, **kwargs): | |
| # do wrapper stuff | |
| return func(*args, **kwargs) | |
| return wrapper | |
| @myDecorator | |
| def someFunc(a:int, b:str) -> tuple[int, str]: | |
| return (a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment