This site is best viewed in Mozilla Firefox or Google Chrome
Fri, 18th May 2012 04:41:58
Never fear, this site is here  

#Dynamically importing Python modules by filename

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!

There are 2 comments on this post. Make a comment.
Powered by Debian, Jack Daniels, Guinness, and excessive quantities of caffeine and sugar.