Python 如何使用 __wrapped__ 键入提示 Callable

Int*_*rer 8 python static-typing type-hinting callable-object mypy

当传递函数时,我通常用 来提示它们typing.Callable

的文档声明collections.abc.Callable它有四种 dunder 方法:

类 collections.abc.Callable

分别提供方法__contains__()__hash__()__len__()和的类的 ABC __call__()

有一次,我想检查__wrapped__函数上是否有属性。通过检查,这在运行时工作得很好hasattr(func, "__wrapped__")

当使用 进行静态类型检查时mypy,它会报告:error: "Callable[..., Any]" has no attribute "__wrapped__" [attr-defined]。这对我来说很有意义,因为Callable不应该有__wrapped__属性。

如何正确输入Callable带有__wrapped__属性的提示 a?我可以做一些其他类型的提示或解决方法吗?


代码示例

我正在使用mypy==0.782Python==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)
Run Code Online (Sandbox Code Playgroud)

Int*_*rer 3

显然,简单的答案是添加# type: ignore评论。然而,在我看来,这实际上并没有解决问题。

我决定为带有__wrapped__属性的可调用对象创建一个类型存根。基于这个答案,这是我当前的解决方案:

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__}.")
Run Code Online (Sandbox Code Playgroud)

现在mypy报道Success: no issues found in 1 source file

我觉得这似乎是很多样板代码,并且希望有一个更精简的答案。