Python vs Java garbage collection?
Paul Moore
gustav at morpheus.demon.co.uk
Sun Dec 29 10:19:29 EST 2002
pinard at iro.umontreal.ca (François Pinard) writes:
>> [...] The proper code:
>
>> fp = open('myfile','r')
>> data = fp.read()
>> fp.close()
>
>> is not as pretty.
>
> This code is surely proper in Jython, working around the fact that Jython
> relies on Java's garbage collector.
Technically, "correct" code should do
fp = open('myfile','r')
try:
data = fp.read()
finally:
fp.close()
as the read() call could raise an exception. And you should catch
exceptions in the open() call. And there are probably other things
that could go wrong.
This is a "practicality beats purity" issue.
The bigger point here is that the C++ "resource acquisition is
initialisation" idiom (and associated principles such as releasing
resources in destructors) doesn't carry across unchanged to Python.
You *can* use the idea, but it's not the end of the story for
exception safety in Python. (For example, Python has "finally", where
C++ doesn't.)
Paul.
--
This signature intentionally left blank
More information about the Python-list
mailing list