@contextlib.contextmanager
def import_state(**kwargs):
 originals = {}
 try:
  for (attr, default) in (('meta_path', []), ('path', []), ('path_hooks', []), ('path_importer_cache', {})):
   originals[attr] = getattr(sys, attr)
   if (attr in kwargs):
    new_value = kwargs[attr]
    del kwargs[attr]
   else:
    new_value = default
   setattr(sys, attr, new_value)
  if len(kwargs):
   raise ValueError('unrecognized arguments: {0}'.format(kwargs.keys()))
  (yield)
 finally:
  for (attr, value) in originals.items():
   setattr(sys, attr, value)

@ contextlib . contextmanager def import_state ( ** kwargs ) : originals = { } try : for ( attr , default ) in ( ( 'meta_path' , [ ] ) , ( 'path' , [ ] ) , ( 'path_hooks' , [ ] ) , ( 'path_importer_cache' , { } ) ) : originals [ attr ] = getattr ( sys , attr ) if ( attr in kwargs ) : new_value = kwargs [ attr ] del kwargs [ attr ] else : new_value = default setattr ( sys , attr , new_value ) if len ( kwargs ) : raise ValueError ( 'unrecognized arguments: {0}' . format ( kwargs . keys ( ) ) ) ( yield ) finally : for ( attr , value ) in originals . items ( ) : setattr ( sys , attr , value )
context manager to manage the various importers and stored state in the sys module .