Reputation: 615
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:
...
Upvotes: 24
Views: 23361
Reputation: 32283
The mypy
documentation contains the section describing the declaration of decorators for functions with an arbitrary signature.
An 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"
Upvotes: 13