gc question

I V ivlenin at gmail.com
Sun Mar 9 14:37:45 EDT 2008


On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote:
> Well, that suits me. The most unnatural thing about Python was adapting
> to the idea of just letting unreleased resources go jogging off
> wherever. :)

Yes, that's a bad habit that garbage collection can encourage. GC is good 
for managing memory, but not good for managing other resources, so if an 
object holds some other resource, it's important to make sure the 
resource is released in a timely fashion rather than relying on the 
finalizer (the __del__ function).

CPython uses reference counting, so it usually destroys objects fairly 
soon after the stop being used. But JPython and IronPython don't do 
reference counting, so forgetting to clean up resources can be a 
significant problem.

> "Where's the f.close?"
> "You don't need it!"

Although, you still don't need f.close, with the new with statement:

with open('myfile') as f:
	string = f.readline()
# f.close() gets called automatically here, without waiting for 	
# garbage collection.

If you want to use this in 2.5, you have to write:

from __future__ import with_statement

The big advantage here is that f.close will get called if the block exits 
normally, or if there is an exception. For more, see 
http://effbot.org/pyref/with.htm .



More information about the Python-list mailing list