(original) (raw)



On Sat, Apr 21, 2012 at 21:02, Eric Snow <ericsnowcurrently@gmail.com> wrote:

It looks like the test suite accommodates a stable import state to

some extent, but would it be worth having a PEP-405-esque context

manager to help with this? For example, something along these lines:





class ImportState:

# sys.modules is part of the interpreter state, so

# repopulate (don't replace)

def __enter__(self):

self.path = sys.path[:]

self.modules = sys.modules.copy()

self.meta_path = sys.meta_path[:]

self.path_hooks = sys.path_hooks[:]

self.path_importer_cache = sys.path_importer_cache.copy()



sys.path = site.getsitepackages()

sys.modules.clear()

sys.meta_path = []

sys.path_hooks = []

sys.path_importer_cache = {}



def __exit__(self, *args, **kwargs):

sys.path = self.path

sys.modules.clear()

sys.modules.update(self.modules)

sys.meta_path = self.meta_path

sys.path_hooks = self.path_hooks

sys.path_importer_cache = self.path_importer_cache







# in some unit test:

with ImportState():

... # tests


That practically all done for you with a combination of importlib.test.util.uncache and importlib.test.util.import_state.