gpt4 book ai didi

Python 输入 : declare type of callable when give it instance method

转载 作者:太空狗 更新时间:2023-10-30 01:26:48 26 4
gpt4 key购买 nike

考虑以下代码:

import typing

def a(x: int, y: int) -> int:
return x + y

class F(object):
def b(self, x: int, y: int) -> int:
return x + y

def call(operation: typing.Callable[[int, int], int]) -> int:
return operation(2, 2)

call(a)

f = F()
call(f.b)

我的 PyCharm IDE 指示最后一行输入错误:

1

是打字/类型声明错误吗? PyCharm 类型检查器是否失败?如果是打字错误,应该是什么?

最佳答案

这是一个 PyCharm 类型检查程序错误。 mypy typechecker在没有警告或错误的情况下接受您的示例:

$ bin/mypy --verbose so_41869174.py
LOG: Mypy version 0.470
LOG: Parsing so_41869174.py (so_41869174)
LOG: Parsing lib/mypy/typeshed/stdlib/3/typing.pyi (typing)
LOG: Parsing lib/mypy/typeshed/stdlib/3/builtins.pyi (builtins)
LOG: Parsing lib/mypy/typeshed/stdlib/3/sys.pyi (sys)
LOG: Parsing lib/mypy/typeshed/stdlib/3/abc.pyi (abc)
LOG: Parsing lib/mypy/typeshed/stdlib/3/types.pyi (types)
LOG: Parsing lib/mypy/typeshed/third_party/2and3/mypy_extensions.pyi (mypy_extensions)
LOG: Parsing lib/mypy/typeshed/stdlib/3/_importlib_modulespec.pyi (_importlib_modulespec)
LOG: Loaded graph with 8 nodes
LOG: Found 2 SCCs; largest has 7 nodes
LOG: Processing SCC of size 7 (_importlib_modulespec mypy_extensions types abc typing sys builtins) as inherently stale
LOG: Processing SCC singleton (so_41869174) as inherently stale
LOG: No fresh SCCs left in queue
LOG: Build finished in 0.482 seconds with 8 modules, 1708 types, and 0 errors

因为 F().b 是一个绑定(bind)方法,它继承了底层函数的签名而没有 self 参数(因为传递绑定(bind)实例是绑定(bind)方法的工作)。

例如,typing.get_type_hints() function ,应用于绑定(bind)方法,正确省略 self:

>>> typing.get_type_hints(f.b)
{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}

关于Python 输入 : declare type of callable when give it instance method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869174/

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