U RѰU?@sdZddlmZddlmZddlmZmZmZm Z m Z m Z m Z e dZ de _dZGdddeZed ZGd d d eZGd d d eZGdddeZejZdS)a+Signals and events. A small implementation of signals, inspired by a snippet of Django signal API client code seen in a blog post. Signals are first-class objects and each manages its own receivers and message emission. The :func:`signal` function provides singleton behavior for named signals. )warn)WeakValueDictionary) WeakTypescontextmanager defaultdicthashable_identity lazy_property referencesymbolANYzToken for "any sender".c@seZdZdZeZeddZeddZd%ddZed fd d Z d&d dZ e efddZ efddZ ddZddZddZefddZddZddZdd Zd!d"Zd#d$ZdS)'SignalzA notification emitter.cCs tddS)zEmitted after each :meth:`connect`. The signal sender is the signal instance, and the :meth:`connect` arguments are passed through: *receiver*, *sender*, and *weak*. .. versionadded:: 1.2 z"Emitted after a receiver connects.docr selfr/base.pyreceiver_connected%s zSignal.receiver_connectedcCs tddS)a Emitted after :meth:`disconnect`. The sender is the signal instance, and the :meth:`disconnect` arguments are passed through: *receiver* and *sender*. Note, this signal is emitted **only** when :meth:`disconnect` is called explicitly. The disconnect signal can not be emitted by an automatic disconnect (due to a weakly referenced receiver or sender going out of scope), as the receiver and/or sender instances are no longer available for use at the time this signal would be emitted. An alternative approach is available by subscribing to :attr:`receiver_connected` and setting up a custom weakref cleanup callback on weak receivers and senders. .. versionadded:: 1.2 z%Emitted after a receiver disconnects.r rrrrrreceiver_disconnected1szSignal.receiver_disconnectedNcCs.|r ||_i|_tt|_tt|_i|_dS)zt :param doc: optional. If provided, will be assigned to the signal's __doc__ attribute. N)__doc__ receiversrset _by_receiver _by_sender _weak_senders)rrrrr__init__Is   zSignal.__init__TcCsFt|}|r t||j}||_n|}|tkr2t}nt|}|j|||j| ||j | |~|tk r||j krzt||j }||_ Wntk rYnX|j ||~d|jkr|jjrz|jj||||dWn|||YnXtjrB|tk rBztj||||dWn|||YnX|S)aaConnect *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 were provided to a call to :meth:`send`. :param sender: Any object or :obj:`ANY`, defaults to ``ANY``. Restricts notifications delivered to *receiver* to only those :meth:`send` emissions sent by *sender*. If ``ANY``, the receiver will always be notified. A *receiver* may be connected to multiple *sender* values on the same Signal through multiple calls to :meth:`connect`. :param weak: If true, the Signal will hold a weakref to *receiver* and automatically disconnect when *receiver* goes out of scope or is garbage collected. Defaults to True. r)receiversenderweak)Z receiver_argZ sender_argZweak_arg)rr _cleanup_receiver receiver_idr ANY_IDr setdefaultraddrr_cleanup_sender sender_id TypeError__dict__rsend disconnect)rrrrr! receiver_refr& sender_refrrrconnect\sV        zSignal.connectFcsfdd}|S)aKConnect the decorated function as a receiver for *sender*. :param sender: Any object or :obj:`ANY`. The decorated function will only receive :meth:`send` emissions sent by *sender*. If ``ANY``, the receiver will always be notified. A function may be decorated multiple times with differing *sender* values. :param weak: If true, the Signal will hold a weakref to the decorated function and automatically disconnect when *receiver* goes out of scope or is garbage collected. Unlike :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 were provided to the call to :meth:`send`. .. versionadded:: 1.1 cs||SN)r-)fnrrrrr decoratorsz%Signal.connect_via..decoratorr)rrrr1rr0r connect_viaszSignal.connect_viaccsB|j||ddz dVWn||Yn X||dS)aExecute a block with the signal temporarily connected to *receiver*. :param receiver: a receiver callable :param sender: optional, a sender to filter on This is a context manager for use in the ``with`` statement. It 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: .. testsetup:: from __future__ import with_statement from blinker import Signal on_ready = Signal() receiver = lambda sender: None .. testcode:: with on_ready.connected_to(receiver): # do stuff on_ready.send(123) .. versionadded:: 1.1 F)rrN)r-r*rrrrrr connected_tos  zSignal.connected_tocCstdt|||S)agAn alias for :meth:`connected_to`. :param receiver: a receiver callable :param sender: optional, a sender to filter on .. versionadded:: 0.9 .. versionchanged:: 1.1 Renamed to :meth:`connected_to`. ``temporarily_connected_to`` was deprecated in 1.2 and will be removed in a subsequent version. zAtemporarily_connected_to is deprecated; use connected_to instead.)rDeprecationWarningr4r3rrrtemporarily_connected_tos zSignal.temporarily_connected_tocs`tdkrdn&tdkr0tdtnd|jsBgSfdd|DSdS)aEmit 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 \*\*kwargs: Data to be sent to receivers. rNz5send() accepts only one positional argument, %s givencsg|]}||ffqSrr).0rkwargsrrr szSignal.send..)lenr'r receivers_for)rrr:rr9rr)s   z Signal.sendcCs2|js dS|jtrdS|tkr$dSt||jkS)zTrue if there is probably a receiver for *sender*. Performs an optimistic check only. Does not guarantee that all weakly referenced receivers are still alive. See :meth:`receivers_for` for a stronger search. FT)rrr"r r)rrrrrhas_receivers_for s zSignal.has_receivers_forccs|jrt|}||jkr.|jt|j|B}n|jt}|D]J}|j|}|dkrZq@t|tr|}|dkr||tq@|}|Vq@dS)z2Iterate all live receivers listening for *sender*.N) rrrr"copyget isinstancer _disconnect)rrr&Zidsr!rZstrongrrrr=s$    zSignal.receivers_forcCsR|tkrt}nt|}t|}|||d|jkrN|jjrN|jj|||ddS)aDisconnect *receiver* from this signal's events. :param receiver: a previously :meth:`connected` callable :param sender: a specific sender to disconnect from, or :obj:`ANY` to disconnect from all senders. Defaults to ``ANY``. r)rrN)r r"rrBr(rrr))rrrr&r!rrrr*3s   zSignal.disconnectcCsd|tkr@|j|dr0|jD]}||q |j|dn |j|||j||dS)NF)r"rpoprvaluesdiscardr)rr!r&bucketrrrrBIs zSignal._disconnectcCs||jtdS)z'Disconnect a receiver from all senders.N)rBr!r")rr+rrrr SszSignal._cleanup_receivercCs<|j}|j|d|j|dD]}|j||q"dS)z'Disconnect all receivers from a sender.Nr)r&rrCrrrE)rr,r&r!rrrr%WszSignal._cleanup_sendercCs<|j|jfD]*}t|D]\}}|s||dqq dS)anPrune unused sender/receiver bookeeping. Not threadsafe. Connecting & disconnecting leave behind a small amount of bookeeping 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. 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 set() for each stale sender/receiver pair.) This method will prune that bookeeping 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 receiver/sender situation that has lead you to this method, that failure mode is perhaps not a big deal for you. N)rrlistitemsrC)rmappingZ_idrFrrr_cleanup_bookkeeping_szSignal._cleanup_bookkeepingcCs,|j|j|j|jdS)z4Throw away all signal state. Useful for unit tests.N)rclearrrrrrrr _clear_stateys   zSignal._clear_state)N)F)__name__ __module__ __qualname__rr rrrrr-r2rr4r6r)r>r=r*rBr r%rJrLrrrrr s*   D $   r a Sent by a :class:`Signal` after a receiver connects. :argument: the Signal that was connected to :keyword receiver_arg: the connected receiver :keyword sender_arg: the sender to connect to :keyword weak_arg: true if the connection to receiver_arg is a weak reference .. deprecated:: 1.2 As of 1.2, individual signals have their own private :attr:`~Signal.receiver_connected` and :attr:`~Signal.receiver_disconnected` signals with a slightly simplified call signature. This global signal is planned to be removed in 1.6. c@s"eZdZdZdddZddZdS) NamedSignalz%A named generic notification emitter.NcCst||||_dSr.)r rnamerrQrrrrrs zNamedSignal.__init__cCs t|}d|dd|jfS)Nz%s; %r>)r __repr__rQ)rbaserrrrTs zNamedSignal.__repr__)N)rMrNrOrrrTrrrrrPs rPc@seZdZdZdddZdS) Namespacez%A mapping of signal names to signals.Nc Cs6z ||WStk r0||t||YSXdSzReturn the :class:`NamedSignal` *name*, creating it if required. Repeated calls to this function will return the same signal object. NKeyErrorr#rPrRrrrsignals zNamespace.signal)NrMrNrOrrZrrrrrVsrVc@seZdZdZdddZdS) WeakNamespacea-A weak mapping of signal names to signals. Automatically cleans up unused Signals when the last reference goes out of scope. This namespace implementation exists for a measure of legacy compatibility with Blinker <= 1.2, and may be dropped in the future. .. versionadded:: 1.3 Nc Cs6z ||WStk r0||t||YSXdSrWrXrRrrrrZs zWeakNamespace.signal)Nr[rrrrr\s r\N)rwarningsrweakrefrZblinker._utilitiesrrrrrr r r r"objectr rrPdictrVr\rZrrrrs  $ e