Question

Possible Duplicate:
Event loop implementation for Python 3?

I am trying to implement an event loop in python2.7. I would like to be able to trigger events based on a time event and as a result of another action taking place.

I understand I can make use of select to do something similar to this.

Is this the right way forwards or is there a better way which I am missing?

Was it helpful?

Solution

An event loop is a loop which handles / deals with events.

An event is something that occurs in the system where some code parts might be interested in.

At the beginning, all components register for events, and after that, an init event is fired:

I am just providing raw code here:

listeners = [component1, component2, component3]
eventqueue.add(InitEvent())
while True:
    event = eventqueue.pop()
    for listener in listeners:
        listener.handle_event(event)

How an eventqueue is implemented and what the Event() class hierarchy looks like is left as an exercise for the reader. Take care about using threading.(R)Locks etc. for the .pop() method.

Additionally, you could have separate listener lists for each event type. An event could thus be "fired" by just calling it (or its .fire() method) and have a mechanism to identify all its own and parent's listeners in order to inform them about the event.

In any case, the listeners then can decide on their own what to do with and according to the event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top