Using Object Events in Pyramid


This code works only in Pyramid 1.1a4+. It will also make your brain explode.

Zope's Component Architecture supports the concept of "object events", which are events which call a subscriber with an context object and the event object.

Here's an example of using an object event subscriber via the @subscriber decorator:

 1from zope.component.event import objectEventNotify
 2from zope.component.interfaces import ObjectEvent
 4from import subscriber
 5from pyramid.view import view_config
 7class ObjectThrownEvent(ObjectEvent):
 8    pass
10class Foo(object):
11  pass
13@subscriber([Foo, ObjectThrownEvent])
14def objectevent_listener(object, event):
15    print object, event
18def theview(request):
19    objectEventNotify(ObjectThrownEvent(Foo()))
20    objectEventNotify(ObjectThrownEvent(None))
21    objectEventNotify(ObjectEvent(Foo()))
22    return 'OK'
24if __name__ == '__main__':
25    from pyramid.config import Configurator
26    from paste.httpserver import serve
27    config = Configurator(autocommit=True)
28    config.hook_zca()
29    config.scan('__main__')
30    serve(config.make_wsgi_app())

The objectevent_listener listener defined above will only be called when the object of the ObjectThrownEvent is of class Foo. We can tell that's the case because only the first call to objectEventNotify actually invokes the subscriber. The second and third calls to objectEventNotify do not call the subscriber. The second call doesn't invoke the subscriber because its object type is None (and not Foo). The third call doesn't invoke the subscriber because its objectevent type is ObjectEvent (and not ObjectThrownEvent). Clear as mud?