gpt4 book ai didi

python - mypy:无类型装饰器使函数 "my_method"无类型

转载 作者:行者123 更新时间:2023-12-04 11:26:20 24 4
gpt4 key购买 nike

当我尝试使用我在另一个包中定义的装饰器时,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"

关于python - mypy:无类型装饰器使函数 "my_method"无类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65621789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com