当引用计数为零时文件对象是否会自动关闭? [英] Does a File Object Automatically Close when its Reference Count Hits Zero?

查看:34
本文介绍了当引用计数为零时文件对象是否会自动关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是文件对象在引用计数达到 0 时会立即关闭,因此该行:

I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line:

foo = open('foo').read()

将获取文件内容并立即关闭文件.但是,在阅读了 的答案后,是关闭的() 在 Python 文件对象上使用迭代器时必须 我觉得这不会发生,并且在文件对象上调用 .close()总是 必要的.

would get you the file's contents and immediately close the file. However, after reading the answer to Is close() necessary when using iterator on a Python file object I get the impression that this does not happen, and that calling .close() on a file object is always necessary.

上面的行是否按照我的想法做,即使它做了,这是 Pythonic 要做的事情吗?

Does the line above do what I think it's doing and even if it does, is it the Pythonic thing to do?

推荐答案

答案在您提供的链接中.

The answer is in the link you provided.

垃圾收集器在销毁文件对象时会关闭文件,但是:

Garbage collector will close file when it destroys file object, but:

  • 你无法真正控制它何时发生.

  • you don't really have control over when it happens.

虽然 CPython 使用引用计数来确定性地释放资源(因此您可以预测对象何时会被销毁)其他版本不必这样做.例如 Jython 或 IronPython 都使用 JVM 和 .NET 垃圾收集器仅在需要恢复内存时才释放(并最终确定)对象并且在程序结束之前可能不会对某些对象执行此操作.甚至对于 CPython GC 算法在未来可能会随着引用计数而改变效率不高.

While CPython uses reference counting to deterministically release resources (so you can predict when object will be destroyed) other versions don't have to. For example both Jython or IronPython use JVM and .NET garbage collector which release (and finalize) objects only when there is need to recover memory and might not do that for some object until the end of the program. And even for CPython GC algorithm may change in the future as reference counting isn't very efficient.

如果在文件对象销毁时关闭文件时抛出异常,你真的无能为力,因为你不会知道.

if exception is thrown when closing file on file object destruction, you can't really do anything about it because you won't know.

这篇关于当引用计数为零时文件对象是否会自动关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆