Comment Re:Reference counting and unmanaged resources (Score 3, Insightful) 196
these implementations pay a penalty for relying on the VM's tracing garbage collection, and this penalty is loss of finalizer functionality.
And this is why it is best practice in Python to use the with statement, to make sure that things get cleaned up when you are done with them.
In CPython you can get away with just dropping your objects on the floor, and the reference counting will clean them up for you. In other implementations, not so much.
This works okay in CPython:
def read_data(fname):
f = open(fname)
return f.read()
In CPython, with no references to f it gets cleaned up, and the open file gets closed.
In any version of Python, this works great:
def read_data(fname):
with open(fname) as f:
return f.read()
The with statement ensures that the open file will be closed, no matter how the function is exited (including by exception).
And I actually prefer the with statement these days... I like how it makes the lifetime explicit for the stuff it wraps.
Raymond Hettinger has expressed the opinion that the with statement is one of the really best ideas in Python. I think that was during his PyCon session where he listed his favorite things in Python.