In python, what code should I generate to do "from FILE import *"?

Viewed 69

I'm working on the pythonizer, a program to translate perl to python, and I'm looking to translate the statement "require FILENAME;" to python. In this case I need to generate "from FILENAME import *". I figured out the "from FILENAME" part (here BASENAME is the FILENAME without the path or extension):

from importlib.machinery import SourceFileLoader
module = SourceFileLoader(BASENAME, FILENAME).load_module()

and the import * part is coded as:

__import__(name, fromlist=['*'])

but how do I combine them?

I see _handle_fromlist in importlib._bootstrap, but calling an internal routine is most likely not the right answer here.

1 Answers

Here is my second thought about implementing this:

[_p, _m] = _prep_import(FILENAME)
sys.path.insert(0, _p)
__import__(_m, fromlist=['*'])
sys.path.pop(0)

def _prep_import(filepath):
    """Prepare a filepath for import by getting the abspath, splitting
    it from the filename, and removing any extension.  Returns a tuple of
    the path and the filename"""
    return os.path.split(os.path.splitext(os.path.abspath(filepath))[0])

Where _prep_import() looks at the FILENAME (which may be an expression), removes any extension, grabs any path info from it into the first result, and leaves the basename as the second result. Note that the FILENAME may contain dashes (-), and I believe __import__ is OK with that.

Related