3

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
darkfeline
  • 9,404
  • 5
  • 31
  • 32

1 Answers1

2

You can import a named .py file as if it were a module by using imp.load_source; see this question.

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 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)
Community
  • 1
  • 1
Eevee
  • 47,412
  • 11
  • 95
  • 127
  • I saw that question actually, but I though that was for python 2 as imp.load_source isn't documented for 3, but I checked just now and it's still there though not documented. Figures. Here, have a cookie. – darkfeline Feb 28 '13 at 06:21
  • ah, it seems it's been obsoleted for 3. updated answer with the new hotness – Eevee Feb 28 '13 at 06:30