Python Mypy属性错误

Python Mypy attribute error

我有一个 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 class 内部时,我可以清楚地看到该属性存在。
那么为什么会出现错误呢?有什么办法可以解决吗?

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

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

相反,您应该调用 infolist() method, which returns exactly what you want (see implementation here if you're curious). You'll notice infolist() is indeed listed within typeshed