pydispatch.decorators
#
New in version 0.2.2.
- receiver(event_name: Union[str, Iterable[str]], cache: bool = False, auto_register: bool = False)[source]#
Decorator to bind a function or method to the Global Dispatcher
Examples
>>> import pydispatch
>>> pydispatch.register_event('foo')
>>> @pydispatch.receiver('foo') ... def on_foo(value, **kwargs): ... print(f'on_foo: "{value}"')
>>> pydispatch.emit('foo', 'spam') on_foo: "spam"
Using the cache argument
>>> @pydispatch.receiver('bar', cache=True) ... def on_bar(value, **kwargs): ... print(f'on_bar: "{value}"')
>>> pydispatch.register_event('bar') >>> pydispatch.emit('bar', 'eggs') on_bar: "eggs"
Using auto_register
>>> @pydispatch.receiver('baz', auto_register=True) ... def on_baz(value, **kwargs): ... print(f'on_baz: "{value}"')
>>> pydispatch.emit('baz', 'ham') on_baz: "ham"
Receiving multiple events
>>> @pydispatch.receiver(['event_one', 'event_two'], auto_register=True) ... def on_event_one_or_two(value, **kwargs): ... print(value)
>>> pydispatch.emit('event_one', 1) 1 >>> pydispatch.emit('event_two', 2) 2
- Parameters
event_name – Event name (or names) to bind the callback to. Can be a string or an iterable of strings
cache – If the event does not exist yet and this is
True
, the callback will be held in a cache until it has been registered. IfFalse
, aDoesNotExistError
will be raised. (Default isFalse
)auto_register – If the event does not exist and this is
True
, it will be registered on the Global Dispatcher. (Default isFalse
)
New in version 0.2.2.