Package netaddr :: Module core
[hide private]
[frames] | no frames]

Source Code for Module netaddr.core

 1  #!/usr/bin/env python
 
 2  #-----------------------------------------------------------------------------
 
 3  #   Copyright (c) 2008-2009, David P. D. Moss. All rights reserved.
 
 4  #
 
 5  #   Released under the BSD license. See the LICENSE file for details.
 
 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  #-----------------------------------------------------------------------------
 
14 -class Subscriber(object):
15 """ 16 Abstract class defining interface expected by a Publisher that concrete 17 subclass instances register with to receive updates from. 18 """
19 - def update(self, data):
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 #-----------------------------------------------------------------------------
27 -class PrettyPrinter(Subscriber):
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
42 - def update(self, data):
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 #-----------------------------------------------------------------------------
52 -class Publisher(object):
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 """
57 - def __init__(self):
58 """Constructor""" 59 self.subscribers = []
60
61 - def attach(self, subscriber):
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
71 - def detach(self, subscriber):
72 """Remove an existing subscriber""" 73 try: 74 self.subscribers.remove(subscriber) 75 except ValueError: 76 pass
77
78 - def notify(self, data):
79 """Send notification message to all registered subscribers""" 80 for subscriber in self.subscribers: 81 subscriber.update(data)
82