Python Mypy 属性错误

标签 python mypy

我有一个 python3.4 项目,我最近决定使用 mypy 来更好地理解。

这段代码可以工作,但是用 mypy 检查会弹出一个错误:

import zipfile

def zip_to_txt(zip: typing.IO[bytes]) -> BytesIO:
zz = zipfile.ZipFile(zip)
output = BytesIO()
for line, info in enumerate(zz.filelist):
    date = "%d-%02d-%02d %02d:%02d:%02d" % info.date_time[:6]
    output.write(str.encode("%-46s %s %12d\n" % (info.filename, date, info.file_size)))
output.seek(0, 0)
return output

错误:

PyPreviewGenerator/file_converter.py:170: error: "ZipFile"has no attribute "filelist" (对应于这一行:for line, info in enumerate(zz.filelist): )

但是当我查看 ZipFile 类内部时,我可以清楚地看到该属性存在。
那么为什么会出现错误呢?有什么办法可以解决吗?

最佳答案

简而言之,原因是 filelist 属性没有记录在 Typeshed 中,这是 stdlib/各种第 3 方库的类型 stub 集合。你可以自己看看这个here .

为什么不包括 filelist?好吧,因为它实际上并不是 documented part of the API。 .如果您搜索整个文档,您会发现 filelist 未在任何地方提及。

相反,您应该调用 infolist() method ,它返回的正是您想要的(如果您好奇,请参阅 implementation here)。您会注意到 infolist() 确实是 listed within typeshed .

关于Python Mypy 属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44020622/

相关文章:

类中的 Python 线程

python - 定义函数以返回样本协方差

python - 从词袋数据框到数组的更快的 Python 实现

python - PyCharm 使用 Mypy 吗?

python - 参数化泛型中 isinstance 和 issubclass 从 python 3.5 到 3.6 的 mypy 差异

python-3.x - Mypy 迭代器和生成器有什么区别?

Python3.5.2 bdist_wininst : Python version -32 required, 在注册表中找不到

python - 是否有使包符合 PEP-561 的最佳实践?

python - 在 mypy 中记录处理程序名称注释

python - 满足这个标准的语言?