是否可以完全删除 TextIOWrapper?

Is it possible to fully delete a TextIOWrapper?

背景

=============

假设我正在编写一些单元测试,并且我想测试日志文件的重新打开(由于某种原因在我的程序外部或内部它已损坏)。我目前有一个来自 运行ning open()TextIOWrapper,我想将其完全删除或“清理”。一旦清理干净,我想重新 运行 open(),我希望那个新 TextIOWrapper 的 ID 是新的。

问题

=============

好像用同一个ID重新出现了。我该如何彻底清理这个东西?是否出于某种原因隐藏在文档中的失败原因?

调试

=============

我的实际代码有更多 try/except 块用于各种边缘情况,但这里是要点:

import gc  # I don't want to do this

# create log
log = open("log", "w")
id(log)  # result = 01111311110

# close log and delete everything I can think to delete
log.close()
log.__del__()
del log
gc.collect()

# TODO clean up some special way?

# re-open the log
log = open("log", "a")
id(log)  # result = 01111311110

为什么生成的 ID 仍然相同?

理论 1:由于 IO 流的工作方式,对于给定文件,TextIOWrapper 将最终位于内存中的相同位置,而我的方法测试此功能需要重新工作。

理论 2:不知何故我没有正确清理它。

我认为您只需调用 log.close() 即可完成清理工作。我的假设(现已证明见下文)基于这样一个事实,即我下面的示例提供了您在问题代码中所期望的结果。

似乎 python 出于某种原因重复使用了 ID 号。

试试这个例子:

log = open("log", "w")
print(id(log))  # result = 01111311110

# close log and delete everything I can think to delete
log.close()
log = open("log", "a")
print(id(log))
log.close()

[编辑] 我找到了假设的证据:

The id is unique only as long as an object is alive. Objects that have no references left to them are removed from memory, allowing the id() value to be re-used for another object, hence the non-overlapping lifetimes wording.

In CPython, id() is the memory address. New objects will be slotted into the next available memory space, so if a specific memory address has enough space to hold the next new object, the memory address will be reused.

The moment all references to an object are gone, the reference count on the object drops to 0 and it is deleted, there and then.

Garbage collection only is needed to break cyclic references, objects that reference one another only, with no further references to the cycle. Because such a cycle will never reach a reference count of 0 without help, the garbage collector periodically checks for such cycles and breaks one of the references to help clear those objects from memory.

有关 Python 在

重用 id 值的更多信息