在 mypy 中使用 Python stdlib 的类型存根

Using type stubs for Python stdlib with mypy

考虑以下 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 正确找到和使用?还有什么要检查的?我哪里错了?

根据回溯,您使用了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