Deterministic destruction and RAII idioms in Python

plahey at alumni.caltech.edu plahey at alumni.caltech.edu
Mon Jan 30 15:18:19 EST 2006


I have been dabbling in Python for a while now.  One of the things that
really appeals to me is that I can seem to be able to use C++-style
RAII idioms to deal with resource management issues.

For those that have no idea what I am talking about (I learn a lot
reading posts on subjects in which I am clueless), consider the
following code snippet:

for line in file(name):
..print line,

This is nice and clean because I don't have to worry about cleaning
up after myself.  If I can't rely on the destructor for the file
object to close the file, I must write the code like this:

file_obj = file(name)
for line in file_obj:
..print line,
file_obj.close()

not nearly as nice.  Depending on the type of work you do, this can be
no problem or a major headache when exceptions are thrown into the mix.

Python objects have destructors so it seems that the original intent
was to support deterministic destruction (destructors are not very
useful in most GC'ed languages since you never know when or even if
they will be called).  The problem is that other implementations of
Python (Jython and IronPython) do not support deterministic
destruction.  So we are left with a problem:  is deterministic
destruction an implementation detail of CPython that can go away at
anytime, or is it an official property of the language.

Giving up deterministic destruction in Python would be a real blow for
me, since it is one of its unique features among GC'ed languages.

So what's the deal, can I rely on it in "mainstream" Python or am
I out of luck here?




More information about the Python-list mailing list