You need to type hints your decorator
Say you have a simple decorator for adding logging before calling a function.
|
|
One day you decide to add type hints for this module -- it's easy to add type hints for two_sum
|
|
But you need to add type hints for your decorator (add_log
in this case) too, or you'll get Any
ed wrapped function. mypy's reveal_type can be used for verifying this.
|
|
Simple type hints for simple decorators
Let's adding type hints for this simple decorator. For a simple decorator which doesn't modify the functions' arguments and return (like add_log
above ), TypeVar should do the job pretty well.
|
|
Hard type hints for hard decorators
But, what if you want to modify the arguments and/or return value? Well, there's no easy way to type arguments, but at least you can type return value correctly
|
|
The dark way for typing arguments & return values
You can do some type gymnastics.. by generating numbers of TypeVar
s and using overload
.
|
|
If you insist to go this way, here's the code snippet I used for generating code above:
|
|
The Future: PEP-612
PEP-612 defines ParamSpec and Concatenate. They can make type hinting decorators pretty easy:
|
|
The sad thing is PEP-612 is not widely supported, as of now mypy does not fully support it.
Fin
May the type be with you.