Properties, Methods, Events

Alex Martelli aleaxit at yahoo.com
Tue May 8 15:46:03 EDT 2001


"John Flynn" <transpicio at yahoo.com.au> wrote in message
news:F1UJ6.3018$ZJ.114158 at ozemail.com.au...
    ...
> would also be nice to have a way of hooking up other message handlers at
> runtime, in a way that the designer of the object emitting the messages
need
> not anticipate.

Sure, a "listener" pattern, why not.  Python makes it VERY easy by
providing bound-methods as callable.

> Following on from your example, it's trivial to make an Events mixin that
> maybe contains a dictionary mapping event-names to a list of
event-handlers.
> If an event-handler is present, it can be automatically invoked by the
> __setattr__ method. But, this only applies to _get_ and _set_ events.

Right.  Objects interested in listening to another object's get and set
"events" should register a callable with the object.  It's indeed easy to
extend the mixin example I gave to provide for this listener pattern,
too.

> Do you know of any way to trap an ordinary method call? Eg. if TimeBomb
has
> a method 'tick', can we find a way to know automatically when it is
called?

Sure!  What helps is that a call to an object's method, "obj.amethod()",
proceeds regularly and without black magic in Python: the attribute
amethod of object obj is getattr'd just like any other attribute access
would be, then the resulting object (must be a callable, normally a
bound method) is called.  So, __getattr__ will enter the picture UNLESS
'amethod' is an entry in the obj's __dict__ -- thus, we need to wrap
the object so that its 'listenable' methods/events are NOT in its
__dict__, and wrap the bound method with a suitable callable that
knows about the registered listeners and calls them at need... i.e.,
in its own __call__ method (before or after it delegates the call to
the actual object's bound-method it wraps).


Personally, I don't consider such abundant use of introspection and
black magic normally appropriate in production programs, but... it
sure IS fun to design such stuff!-)  Performance may be an issue in
some cases, of course -- if you DO want to rely on such architectures
for production software, once the framework works, this might be
the kind of thing worth recoding in C (profiling will tell you...).


Alex






More information about the Python-list mailing list