Python 如何编写一个接受任何函数并传递mypy的装饰器——不允许任何装饰?
我上一次尝试编写一个decorator,该decorator接受任何可能的python函数并通过mypy检查,带有Python 如何编写一个接受任何函数并传递mypy的装饰器——不允许任何装饰?,python,decorator,python-decorators,mypy,typechecking,Python,Decorator,Python Decorators,Mypy,Typechecking,我上一次尝试编写一个decorator,该decorator接受任何可能的python函数并通过mypy检查,带有——disallow any decorded标志,如下所示: from typing import Any, Callable, TypeVar T = TypeVar('T') def decorator(func: Callable[..., T]) -> Callable[..., T]: def decorated(*args: Any, **kwar
——disallow any decorded
标志,如下所示:
from typing import Any, Callable, TypeVar
T = TypeVar('T')
def decorator(func: Callable[..., T]) -> Callable[..., T]:
def decorated(*args: Any, **kwargs: Any) -> Any:
print('decorated')
return func(*args, **kwargs)
return decorated
@decorator
def foo() -> int:
print('foo')
return 42
print(foo())
但是,当修饰函数的类型包含类型“Any”(“Callable[…,int]”)时,它仍然会失败。
我做错了什么?我还尝试使用mypy\u extensions
中的VarArg
和KwArg
而不是。
,但没有效果。:
在decorator转换之后,不允许在其签名中包含Any
Callable[…,T]
中的..
是一种表示可调用函数接受零个或多个任何参数的方法。因此,即使声明本身不包含Any
,它仍然会解析为包含Any
的声明:
在decorator转换之后,不允许在其签名中包含Any
Callable[…,T]
中的..
是一种表示可调用函数接受零个或多个任何参数的方法。因此,即使声明本身不包含Any
,它仍然解析为包含Any
的声明,使用TypeVar吞掉整个可调用的内容,而不仅仅是返回类型。然后,您向MyPy澄清,修饰函数的类型与原始函数的类型相同,从而使它不必担心“哦,但是这里的返回类型几乎可以是任何类型。”
可能需要在最终回流管上使用铸件
FuncT = TypeVar(FuncT, bound=Callable)
def decorator(func: FuncT) -> FuncT:
...
return cast(FuncT, decorated)
使用TypeVar吞并整个可调用的内容,而不仅仅是返回类型。然后,您向MyPy澄清,修饰函数的类型与原始函数的类型相同,从而使它不必担心“哦,但是这里的返回类型几乎可以是任何类型。”
可能需要在最终回流管上使用铸件
FuncT = TypeVar(FuncT, bound=Callable)
def decorator(func: FuncT) -> FuncT:
...
return cast(FuncT, decorated)
是的,我明白。你有什么办法来诠释这样一个装饰者吗?是的,我理解。你有什么办法来诠释这样一个装饰者吗?谢谢你的回答。我现在不能测试它,但看起来它可以解决我的问题。谢谢你的回答。我现在无法测试它,但看起来它可以解决我的问题。