@@ -68,7 +68,8 @@ def __init__(self, *args):
68
68
69
69
def subscribe (self , subscriber , message_class ,
70
70
handler = None ,
71
- filter = lambda x : True ):
71
+ filter = lambda x : True ,
72
+ priority = 10 ):
72
73
"""Subscribe an object to a type of message class.
73
74
74
75
:param subscriber: The subscribing object
@@ -88,6 +89,11 @@ def subscribe(self, subscriber, message_class,
88
89
are only passed to the subscriber if filter(message) == True.
89
90
The default is to always pass messages.
90
91
92
+ :param priority:
93
+ An optional integer to set the priority of the handler. Handlers
94
+ are sorted such that higher priority handlers get called first
95
+ when broadcasting a message.
96
+
91
97
92
98
Raises:
93
99
InvalidMessage: If the input class isn't a
@@ -113,7 +119,7 @@ def subscribe(self, subscriber, message_class,
113
119
if subscriber not in self ._subscriptions :
114
120
self ._subscriptions [subscriber ] = HubCallbackContainer ()
115
121
116
- self ._subscriptions [subscriber ][message_class ] = handler , filter
122
+ self ._subscriptions [subscriber ][message_class ] = handler , filter , priority
117
123
118
124
def is_subscribed (self , subscriber , message ):
119
125
"""
@@ -160,9 +166,10 @@ def _find_handlers(self, message):
160
166
"""Yields all (subscriber, handler) pairs that should receive a message
161
167
"""
162
168
# self._subscriptions:
163
- # subscriber => { message type => (filter, handler)}
169
+ # subscriber => { message type => (filter, handler, priority )}
164
170
165
171
# loop over subscribed objects
172
+ prioritized_handlers = []
166
173
for subscriber , subscriptions in list (self ._subscriptions .items ()):
167
174
168
175
# subscriptions to message or its superclasses
@@ -175,9 +182,12 @@ def _find_handlers(self, message):
175
182
# narrow to the most-specific message
176
183
candidate = max (messages , key = _mro_count )
177
184
178
- handler , test = subscriptions [candidate ]
185
+ handler , test , priority = subscriptions [candidate ]
179
186
if test (message ):
180
- yield subscriber , handler
187
+ prioritized_handlers .append ((subscriber , handler , priority ))
188
+
189
+ for subscriber , handler , _ in sorted (prioritized_handlers , key = lambda x : x [2 ], reverse = True ):
190
+ yield subscriber , handler
181
191
182
192
@contextmanager
183
193
def ignore_callbacks (self , ignore_type ):
0 commit comments