【问题标题】:Using type stubs for Python stdlib with mypy通过 mypy 使用 Python stdlib 的类型存根
【发布时间】:2021-07-16 08:31:35
【问题描述】:

考虑以下 MWE:

import hashlib


def tstfun(h: hashlib._hashlib.HASH):
    print(h)


h = hashlib.md5()
tstfun(h)
# reveal_type(h)

按原样运行会产生 - 不足为奇:

$ python mypytest.py
<md5 _hashlib.HASH object @ 0x7fa645dedd90>

但使用 mypy 进行检查失败:

$ mypy mypytest.py 
mypytest.py:4: error: Name 'hashlib._hashlib.HASH' is not defined
Found 1 error in 1 file (checked 1 source file)

现在,在h 上显示类型(在reveal_type 行中评论):

$ mypy mypytest.py 
mypytest.py:4: error: Name 'hashlib._hashlib.HASH' is not defined
mypytest.py:10: note: Revealed type is 'hashlib._Hash'
Found 1 error in 1 file (checked 1 source file)

嗯,好的,然后将类型提示从 hashlib._hashlib.HASH 更改为 hashlib._Hash

$ python mypytest.py 
Traceback (most recent call last):
  File "/radarugs/hintze/s4-cnc-tools/mypytest.py", line 4, in <module>
    def tstfun(h: hashlib._HASH):
AttributeError: module 'hashlib' has no attribute '_HASH'
$ mypy mypytest.py 
mypytest.py:4: error: Name 'hashlib._HASH' is not defined
Found 1 error in 1 file (checked 1 source file)

...这是最坏的结果。

如何检查hashlib 的类型存根是否被mypy 正确找到并使用?还有什么要检查的?我怎么了?

【问题讨论】:

    标签: python python-3.x mypy python-typing


    【解决方案1】:

    根据回溯,您使用了hashlib._HASH

    使用此代码:

    import hashlib
    
    def tstfun(h: hashlib._Hash):
        print(h)
    
    h = hashlib.md5()
    tstfun(h)
    

    Mypy 报告:Success: no issues found in 1 source file

    【讨论】:

    • 如果这有帮助的话,我正在使用 Python 3.9.0 和 Mypy 0.812。
    • 现在这对我来说简直是个面子问题。谢谢!!!我用大写字母写了它,而且我已经看了好几天的代码了。我的天啊。你救了我的理智。
    • 这适合你吗?我得到一个回溯:AttributeError: module 'hashlib' has no attribute '_Hash',因此必须引用此类型提示
    • 是的,我运行答案中发布的代码没有错误(不需要引号)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 2020-05-31
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多