在传递函数时,我通常用 typing.Callable
来提示它们.
collections.abc.Callable
的文档声明它有四种 dunder 方法:
class collections.abc.Callable
ABCs for classes that provide respectively the methods contains(), hash(), len(), and call().
有一次,我想检查是否有
__wrapped__
函数上的属性。通过检查 hasattr(func, "__wrapped__")
在运行时可以正常工作.当使用
mypy
进行静态类型检查时,报告:error: "Callable[..., Any]" has no attribute "__wrapped__" [attr-defined]
.这对我来说很有意义,因为 Callable
不应该有 __wrapped__
属性。如何正确键入提示
Callable
与 __wrapped__
属性?我可以做一些其他类型的提示或解决方法吗?代码示例
我正在使用
mypy==0.782
和 Python==3.8.2
:from functools import wraps
from typing import Callable
def print_int_arg(arg: int) -> None:
"""Print the integer argument."""
print(arg)
@wraps(print_int_arg)
def wrap_print_int_arg(arg: int) -> None:
print_int_arg(arg)
# do other stuff
def print_is_wrapped(func: Callable) -> None:
"""Print if a function is wrapped."""
if hasattr(func, "__wrapped__"):
# error: "Callable[..., Any]" has no attribute "__wrapped__" [attr-defined]
print(f"func named {func.__name__} wraps {func.__wrapped__.__name__}.")
print_is_wrapped(wrap_print_int_arg)
最佳答案
显然,简单的答案是添加 # type: ignore
评论。然而,这实际上并没有解决问题,IMO。
我决定使用 __wrapped__
为可调用对象制作类型 stub 属性。基于 this answer ,这是我目前的解决方案:
from typing import Callable, cast
class WrapsCallable:
"""Stub for a Callable with a __wrapped__ attribute."""
__wrapped__: Callable
__name__: str
def __call__(self, *args, **kwargs):
...
def print_is_wrapped(func: Callable) -> None:
"""Print if a function is wrapped."""
if hasattr(func, "__wrapped__"):
func = cast(WrapsCallable, func)
print(f"func named {func.__name__} wraps {func.__wrapped__.__name__}.")
和 mypy
现在报告Success: no issues found in 1 source file
.我觉得这好像是很多样板代码,并且希望得到更精简的答案。
关于Python 如何使用 __wrapped__ 键入提示 Callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62703400/