When I try using a decorator that I defined in another package, mypy fails with the error message Untyped decorator makes function "my_method" untyped
. How should I define my decorator to make sure this passes?
from mypackage import mydecorator
@mydecorator
def my_method(date: int) -> str:
...
The mypy
documentation contains the section describing the declaration of decorators for functions with an arbitrary signature. Example from there:
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)
# A decorated function.
@my_decorator
def foo(a: int) -> str:
return str(a)
a = foo(12)
reveal_type(a) # str
foo('x') # Type check error: incompatible type "str"; expected "int"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With