0

I would like to do the equivalent of this python import statement

from module import func1, func2, func3, var1, var2, ...

but the module name and location are passed to the script as command line arguments, so I'm using importlib.util. Is there a more pythonic way to get the variable names into the main module's namespace?

import importlib.util
import sys

modulepath = sys.argv[1]
spec = importlib.util.spec_from_file_location('modulename', modulepath)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

# Is there a better way than this?
func1 = module.func1
func2 = module.func2
func3 = module.func3

2 Answers 2

0

I'm not sure about

from module import func1, func2, func3, var1, var2, ...

but you can do

func1, func2, func3 = module.func1, module.func2, module.func3
0

Not sure in what sense you would like to have a "better" way to do it, but you could simply encapsulate your code in a function like:

import importlib.util

def import_from(modulename, modulepath, *names):
    spec = importlib.util.spec_from_file_location(modulename, modulepath)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return tuple(getattr(module, name) for name in names)

Then you could just do:

import sys

modulepath = sys.argv[1]
func1, func2, func3 = import_from('modulename', modulepath, 'func1', 'func2', 'func3')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.