Dynamically importing Python modules by filename

doug
Sun, 10 May 2009 14:56:08 +0000

After looking for a way to import Python modules when given a valid filepath I came across a description of a technique to do so here.

What I did not like about this approach was the use of null_module. In his approach you needed to have a module called null_module somewhere in your PYTHONPATH. This was then cloned and the information about the actual module you wish to report overwrites this module. In short, he was using null_module as a skeleton module for the import. This is unnecessary.

To do the entire import in a much nicer way you can simply do:

import types
def CreateNewModule(name, filename):
    """Create a new module instance with the given name and
    load Python code into it."""
    # Note: Does not add the created module to sys.modules
    module = types.ModuleType(name)
    execfile(filename, module.__dict__, module.__dict__)
    return module

Tada!