Skip to content

Instantly share code, notes, and snippets.

@Bl41r
Created February 18, 2018 02:18
Show Gist options
  • Save Bl41r/93a89e3efc6c86cb6edd80e0b41a401d to your computer and use it in GitHub Desktop.
Save Bl41r/93a89e3efc6c86cb6edd80e0b41a401d to your computer and use it in GitHub Desktop.
Decorator to create a deep copy of a module
def create_copy_of_module(module, new_name):
"""Decorator to copy a module for mock testing without side effects.
module and new_name are strings of the module to copy, and the name that
the copy will be called so that it can then be imported.
"""
def wrap(f):
def wrapped_f(*args):
orig_spec = importlib.util.find_spec(module)
new = importlib.util.module_from_spec(orig_spec)
orig_spec.loader.exec_module(new)
sys.modules[new_name] = new
f(*args)
orig_spec = None
sys.modules.pop(new_name, None)
new = None
return wrapped_f
return wrap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment