Skip to content

Instantly share code, notes, and snippets.

@spbrien
Created May 15, 2017 14:19
Show Gist options
  • Save spbrien/758639c162b0a36eb7d69d071c84686a to your computer and use it in GitHub Desktop.
Save spbrien/758639c162b0a36eb7d69d071c84686a to your computer and use it in GitHub Desktop.
"""Use custom meta hook to import modules available as strings.
Cp. PEP 302 http://www.python.org/dev/peps/pep-0302/#specification-part-2-registering-hooks"""
import sys
import imp
modules = {"a" :
"""def hello():
return 'Hello World A!'""",
"b":
"""def hello():
return 'Hello World B!'"""}
class StringImporter(object):
def __init__(self, modules):
self._modules = dict(modules)
def find_module(self, fullname, path):
if fullname in self._modules.keys():
return self
return None
def load_module(self, fullname):
if not fullname in self._modules.keys():
raise ImportError(fullname)
new_module = imp.new_module(fullname)
exec self._modules[fullname] in new_module.__dict__
return new_module
if __name__ == '__main__':
sys.meta_path.append(StringImporter(modules))
# Let's use our import hook
from a import hello
print hello()
from b import hello
print hello()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment