-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddCallback.py
308 lines (257 loc) · 11.7 KB
/
AddCallback.py
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""Mixing class(es) for adding callback capabilities.
History:
2003-07-09 ROwen
2003-08-04 ROwen Added TkButtonMixin.
2003-10-29 ROwen Modified TkVarMixin to store the tk var in self._var.
2004-03-04 ROwen Modified addCallback to first to try to delete the function.
2004-05-21 ROwen Modified to continue with other callbacks if one callback fails
(after printing a message and a traceback).
2004-06-15 ROwen Bug fix: used sys and traceback for error reporting but did not import them.
2004-07-21 ROwen Modified _doCallbacks to pass *args and **kargs to the callback functions;
this makes BaseMixin easier to subclass.
Overhauled removeCallback:
- added doRaise argument
- returns True on success, False or exception on failure
- fail if callbacks are being executed
2004-09-14 ROwen Bug fix: TkButtonMixin.__init__ did not obey callNow.
Bug fix: removeCallback spelled a class attribute wrong.
2004-09-23 ROwen Added defCallNow argument.
2004-09-28 ROwen Modified to allow removing callbacks while executing.
Removed use of attribute _inCallbacks.
2004-10-07 ROwen Modified addCallback to not add a function
if it is already in the callback list.
2005-06-08 ROwen Changed BaseMixin to a new style class.
2005-06-13 ROwen Added method _removeAllCallbacks().
2010-05-26 ROwen Added method _disableCallbacksContext.
Added boolean member variable _enableCallbacks.
Added a guard to prevent infinite recursion while running callbacks.
2010-06-07 ROwen Added a few commented-out print statements.
2010-08-26 ROwen Tweaked commented-out print statements.
2011-02-18 ROwen Added callbacksEnabled method.
2011-06-16 ROwen Ditched obsolete "except (SystemExit, KeyboardInterrupt): raise" code.
2013-09-24 ROwen Added safeCall.
2014-04-17 ROwen Added safeCall2, which gives more feedback than safeCall.
2015-09-24 ROwen Replace "== None" with "is None" to modernize the code.
2015-11-03 ROwen Replace "!= None" with "is not None" to modernize the code.
"""
__all__ = ["safeCall", "safeCall2", "BaseMixin", "TkButtonMixin", "TkVarMixin"]
import sys
import traceback
def safeCall(func, *args, **kwargs):
"""Call a function; print a traceback and continue if it fails
Inputs:
- func: function to call
- *args, **kwargs: arguments for the function
@warning: be sure to provide the function and its arguments as separate arguments,
result = safeCall(myFunc, arg1, arg2, kwarg1=foo, kwarg2=bar) # correct
a common mistake is to call the function when passing it to safeCall:
restult = safeCall(myFunc(...)) # wrong; safeCall tries to call the result of calling myFuc
"""
try:
return func(*args, **kwargs)
except Exception as e:
sys.stderr.write("%s(*%s, **%s) failed: %s\n" % (func, args, kwargs, e,))
traceback.print_exc(file=sys.stderr)
def safeCall2(descr, func, *args, **kwargs):
"""Call a function; print a traceback and continue if it fails
This variant of safeCall gives more information on failure.
Inputs:
- descr: description of why this is being called, for use in error messages
- func: function to call
- *args, **kwargs: arguments for the function
@warning: be sure to provide the function and its arguments as separate arguments,
result = safeCall2(myFunc, arg1, arg2, kwarg1=foo, kwarg2=bar) # correct
a common mistake is to call the function when passing it to safeCall2:
restult = safeCall2(myFunc(...)) # wrong; safeCall2 tries to call the result of calling myFuc
"""
try:
return func(*args, **kwargs)
except Exception as e:
sys.stderr.write("%s %s(*%s, **%s) failed: %s\n" % (descr, func, args, kwargs, e,))
traceback.print_exc(file=sys.stderr)
class _DisableCallbacksContext(object):
"""Context object to temporarily disable callbacks
After the with statement finishes, _enableCallbacks is returned to its initial state
"""
def __init__(self, callbackObj):
self.callbackObj = callbackObj
def __enter__(self):
self.initialCallbacksEnabled = self.callbackObj._enableCallbacks
self.callbackObj._enableCallbacks = False
# print "%s.__enter__; _enableCallbacks %s -> %s" % (self.callbackObj, self.initialCallbacksEnabled, self.callbackObj._enableCallbacks)
def __exit__(self, type, value, traceback):
# temp = self.callbackObj._enableCallbacks
self.callbackObj._enableCallbacks = self.initialCallbacksEnabled
# print "%s.__exit__; _enableCallbacks %s -> %s" % (self.callbackObj, temp, self.callbackObj._enableCallbacks)
class BaseMixin(object):
"""Add support for callback functions.
Inputs:
- callFunc see addCallback
- callNow see addCallback
- defCallNow default for callNow
Subclasses may wish to override _doCallbacks
Adds the following attributes:
_enableCallbacks: a boolean: normally True; set False to disable all callbacks
warning: is always False while callbacks are running
"""
def __init__(self,
callFunc = None,
callNow = None,
defCallNow = False,
):
self._defCallNow = bool(defCallNow)
self._callbacks = []
self._enableCallbacks = True
if callFunc is not None:
self.addCallback(callFunc, callNow)
def addCallback(self,
callFunc,
callNow = None,
):
"""Add a callback function to the list.
If the callback is already present, it is not re-added.
Inputs:
- callFunc a callback function.
It will receive one argument: self (the object doing the calling);
If None, no callback function is added.
- callNow if True, calls the function immediately
if omitted or None, the default is used
Raises ValueError if callFunc is not callable
"""
if callFunc is None:
return
#if not callable(callFunc):
if not hasattr(callFunc, '__call__'):
raise ValueError("callFunc %r is not callable" % (callFunc,))
# add new function
if callFunc not in self._callbacks:
self._callbacks.append(callFunc)
# if wanted, call the new function
if callNow or (callNow is None and self._defCallNow):
# use _doCallbacks in case it was overridden,
# but only call this one function
currCallbacks = self._callbacks
self._callbacks = (callFunc,)
self._doCallbacks()
self._callbacks = currCallbacks
def callbacksEnabled(self):
"""Are callbacks enabled?
False if executing callbacks (and possibly other reasons if using _disableCallbacksContext).
"""
return self._enableCallbacks
def removeCallback(self, callFunc, doRaise=True):
"""Delete the callback function.
Inputs:
- callFunc callback function to remove
- doRaise raise exception if unsuccessful? True by default.
Return:
- True if successful, raise error or return False otherwise.
If doRaise true:
- Raises ValueError if callback not found
- Raises RuntimeError if executing callbacks when called
Otherwise returns False in either case.
"""
try:
self._callbacks.remove(callFunc)
return True
except ValueError:
if doRaise:
raise ValueError("Callback %r not found" % callFunc)
return False
def _basicDoCallbacks(self, *args, **kwargs):
"""Execute the callbacks, passing *args and **kwargs to the callback functions.
If callbacks are already being executed then this function is a no-op
"""
#print("basic do call backs " + str(args) + str(kwargs))
# print "%s._basicDoCallbacks; _enableCallbacks=%s" % (self, self._enableCallbacks)
if not self._enableCallbacks:
return
try:
self._enableCallbacks = False
for func in self._callbacks[:]:
safeCall2(str(self), func, *args, **kwargs)
finally:
self._enableCallbacks = True
def _disableCallbacksContext(self):
"""Return a context (for a "with" statement) that temporarily disables callbacks.
After the with statement _enableCallbacks is returned to its initial state.
To use:
with self._disableCallbacksContext():
# perform operations with callbacks disabled
"""
return _DisableCallbacksContext(self)
def _doCallbacks(self):
"""Execute the callback functions, passing self as the argument.
Subclass this to return something else.
"""
self._basicDoCallbacks(self)
def _removeAllCallbacks(self):
"""Remove all callbacks.
If you know there will be no more callbacks
then call this to avoid memory leaks.
"""
self._callbacks = []
class TkButtonMixin(BaseMixin):
"""Add support for callback functions triggered by a Tk button's command.
Use instead of TkVarMixin for Tk buttons so the callback is fired
at the right time (when the button's "command" is executed).
Inputs:
- callFunc a callback function.
It will receive one argument: self (the object doing the calling);
If None, no callback function is added.
- callNow if True, calls callFunc (but not command) immediately
- command: conventional Tk button callback taking no args;
this allows a conventional Tk button interface; as such,
command is not called immediately even if callNow is true
- all remaining keyword arguments are ignored; they are accepted so one can
easily handle subclasses of Tk buttons by accepting arbitrary keywords
that might include command
"""
def __init__(self,
callFunc = None,
callNow = None,
command = None,
defCallNow = False,
**kwargs):
self["command"] = self._doCallbacks
BaseMixin.__init__(self,
callFunc = callFunc,
callNow = callNow,
defCallNow = defCallNow,
)
if command is not None:
#if not callable(command):
if not hasattr(command, '__call__'):
raise ValueError("command %r is not callable" % (command,))
def doCommand(wdg):
return command()
self.addCallback(doCommand)
class TkVarMixin(BaseMixin):
"""Add support for callback functions triggered by a tk variable.
The functions are called whenever the specified tk variable changes.
The user may also call _doCallback when desired.
Inputs:
- tkVar: the tk variable to watch
- callFunc a callback function.
It will receive one argument: self (the object doing the calling);
If None, no callback function is added.
- callNow if True, calls the function immediately
Adds the following attribute:
_var: the tk variable
"""
def __init__(self,
tkVar,
callFunc = None,
callNow = False,
defCallNow = False,
):
self._var = tkVar
BaseMixin.__init__(self,
callFunc = callFunc,
callNow = callNow,
defCallNow = defCallNow,
)
def doTraceVar(*args):
"""ignore trace_variable callback arguments"""
self._doCallbacks()
tkVar.trace_variable("w", doTraceVar)