Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ensure proper order of signal emission #281

Merged
merged 8 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions src/psygnal/_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,9 @@ class Emitter:
Whether to check the callback parameter types against `signature` when
connecting a new callback. This can also be provided at connection time using
`.connect(..., check_types=True)`. By default, False.
raise_on_emit_during_emission: bool
raise exception if signal is emitted while already emitting.
This could be used to detect callback loops. By default, False.

Raises
------
Expand All @@ -319,6 +322,7 @@ def __init__(
name: str | None = None,
check_nargs_on_connect: bool = True,
check_types_on_connect: bool = False,
raise_on_emit_during_emission: bool = False,
) -> None:
self._name = name
self._instance: Callable = self._instance_ref(instance)
Expand All @@ -335,10 +339,12 @@ def __init__(
self._signature = signature
self._check_nargs_on_connect = check_nargs_on_connect
self._check_types_on_connect = check_types_on_connect
self._raise_on_emit_during_emission = raise_on_emit_during_emission
self._slots: list[WeakCallback] = []
self._is_blocked: bool = False
self._is_paused: bool = False
self._lock = threading.RLock()
self._emit_queue: list[tuple] = []

@staticmethod
def _instance_ref(instance: Any) -> Callable[[], Any]:
Expand Down Expand Up @@ -1034,14 +1040,25 @@ def __call__(
def _run_emit_loop(self, args: tuple[Any, ...]) -> None:
# allow receiver to query sender with Signal.current_emitter()
with self._lock:
with Signal._emitting(self):
for caller in self._slots:
try:
caller.cb(args)
except Exception as e:
raise EmitLoopError(
cb=caller, args=args, exc=e, signal=self
) from e
self._emit_queue.append(args)
if len(self._emit_queue) > 1:
if self._raise_on_emit_during_emission:
raise RuntimeError(
f"Signal {self!r} emitted while already emitting."
)
return None
try:
with Signal._emitting(self):
i = 0
while i < len(self._emit_queue):
arg = self._emit_queue[i]
for caller in self._slots:
caller.cb(arg)
i += 1
except Exception as e:
raise EmitLoopError(cb=caller, args=args, exc=e, signal=self) from e
finally:
self._emit_queue.clear()

return None
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Works for me! Thanks.

I'm not worried about the very small benchmark decreases on emit to setattr and setitem for large numbers of callbacks.

Thanks for working on this


Expand Down Expand Up @@ -1190,6 +1207,7 @@ def __getstate__(self) -> dict:
"_args_queue",
"_check_nargs_on_connect",
"_check_types_on_connect",
"_emit_queue",
)
dd = {slot: getattr(self, slot) for slot in attrs}
dd["_instance"] = self._instance()
Expand Down
36 changes: 36 additions & 0 deletions tests/test_psygnal.py
Original file line number Diff line number Diff line change
Expand Up @@ -996,3 +996,39 @@ def test_pickle():
x = pickle.loads(_dump)
x.sig.emit()
mock.assert_called_once()


def test_signal_order():
"""Test that signals are emitted in the order they were connected."""
emitter = Emitter()
mock1 = Mock()
mock2 = Mock()

def callback(x):
if x != 10:
emitter.one_int.emit(10)

emitter.one_int.connect(mock1)
emitter.one_int.connect(callback)
emitter.one_int.connect(mock2)
emitter.one_int.emit(1)

mock1.assert_has_calls([call(1), call(10)])
mock2.assert_has_calls([call(1), call(10)])


def test_double_emmision_error():
s = SignalInstance(raise_on_emit_during_emission=True)

i = 0

def callback():
nonlocal i
if i == 0:
s.emit()
i += 1

s.connect(callback)

with pytest.raises(EmitLoopError):
s.emit()
Loading