Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9e9b82a

Browse files
committed
ENH: add optional exception_handler to CallbackRegisty
1 parent 225a4a0 commit 9e9b82a

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

lib/matplotlib/cbook/__init__.py

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -250,8 +250,7 @@ def __hash__(self):
250250

251251

252252
class CallbackRegistry(object):
253-
"""
254-
Handle registering and disconnecting for a set of signals and
253+
"""Handle registering and disconnecting for a set of signals and
255254
callbacks:
256255
257256
>>> def oneat(x):
@@ -286,8 +285,24 @@ class CallbackRegistry(object):
286285
functions). This technique was shared by Peter Parente on his
287286
`"Mindtrove" blog
288287
<http://mindtrove.info/python-weak-references/>`_.
288+
289+
290+
Parameters
291+
----------
292+
exception_handler : callable, optional
293+
If provided must have signature ::
294+
295+
def handler(exception: Exception) -> None:
296+
297+
If not None this function will be called with any `Exception`
298+
subclass raised by the callbacks in `CallbackRegistry.process`.
299+
The handler may either consume the exception or re-raise.
300+
301+
The callable must be pickle-able.
302+
289303
"""
290-
def __init__(self):
304+
def __init__(self, exception_handler=None):
305+
self.exception_handler = exception_handler
291306
self.callbacks = dict()
292307
self._cid = 0
293308
self._func_cid_map = {}
@@ -301,10 +316,10 @@ def __init__(self):
301316
# http://bugs.python.org/issue12290).
302317

303318
def __getstate__(self):
304-
return True
319+
return {'exception_handler': self.exception_handler}
305320

306321
def __setstate__(self, state):
307-
self.__init__()
322+
self.__init__(**state)
308323

309324
def connect(self, s, func):
310325
"""
@@ -365,6 +380,17 @@ def process(self, s, *args, **kwargs):
365380
proxy(*args, **kwargs)
366381
except ReferenceError:
367382
self._remove_proxy(proxy)
383+
# this does not capture KeyboardInterrupt, SystemExit,
384+
# and GeneratorExit
385+
except Exception as e:
386+
if self.exception_handler is not None:
387+
self.exception_handler(e)
388+
else:
389+
raise
390+
391+
392+
def exception_printer(exception):
393+
traceback.print_exc()
368394

369395

370396
class silent_list(list):

0 commit comments

Comments
 (0)