Question

Django happens to have a Signals system built in and it would be quite useful for a project I'm working on.

I've been reading though the Pyramid docs and it does appear to have an Events system which is tied very closely to Signals, but not quite. Would something like this work for a general purpose signal system or should I roll my own?

Was it helpful?

Solution

The events system used by Pyramid fulfils the exact same use-cases as the Signals system. Your application can define arbitrary events and attach subscribers to them.

To create a new event, define an interface for it:

from zope.interface import (
    Attribute,
    Interface,
    )

class IMyOwnEvent(Interface):
    foo = Attribute('The foo value')
    bar = Attribute('The bar value')

You then define an actual implementation of the event:

from zope.interface import implementer

@implementer(IMyOwnEvent)
class MyOwnEvent(object):
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

The interface is actually optional, but helps documentation and makes it easier to provide multiple implementations. So you could get away with omitting the interface definition and @implementer parts altogether.

Wherever you want to signal this event, use the registry.notify method; here I assume you have a request available to reach the registry:

request.registry.notify(MyOwnEvent(foo, bar))

This'll send the request to any subscribers you've registered; either with config.add_subscriper or with pyramid.events.subscriber:

from pyramid.events import subscriber
from mymodule.events import MyOwnEvent

@subscriber(MyOwnEvent)
def owneventsubscriber(event):
    event.foo.spam = 'eggs'

You can also use the IMyOwnEvent interface instead of the MyOwnEvent class and your subscriber will be notified of all events that implement the interface, not just your specific implementation of that event.

Note that notifying subscribers never catches exceptions (like send_robust in Django would do).

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