[Tutor] Let imported module access calling program

Kent Johnson kent37 at tds.net
Tue Mar 25 14:01:12 CET 2008

Shrutarshi Basu wrote:
> The event handling approach looks interesting and isn't something that
> I haven't encountered before. Could you to point me somewhere I could
> learn more about it?

Not really...this is commonly used by GUI frameworks. For example in 
Tkinter you can register a mouse-button callback on a widget by calling
widget.bind('<Button-1>', callback)
where callback is the event handler.

In your case, you would define the possible events and make a registry. 
For example, the registry could be a dict mapping event name to a list 
of handlers:

from collections import defaultdict
event_registry = defaultdict(list)

def register(event, handler):
   # Should check that event is a real event name

A client might call
register('sensor_front', handle_sensor_front)

Then in your main loop you check for the various events and call the 
callbacks. Perhaps you have a dict mapping event names to functions that 
query a condition:

events = dict(sensor_front = lambda: robot.sensor('front')

for event, query in events.items():
   if query():
     for handler in event_registry[event]:

This is simplistic - it needs error handling, a way to remove event 
handlers and probably much more - but perhaps it will give you enough to 
evaluate the idea.


More information about the Tutor mailing list