<s> from collections import defaultdict <EOL> import logging <EOL> import sys <EOL> import inspect <EOL> log = logging . getLogger ( __name__ ) <EOL> _registry = { } <EOL> _consumer_map = defaultdict ( list ) <EOL> _methods = { } <EOL> _registered_modules = [ ] <EOL> def register ( name , service , export_methods = False ) : <EOL> _registry [ name ] = service <EOL> if service not in _registered_modules : <EOL> _registered_modules . append ( service ) <EOL> if export_methods : <EOL> _methods [ name ] = { } <EOL> if inspect . ismodule ( service ) : <EOL> for attr , value in service . __dict__ . items ( ) : <EOL> if not attr . startswith ( "<STR_LIT:_>" ) and not _registry . get ( attr ) and hasattr ( value , '<STR_LIT>' ) : <EOL> _methods [ name ] [ attr ] = value <EOL> else : <EOL> for attr , value in service . __class__ . __dict__ . items ( ) : <EOL> if not attr . startswith ( "<STR_LIT:_>" ) and not _registry . get ( attr ) and hasattr ( value , '<STR_LIT>' ) : <EOL> _methods [ name ] [ attr ] = value . __get__ ( service , service . __class__ ) <EOL> for cls in _consumer_map . get ( name , [ ] ) : <EOL> _inject ( cls , name , service ) <EOL> if name in _consumer_map : <EOL> del _consumer_map [ name ] <EOL> return service <EOL> def inject ( cls , name ) : <EOL> service = _registry . get ( name , None ) <EOL> if service : <EOL> _inject ( cls , name , service ) <EOL> return <EOL> _consumer_map [ name ] . append ( cls ) <EOL> def requires ( * resources ) : <EOL> def wrapper ( cls ) : <EOL> for name in resources : <EOL> inject ( cls , name ) <EOL> return cls <EOL> return wrapper <EOL> def m_requires ( module_name , * resources ) : <EOL> module = sys . modules [ module_name ] <EOL> for name in resources : <EOL> inject ( module , name ) <EOL> if module not in _registered_modules : <EOL> _registered_modules . append ( module ) <EOL> def get_resource ( name ) : <EOL> return _registry [ name ] <EOL> def context_post_init ( ) : <EOL> for name , consumers in _consumer_map . items ( ) : <EOL> for consumer in consumers : <EOL> log . error ( "<STR_LIT>" , name , getattr ( consumer , '<STR_LIT>' , consumer ) ) <EOL> for module in sorted ( _registered_modules , key = _priority_sort ) : <EOL> if hasattr ( module , '<STR_LIT>' ) : <EOL> module . _post_init ( ) <EOL> def _priority_sort ( module ) : <EOL> try : <EOL> return getattr ( module , '<STR_LIT>' ) <EOL> except AttributeError : <EOL> if inspect . isclass ( module ) : <EOL> return <NUM_LIT:1000> <EOL> return <NUM_LIT> <EOL> def _inject ( cls , name , service ) : <EOL> if hasattr ( service , '<STR_LIT>' ) : <EOL> setattr ( cls , name , service . factory ( cls ) ) <EOL> else : <EOL> setattr ( cls , name , service ) <EOL> for attr , value in _methods . get ( name , { } ) . items ( ) : <EOL> if not getattr ( cls , attr , None ) : <EOL> setattr ( cls , attr , value ) </s>
