Last active
June 4, 2023 18:57
-
-
Save chrislawlor/92477b016f966cb51ef25ccd76faa628 to your computer and use it in GitHub Desktop.
Multicast delegates in Python. Uses operator overloading for subscription, C# style.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A multicast delegate implementation. Subscribe or | |
unsubscribe callback functions using += or -= | |
operators, respectively. | |
Example: | |
```python | |
In [1]: from delegate import Multicast | |
In [2]: m = Multicast() | |
In [3]: m += lambda: print("first") | |
In [4]: m += lambda: print("second") | |
In [5]: m() | |
first | |
second | |
``` | |
This code is experimental. Its quality, and the design patterns | |
it encourages, are of questionable value in Python. I suspect | |
one should be wary of any class overriding `__call__` that isn't | |
a decorator, though I'd be happy to be proven wrong as they | |
are fun to write if nothing else. | |
""" | |
from typing import Any, Callable, List | |
class EmptyDelegateException(ValueError): | |
pass | |
class Multicast: | |
def __init__(self): | |
self._invocation_list: List[Callable] = [] | |
@property | |
def invocation_list(self): | |
return self._invocation_list | |
def __call__(self, *args, **kwargs) -> Any: | |
# return only the last value | |
if len(self._invocation_list) == 0: | |
raise EmptyDelegateException() | |
ret = None | |
for method in self._invocation_list: | |
ret = method(*args, **kwargs) | |
return ret | |
def __iadd__(self, method: Callable) -> "Multicast": | |
"""Multicast += some_function""" | |
if method not in self._invocation_list: | |
self._invocation_list.append(method) | |
return self | |
def __isub__(self, method: Callable): | |
"""Multicast -= some_function""" | |
if method in self._invocation_list: | |
self._invocation_list.remove(method) | |
return self | |
def __len__(self) -> int: | |
return len(self._invocation_list) | |
def __bool__(self) -> bool: | |
return bool(len(self)) | |
def __str__(self) -> str: | |
return f"Multicast[{len(self)}]" | |
def __eq__(self, other) -> bool: | |
return isinstance(other, self.__class__) and self._invocation_list == other._invocation_list |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Copyright 2020 Christopher Lawlor | |
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from unittest.mock import Mock | |
import pytest | |
from delegate import Multicast | |
@pytest.fixture | |
def delegate(): | |
return Multicast() | |
def test1(): | |
return "test1" | |
def test2(): | |
return "test2" | |
def test_no_methods_throws(delegate): | |
"""Invoking a delegate with no subscriptions throws""" | |
with pytest.raises(ValueError): | |
value = delegate() | |
def test_can_add_method(delegate): | |
"""Tests subscription via += operator""" | |
delegate += test1 | |
value = delegate() | |
assert value == "test1" | |
def test_len(delegate): | |
"""Delegate has a length""" | |
assert len(delegate) == 0 | |
delegate += test1 | |
assert len(delegate) == 1 | |
def test_can_remove_method(delegate): | |
"""Test unsubscribe by -= operator""" | |
delegate += test1 | |
delegate -= test1 | |
assert len(delegate) == 0 | |
def test_return_value_is_last_method(delegate): | |
"""Return the result of the last subscribed function when invoked""" | |
delegate += test1 | |
delegate += test2 | |
value = delegate() | |
assert value == "test2" | |
def test_eq(): | |
"""Can compare for equality""" | |
d1 = Multicast() | |
d2 = Multicast() | |
assert d1 == d2 | |
d1 += test1 | |
assert d1 != d2 | |
d2 += test1 | |
assert d1 == d2 | |
def test_does_not_hide_exceptions(delegate): | |
"""Exceptions raised by subscribed functions are not swallowed""" | |
method = Mock() | |
method.side_effect = ValueError | |
delegate += method | |
with pytest.raises(ValueError): | |
delegate() | |
def test_next_method_not_called_if_previous_throws(delegate): | |
"""Subsequent method is not called if the previous threw""" | |
first = Mock() | |
first.side_effect = ValueError | |
second = Mock() | |
delegate += first | |
delegate += second | |
with pytest.raises(ValueError): | |
delegate() | |
assert first.call_count == 1 | |
assert second.call_count == 0 | |
if __name__ == "__main__": | |
import sys | |
sys.exit(pytest.main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment