does python have useless destructors?

David Turner dkturner at telkomsa.net
Sat Jun 12 06:21:26 EDT 2004


Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote in message news:<7xekolx229.fsf at ruckus.brouhaha.com>...
> David Bolen <db3l at fitlinxx.com> writes:
> > It lets you write code like:
> > 
> >         void some_function(void) {
> >             Lock_object lock(some_parms);
> > 
> >             - do something needing the lock -
> >         }
> 
> There's a PEP for something like that in Python:
> 
>   http://www.python.org/peps/pep-0310.html
> 

The PEP in question describes the "with" statement, which is more or
less analogous to the C# "using" statement.

There is a serious problem with this approach.

The serious problem is that the end-user has to remember to use it. 
Yes, it's less typing than try/finally, but it's *still not obvious
when you have to use it*.

The huge advantage that the RAII approach holds in this respect is
that the user of the library just does what comes naturally - for
example, he declares a file object and uses it.  He would have done
that anyway.  He doesn't need to know whether or not it's a RAII
object that needs a "with" or "using" or "dispose" or "try/finally"
clause.

"With" will save typing, but it won't eliminate the important class of
errors that stem from the user's ignorance of the dispose semantics of
the object he's using.  Nor will it eliminate the "careless" errors
that we're all prone to - 30 years' experience notwithstanding.

Well-defined destructor semantics have proven to be a robust,
reliable, and surprisingly general solution to a wide range of
problems.  It wouldn't be *that* hard to implement them in Python - so
why not adopt a good idea?


> I think that's greatly preferable to dictating that the GC system act
> a certain way and free resources as soon as they go out of scope.
> That's just not the correct semantics for GC.  GC should simply create
> the illusion for the application that all objects stay around forever.

Also, I'd like to point out that destructor semantics and GC are not
necessarily related.  There's no rule that says the destructor has to
be called at the same time as the memory is freed.  In fact, there are
several good reasons for separating the events.

One could conceivably even use a pre-processor to implement Python
deterministic destructor semantics in Python.  It's really just a case
of the compiler inserting a number of implicit try/finally blocks, and
reference counting.  I can't see any reason why it couldn't be done in
Jython.

Regards
David Turner



More information about the Python-list mailing list