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
 3
 4from pyramid.events import subscriber
 5from pyramid.view import view_config
 6
 7class ObjectThrownEvent(ObjectEvent):
 8    pass
 9
10class Foo(object):
11  pass
12
13@subscriber([Foo, ObjectThrownEvent])
14def objectevent_listener(object, event):
15    print object, event
16
17@view_config(renderer='string')
18def theview(request):
19    objectEventNotify(ObjectThrownEvent(Foo()))
20    objectEventNotify(ObjectThrownEvent(None))
21    objectEventNotify(ObjectEvent(Foo()))
22    return 'OK'
23
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?