does python have useless destructors?

David Bolen db3l at fitlinxx.com
Fri Jun 11 14:06:23 EDT 2004


"Terry Reedy" <tjreedy at udel.edu> writes:

> > I've read the rest of the thread, but the ensuing references to C++ RAII
> 
> With 30yrs experience, I have no idea what this is either.  It must be
> something new in C++ since I ceased paying attention some years ago after
> settling on Python for my needs.

Resource Acquisition is Initialization.  It's certainly not a new
idiom, but I'm not sure how far back the RAII term (or at least the
acronym) was first coined.  It is used in Stroustrup's "The C++
Programming Language" at least as of the 1997 edition, but I'm not
sure about earlier editions.  So you may have used it without even
realizing you were doing it :-)

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
automatic stack unwinding in exception handling or normal function
returns.  In other words, the desired approach mentioned in this
thread, of being able to encapsulate resource ownership (files, locks,
etc...) within an object, whose destructor can reliably and
predictably take care of cleaning up the resource.

It lets you write code like:

        void some_function(void) {
            Lock_object lock(some_parms);

            - do something needing the lock -
        }

The very fact that you can create the instance of Lock_object means
you have obtained the lock (thus the "acquisition is initialization"
part).  And then since it is a stack based automatic variable, you are
guaranteed that it will be destroyed however you leave scope (normally,
exception whatever) and thus the lock object's destructor can release
the lock.

The predictable objection creation and destruction mechanisms let you
cascade such operations when multiple resources are needed - for
example:

        void some_function(void) {
            ResourceA get_resourceA();
            ResourceB get_resourceB();

            - do something needing both resources -
        }

In this case, you'll acquire resource A and then B in that order (up
to any number of nested resources).  If one should fail, any of the
others already acquired will naturally be released.  And whether a
normal execution, or exception, they'll always be released in exactly
the opposite order of acquisition due to stack unwinding and the
destruction semantics.

I'm not sure if RAII is intended to also cover non-stack based
objects, in terms handing ownership of the object reference equating
transferring ownership of the resource.  Certainly the classic example
is the stack based approach.

Some google searches should probably show up a variety of descriptions
and further information.

-- David



More information about the Python-list mailing list