Skip to content

Instantly share code, notes, and snippets.

@runeh
Created July 1, 2009 12:33
Show Gist options
  • Save runeh/138755 to your computer and use it in GitHub Desktop.
Save runeh/138755 to your computer and use it in GitHub Desktop.
"""Ban some modules from being importable inside the context
For example:
with missing_modules("sys"):
try:
import sys
except ImportError:
print "sys not found"
import sys
print sys.version
results in:
sys not found
(2, 5, 2, 'final', 0)
"""
from __future__ import with_statement
from contextlib import contextmanager
import __builtin__
@contextmanager
def missing_modules(*modnames):
def myimp(name, *args, **kwargs):
if name in modnames:
raise ImportError("No module named %s" % name)
else:
return realimport(name, *args, **kwargs)
realimport = __builtin__.__import__
__builtin__.__import__ = myimp
yield
__builtin__.__import__ = realimport
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment