gpt4 book ai didi

python - 为什么执行pytest后os.remove None?

转载 作者:行者123 更新时间:2023-11-28 18:56:43 25 4
gpt4 key购买 nike

我创建了一个 LazyLoader 类,它将文件从 S3 下载到本地文件系统,但前提是它们之前没有下载过。这个类一旦被销毁就会删除它下载的东西:

def __del__(self):
"""Remove downloaded files when this object is deleted."""
for downloaded_file in self.loaded_data.values():
os.remove(downloaded_file)

测试通过,但在 pytest 告诉我测试通过后,我得到:

Exception ignored in: <bound method LazyLoader.__del__ of LazyLoader({})>
Traceback (most recent call last):
File "my_lazy_loader.py", line 47, in __del__
TypeError: 'NoneType' object is not callable

第 47 行是 os.remove(downloaded_file)。所以 os.remove is None 的计算结果为 True。为什么?我该如何解决?

如果我将 __del__ 中的代码移动到方法 clean() 中,我就不会有那个问题。

最佳答案

https://docs.python.org/3/reference/datamodel.html#object.del

'del()' can be executed during interpreter shutdown. As a consequence, the global variables it needs to access (including other modules) may already have been deleted or set to None. Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the del() method is called.

关于python - 为什么执行pytest后os.remove None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57388336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com