| 1 |
.. rst-class:: hide-header |
| 2 |
|
| 3 |
Blinker Documentation |
| 4 |
===================== |
| 5 |
|
| 6 |
.. image:: _static/blinker-named.png |
| 7 |
:align: center |
| 8 |
|
| 9 |
.. currentmodule:: blinker |
| 10 |
|
| 11 |
Blinker provides fast & simple object-to-object and broadcast |
| 12 |
signaling for Python objects. |
| 13 |
|
| 14 |
The core of Blinker is quite small but provides powerful features: |
| 15 |
|
| 16 |
- a global registry of named signals |
| 17 |
- anonymous signals |
| 18 |
- custom name registries |
| 19 |
- permanently or temporarily connected receivers |
| 20 |
- automatically disconnected receivers via weak referencing |
| 21 |
- sending arbitrary data payloads |
| 22 |
- collecting return values from signal receivers |
| 23 |
- thread safety |
| 24 |
|
| 25 |
Blinker was written by Jason Kirtand and is provided under the MIT |
| 26 |
License. The library supports Python 3.8 or later; or PyPy3.9 or later. |
| 27 |
|
| 28 |
|
| 29 |
Decoupling With Named Signals |
| 30 |
----------------------------- |
| 31 |
|
| 32 |
Named signals are created with :func:`signal`: |
| 33 |
|
| 34 |
.. code-block:: python |
| 35 |
|
| 36 |
>>> from blinker import signal |
| 37 |
>>> initialized = signal('initialized') |
| 38 |
>>> initialized is signal('initialized') |
| 39 |
True |
| 40 |
|
| 41 |
Every call to ``signal('name')`` returns the same signal object, |
| 42 |
allowing unconnected parts of code (different modules, plugins, |
| 43 |
anything) to all use the same signal without requiring any code |
| 44 |
sharing or special imports. |
| 45 |
|
| 46 |
|
| 47 |
Subscribing to Signals |
| 48 |
---------------------- |
| 49 |
|
| 50 |
:meth:`Signal.connect` registers a function to be invoked each time |
| 51 |
the signal is emitted. Connected functions are always passed the |
| 52 |
object that caused the signal to be emitted. |
| 53 |
|
| 54 |
.. code-block:: python |
| 55 |
|
| 56 |
>>> def subscriber(sender): |
| 57 |
... print(f"Got a signal sent by {sender!r}") |
| 58 |
... |
| 59 |
>>> ready = signal('ready') |
| 60 |
>>> ready.connect(subscriber) |
| 61 |
<function subscriber at 0x...> |
| 62 |
|
| 63 |
|
| 64 |
Emitting Signals |
| 65 |
---------------- |
| 66 |
|
| 67 |
Code producing events of interest can :meth:`Signal.send` |
| 68 |
notifications to all connected receivers. |
| 69 |
|
| 70 |
Below, a simple ``Processor`` class emits a ``ready`` signal when it's |
| 71 |
about to process something, and ``complete`` when it is done. It |
| 72 |
passes ``self`` to the :meth:`~Signal.send` method, signifying that |
| 73 |
that particular instance was responsible for emitting the signal. |
| 74 |
|
| 75 |
.. code-block:: python |
| 76 |
|
| 77 |
>>> class Processor: |
| 78 |
... def __init__(self, name): |
| 79 |
... self.name = name |
| 80 |
... |
| 81 |
... def go(self): |
| 82 |
... ready = signal('ready') |
| 83 |
... ready.send(self) |
| 84 |
... print("Processing.") |
| 85 |
... complete = signal('complete') |
| 86 |
... complete.send(self) |
| 87 |
... |
| 88 |
... def __repr__(self): |
| 89 |
... return f'<Processor {self.name}>' |
| 90 |
... |
| 91 |
>>> processor_a = Processor('a') |
| 92 |
>>> processor_a.go() |
| 93 |
Got a signal sent by <Processor a> |
| 94 |
Processing. |
| 95 |
|
| 96 |
Notice the ``complete`` signal in ``go()``? No receivers have |
| 97 |
connected to ``complete`` yet, and that's a-ok. Calling |
| 98 |
:meth:`~Signal.send` on a signal with no receivers will result in no |
| 99 |
notifications being sent, and these no-op sends are optimized to be as |
| 100 |
inexpensive as possible. |
| 101 |
|
| 102 |
|
| 103 |
Subscribing to Specific Senders |
| 104 |
------------------------------- |
| 105 |
|
| 106 |
The default connection to a signal invokes the receiver function when |
| 107 |
any sender emits it. The :meth:`Signal.connect` function accepts an |
| 108 |
optional argument to restrict the subscription to one specific sending |
| 109 |
object: |
| 110 |
|
| 111 |
.. code-block:: python |
| 112 |
|
| 113 |
>>> def b_subscriber(sender): |
| 114 |
... print("Caught signal from processor_b.") |
| 115 |
... assert sender.name == 'b' |
| 116 |
... |
| 117 |
>>> processor_b = Processor('b') |
| 118 |
>>> ready.connect(b_subscriber, sender=processor_b) |
| 119 |
<function b_subscriber at 0x...> |
| 120 |
|
| 121 |
This function has been subscribed to ``ready`` but only when sent by |
| 122 |
``processor_b``: |
| 123 |
|
| 124 |
.. code-block:: python |
| 125 |
|
| 126 |
>>> processor_a.go() |
| 127 |
Got a signal sent by <Processor a> |
| 128 |
Processing. |
| 129 |
>>> processor_b.go() |
| 130 |
Got a signal sent by <Processor b> |
| 131 |
Caught signal from processor_b. |
| 132 |
Processing. |
| 133 |
|
| 134 |
|
| 135 |
Sending and Receiving Data Through Signals |
| 136 |
------------------------------------------ |
| 137 |
|
| 138 |
Additional keyword arguments can be passed to :meth:`~Signal.send`. |
| 139 |
These will in turn be passed to the connected functions: |
| 140 |
|
| 141 |
.. code-block:: python |
| 142 |
|
| 143 |
>>> send_data = signal('send-data') |
| 144 |
>>> @send_data.connect |
| 145 |
... def receive_data(sender, **kw): |
| 146 |
... print(f"Caught signal from {sender!r}, data {kw!r}") |
| 147 |
... return 'received!' |
| 148 |
... |
| 149 |
>>> result = send_data.send('anonymous', abc=123) |
| 150 |
Caught signal from 'anonymous', data {'abc': 123} |
| 151 |
|
| 152 |
The return value of :meth:`~Signal.send` collects the return values of |
| 153 |
each connected function as a list of (``receiver function``, ``return |
| 154 |
value``) pairs: |
| 155 |
|
| 156 |
.. code-block:: python |
| 157 |
|
| 158 |
>>> result |
| 159 |
[(<function receive_data at 0x...>, 'received!')] |
| 160 |
|
| 161 |
|
| 162 |
Muting signals |
| 163 |
-------------- |
| 164 |
|
| 165 |
To mute a signal, as may be required when testing, the |
| 166 |
:meth:`~Signal.muted` can be used as a context decorator: |
| 167 |
|
| 168 |
.. code-block:: python |
| 169 |
|
| 170 |
sig = signal('send-data') |
| 171 |
with sig.muted(): |
| 172 |
... |
| 173 |
|
| 174 |
|
| 175 |
Anonymous Signals |
| 176 |
----------------- |
| 177 |
|
| 178 |
Signals need not be named. The :class:`Signal` constructor creates a |
| 179 |
unique signal each time it is invoked. For example, an alternative |
| 180 |
implementation of the Processor from above might provide the |
| 181 |
processing signals as class attributes: |
| 182 |
|
| 183 |
.. code-block:: python |
| 184 |
|
| 185 |
>>> from blinker import Signal |
| 186 |
>>> class AltProcessor: |
| 187 |
... on_ready = Signal() |
| 188 |
... on_complete = Signal() |
| 189 |
... |
| 190 |
... def __init__(self, name): |
| 191 |
... self.name = name |
| 192 |
... |
| 193 |
... def go(self): |
| 194 |
... self.on_ready.send(self) |
| 195 |
... print("Alternate processing.") |
| 196 |
... self.on_complete.send(self) |
| 197 |
... |
| 198 |
... def __repr__(self): |
| 199 |
... return f'<AltProcessor {self.name}>' |
| 200 |
... |
| 201 |
|
| 202 |
``connect`` as a Decorator |
| 203 |
-------------------------- |
| 204 |
|
| 205 |
You may have noticed the return value of :meth:`~Signal.connect` in |
| 206 |
the console output in the sections above. This allows ``connect`` to |
| 207 |
be used as a decorator on functions: |
| 208 |
|
| 209 |
.. code-block:: python |
| 210 |
|
| 211 |
>>> apc = AltProcessor('c') |
| 212 |
>>> @apc.on_complete.connect |
| 213 |
... def completed(sender): |
| 214 |
... print f"AltProcessor {sender.name} completed!" |
| 215 |
... |
| 216 |
>>> apc.go() |
| 217 |
Alternate processing. |
| 218 |
AltProcessor c completed! |
| 219 |
|
| 220 |
While convenient, this form unfortunately does not allow the |
| 221 |
``sender`` or ``weak`` arguments to be customized for the connected |
| 222 |
function. For this, :meth:`~Signal.connect_via` can be used: |
| 223 |
|
| 224 |
.. code-block:: python |
| 225 |
|
| 226 |
>>> dice_roll = signal('dice_roll') |
| 227 |
>>> @dice_roll.connect_via(1) |
| 228 |
... @dice_roll.connect_via(3) |
| 229 |
... @dice_roll.connect_via(5) |
| 230 |
... def odd_subscriber(sender): |
| 231 |
... print(f"Observed dice roll {sender!r}.") |
| 232 |
... |
| 233 |
>>> result = dice_roll.send(3) |
| 234 |
Observed dice roll 3. |
| 235 |
|
| 236 |
|
| 237 |
Optimizing Signal Sending |
| 238 |
------------------------- |
| 239 |
|
| 240 |
Signals are optimized to send very quickly, whether receivers are |
| 241 |
connected or not. If the keyword data to be sent with a signal is |
| 242 |
expensive to compute, it can be more efficient to check to see if any |
| 243 |
receivers are connected first by testing the :attr:`~Signal.receivers` |
| 244 |
property: |
| 245 |
|
| 246 |
.. code-block:: python |
| 247 |
|
| 248 |
>>> bool(signal('ready').receivers) |
| 249 |
True |
| 250 |
>>> bool(signal('complete').receivers) |
| 251 |
False |
| 252 |
>>> bool(AltProcessor.on_complete.receivers) |
| 253 |
True |
| 254 |
|
| 255 |
Checking for a receiver listening for a particular sender is also |
| 256 |
possible: |
| 257 |
|
| 258 |
.. code-block:: python |
| 259 |
|
| 260 |
>>> signal('ready').has_receivers_for(processor_a) |
| 261 |
True |
| 262 |
|
| 263 |
|
| 264 |
Documenting Signals |
| 265 |
------------------- |
| 266 |
|
| 267 |
Both named and anonymous signals can be passed a ``doc`` argument at |
| 268 |
construction to set the pydoc help text for the signal. This |
| 269 |
documentation will be picked up by most documentation generators (such |
| 270 |
as sphinx) and is nice for documenting any additional data parameters |
| 271 |
that will be sent down with the signal. |
| 272 |
|
| 273 |
|
| 274 |
Async receivers |
| 275 |
--------------- |
| 276 |
|
| 277 |
Receivers can be coroutine functions which can be called and awaited |
| 278 |
via the :meth:`~Signal.send_async` method: |
| 279 |
|
| 280 |
.. code-block:: python |
| 281 |
|
| 282 |
sig = blinker.Signal() |
| 283 |
|
| 284 |
async def receiver(): |
| 285 |
... |
| 286 |
|
| 287 |
sig.connect(receiver) |
| 288 |
await sig.send_async() |
| 289 |
|
| 290 |
This however requires that all receivers are awaitable which then |
| 291 |
precludes the usage of :meth:`~Signal.send`. To mix and match the |
| 292 |
:meth:`~Signal.send_async` method takes a ``_sync_wrapper`` argument |
| 293 |
such as: |
| 294 |
|
| 295 |
.. code-block:: python |
| 296 |
|
| 297 |
sig = blinker.Signal() |
| 298 |
|
| 299 |
def receiver(): |
| 300 |
... |
| 301 |
|
| 302 |
sig.connect(receiver) |
| 303 |
|
| 304 |
def wrapper(func): |
| 305 |
|
| 306 |
async def inner(*args, **kwargs): |
| 307 |
func(*args, **kwargs) |
| 308 |
|
| 309 |
return inner |
| 310 |
|
| 311 |
await sig.send_async(_sync_wrapper=wrapper) |
| 312 |
|
| 313 |
The equivalent usage for :meth:`~Signal.send` is via the |
| 314 |
``_async_wrapper`` argument. This usage is will depend on your event |
| 315 |
loop, and in the simple case whereby you aren't running within an |
| 316 |
event loop the following example can be used: |
| 317 |
|
| 318 |
.. code-block:: python |
| 319 |
|
| 320 |
sig = blinker.Signal() |
| 321 |
|
| 322 |
async def receiver(): |
| 323 |
... |
| 324 |
|
| 325 |
sig.connect(receiver) |
| 326 |
|
| 327 |
def wrapper(func): |
| 328 |
|
| 329 |
def inner(*args, **kwargs): |
| 330 |
asyncio.run(func(*args, **kwargs)) |
| 331 |
|
| 332 |
return inner |
| 333 |
|
| 334 |
await sig.send(_async_wrapper=wrapper) |
| 335 |
|
| 336 |
|
| 337 |
Call receivers in order of registration |
| 338 |
--------------------------------------- |
| 339 |
|
| 340 |
It can be advantageous to call a signal's receivers in the order they |
| 341 |
were registered. To achieve this the storage class for receivers should |
| 342 |
be changed from an (unordered) set to an ordered set, |
| 343 |
|
| 344 |
.. code-block:: python |
| 345 |
|
| 346 |
from blinker import Signal |
| 347 |
from ordered_set import OrderedSet |
| 348 |
|
| 349 |
Signal.set_class = OrderedSet |
| 350 |
|
| 351 |
Please note that ``ordered_set`` is a PyPI package and is not |
| 352 |
installed with blinker. |
| 353 |
|
| 354 |
|
| 355 |
API Documentation |
| 356 |
----------------- |
| 357 |
|
| 358 |
All public API members can (and should) be imported from ``blinker``:: |
| 359 |
|
| 360 |
from blinker import ANY, signal |
| 361 |
|
| 362 |
Basic Signals |
| 363 |
+++++++++++++ |
| 364 |
|
| 365 |
.. data:: ANY |
| 366 |
|
| 367 |
Symbol for "any sender". |
| 368 |
|
| 369 |
.. autoclass:: Signal |
| 370 |
:members: |
| 371 |
|
| 372 |
Named Signals |
| 373 |
+++++++++++++ |
| 374 |
|
| 375 |
.. function:: signal(name, doc=None) |
| 376 |
|
| 377 |
Return a :class:`NamedSignal` in :data:`default_namespace` for the given |
| 378 |
name, creating it if required. Repeated calls with the same name return the |
| 379 |
same signal. |
| 380 |
|
| 381 |
:param name: The name of the signal. |
| 382 |
:type name: str |
| 383 |
:param doc: The docstring of the signal. |
| 384 |
:type doc: str | None |
| 385 |
:rtype: NamedSignal |
| 386 |
|
| 387 |
.. data:: default_namespace |
| 388 |
|
| 389 |
A default :class:`Namespace` for creating named signals. :func:`signal` |
| 390 |
creates a :class:`NamedSignal` in this namespace. |
| 391 |
|
| 392 |
.. autoclass:: NamedSignal |
| 393 |
:show-inheritance: |
| 394 |
|
| 395 |
.. autoclass:: Namespace |
| 396 |
:show-inheritance: |
| 397 |
:members: signal |
| 398 |
|
| 399 |
|
| 400 |
Changes |
| 401 |
======= |
| 402 |
|
| 403 |
.. include:: ../CHANGES.rst |
| 404 |
|
| 405 |
|
| 406 |
MIT License |
| 407 |
=========== |
| 408 |
|
| 409 |
.. literalinclude:: ../LICENSE.txt |
| 410 |
:language: text |