mypy: Untyped decorator makes function "my_method" untyped

Question:

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:
   ...
Asked By: 1step1leap

||

Answers:

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"
Answered By: alex_noname
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.