【问题标题】:Python Mypy attribute errorPython Mypy 属性错误
【发布时间】:2017-05-17 09:20:49
【问题描述】:

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

【问题讨论】:

    标签: python mypy


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,我不知道它需要被使用,因为它被记录在与 mypy 一起使用。
    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 2021-03-02
    • 2014-03-21
    • 2013-07-01
    • 2011-10-12
    • 1970-01-01
    • 2016-05-01
    • 2021-07-24
    相关资源
    最近更新 更多