Observer-Pattern by (simple) decorator

Steven Bethard steven.bethard at gmail.com
Sat Jun 2 12:12:37 EDT 2007


Wildemar Wildenburger wrote:
>>>> class Observable(object):
> ...     def __init__(self, func, instance=None, observers=None):
> ...         self.func = func
> ...         self.instance = instance
> ...         self.observers = observers or []

Unless you also changed code in __get__, this means you'll get a new 
list every time you access the "meth" attribute since the __get__ method 
is called anew for every attribute access::

 >>> class SomeActor(object):
...     @Observable
...     def meth(self, foo):
...         print foo
...
 >>> def callback(instance):
...     print "Yippie, I've been called on", instance
...     instance.bar = True
...
 >>> # only accessing the "meth" attribute once
 >>> meth = a1.meth
 >>> meth.add_callback(callback)
 >>> meth('a1')
a1
Yippie, I've been called on <__main__.SomeActor object at 0x00E87CB0>
 >>> # accessing the "meth" attribute multiple times
 >>> a1 = SomeActor()
 >>> a1.meth.add_callback(callback)
 >>> a1.meth('a1')
a1

See my other post for how to get instance-level observer lists using a 
WeakKeyDictionary.

STeVe



More information about the Python-list mailing list