Is RAII possible in Python?

Pierre Rouleau prouleau at impathnetworks.com
Sat Nov 15 14:18:23 EST 2003


As much as I love Python, I sometimes find myself wishing Python 
supported the RAII idiom (resource acquisition is initialization) that 
is available in C++, the emerging D language, and others.

In some situations (like controlling non-memory resources) it is nice to 
be able to create an object that will execute some code on its 
destruction.  For example, an object that controls access to a critical 
section: the creation of the object calls the function required to enter 
the critical section, and the __del__() calls the function required to 
exit the critical section.  If an exception occurs while the code is 
insinde the critical section managed by the object, the the object's 
__del__() is automatically called and the critical section exited.

AFAIK, the call of __del__() method on object destruction is not 
garanteed to be called when the interpreter exists.  Is this true?

Is the __del__() mehod of an object garanteed to be called when a 
function exists normally or is forced to exit by an exception?

Is RAII available in Python?

Thanks

Pierre







More information about the Python-list mailing list