Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mypy: Untyped decorator makes function "my_method" untyped

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:
   ...
like image 673
1step1leap Avatar asked Jan 08 '21 00:01

1step1leap


1 Answers

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"
like image 197
alex_noname Avatar answered Nov 20 '22 17:11

alex_noname