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
|
import unittest
from rdflib import events
class AddedEvent(events.Event):
pass
class RemovedEvent(events.Event):
pass
def subscribe_to(source, target):
target.subscribe(AddedEvent, source._add_handler)
target.subscribe(RemovedEvent, source._remove_handler)
def subscribe_all(caches):
for cache in caches:
for other in caches:
if other != cache:
subscribe_to(cache, other)
class Cache(events.Dispatcher):
def __init__(self, data=None):
if data is None:
data = {}
self._data = data
self.subscribe(AddedEvent, self._add_handler)
self.subscribe(RemovedEvent, self._remove_handler)
def _add_handler(self, event):
self._data[event.key] = event.value
def _remove_handler(self, event):
del self._data[event.key]
def __getitem__(self, key):
return self._data[key]
def __setitem__(self, key, value):
self.dispatch(AddedEvent(key=key, value=value))
def __delitem__(self, key):
self.dispatch(RemovedEvent(key=key))
def __contains__(self, key):
return key in self._data
has_key = __contains__
class EventTestCase(unittest.TestCase):
def testEvents(self):
c1 = Cache()
c2 = Cache()
c3 = Cache()
subscribe_all([c1, c2, c3])
c1["bob"] = "uncle"
assert c2["bob"] == "uncle"
assert c3["bob"] == "uncle"
del c3["bob"]
assert ("bob" in c1) == False
assert ("bob" in c2) == False
if __name__ == "__main__":
unittest.main()
|