mypy:无类型装饰器使函数“my_method”无类型

时间:2021-01-08 00:20:21

标签: python python-decorators mypy

当我尝试使用在另一个包中定义的装饰器时,mypy 失败并显示错误消息 Untyped decorator makes function "my_method" untyped。我应该如何定义我的装饰器以确保它通过?

from mypackage import mydecorator

@mydecorator
def my_method(date: int) -> str:
   ...

1 个答案:

答案 0 :(得分:1)

mypy 文档包含描述具有任意签名的函数的装饰器声明的 section。示例:

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"