[Pythonmac-SIG] RefCount ?
Jack Jansen
jack@oratrix.nl
Mon, 03 May 1999 15:51:38 +0200
> It would really be very nice to make __del__ "closing" the object automaticly.
> To decrement the refcount would *really* be the least dangerous, fastest and
> most reliable solution.
Believe Just (and me:-): you _really_ don't want to do this. Maybe some future
version of Python will provide something like soft references, and then its
fine, but currently things will break rather spectacularly if you decref an
object and keep a reference around.
What you really want to do is go from object B to object A without keeping a
refcounted reference to A in B. Just suggested one way to do this, another is
to use indirection through a dictionary. Something like this (typed in here,
so untested):
class ObjectKeeper:
def __init__(self):
self.dict = {}
self.counter = 0
def register(self, object):
self.counter = self.counter + 1
self.dict[self.counter] = object
return self.counter
def unregister(self, key):
del self.dict[key]
def get(self, key):
return self.dict[key]
objectkeeper = ObjectKeeper()
Now in de parent __init__ you register and remember the key. Store the key in
the children, and when you need the parent you use objectkeeper.get() to
obtain it. In the parent __del__ do an unregister.
And, of course, ObjectKeeper can have lots of bells and whistles like
__getitem__ methods, the objectkeeper object can be kept as a class attribute
in the parent class, etc etc etc.
--
Jack Jansen | ++++ stop the execution of Mumia Abu-Jamal ++++
Jack.Jansen@oratrix.com | ++++ if you agree copy these lines to your sig ++++
www.oratrix.nl/~jack | see http://www.xs4all.nl/~tank/spg-l/sigaction.htm