does python have useless destructors?

David Turner dkturner at
Mon Jun 14 09:35:14 CEST 2004

"Terry Reedy" <tjreedy at> wrote in message news:<mailman.891.1087014838.6949.python-list at>...
> "David Bolen" <db3l at> wrote in message
> news:u4qpi7yw0.fsf at
> > Resource Acquisition is Initialization.
>  ,,,
> > It comes from a common method in C++ of using stack-allocated objects
> > to own or manage resources, because of the explicit construction and
> > destruction semantics of C++ objects (and their members) during
>  ...
> > I'm not sure if RAII is intended to also cover non-stack based
> > objects, in terms handing ownership of the object reference equating
> Thanks.  This makes it much clearer what behavior some people miss, and why
> the behavior is hard to simulate in CPython (all PyObjects are heap
> allocated).

In fact, the RAII idiom is quite commonly used with heap-allocated
objects.  All that is required is a clear trail of ownership, which is
generally not that difficult to achieve.  Here's some C++ code I wrote

typedef boost::shared_ptr<std::ifstream> file_ptr;
typedef std::stack<file_ptr> file_stack;

file_stack files;

files.push(file_ptr(new std::ifstream(file_to_compile)));
    std::ifstream& f =;
    token << f;
    if (token == Token::eof)

The RAII object in this case is std::ifstream.  What I have is a stack
of file objects, wrapped in the reference-counting container
boost::shared_ptr.  I know that the files will be closed no matter
what happens in the while() loop, because the ifstream class closes
the file when it is destroyed.  It will be destroyed by shared_ptr
when the last reference disappears.  The last reference will disappear
(assuming stored another reference in some outer scope) when the
"files" container goes out of scope.

It's pretty darn hard to mess something like this up.  So yes, you
*can* use heap-based objects as RAII containers.

David Turner

More information about the Python-list mailing list