Python vs Java garbage collection?

Andrew Dalke adalke at mindspring.com
Mon Dec 23 05:06:45 EST 2002


Stuart D. Gathman wrote:
> The problem with Python reference counting, is that it encourages sloppy
> programming like:
> 
>   data = open('myfile','r').read()
> 
> depending on the reference counting GC to release and close the file
> object immediately when read() returns.  This habit must be broken before
> Python can evolve to Lisp like speed.  The proper code:
> 
>   fp = open('myfile','r')
>   data = fp.read()
>   fp.close()
> 
> is not as pretty.

Actually, that's not proper either.  Suppose the read fails and
raises an exception.  Then the 'close' will never be called and you
are again dependent on the implementation defined garbage collection
behaviour.

The proper code is more like

fp = open('myfile', 'r')
try:
   data = fp.read()
finally:
   fp.close()

This guarantees that fp.close() will be called no matter what,
and if an exception was raised in the try block it will be
propogated upwards after the finally clause executes.


However, if there's an exception in the finally clause then
that's the one which will be propogated, as you can see in

 >>> try:
...     1/0
... finally:
...     qwert
...
Traceback (most recent call last):
   File "<stdin>", line 4, in ?
NameError: name 'qwert' is not defined
 >>>

So if you want to be really, really correct, you might try
something more like

fp = open('myfile', 'r')
try:
   data = fp.read()
finally:
   try:
     fp.close()
   except IOError:
     pass

See why automatic garbage collection is so nice?

					Andrew
					dalke at dalkescientific.com




More information about the Python-list mailing list