does python have useless destructors?

Humpdydum oliver.schoenborn at utoronto.ca
Fri Jun 11 15:37:36 EDT 2004


"Duncan Booth" <me at privacy.net> wrote in message
news:Xns95055B29ADABBduncanrcpcouk at 127.0.0.1...
> > The correct answer of course is that the object itself
> > should be aware that it needs to be disposed of and that
> > real world resources can leak if it isn't.
> >
>
> The object itself can know that it needs to be safely disposed of, but it
> cannot tell *when* to dispose of itself. My example function might create
> multiple objects some of which need disposing when the function returns,
> and others have a longer lifetime. The choice between disposing at the end
> of the function or when some containing object is disposed has to be one
> for the caller.

The object actually *does* know when to dispose of itself: when its ref
count goes to zero. Naturally, if you have an object that wraps a resource
that needs cleanup, it goes without saying that that object shouldnt' be
referenced all over the place; rather, there should be only one ref to it,
in the function that instantiates it, and that's all. Then when the function
exits, the object sees ref cnt=0 and knows to cleanup after itself.

Also naturally, if you have (inadvertently) created a cyclical reference, in
which one of the members of the cycle refers to your object, its ref cnt
will not be zero on function exit. In this case such object should force a
garbage collection and test gc.garbage and see if somehow it is involved in
a cycle. If not, it's the user's fault (some other refs were stored
somewhere), otherwise, need to find a way to break the cycle. In any case
each object individually knows when to destroy itself.

Oliver.





More information about the Python-list mailing list