如何解决mypy:无类型装饰器使函数“my_method”无类型
当我尝试使用在另一个包中定义的装饰器时,mypy 失败并显示错误消息 Untyped decorator makes function "my_method" untyped
。我应该如何定义我的装饰器以确保它通过?
from mypackage import mydecorator
@mydecorator
def my_method(date: int) -> str:
...
解决方法
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"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。