does python have useless destructors?

David Turner dkturner at telkomsa.net
Thu Jun 10 04:11:40 EDT 2004


"Michael P. Soulier" <msoulier at digitaltorque.ca._nospam> wrote in message news:<slrnccetd9.gag.msoulier at tigger.digitaltorque.ca>...

> So putting a close of some external resource in a destructor would be a
> bad idea, apparently. As this is the kind of thing I typically use
> destructors in OO programming for, I found this quite surprising.
> 

Me too.  Fortunately, in the current vanilla Python implementation,
the destructors are fairly reliable.  However there is a fatal flaw: 
locals get extra references when exceptions are raised.  Which pretty
much means you can't use RAII wherever it would be most useful.

This makes me sad.  But there is some hope in the following pattern,
although it can be quite awkward:

def with_file(fname, mode, oper):
    f = open(fname, mode);
    try:
        oper()
    finally:
        f.close()

Of course, this can very quickly turn your code into so much
functional goo.  That's not necessarily a bad thing, as Lisp
programmers can attest...  But it's still not quite as powerful as
RAII.


Regards
David Turner



More information about the Python-list mailing list