Events

Scott David Daniels Scott.Daniels at Acm.Org
Fri Nov 19 19:13:14 CET 2004


factory wrote:
>   Anyone want to comment on what they think of this following bit of a 
> simple event framework?
>   Are there any really obvious things I should be doing with this code 
> that stop me from getting bitten on the arse in the future?
...
> class FoobarTalker( Talker ):
>     importantEvent= 42
>     
>     def SomethingHappened( self, something ):
>         self.Talk( FoobarTalker.importantEvent, something )
...

Rather than making events be numbers (simple discrete things),
I suspect that you'd be happier with a hierarchy.  This way
You can listen to "all kinds of events."

Python gives you a nice way to define hierarchies in classes,
so you could use classes directly as your events, or make
your events instances (and thus allow data to be attached to
the event).  Certainly if you are attaching data, and possibly
even if you you are not, you may want to provide a means of
retrieving "the current event."  You could even look at the
history of exceptions in python for a model of what you might want.

So, for events:
class Event(object): pass   # The mother event in case you need to share
class ImportantEvent(Event): pass
class IgnorableEvent(Event): pass
class UsefulEvent(Event): pass

you could change the guts of your Talk method from:
...
 >             evt, listener = i
 >             if evt == event:
 >                 listener(*args)
To:
...
               criterion, listener = i
               if issubclass(event, criterion):
                   listener(*args)

Or (for the data-attached form):
               criterion, listener = i
               if isinstance(event, criterion):
                   listener(*args)
...



More information about the Python-list mailing list