Welcome, guest | Sign In | My Account | Store | Cart

This module, dispatcher.py, provides global signal dispatching services suitable for a wide variety of purposes, similar to Model-View-Controller or Model-View-Presenter patterns. This particular implementation allows a looser coupling than most Observer patterns. It also does transparent cleanup through the use of weak references and weak reference callbacks. This version defaults to using weak references, but provides an option to not use weak references for those cases where weak references are problematic (lambdas and such).

Python, 230 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Provides global signal dispatching services."""

__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id: dispatcher.py,v 1.11 2001/11/16 15:22:54 pobrien Exp $"
__version__ = "$Revision: 1.11 $"[11:-2]

import exceptions
import types
import weakref


class DispatcherError(exceptions.Exception):
    def __init__(self, args=None):
        self.args = args


class _Any:
    pass

Any = _Any()

connections = {}
senders = {}


def connect(receiver, signal=Any, sender=Any, weak=1):
    """Connect receiver to sender for signal.
    
    If sender is Any, receiver will receive signal from any sender.
    If signal is Any, receiver will receive any signal from sender.
    If sender is None, receiver will receive signal from anonymous.
    If signal is Any and sender is None, receiver will receive any 
        signal from anonymous.
    If signal is Any and sender is Any, receiver will receive any 
        signal from any sender.
    If weak is true, weak references will be used."""
    if signal is None:
        raise DispatcherError, 'signal cannot be None'
    if signal is not Any:
        signal = str(signal)
    if weak: receiver = safeRef(receiver)
    senderkey = id(sender)
    signals = {}
    if connections.has_key(senderkey):
        signals = connections[senderkey]
    else:
        connections[senderkey] = signals
        # Keep track of senders for cleanup.
        if sender not in (None, Any):
            def remove(object, senderkey=senderkey):
                _removeSender(senderkey=senderkey)
            # Skip objects that can not be weakly referenced, which means
            # they won't be automatically cleaned up, but that's too bad.
            try:
                weakSender = weakref.ref(sender, remove)
                senders[senderkey] = weakSender
            except:
                pass
    receivers = []
    if signals.has_key(signal):
        receivers = signals[signal]
    else:
        signals[signal] = receivers
    try: receivers.remove(receiver)
    except ValueError: pass
    receivers.append(receiver)

def disconnect(receiver, signal=Any, sender=Any, weak=1):
    """Disconnect receiver from sender for signal.
    
    Disconnecting is not required. The use of disconnect is the same as for
    connect, only in reverse. Think of it as undoing a previous connection."""
    if signal is None:
        raise DispatcherError, 'signal cannot be None'
    if signal is not Any:
        signal = str(signal)
    if weak: receiver = safeRef(receiver)
    senderkey = id(sender)
    try:
        receivers = connections[senderkey][signal]
    except KeyError:
        raise DispatcherError, \
              'No receivers for signal %s from sender %s' % \
              (repr(signal), sender)
    try:
        receivers.remove(receiver)
    except ValueError:
        raise DispatcherError, \
              'No connection to receiver %s for signal %s from sender %s' % \
              (receiver, repr(signal), sender)
    _cleanupConnections(senderkey, signal)

def send(signal, sender=None, **kwds):
    """Send signal from sender to all connected receivers.
    
    Return a list of tuple pairs [(receiver, response), ... ].
    If sender is None, signal is sent anonymously."""
    signal = str(signal)
    senderkey = id(sender)
    anykey = id(Any)
    # Get receivers that receive *this* signal from *this* sender.
    receivers = []
    try: receivers.extend(connections[senderkey][signal])
    except KeyError: pass
    # Add receivers that receive *any* signal from *this* sender.
    anyreceivers = []
    try: anyreceivers = connections[senderkey][Any]
    except KeyError: pass
    for receiver in anyreceivers:
        if receivers.count(receiver) == 0:
            receivers.append(receiver)
    # Add receivers that receive *this* signal from *any* sender.
    anyreceivers = []
    try: anyreceivers = connections[anykey][signal]
    except KeyError: pass
    for receiver in anyreceivers:
        if receivers.count(receiver) == 0:
            receivers.append(receiver)
    # Add receivers that receive *any* signal from *any* sender.
    anyreceivers = []
    try: anyreceivers = connections[anykey][Any]
    except KeyError: pass
    for receiver in anyreceivers:
        if receivers.count(receiver) == 0:
            receivers.append(receiver)
    # Call each receiver with whatever arguments it can accept.
    # Return a list of tuple pairs [(receiver, response), ... ].
    responses = []
    for receiver in receivers:
        if type(receiver) is weakref.ReferenceType \
        or isinstance(receiver, BoundMethodWeakref):
            # Dereference the weak reference.
            receiver = receiver()
            if receiver is None:
                # This receiver is dead, so skip it.
                continue
        response = _call(receiver, signal=signal, sender=sender, **kwds)
        responses += [(receiver, response)]
    return responses

def _call(receiver, **kwds):
    """Call receiver with only arguments it can accept."""
    if type(receiver) is types.InstanceType:
        # receiver is a class instance; assume it is callable.
        # Reassign receiver to the actual method that will be called.
        receiver = receiver.__call__
    if hasattr(receiver, 'im_func'):
        # receiver is a method. Drop the first argument, usually 'self'.
        fc = receiver.im_func.func_code
        acceptable = fc.co_varnames[1:fc.co_argcount]
    elif hasattr(receiver, 'func_code'):
        # receiver is a function.
        fc = receiver.func_code
        acceptable = fc.co_varnames[0:fc.co_argcount]
    if not (fc.co_flags & 8):
        # fc does not have a **kwds type parameter, therefore 
        # remove unacceptable arguments.
        for arg in kwds.keys():
            if arg not in acceptable:
                del kwds[arg]
    return receiver(**kwds)

_boundMethods = weakref.WeakKeyDictionary()

def safeRef(object):
    """Return a *safe* weak reference to a callable object."""
    if hasattr(object, 'im_self'):
        if object.im_self is not None:
            # Turn a bound method into a BoundMethodWeakref instance.
            # Keep track of these instances for lookup by disconnect().
            selfkey = object.im_self
            funckey = object.im_func
            if not _boundMethods.has_key(selfkey):
                _boundMethods[selfkey] = weakref.WeakKeyDictionary()
            if not _boundMethods[selfkey].has_key(funckey):
                _boundMethods[selfkey][funckey] = \
                BoundMethodWeakref(boundMethod=object)
            return _boundMethods[selfkey][funckey]
    return weakref.ref(object, _removeReceiver)

class BoundMethodWeakref:
    """BoundMethodWeakref class."""
    def __init__(self, boundMethod):
        """Return a weak-reference-like instance for a bound method."""
        self.isDead = 0
        def remove(object, self=self):
            """Set self.isDead to true when method or instance is destroyed."""
            self.isDead = 1
            _removeReceiver(receiver=self)
        self.weakSelf = weakref.ref(boundMethod.im_self, remove)
        self.weakFunc = weakref.ref(boundMethod.im_func, remove)
    def __repr__(self):
        """Return the closest representation."""
        return repr(self.weakFunc)
    def __call__(self):
        """Return a strong reference to the bound method."""
        if self.isDead:
            return None
        else:
            object = self.weakSelf()
            method = self.weakFunc().__name__
            return getattr(object, method)

def _removeReceiver(receiver):
    """Remove receiver from connections."""
    for senderkey in connections.keys():
        for signal in connections[senderkey].keys():
            receivers = connections[senderkey][signal]
            try: receivers.remove(receiver)
            except: pass
            _cleanupConnections(senderkey, signal)
            
def _cleanupConnections(senderkey, signal):
    """Delete any empty signals for senderkey. Delete senderkey if empty."""
    receivers = connections[senderkey][signal]
    if not receivers:
        # No more connected receivers. Therefore, remove the signal.
        signals = connections[senderkey]
        del signals[signal]
        if not signals:
            # No more signal connections. Therefore, remove the sender.
            _removeSender(senderkey)
            
def _removeSender(senderkey):
    """Remove senderkey from connections."""
    del connections[senderkey]
    # Senderkey will only be in senders dictionary if sender 
    # could be weakly referenced.
    try: del senders[senderkey]
    except: pass

5 comments

Patrick O'Brien (author) 22 years, 5 months ago  # | flag

Credit where credit is due... I'd like to recognize and thank the following people who either helped with the code or gave inspiration: Joseph A. Knapka has his own variation on this theme, from which I learned a lot; Bernhard Herzog's Sketch project has a message passing system from which I drew inspiration; Magnus Lie Hetland provided his share of ideas, as did Paolo Invernizzi and others on the anygui project. Of course, any flaws in the code are strictly my own doing.

Drew Perttula 20 years, 3 months ago  # | flag

now a separate sourceforge project. FYI, this system is now maintained at pydispatcher.sourceforge.net with additional features and bugfixes. (Not by me)

Patrick O'Brien (author) 18 years, 4 months ago  # | flag

Now there is Louie, too. Another variant called Louie is now available at http://louie.berlios.de/.

David Greaves 14 years, 8 months ago  # | flag

I just wanted to say how insanely hard it is to find any documentation for sample usage of this supposedly 'popular' module or any derivatives.

8 years after being written the author and community have done a stunningly underwhelming job - and that's a real shame.

Dan Gayle 9 years, 2 months ago  # | flag

@David Greaves

Django's django.dispatch.dispatcher is PyDispatcher, slightly modified to better fit Django's needs. You can find tons of sample usage and documentation in that context.