如何解决在 mypy 中使用 Python stdlib 的类型存根
考虑以下 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。