Searching equivalent to C++ RAII or deterministic destructors

Jack Diederich jackdied at
Fri Jul 3 08:34:01 EDT 2009

On Thu, Jul 2, 2009 at 2:36 PM, Carl Banks<pavlovevidence at> wrote:
> On Jul 2, 3:12 am, Ulrich Eckhardt <eckha... at> wrote:
>> Bearophile wrote:
>> > Ulrich Eckhardt:
>> >> a way to automatically release the resource, something
>> >> which I would do in the destructor in C++.
>> > Is this helpful?
>> >
>> Yes, it aims in the same direction. However, I'm not sure this applies to my
>> case. The point is that the resource handle is not just used locally in a
>> restricted scope but it is allocated and stored. The 'with' is something
>> that makes sense in the context of mutex locking, where you have a
>> well-defined critical section. What I need is something similar to open(),
>> which returs a file. When the last reference to that object goes out of
>> scope, the underlying file object is closed.
> On CPython you can do it with a __del__ attribute.
> Warning: objects with a __del__ attribute prevent reference cycle
> detection, which can potentially lead to memory (and resource) leaks.
> So you must be careful to avoid creating reference loops with that
> object.

WARNING-er: As Carl points out, adding a __del__ method actually makes
it /less/ likely that your object will be cleaned up.  __del__ is only
useful if you have a complicated tear-down procedure.  Since you come
from C++ RAII land (my old haunt) your objects probably only allocate
one resource each, or worse: a bunch of objects that allocate one
resource each.  In that case __del__ will always hurt you.

The C++ temptation is to match every __init__ with a __del__.  A
better rule of thumb is to only add a __del__ method after confirming
with someone else that it would be useful.  Better still is to ask
them by postal courier.  For best results that someone should be your

> Note that file objects have a close method; you can explicitly close
> it at any time.  Your object should follow that example, and define a
> close (or release, or whatever) method.  I'd recommend making an
> effort to call it and to rely on __del__ as little as possible.

This.  If you care enough about a resource to write a __del__ method
you care enough to clean it up explicitly.  'with' blocks are very
nice for that.


More information about the Python-list mailing list