Created
July 1, 2009 12:33
-
-
Save runeh/138755 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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