<s> from __future__ import unicode_literals , print_function , division <EOL> __author__ = "<STR_LIT>" <EOL> try : <EOL> from weakref import WeakSet <EOL> except ImportError : <EOL> from weakrefset import WeakSet <EOL> class Observer ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self ) : <EOL> self . _listeners = dict ( ) <EOL> def subscribe ( self , event , listener_object ) : <EOL> event_handler_name = "<STR_LIT>" % event <EOL> if not hasattr ( listener_object , event_handler_name ) : <EOL> raise AttributeError ( "<STR_LIT>" % event ) <EOL> try : <EOL> event_listeners = self . _listeners [ event ] <EOL> except KeyError : <EOL> event_listeners = WeakSet ( ) <EOL> self . _listeners [ event ] = event_listeners <EOL> event_listeners . add ( listener_object ) <EOL> def unsubscribe ( self , event , listener_object ) : <EOL> event_listeners = self . _listeners [ event ] <EOL> event_listeners . remove ( listener_object ) <EOL> def broadcast ( self , event , msg = None , root = None ) : <EOL> """<STR_LIT>""" <EOL> event_handler_name = "<STR_LIT>" % event <EOL> def get_event_handler ( listener ) : <EOL> return getattr ( listener , event_handler_name ) <EOL> def send_to_all ( listener ) : <EOL> handler = get_event_handler ( listener ) <EOL> handler ( msg = msg ) <EOL> def send_to_root ( listener ) : <EOL> try : <EOL> listener_root = listener . get_xmlroot ( ) <EOL> except AttributeError : <EOL> return <EOL> if listener_root is root : <EOL> handler = get_event_handler ( listener ) <EOL> handler ( msg = msg ) <EOL> try : <EOL> event_listeners = self . _listeners [ event ] <EOL> except KeyError : <EOL> return <EOL> send = send_to_root if root else send_to_all <EOL> for listener in event_listeners : <EOL> send ( listener ) <EOL> def _has_listener ( self , event ) : <EOL> return self . _count_listeners ( event ) > <NUM_LIT:0> <EOL> def _count_listeners ( self , event ) : <EOL> try : <EOL> return len ( self . _listeners [ event ] ) <EOL> except KeyError : <EOL> return <NUM_LIT:0> <EOL> _global_observer = Observer ( ) <EOL> subscribe = _global_observer . subscribe <EOL> unsubscripe = _global_observer . unsubscribe <EOL> broadcast = _global_observer . broadcast </s>
