Object instance "reporting" to a container class instance

Alex Martelli aleax at mac.com
Sun Mar 11 22:06:06 EDT 2007


Daniel Lipovetsky <daniel.lipovetsky at gmail.com> wrote:

> I would like for an object to "report" to a container object when a
> new instance is created or deleted. I could have a container object
> that is called when a new instance is created, as below.
> 
> class AnyObject:
>     pass
> 
> class Container:
>     links = []

Why a class variable rather than a normal instance variable?

>     def add(self,other):
>         while other not in self.links:
>             self.links.append(other)

What a weird implementation... why the while, &c?!

>     def rem(self,other):
>         while other in self.links:
>             self.links.remove(other)

Ditto.

> ...
> 
> container = Container()
> a = AnyObject()
> container.add(a)
> 
> My question is: can (should? :-) this "reporting" be done inside the
> instance's __init__ and __del__ methods (that is, an instance
> "reports" to the container as soon as it is created or deleted)?

The object's __del__ will never be called, because the object's presence
in the Container's self.links will always keep the object alive.

Study weak references -- and make the Container's links (whether it
needs to be a class or instance variable for the container) a
weakref.WeakValueDictionary (as keys, use unique, always-incrementing
integers) -- a WeakKeyDictionary is OK too if contained objects are
hashable by identity (and might make other things easier, e.g. moving an
object from one container to another by removing it from one and adding
it from the other).

With weak references, the "reporting" of the object's demise will be
automatic and transparent - the relevant dict entry just disappears when
the object does.  For the "registration", the call to the add method of
the container, it's fine to do it in __init__ if at contained-object's
init time you already know, invariably, what container it will be in.


Alex



More information about the Python-list mailing list