将Python stdlib的类型存根与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是正确的,但如果不想使用引号,也需要使用from __future__ import annotations。看见https://github.com/python/typeshed/issues/2928

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

N。B.:__future__.annotations从python 3.7.0b1开始可用。看见https://docs.python.org/3/library/__future__.html

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

最新更新