【问题标题】:Python typing: declare type of callable when give it instance methodPython类型:在给它实例方法时声明可调用的类型
【发布时间】:2017-06-11 16:06:35
【问题描述】:

考虑以下代码:

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。这对我来说就像一个错误。绑定的方法具有正确的签名,self 参数被删除。
  • @MoinuddinQuadri:self 的类型是隐含的,不需要指定。即使你这样做了,你也必须使用self: 'F'(字符串文字),因为在创建函数时F 类还不存在。
  • pycharm 错误。而@MoinuddinQuadri 不,正如您从错误中看到的那样,它被正确检测到。
  • 好的,感谢您的回复和错误报告。
  • 这个bug仍然存在CAO这个时间戳。

标签: python pycharm type-hinting


【解决方案1】:

这是一个 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() function,正确地省略了self

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

【讨论】:

    猜你喜欢
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多