[英]Python typing: declare type of callable when give it instance method
请考虑以下代码:
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指示最后一行的输入错误:
这是打字/类型声明错误吗? 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
是一个绑定方法 ,所以它在没有self
参数的情况下继承了底层函数的签名(因为它是绑定方法在绑定实例中传递的工作)。
例如,应用于绑定方法的typing.get_type_hints()
函数正确地省略了self
:
>>> typing.get_type_hints(f.b)
{'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.