How to load user code?
Question: I have a program which automatically generates a data structure from user-
provided JSON code. I also want to provide an option to allow users to write
their own function to generate this data structure programmatically. Is there
a way for Python to load an arbitrary module by path and return that module's
namespace so I can call the user's function from my program?

Example, I want something like the following:

    
    
    def make(custom):
        if not custom:
            return helper('example.json')
        else:
            return load('path/to/user-script.py').make()  # this line here
    


Answer: You can import a named `.py` file as if it were a module by using
`imp.load_source`; see [this
question](http://stackoverflow.com/questions/67631/how-to-import-a-module-
given-the-full-path).

This is usually a pretty weird thing to do, but loading user hooks that don't
live in the Python module hierarchy seem like an okay excuse. :)

* * *

[This Python bug](http://bugs.python.org/issue14551) claims that `load_source`
is obsolete in Python 3, and advises the somewhat more cumbersome and less
obvious invocation:

    
    
    importlib.SourceFileLoader(name, path).load_module(name)
    

