2 ms·
Why? Wouldn't any garbage collector collect the file object when it goes out of scope? def foolish(): f = open('filename.txt') Once `foolish` retu
by Derbasti 12y ago
Why? Wouldn't any garbage collector collect the file object when it goes out of scope?
def foolish():
f = open('filename.txt')
Once `foolish` returns, `f` goes out of scope, refcounting or not. Once `f` goes out of scope, its destructor closes the file. In CPython, the destructor is called when the refcount reaches zero. In Pypy, the destructor is called when there are no more references to `f`. Both happen when `foolish` returns, in both Pypy and CPython.
This is an implementation detail of file, not CPython.
Or did I fundamentally misunderstand something here?
- Jweb_Guru 12y agoYes, you misunderstood how tracing garbage collection works. Cleanup of data allocated on the heap occurs during tracing phases, not when a reference goes out of scope. Otherwise, imagine if before it returned f copied the object into some global structure g--how would the garbage collector know it was safe to close? (Some garbage collected languages can do automated "escape analysis" to figure out whether an object "escapes" the scope, and if it doesn't place it on the stack instead of the heap and deterministically free it when it goes out of scope. But that's surprisingly limited in real world programs and is generally speaking an implementation / optimization detail, not a core guarantee of the language).
- Derbasti 12y agoHow does that contradict what I was saying? The garbage collector would still close the file eventually, right? Unless of course it was copied somewhere else in the meantime, but in the code example, that is clearly not the case.
- Jweb_Guru 12y agoEventually, yes. But if you're relying on the file being deterministically closed (e.g. if you're using the POSIX file locking mechanism) in CPython, it won't necessarily be correct in non-reference counting garbage-collected languages, and the same is true if you're relying on any other sort of deterministic resource cleanup (e.g. in memory-constrained environments).