gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:51:13 30 4
gpt4 key购买 nike

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

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

如果我在类里面做同样的事情。没有报告错误。似乎只评估了 Callable 定义的返回类型。我看不出有什么不妥。有什么建议吗?

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)

关于python - Mypy Callable 类型似乎在类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63085343/

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