1
2
3
4
5
6
7 """
8 Classes and routines that are common to various netaddr sub modules.
9 """
10 import sys as _sys
11 import pprint as _pprint
12
13
15 """
16 Abstract class defining interface expected by a Publisher that concrete
17 subclass instances register with to receive updates from.
18 """
20 """
21 Callback function used by Publisher to notify this Subscriber about
22 an update.
23 """
24 raise NotImplementedError('cannot invoke virtual method!')
25
26
28 """
29 Concrete Subscriber that uses the pprint module to format all data from
30 updates received writing them to any file-like object. Useful for
31 debugging.
32 """
33 - def __init__(self, fh=_sys.stdout, write_eol=True):
34 """
35 Constructor.
36
37 fh - file or file like object to write to. Default: sys.stdout.
38 """
39 self.fh = fh
40 self.write_eol = write_eol
41
43 """
44 Callback function used by Publisher to notify this Subscriber about
45 an update.
46 """
47 self.fh.write(_pprint.pformat(data))
48 if self.write_eol:
49 self.fh.write("\n")
50
51
53 """
54 A 'push' publisher that maintains a list of Subscriber objects notifying
55 them of state changes when its subclasses encounter events of interest.
56 """
58 """Constructor"""
59 self.subscribers = []
60
62 """Add a new subscriber"""
63 if hasattr(subscriber, 'update') and \
64 callable(eval('subscriber.update')):
65 if subscriber not in self.subscribers:
66 self.subscribers.append(subscriber)
67 else:
68 raise TypeError('%r does not support required interface!' \
69 % subscriber)
70
72 """Remove an existing subscriber"""
73 try:
74 self.subscribers.remove(subscriber)
75 except ValueError:
76 pass
77
79 """Send notification message to all registered subscribers"""
80 for subscriber in self.subscribers:
81 subscriber.update(data)
82