Mypy Callable 类型似乎在 class 中不起作用

Mypy Callable type does not seem to work inside a class

我正在尝试对作为参数传递的回调 function/method 使用类型提示。 请参见下面的示例。 “基于函数”的实现有效:Mypy 报告了预期的错误。

error: Argument 1 to "main_with_callback" has incompatible type "Callable[[], Any]"; expected "Callable[[str], Any]"

如果我在 class 中做同样的事情。没有报告错误。似乎只评估 Callable 定义的 return 类型。 我看不出有什么不对。有人有什么建议吗?

from typing import Callable, Any

# Functions with callback as argument.

def callback():
    print("any arg")


def main_with_callback(callback: Callable[[str], Any]):
    callback("this is the callback")


main_with_callback(callback)

# Class with callback as argument.

class A:
    def __init__(self):
        self.main_with_callback(self.the_callback)

    def main_with_callback(self, _callback: Callable[[str], Any]):
        _callback("this is the callback")

    def the_callback(self):
        print("called")


a = A()

Mypy docs 说:

Functions that do not have any annotations (neither for any argument nor for the return type) are not type-checked

换句话说 here:

bodies of functions that don’t have any explicit types in their function annotation are dynamically typed (operations are checked at runtime). Code outside functions is statically typed by default, and types of variables are inferred.

调用main_with_callback在任何函数之外,因此,默认情况下对此执行静态类型检查。但是调用 self.main_with_callback 是在未注释的 __init__ 函数中,为此执行动态类型检查。

要对 __init__ 中的代码启用静态类型检查,您可以 为 __init__ 添加一些注释,或使用描述 here 的 mypy 命令行选项,例如 --check-untyped-defs

class A:
    def __init__(self) -> None:
        self.main_with_callback(self.the_callback) # error
        reveal_type(self.the_callback)