 <p>You'll need to add a custom import hook. Python added a way to register custom import hooks. Prior to this mechanism, you would have to override the built-in <code>__import__</code> function. But it was particularly error-prone, especially if multiple libraries were both trying to add custom import behavior.</p> <p><a href="https://www.python.org/dev/peps/pep-0302/" rel="nofollow">PEP 0302</a> describes the mechanism in detail.</p> <p>Essentially, you need to create two objects -- a Finder object and a Loader object.</p> <p>The Finder object should define a function called <code>find_module</code> </p> <blockquote> <p>This method will be called with the fully qualified name of the module. If the finder is installed on sys.meta_path , it will receive a second argument, which is None for a top-level module, or <code>package.__path__</code> for submodules or subpackages [5] . It should return a loader object if the module was found, or None if it wasn't.</p> </blockquote> <p>If the <code>find_module</code> function finds the module and returns a Loader object, the Loader object should define a <code>load_module</code> function</p> <blockquote> <p>This method returns the loaded module or raises an exception, preferably ImportError if an existing exception is not being propagated. If load_module() is asked to load a module that it cannot, ImportError is to be raised.</p> </blockquote> <p>Here is a short example detailing how it would work:</p> <pre><code>import sys import imp class CustomImportFinder(object): @staticmethod def find_module(fullname, path=None): # Do your custom stuff here, look in database, etc. code_from_database = "VAR = 1" return CustomImportLoader(fullname, path, code_from_database) class CustomImportLoader(object): def __init__(self, fullname, path, code_from_database): super(CustomImportLoader, self).__init__() self.fullname = fullname self.path = path self.code_from_database = code_from_database def is_package(fullname): # is this a package? return False def load_module(self, fullname): code = self.code_from_database ispkg = self.is_package(fullname) mod = sys.modules.setdefault(fullname, imp.new_module(fullname)) mod.__file__ = "&lt;%s&gt;" % self.__class__.__name__ mod.__loader__ = self if ispkg: mod.__path__ = [] mod.__package__ = fullname else: mod.__package__ = fullname.rpartition('.')[0] exec(code, mod.__dict__) return mod sys.meta_path.append(CustomImportFinder) import blah print(blah) # &lt;module 'blah' (built-in)&gt; print(blah.VAR) # 1 </code></pre>