Event system

Generic library provides generic.event module which helps you implement event systems in your application. By event system I mean an API for subscribing for some types of events and to fire those events so previously subscribed handlers are being executed.

Basic usage

First you need to describe event types you want to use in your application, generic.event dispatches events to corresponding handlers by inspecting events’ types, so it’s natural to model those as classes:

class CommentAdded(object):
  def __init__(self, post_id, comment):
    self.post_id = post_id
    self.comment = comment

Now you want to register handler for your event type:

from generic.event import subscriber

@subscriber(CommentAdded)
def print_comment(ev):
  print "Got new comment: %s" % ev.comment

Then you just call generic.event.fire function with CommentAdded instance as its argument:

from generic.event import fire

fire(CommentAdded(167, "Hello!")) # prints `Got new comment: Hello!`

This is how it works.

API reference

class generic.event.Manager

Event manager

Provides API for subscribing for and firing events. There’s also global event manager instantiated at module level with functions subscribe(), fire() and decorator subscriber() aliased to corresponding methods of class.

subscribe(handler, event_type)

Subscribe handler to specified event_type

subscriber(event_type)

Decorator for subscribing handlers

Works like this:

>>> @mymanager.subscriber(MyEvent)
... def mysubscriber(evt):
...     # handle event
...     return
>>> mymanager.fire(MyEvent())
fire(event)

Fire event

All subscribers will be executed with no determined order.

unsubscribe(handler, event_type)

Unsubscribe handler from event_type

Functions below are just aliases for methods of globally instantiated manager:

generic.event.subscribe(handler, event_type)

Subscribe handler to specified event_type

generic.event.subscriber(event_type)

Decorator for subscribing handlers

Works like this:

>>> @mymanager.subscriber(MyEvent)
... def mysubscriber(evt):
...     # handle event
...     return
>>> mymanager.fire(MyEvent())
generic.event.fire(event)

Fire event

All subscribers will be executed with no determined order.

generic.event.unsubscribe(handler, event_type)

Unsubscribe handler from event_type