Manage a collection of events and a sequence of callbacks for each. This is attached to :class:`~IPython.core.interactiveshell.InteractiveShell` instances as an ``events`` attribute. .. note:: This API is experimental in IPython 2.0, and may be revised in future version
| 17 | |
| 18 | |
| 19 | class EventManager(object): |
| 20 | """Manage a collection of events and a sequence of callbacks for each. |
| 21 | |
| 22 | This is attached to :class:`~IPython.core.interactiveshell.InteractiveShell` |
| 23 | instances as an ``events`` attribute. |
| 24 | |
| 25 | .. note:: |
| 26 | |
| 27 | This API is experimental in IPython 2.0, and may be revised in future versions. |
| 28 | """ |
| 29 | def __init__(self, shell, available_events): |
| 30 | """Initialise the :class:`CallbackManager`. |
| 31 | |
| 32 | Parameters |
| 33 | ---------- |
| 34 | shell |
| 35 | The :class:`~IPython.core.interactiveshell.InteractiveShell` instance |
| 36 | available_callbacks |
| 37 | An iterable of names for callback events. |
| 38 | """ |
| 39 | self.shell = shell |
| 40 | self.callbacks = {n:[] for n in available_events} |
| 41 | |
| 42 | def register(self, event, function): |
| 43 | """Register a new event callback. |
| 44 | |
| 45 | Parameters |
| 46 | ---------- |
| 47 | event : str |
| 48 | The event for which to register this callback. |
| 49 | function : callable |
| 50 | A function to be called on the given event. It should take the same |
| 51 | parameters as the appropriate callback prototype. |
| 52 | |
| 53 | Raises |
| 54 | ------ |
| 55 | TypeError |
| 56 | If ``function`` is not callable. |
| 57 | KeyError |
| 58 | If ``event`` is not one of the known events. |
| 59 | """ |
| 60 | if not callable(function): |
| 61 | raise TypeError('Need a callable, got %r' % function) |
| 62 | callback_proto = available_events.get(event) |
| 63 | self.callbacks[event].append(callback_proto.adapt(function)) |
| 64 | |
| 65 | def unregister(self, event, function): |
| 66 | """Remove a callback from the given event.""" |
| 67 | if function in self.callbacks[event]: |
| 68 | return self.callbacks[event].remove(function) |
| 69 | |
| 70 | # Remove callback in case ``function`` was adapted by `backcall`. |
| 71 | for callback in self.callbacks[event]: |
| 72 | try: |
| 73 | if callback.__wrapped__ is function: |
| 74 | return self.callbacks[event].remove(callback) |
| 75 | except AttributeError: |
| 76 | pass |
no outgoing calls