diff --git a/script.module.blinker/CHANGES b/script.module.blinker/CHANGES deleted file mode 100644 index a63c0ae22..000000000 --- a/script.module.blinker/CHANGES +++ /dev/null @@ -1,77 +0,0 @@ - -Blinker Changelog -================= - -Version 1.4 ------------ - -Released July 23, 2015 - -- Verified Python 3.4 support (no changes needed) -- Additional bookkeeping cleanup for non-ANY connections at disconnect - time. -- Added Signal._cleanup_bookeeping() to prune stale bookkeeping on - demand - -Version 1.3 ------------ - -Released July 3, 2013 - -- The global signal stash behind blinker.signal() is now backed by a - regular name-to-Signal dictionary. Previously, weak references were - held in the mapping and ephermal usage in code like - ``signal('foo').connect(...)`` could have surprising program behavior - depending on import order of modules. -- blinker.Namespace is now built on a regular dict. Use - blinker.WeakNamespace for the older, weak-referencing behavior. -- Signal.connect('text-sender') uses an alterate hashing strategy to - avoid sharp edges in text identity. - -Version 1.2 ------------ - -Released October 26, 2011 - -- Added Signal.receiver_connected and - Signal.receiver_disconnected per-Signal signals. -- Deprecated the global 'receiver_connected' signal. -- Verified Python 3.2 support (no changes needed!) - -Version 1.1 ------------ - -Released July 21, 2010 - -- Added ``@signal.connect_via(sender)`` decorator -- Added ``signal.connected_to`` shorthand name for the - ``temporarily_connected_to`` context manager. - - -Version 1.0 ------------ - -Released March 28, 2010 - -- Python 3.0 and 3.1 compatibility - - -Version 0.9 ------------ - -Released February 26, 2010 - -- Added ``Signal.temporarily_connected_to`` context manager -- Docs! Sphinx docs, project web site. - - -Version 0.8 ------------ - -Released February 14, 2010 - -- Initial release -- Extracted from flatland.util.signals -- Added Python 2.4 compatibility -- Added nearly functional Python 3.1 compatibility (everything except - connecting to instance methods seems to work.) diff --git a/script.module.blinker/LICENSE.txt b/script.module.blinker/LICENSE.txt new file mode 100644 index 000000000..79c9825ad --- /dev/null +++ b/script.module.blinker/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright 2010 Jason Kirtland + +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. diff --git a/script.module.blinker/README.md b/script.module.blinker/README.md deleted file mode 100644 index fcdccdc4a..000000000 --- a/script.module.blinker/README.md +++ /dev/null @@ -1,72 +0,0 @@ -[![Build Status](https://travis-ci.org/jek/blinker.svg?branch=master)](https://travis-ci.org/jek/blinker) - - -# Blinker - -Blinker provides a fast dispatching system that allows any number of -interested parties to subscribe to events, or "signals". - -Signal receivers can subscribe to specific senders or receive signals -sent by any sender. - - >>> from blinker import signal - >>> started = signal('round-started') - >>> def each(round): - ... print "Round %s!" % round - ... - >>> started.connect(each) - - >>> def round_two(round): - ... print "This is round two." - ... - >>> started.connect(round_two, sender=2) - - >>> for round in range(1, 4): - ... started.send(round) - ... - Round 1! - Round 2! - This is round two. - Round 3! - -See the [Blinker documentation](https://pythonhosted.org/blinker/) for more information. - -## Requirements - -Blinker requires Python 2.4 or higher, Python 3.0 or higher, or Jython 2.5 or higher. - -## Changelog Summary - -1.3 (July 3, 2013) - - - The global signal stash behind blinker.signal() is now backed by a - regular name-to-Signal dictionary. Previously, weak references were - held in the mapping and ephemeral usage in code like - ``signal('foo').connect(...)`` could have surprising program behavior - depending on import order of modules. - - blinker.Namespace is now built on a regular dict. Use - blinker.WeakNamespace for the older, weak-referencing behavior. - - Signal.connect('text-sender') uses an alternate hashing strategy to - avoid sharp edges in text identity. - -1.2 (October 26, 2011) - - - Added Signal.receiver_connected and Signal.receiver_disconnected - per-Signal signals. - - Deprecated the global 'receiver_connected' signal. - - Verified Python 3.2 support (no changes needed!) - -1.1 (July 21, 2010) - - - Added ``@signal.connect_via(sender)`` decorator - - Added ``signal.connected_to`` shorthand name for the - ``temporarily_connected_to`` context manager. - -1.0 (March 28, 2010) - - - Python 3.x compatibility - -0.9 (February 26, 2010) - - - Sphinx docs, project website - - Added ``with a_signal.temporarily_connected_to(receiver): ...`` support diff --git a/script.module.blinker/addon.xml b/script.module.blinker/addon.xml index 5cf49930f..7f688f217 100644 --- a/script.module.blinker/addon.xml +++ b/script.module.blinker/addon.xml @@ -1,18 +1,18 @@ - - - - - - - all - Blinker provides a fast dispatching system that allows any number of interested parties to subscribe to events, or signals - Blinker provides a fast dispatching system that allows any number of interested parties to subscribe to events, or signals - MIT - https://pythonhosted.org/blinker/ - https://pypi.org/project/blinker/ - - icon.png - - + + + + + + + Fast, simple object-to-object and broadcast signaling + Blinker provides a fast dispatching system that allows any number of interested parties to subscribe to events, or "signals". + MIT + all + https://blinker.readthedocs.io/ + https://github.com/pallets-eco/blinker/ + + resources/icon.png + + diff --git a/script.module.blinker/lib/blinker/__init__.py b/script.module.blinker/lib/blinker/__init__.py index 3ea239c66..d014caa0f 100644 --- a/script.module.blinker/lib/blinker/__init__.py +++ b/script.module.blinker/lib/blinker/__init__.py @@ -1,22 +1,19 @@ -from blinker.base import ( - ANY, - NamedSignal, - Namespace, - Signal, - WeakNamespace, - receiver_connected, - signal, -) +from blinker.base import ANY +from blinker.base import NamedSignal +from blinker.base import Namespace +from blinker.base import receiver_connected +from blinker.base import Signal +from blinker.base import signal +from blinker.base import WeakNamespace __all__ = [ - 'ANY', - 'NamedSignal', - 'Namespace', - 'Signal', - 'WeakNamespace', - 'receiver_connected', - 'signal', - ] + "ANY", + "NamedSignal", + "Namespace", + "Signal", + "WeakNamespace", + "receiver_connected", + "signal", +] - -__version__ = '1.4' +__version__ = "1.7.0" diff --git a/script.module.blinker/lib/blinker/_saferef.py b/script.module.blinker/lib/blinker/_saferef.py index 269e36246..dcb70c189 100644 --- a/script.module.blinker/lib/blinker/_saferef.py +++ b/script.module.blinker/lib/blinker/_saferef.py @@ -33,26 +33,14 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # """Refactored 'safe reference from dispatcher.py""" - import operator import sys import traceback import weakref -try: - callable -except NameError: - def callable(object): - return hasattr(object, '__call__') - - -if sys.version_info < (3,): - get_self = operator.attrgetter('im_self') - get_func = operator.attrgetter('im_func') -else: - get_self = operator.attrgetter('__self__') - get_func = operator.attrgetter('__func__') +get_self = operator.attrgetter("__self__") +get_func = operator.attrgetter("__func__") def safe_ref(target, on_delete=None): @@ -78,14 +66,15 @@ def safe_ref(target, on_delete=None): if im_self is not None: # Turn a bound method into a BoundMethodWeakref instance. # Keep track of these instances for lookup by disconnect(). - assert hasattr(target, 'im_func') or hasattr(target, '__func__'), ( - "safe_ref target %r has im_self, but no im_func, " - "don't know how to create reference" % target) + assert hasattr(target, "im_func") or hasattr(target, "__func__"), ( + f"safe_ref target {target!r} has im_self, but no im_func, " + "don't know how to create reference" + ) reference = BoundMethodWeakref(target=target, on_delete=on_delete) return reference -class BoundMethodWeakref(object): +class BoundMethodWeakref: """'Safe' and reusable weak references to instance methods. BoundMethodWeakref objects provide a mechanism for referencing a @@ -119,13 +108,13 @@ class BoundMethodWeakref(object): produce the same BoundMethodWeakref instance. """ - _all_instances = weakref.WeakValueDictionary() + _all_instances = weakref.WeakValueDictionary() # type: ignore[var-annotated] def __new__(cls, target, on_delete=None, *arguments, **named): """Create new instance or return current instance. Basically this method of construction allows us to - short-circuit creation of references to already- referenced + short-circuit creation of references to already-referenced instance methods. The key corresponding to the target is calculated, and if there is already an existing reference, that is returned, with its deletion_methods attribute updated. @@ -138,7 +127,7 @@ def __new__(cls, target, on_delete=None, *arguments, **named): current.deletion_methods.append(on_delete) return current else: - base = super(BoundMethodWeakref, cls).__new__(cls) + base = super().__new__(cls) cls._all_instances[key] = base base.__init__(target, on_delete, *arguments, **named) return base @@ -159,6 +148,7 @@ def __init__(self, target, on_delete=None): single argument, which will be passed a pointer to this object. """ + def remove(weak, self=self): """Set self.isDead to True when method or instance is destroyed.""" methods = self.deletion_methods[:] @@ -176,8 +166,11 @@ def remove(weak, self=self): traceback.print_exc() except AttributeError: e = sys.exc_info()[1] - print ('Exception during saferef %s ' - 'cleanup function %s: %s' % (self, function, e)) + print( + f"Exception during saferef {self} " + f"cleanup function {function}: {e}" + ) + self.deletion_methods = [on_delete] self.key = self.calculate_key(target) im_self = get_self(target) @@ -187,6 +180,7 @@ def remove(weak, self=self): self.self_name = str(im_self) self.func_name = str(im_func.__name__) + @classmethod def calculate_key(cls, target): """Calculate the reference key for this reference. @@ -194,27 +188,29 @@ def calculate_key(cls, target): object and the target function respectively. """ return (id(get_self(target)), id(get_func(target))) - calculate_key = classmethod(calculate_key) def __str__(self): """Give a friendly representation of the object.""" - return "%s(%s.%s)" % ( + return "{}({}.{})".format( self.__class__.__name__, self.self_name, self.func_name, - ) + ) __repr__ = __str__ + def __hash__(self): + return hash((self.self_name, self.key)) + def __nonzero__(self): """Whether we are still a valid reference.""" return self() is not None - def __cmp__(self, other): + def __eq__(self, other): """Compare with another reference.""" if not isinstance(other, self.__class__): - return cmp(self.__class__, type(other)) - return cmp(self.key, other.key) + return operator.eq(self.__class__, type(other)) + return operator.eq(self.key, other.key) def __call__(self): """Return a strong reference to the bound method. diff --git a/script.module.blinker/lib/blinker/_utilities.py b/script.module.blinker/lib/blinker/_utilities.py index 056270d7d..4b711c67d 100644 --- a/script.module.blinker/lib/blinker/_utilities.py +++ b/script.module.blinker/lib/blinker/_utilities.py @@ -1,74 +1,14 @@ +from __future__ import annotations + +import typing as t from weakref import ref from blinker._saferef import BoundMethodWeakref +IdentityType = t.Union[t.Tuple[int, int], str, int] -try: - callable -except NameError: - def callable(object): - return hasattr(object, '__call__') - - -try: - from collections import defaultdict -except: - class defaultdict(dict): - - def __init__(self, default_factory=None, *a, **kw): - if (default_factory is not None and - not hasattr(default_factory, '__call__')): - raise TypeError('first argument must be callable') - dict.__init__(self, *a, **kw) - self.default_factory = default_factory - - def __getitem__(self, key): - try: - return dict.__getitem__(self, key) - except KeyError: - return self.__missing__(key) - - def __missing__(self, key): - if self.default_factory is None: - raise KeyError(key) - self[key] = value = self.default_factory() - return value - - def __reduce__(self): - if self.default_factory is None: - args = tuple() - else: - args = self.default_factory, - return type(self), args, None, None, self.items() - - def copy(self): - return self.__copy__() - - def __copy__(self): - return type(self)(self.default_factory, self) - - def __deepcopy__(self, memo): - import copy - return type(self)(self.default_factory, - copy.deepcopy(self.items())) - - def __repr__(self): - return 'defaultdict(%s, %s)' % (self.default_factory, - dict.__repr__(self)) - - -try: - from contextlib import contextmanager -except ImportError: - def contextmanager(fn): - def oops(*args, **kw): - raise RuntimeError("Python 2.5 or above is required to use " - "context managers.") - oops.__name__ = fn.__name__ - return oops - -class _symbol(object): +class _symbol: def __init__(self, name): """Construct a new named symbol.""" self.__name__ = self.name = name @@ -78,10 +18,12 @@ def __reduce__(self): def __repr__(self): return self.name -_symbol.__name__ = 'symbol' -class symbol(object): +_symbol.__name__ = "symbol" + + +class symbol: """A constant symbol. >>> symbol('foo') is symbol('foo') @@ -95,7 +37,8 @@ class symbol(object): Repeated calls of symbol('name') will all return the same instance. """ - symbols = {} + + symbols = {} # type: ignore[var-annotated] def __new__(cls, name): try: @@ -104,18 +47,12 @@ def __new__(cls, name): return cls.symbols.setdefault(name, _symbol(name)) -try: - text = (str, unicode) -except NameError: - text = str - - -def hashable_identity(obj): - if hasattr(obj, '__func__'): - return (id(obj.__func__), id(obj.__self__)) - elif hasattr(obj, 'im_func'): - return (id(obj.im_func), id(obj.im_self)) - elif isinstance(obj, text): +def hashable_identity(obj: object) -> IdentityType: + if hasattr(obj, "__func__"): + return (id(obj.__func__), id(obj.__self__)) # type: ignore[attr-defined] + elif hasattr(obj, "im_func"): + return (id(obj.im_func), id(obj.im_self)) # type: ignore[attr-defined] + elif isinstance(obj, (int, str)): return obj else: return id(obj) @@ -127,8 +64,13 @@ def hashable_identity(obj): class annotatable_weakref(ref): """A weakref.ref that supports custom instance attributes.""" + receiver_id: t.Optional[IdentityType] + sender_id: t.Optional[IdentityType] + -def reference(object, callback=None, **annotations): +def reference( # type: ignore[no-untyped-def] + object, callback=None, **annotations +) -> annotatable_weakref: """Return an annotated weak ref.""" if callable(object): weak = callable_reference(object, callback) @@ -136,19 +78,19 @@ def reference(object, callback=None, **annotations): weak = annotatable_weakref(object, callback) for key, value in annotations.items(): setattr(weak, key, value) - return weak + return weak # type: ignore[no-any-return] def callable_reference(object, callback=None): """Return an annotated weak ref, supporting bound instance methods.""" - if hasattr(object, 'im_self') and object.im_self is not None: + if hasattr(object, "im_self") and object.im_self is not None: return BoundMethodWeakref(target=object, on_delete=callback) - elif hasattr(object, '__self__') and object.__self__ is not None: + elif hasattr(object, "__self__") and object.__self__ is not None: return BoundMethodWeakref(target=object, on_delete=callback) return annotatable_weakref(object, callback) -class lazy_property(object): +class lazy_property: """A @property that is only evaluated once.""" def __init__(self, deferred): diff --git a/script.module.blinker/lib/blinker/base.py b/script.module.blinker/lib/blinker/base.py index cc5880e69..b9d703586 100644 --- a/script.module.blinker/lib/blinker/base.py +++ b/script.module.blinker/lib/blinker/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8; fill-column: 76 -*- """Signals and events. A small implementation of signals, inspired by a snippet of Django signal @@ -8,34 +7,54 @@ The :func:`signal` function provides singleton behavior for named signals. """ +from __future__ import annotations + +import typing as t +from collections import defaultdict +from contextlib import contextmanager +from inspect import iscoroutinefunction from warnings import warn from weakref import WeakValueDictionary -from blinker._utilities import ( - WeakTypes, - contextmanager, - defaultdict, - hashable_identity, - lazy_property, - reference, - symbol, - ) +from blinker._utilities import annotatable_weakref +from blinker._utilities import hashable_identity +from blinker._utilities import IdentityType +from blinker._utilities import lazy_property +from blinker._utilities import reference +from blinker._utilities import symbol +from blinker._utilities import WeakTypes + +if t.TYPE_CHECKING: + import typing_extensions as te + + T_callable = t.TypeVar("T_callable", bound=t.Callable[..., t.Any]) + T = t.TypeVar("T") + P = te.ParamSpec("P") -ANY = symbol('ANY') + AsyncWrapperType = t.Callable[[t.Callable[P, t.Awaitable[T]]], t.Callable[P, T]] + SyncWrapperType = t.Callable[[t.Callable[P, T]], t.Callable[P, t.Awaitable[T]]] + +ANY = symbol("ANY") ANY.__doc__ = 'Token for "any sender".' ANY_ID = 0 +# NOTE: We need a reference to cast for use in weakref callbacks otherwise +# t.cast may have already been set to None during finalization. +cast = t.cast + -class Signal(object): +class Signal: """A notification emitter.""" #: An :obj:`ANY` convenience synonym, allows ``Signal.ANY`` #: without an additional import. ANY = ANY + set_class: type[set] = set + @lazy_property - def receiver_connected(self): + def receiver_connected(self) -> Signal: """Emitted after each :meth:`connect`. The signal sender is the signal instance, and the :meth:`connect` @@ -47,7 +66,7 @@ def receiver_connected(self): return Signal(doc="Emitted after a receiver connects.") @lazy_property - def receiver_disconnected(self): + def receiver_disconnected(self) -> Signal: """Emitted after :meth:`disconnect`. The sender is the signal instance, and the :meth:`disconnect` arguments @@ -70,7 +89,7 @@ def receiver_disconnected(self): """ return Signal(doc="Emitted after a receiver disconnects.") - def __init__(self, doc=None): + def __init__(self, doc: str | None = None) -> None: """ :param doc: optional. If provided, will be assigned to the signal's __doc__ attribute. @@ -84,16 +103,23 @@ def __init__(self, doc=None): #: internal :class:`Signal` implementation, however the boolean value #: of the mapping is useful as an extremely efficient check to see if #: any receivers are connected to the signal. - self.receivers = {} - self._by_receiver = defaultdict(set) - self._by_sender = defaultdict(set) - self._weak_senders = {} - - def connect(self, receiver, sender=ANY, weak=True): + self.receivers: dict[IdentityType, t.Callable | annotatable_weakref] = {} + self.is_muted = False + self._by_receiver: dict[IdentityType, set[IdentityType]] = defaultdict( + self.set_class + ) + self._by_sender: dict[IdentityType, set[IdentityType]] = defaultdict( + self.set_class + ) + self._weak_senders: dict[IdentityType, annotatable_weakref] = {} + + def connect( + self, receiver: T_callable, sender: t.Any = ANY, weak: bool = True + ) -> T_callable: """Connect *receiver* to signal events sent by *sender*. :param receiver: A callable. Will be invoked by :meth:`send` with - `sender=` as a single positional argument and any \*\*kwargs that + `sender=` as a single positional argument and any ``kwargs`` that were provided to a call to :meth:`send`. :param sender: Any object or :obj:`ANY`, defaults to ``ANY``. @@ -109,11 +135,14 @@ def connect(self, receiver, sender=ANY, weak=True): """ receiver_id = hashable_identity(receiver) + receiver_ref: T_callable | annotatable_weakref + if weak: receiver_ref = reference(receiver, self._cleanup_receiver) receiver_ref.receiver_id = receiver_id else: receiver_ref = receiver + sender_id: IdentityType if sender is ANY: sender_id = ANY_ID else: @@ -136,28 +165,27 @@ def connect(self, receiver, sender=ANY, weak=True): del sender_ref # broadcast this connection. if receivers raise, disconnect. - if ('receiver_connected' in self.__dict__ and - self.receiver_connected.receivers): + if "receiver_connected" in self.__dict__ and self.receiver_connected.receivers: try: - self.receiver_connected.send(self, - receiver=receiver, - sender=sender, - weak=weak) - except: + self.receiver_connected.send( + self, receiver=receiver, sender=sender, weak=weak + ) + except TypeError as e: self.disconnect(receiver, sender) - raise + raise e if receiver_connected.receivers and self is not receiver_connected: try: - receiver_connected.send(self, - receiver_arg=receiver, - sender_arg=sender, - weak_arg=weak) - except: + receiver_connected.send( + self, receiver_arg=receiver, sender_arg=sender, weak_arg=weak + ) + except TypeError as e: self.disconnect(receiver, sender) - raise + raise e return receiver - def connect_via(self, sender, weak=False): + def connect_via( + self, sender: t.Any, weak: bool = False + ) -> t.Callable[[T_callable], T_callable]: """Connect the decorated function as a receiver for *sender*. :param sender: Any object or :obj:`ANY`. The decorated function @@ -171,20 +199,24 @@ def connect_via(self, sender, weak=False): :meth:`connect`, this defaults to False. The decorated function will be invoked by :meth:`send` with - `sender=` as a single positional argument and any \*\*kwargs that + `sender=` as a single positional argument and any ``kwargs`` that were provided to the call to :meth:`send`. .. versionadded:: 1.1 """ - def decorator(fn): + + def decorator(fn: T_callable) -> T_callable: self.connect(fn, sender, weak) return fn + return decorator @contextmanager - def connected_to(self, receiver, sender=ANY): + def connected_to( + self, receiver: t.Callable, sender: t.Any = ANY + ) -> t.Generator[None, None, None]: """Execute a block with the signal temporarily connected to *receiver*. :param receiver: a receiver callable @@ -195,14 +227,7 @@ def connected_to(self, receiver, sender=ANY): the duration of the ``with`` block, and will be disconnected automatically when exiting the block: - .. testsetup:: - - from __future__ import with_statement - from blinker import Signal - on_ready = Signal() - receiver = lambda sender: None - - .. testcode:: + .. code-block:: python with on_ready.connected_to(receiver): # do stuff @@ -214,13 +239,25 @@ def connected_to(self, receiver, sender=ANY): self.connect(receiver, sender=sender, weak=False) try: yield None - except: - self.disconnect(receiver) - raise - else: + finally: self.disconnect(receiver) - def temporarily_connected_to(self, receiver, sender=ANY): + @contextmanager + def muted(self) -> t.Generator[None, None, None]: + """Context manager for temporarily disabling signal. + Useful for test purposes. + """ + self.is_muted = True + try: + yield None + except Exception as e: + raise e + finally: + self.is_muted = False + + def temporarily_connected_to( + self, receiver: t.Callable, sender: t.Any = ANY + ) -> t.ContextManager[None]: """An alias for :meth:`connected_to`. :param receiver: a receiver callable @@ -233,40 +270,100 @@ def temporarily_connected_to(self, receiver, sender=ANY): deprecated in 1.2 and will be removed in a subsequent version. """ - warn("temporarily_connected_to is deprecated; " - "use connected_to instead.", - DeprecationWarning) + warn( + "temporarily_connected_to is deprecated; use connected_to instead.", + DeprecationWarning, + ) return self.connected_to(receiver, sender) - def send(self, *sender, **kwargs): - """Emit this signal on behalf of *sender*, passing on \*\*kwargs. + def send( + self, + *sender: t.Any, + _async_wrapper: AsyncWrapperType | None = None, + **kwargs: t.Any, + ) -> list[tuple[t.Callable, t.Any]]: + """Emit this signal on behalf of *sender*, passing on ``kwargs``. Returns a list of 2-tuples, pairing receivers with their return value. The ordering of receiver notification is undefined. - :param \*sender: Any object or ``None``. If omitted, synonymous + :param sender: Any object or ``None``. If omitted, synonymous with ``None``. Only accepts one positional argument. + :param _async_wrapper: A callable that should wrap a coroutine + receiver and run it when called synchronously. - :param \*\*kwargs: Data to be sent to receivers. + :param kwargs: Data to be sent to receivers. + """ + if self.is_muted: + return [] + sender = self._extract_sender(sender) + results = [] + for receiver in self.receivers_for(sender): + if iscoroutinefunction(receiver): + if _async_wrapper is None: + raise RuntimeError("Cannot send to a coroutine function") + receiver = _async_wrapper(receiver) + result = receiver(sender, **kwargs) + results.append((receiver, result)) + return results + + async def send_async( + self, + *sender: t.Any, + _sync_wrapper: SyncWrapperType | None = None, + **kwargs: t.Any, + ) -> list[tuple[t.Callable, t.Any]]: + """Emit this signal on behalf of *sender*, passing on ``kwargs``. + + Returns a list of 2-tuples, pairing receivers with their return + value. The ordering of receiver notification is undefined. + + :param sender: Any object or ``None``. If omitted, synonymous + with ``None``. Only accepts one positional argument. + :param _sync_wrapper: A callable that should wrap a synchronous + receiver and run it when awaited. + + :param kwargs: Data to be sent to receivers. """ + if self.is_muted: + return [] + + sender = self._extract_sender(sender) + results = [] + for receiver in self.receivers_for(sender): + if not iscoroutinefunction(receiver): + if _sync_wrapper is None: + raise RuntimeError("Cannot send to a non-coroutine function") + receiver = _sync_wrapper(receiver) + result = await receiver(sender, **kwargs) + results.append((receiver, result)) + return results + + def _extract_sender(self, sender: t.Any) -> t.Any: + if not self.receivers: + # Ensure correct signature even on no-op sends, disable with -O + # for lowest possible cost. + if __debug__ and sender and len(sender) > 1: + raise TypeError( + f"send() accepts only one positional argument, {len(sender)} given" + ) + return [] + # Using '*sender' rather than 'sender=None' allows 'sender' to be # used as a keyword argument- i.e. it's an invisible name in the # function signature. if len(sender) == 0: sender = None elif len(sender) > 1: - raise TypeError('send() accepts only one positional argument, ' - '%s given' % len(sender)) + raise TypeError( + f"send() accepts only one positional argument, {len(sender)} given" + ) else: sender = sender[0] - if not self.receivers: - return [] - else: - return [(receiver, receiver(sender, **kwargs)) - for receiver in self.receivers_for(sender)] + return sender - def has_receivers_for(self, sender): + def has_receivers_for(self, sender: t.Any) -> bool: """True if there is probably a receiver for *sender*. Performs an optimistic check only. Does not guarantee that all @@ -282,14 +379,15 @@ def has_receivers_for(self, sender): return False return hashable_identity(sender) in self._by_sender - def receivers_for(self, sender): + def receivers_for( + self, sender: t.Any + ) -> t.Generator[t.Callable[[t.Any], t.Any], None, None]: """Iterate all live receivers listening for *sender*.""" # TODO: test receivers_for(ANY) if self.receivers: sender_id = hashable_identity(sender) if sender_id in self._by_sender: - ids = (self._by_sender[ANY_ID] | - self._by_sender[sender_id]) + ids = self._by_sender[ANY_ID] | self._by_sender[sender_id] else: ids = self._by_sender[ANY_ID].copy() for receiver_id in ids: @@ -302,9 +400,9 @@ def receivers_for(self, sender): self._disconnect(receiver_id, ANY_ID) continue receiver = strong - yield receiver + yield receiver # type: ignore[misc] - def disconnect(self, receiver, sender=ANY): + def disconnect(self, receiver: t.Callable, sender: t.Any = ANY) -> None: """Disconnect *receiver* from this signal's events. :param receiver: a previously :meth:`connected` callable @@ -313,6 +411,7 @@ def disconnect(self, receiver, sender=ANY): to disconnect from all senders. Defaults to ``ANY``. """ + sender_id: IdentityType if sender is ANY: sender_id = ANY_ID else: @@ -320,13 +419,13 @@ def disconnect(self, receiver, sender=ANY): receiver_id = hashable_identity(receiver) self._disconnect(receiver_id, sender_id) - if ('receiver_disconnected' in self.__dict__ and - self.receiver_disconnected.receivers): - self.receiver_disconnected.send(self, - receiver=receiver, - sender=sender) + if ( + "receiver_disconnected" in self.__dict__ + and self.receiver_disconnected.receivers + ): + self.receiver_disconnected.send(self, receiver=receiver, sender=sender) - def _disconnect(self, receiver_id, sender_id): + def _disconnect(self, receiver_id: IdentityType, sender_id: IdentityType) -> None: if sender_id == ANY_ID: if self._by_receiver.pop(receiver_id, False): for bucket in self._by_sender.values(): @@ -336,22 +435,22 @@ def _disconnect(self, receiver_id, sender_id): self._by_sender[sender_id].discard(receiver_id) self._by_receiver[receiver_id].discard(sender_id) - def _cleanup_receiver(self, receiver_ref): + def _cleanup_receiver(self, receiver_ref: annotatable_weakref) -> None: """Disconnect a receiver from all senders.""" - self._disconnect(receiver_ref.receiver_id, ANY_ID) + self._disconnect(cast(IdentityType, receiver_ref.receiver_id), ANY_ID) - def _cleanup_sender(self, sender_ref): + def _cleanup_sender(self, sender_ref: annotatable_weakref) -> None: """Disconnect all receivers from a sender.""" - sender_id = sender_ref.sender_id + sender_id = cast(IdentityType, sender_ref.sender_id) assert sender_id != ANY_ID self._weak_senders.pop(sender_id, None) for receiver_id in self._by_sender.pop(sender_id, ()): self._by_receiver[receiver_id].discard(sender_id) - def _cleanup_bookkeeping(self): - """Prune unused sender/receiver bookeeping. Not threadsafe. + def _cleanup_bookkeeping(self) -> None: + """Prune unused sender/receiver bookkeeping. Not threadsafe. - Connecting & disconnecting leave behind a small amount of bookeeping + Connecting & disconnecting leave behind a small amount of bookkeeping for the receiver and sender values. Typical workloads using Blinker, for example in most web apps, Flask, CLI scripts, etc., are not adversely affected by this bookkeeping. @@ -359,10 +458,10 @@ def _cleanup_bookkeeping(self): With a long-running Python process performing dynamic signal routing with high volume- e.g. connecting to function closures, "senders" are all unique object instances, and doing all of this over and over- you - may see memory usage will grow due to extraneous bookeeping. (An empty + may see memory usage will grow due to extraneous bookkeeping. (An empty set() for each stale sender/receiver pair.) - This method will prune that bookeeping away, with the caveat that such + This method will prune that bookkeeping away, with the caveat that such pruning is not threadsafe. The risk is that cleanup of a fully disconnected receiver/sender pair occurs while another thread is connecting that same pair. If you are in the highly dynamic, unique @@ -374,7 +473,7 @@ def _cleanup_bookkeeping(self): if not bucket: mapping.pop(_id, None) - def _clear_state(self): + def _clear_state(self) -> None: """Throw away all signal state. Useful for unit tests.""" self._weak_senders.clear() self.receivers.clear() @@ -382,7 +481,8 @@ def _clear_state(self): self._by_receiver.clear() -receiver_connected = Signal("""\ +receiver_connected = Signal( + """\ Sent by a :class:`Signal` after a receiver connects. :argument: the Signal that was connected to @@ -397,36 +497,38 @@ def _clear_state(self): :attr:`~Signal.receiver_disconnected` signals with a slightly simplified call signature. This global signal is planned to be removed in 1.6. -""") +""" +) class NamedSignal(Signal): """A named generic notification emitter.""" - def __init__(self, name, doc=None): + def __init__(self, name: str, doc: str | None = None) -> None: Signal.__init__(self, doc) #: The name of this signal. self.name = name - def __repr__(self): + def __repr__(self) -> str: base = Signal.__repr__(self) - return "%s; %r>" % (base[:-1], self.name) + return f"{base[:-1]}; {self.name!r}>" # noqa: E702 class Namespace(dict): """A mapping of signal names to signals.""" - def signal(self, name, doc=None): + def signal(self, name: str, doc: str | None = None) -> NamedSignal: """Return the :class:`NamedSignal` *name*, creating it if required. Repeated calls to this function will return the same signal object. """ try: - return self[name] + return self[name] # type: ignore[no-any-return] except KeyError: - return self.setdefault(name, NamedSignal(name, doc)) + result = self.setdefault(name, NamedSignal(name, doc)) + return result # type: ignore[no-any-return] class WeakNamespace(WeakValueDictionary): @@ -440,16 +542,17 @@ class WeakNamespace(WeakValueDictionary): """ - def signal(self, name, doc=None): + def signal(self, name: str, doc: str | None = None) -> NamedSignal: """Return the :class:`NamedSignal` *name*, creating it if required. Repeated calls to this function will return the same signal object. """ try: - return self[name] + return self[name] # type: ignore[no-any-return] except KeyError: - return self.setdefault(name, NamedSignal(name, doc)) + result = self.setdefault(name, NamedSignal(name, doc)) + return result # type: ignore[no-any-return] signal = Namespace().signal diff --git a/script.module.blinker/icon.png b/script.module.blinker/resources/icon.png similarity index 100% rename from script.module.blinker/icon.png rename to script.module.blinker/resources/icon.png