does python have useless destructors?

David Turner dkturner at telkomsa.net
Tue Jun 15 07:26:07 EDT 2004


Roy Smith <roy at panix.com> wrote in message news:<roy-70C5F4.08031214062004 at reader2.panix.com>...
> dkturner at telkomsa.net (David Turner) wrote:
> 
> > Destruction and finalization are *different things*.
> 
> For those of us not up on such things, could you explain the differences?

Destruction is what happens to objects in C++.  C++ does not manage
your memory for you, so destruction happens at very specific times:

1. For stack-based objects, when the object "goes out of scope".
2. For heap-based objects, when the object is explicitly destroyed
with the delete operator.

Finalization is what happens to objects in Java.  Java manages your
memory for you, so finalization happens at very specific times:

1. When the object is garbage collected.

The difficulty here is of course that garbage collection is
unpredictable, and finalization may not happen at all.

So essentially, when we say "destruction", we mean an operation that
is called clean up the object, where the programmer has some sort of
control over when it happens; when we say "finalization" we mean an
operation that is called to clean up the object, where the programmer
has no control over when it happens.

It's perfectly possible to have both destruction and finalization. 
Here is one way of doing it in Python:

-----
class Both:
    def __init__(self):
        self.refcount = 0
    def copy(self):
        self.refcount += 1
        return self
    def unref(self):
        self.refcount -= 1
        if self.refcount == 0:
            self.destruct()
    def destruct(self):
        print "destruction"
    def __del__(self):
        print "finalization"

if __name__ == "__main__":
    x = Both().copy()
    y = x.copy()
    x.unref()
    y.unref()   # "destruction" printed at this point

# "finalization" probably printed here
-----

Hmm... I wonder if it would be possible to override the "="
operator...?

Regards
David Turner



More information about the Python-list mailing list