Reference Tracking

Alex Martelli aleax at aleax.it
Sat Apr 12 20:27:54 CEST 2003


Matt Bergin wrote:

> I am trying to write a class which gives out objects and keeps track of
> them so they can be returned to the class and given out to other code
> when the code they were given out to no longer has any reference to the
> objects (i.e. has finished using it).

OK, makes sense.

> The trouble is, the manual says not to try and stop objects from being
> killed by creating new references in __del__. My original thoughts were
> to write some code in __del__ of the given out object that returned it
> to the original class. Is this is a good way of going about this
> problem? Any ideas would be welcome!

That might cause you problems at termination time, I think.  Also,
is there any risk that your objects could end up as parts of cycles
of mutual references?  If so, defining a __del__ makes it impossible
for the garbage collector to ever reclaim them.

Rather, you might ensure that all objects "given out" by the class
are kept alive anyway -- by simply keeping a reference to them in a
class variable, e.g. a list -- and, periodically, checking which
objects have no other references extant except the one in the list
(sys.getrefcount returning 2) so you can move them to a separate
list of "objects ready to be recycled".

You can try to avoid the periodic scanning overhead by using a
tricky __del__, or a non-tricky __del__ or weak-reference callback
for some object that's "packed together with" the object you give
out (keeping the latter alive in a per-class container anyway).  A
radically different and far cleaner approach would be to specify
a way (e.g. a method) for the using-code to say "I'm finished with
this object, reuse it freely from now on" -- no black magic at all
(of course, perhaps marginally smaller convenience for the using
code, but it's not all that bad to ensure a finalization method
gets explicitly called, IMHO).


Alex





More information about the Python-list mailing list