Observer-Pattern by (simple) decorator

Wildemar Wildenburger wildemar at freakmail.de
Fri Jun 1 17:27:58 EDT 2007


Hello folks :)
This has got to be an FAQ, but somehow I can't seem to find an answer 
that I understand ...

I thought: I'll just write a decorator that lets me react to method 
calls easily (the ever so popular observer-pattern). I've looked at some 
recepies, but I just don't get them (I'm feeling kinda dumb today, sorry).
What I'd *like* to do is this:

def observable(func):
    # magic code

class SomeActor(object):
    @observable
    def meth(self, foo):
        print foo

def callback(instance):
    print "Yippie, I've been called on", instance
    instance.bar = True

sa = SomeActor()
sa.meth.add_callback(callback)

# now this
sa.meth("I'm the boring old argument")

# I would like to result in this
>>> I'm the boring old argument
>>> Yippie, I've been called on <__main__.SomeActor object at 0xb7e8b40c>
# or so
 


This is more complicated than expected mainly for two reasons:

    * I can't find a way to pass the proper 'instance' argument to
      callback, that is, I don't know how to retrieve the instance that
      meth() was called on, because the observable decorator only gets
      the *function* object but not the *method*. (I hope this was clear
      enough)
    * Also, I don't see how I could add the add_callback() method to the
      meth object. That doesn't seem possible. I can add it to meth's
      function object just fine in the definition of observable, but I
      thats not what I really want. This is probably just a cosmetic
      issue because I don't like the idea of calling
      sa.meth.im_func.add_callback(callback).


Any ideas? Would be great.
/W



More information about the Python-list mailing list