Skip to content

Instantly share code, notes, and snippets.

@asottile
Last active December 21, 2015 06:39
Show Gist options
  • Save asottile/6265617 to your computer and use it in GitHub Desktop.
Save asottile/6265617 to your computer and use it in GitHub Desktop.
Patching out modules in Python
import contextlib
import collections
import mock
import sys
def fake_module(**args):
return (collections.namedtuple('module', args.keys())(**args))
def get_patch_dict(dotted_module_path, module):
patch_dict = {}
module_splits = dotted_module_path.split('.')
# Add our module to the patch dict
patch_dict[dotted_module_path] = module
# We add the rest of the fake modules in backwards
while len(module_splits) > 1:
# This adds the next level up into the patch dict which is a fake
# module that points at the next level down
patch_dict['.'.join(module_splits[:-1])] = fake_module(
**{module_splits[-1]: patch_dict['.'.join(module_splits)]}
)
module_splits = module_splits[:-1]
return patch_dict
with mock.patch.dict(
sys.modules,
get_patch_dict('herp.derp', fake_module(foo='bar'))
):
import herp.derp
# prints bar
print herp.derp.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment