diff options
| author | jason kirtland <jek@discorporate.us> | 2010-02-14 12:36:57 -0800 |
|---|---|---|
| committer | jason kirtland <jek@discorporate.us> | 2010-02-14 12:36:57 -0800 |
| commit | c4579f81ac5490a5722678c01c0fc9e0589a4d5b (patch) | |
| tree | 76b063b787469b8fafa85aab0b2c4cfae655f6e2 /blinker/base.py | |
| parent | f1d320a540c3cd1838bb1b888cca73665f13b8f4 (diff) | |
| download | blinker-c4579f81ac5490a5722678c01c0fc9e0589a4d5b.tar.gz | |
Added ``Signal.temporarily_connected_to`` context manager
Diffstat (limited to 'blinker/base.py')
| -rw-r--r-- | blinker/base.py | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/blinker/base.py b/blinker/base.py index 14ee6d9..56b1c54 100644 --- a/blinker/base.py +++ b/blinker/base.py @@ -12,6 +12,7 @@ from weakref import WeakValueDictionary from blinker._utilities import ( WeakTypes, + contextmanager, defaultdict, hashable_identity, reference, @@ -94,6 +95,32 @@ class Signal(object): raise return receiver + @contextmanager + def temporarily_connected_to(self, receiver, sender=ANY): + """Execute a block with the signal connected *receiver*. + + This is a context manager for use in the ``with`` statement, and can + be useful in unit tests. *receiver* is connected to the signal for + the duration of the ``with`` block, and will be disconnected + automatically when exiting the block:: + + ready = Signal() + receiver = lambda sender: pass + + with ready.temporarily_connected_to(receiver): + # do stuff + ready.send(123) + + """ + self.connect(receiver, sender=sender, weak=False) + try: + yield None + except: + self.disconnect(receiver) + raise + else: + self.disconnect(receiver) + def send(self, *sender, **kwargs): """Emit this signal on behalf of *sender*, passing on \*\*kwargs. |
