Source code

Download source archive ↓

src/rdflib/events.py

1"""
2Dirt Simple Events
3
4A Dispatcher (or a subclass of Dispatcher) stores event handlers that
5are 'fired' simple event objects when interesting things happen.
6
7Create a dispatcher:
8
9```python
10>>> d = Dispatcher()
11
12```
13
14Now create a handler for the event and subscribe it to the dispatcher
15to handle Event events.  A handler is a simple function or method that
16accepts the event as an argument:
17
18```python
19>>> def handler1(event): print(repr(event))
20>>> d.subscribe(Event, handler1) # doctest: +ELLIPSIS
21<rdflib.events.Dispatcher object at ...>
22
23```
24
25Now dispatch a new event into the dispatcher, and see handler1 get
26fired:
27
28```python
29>>> d.dispatch(Event(foo='bar', data='yours', used_by='the event handlers'))
30<rdflib.events.Event ['data', 'foo', 'used_by']>
31
32```
33"""
34
35from __future__ import annotations
36
37from typing import Any, Dict, Optional
38
39__all__ = ["Event", "Dispatcher"]
40
41
42class Event:
43    """
44    An event is a container for attributes.  The source of an event
45    creates this object, or a subclass, gives it any kind of data that
46    the events handlers need to handle the event, and then calls
47    notify(event).
48
49    The target of an event registers a function to handle the event it
50    is interested with subscribe().  When a sources calls
51    notify(event), each subscriber to that event will be called in no
52    particular order.
53    """
54
55    def __init__(self, **kw):
56        self.__dict__.update(kw)
57
58    def __repr__(self):
59        attrs = sorted(self.__dict__.keys())
60        return "<rdflib.events.Event %s>" % ([a for a in attrs],)
61
62
63class Dispatcher:
64    """
65    An object that can dispatch events to a privately managed group of
66    subscribers.
67    """
68
69    _dispatch_map: Optional[Dict[Any, Any]] = None
70
71    def set_map(self, amap: Dict[Any, Any]):
72        self._dispatch_map = amap
73        return self
74
75    def get_map(self):
76        return self._dispatch_map
77
78    def subscribe(self, event_type, handler):
79        """Subscribe the given handler to an event_type.  Handlers
80        are called in the order they are subscribed.
81        """
82        if self._dispatch_map is None:
83            self.set_map({})
84        # type error: error: Item "None" of "Optional[Dict[Any, Any]]" has no attribute "get"
85        lst = self._dispatch_map.get(event_type, None)  # type: ignore[union-attr]
86        if lst is None:
87            lst = [handler]
88        else:
89            lst.append(handler)
90        # type error: Unsupported target for indexed assignment ("Optional[Dict[Any, Any]]")
91        self._dispatch_map[event_type] = lst  # type: ignore[index]
92        return self
93
94    def dispatch(self, event):
95        """Dispatch the given event to the subscribed handlers for
96        the event's type"""
97        if self._dispatch_map is not None:
98            lst = self._dispatch_map.get(type(event), None)
99            if lst is None:
100                raise ValueError("unknown event type: %s" % type(event))
101            for l_ in lst:
102                l_(event)