Skip to content Skip to sidebar Skip to footer

Using Importlib To Dynamically Import Module(s) Containing Relative Imports

I am trying to figure out how to programmatically execute a module that contains relative imports. psuedo code spec = importlib.util.spec_from_file_location(name, path) mod = impor

Solution 1:

Your code works fine for me, as is.

One possible issue is what the value of the name you're using is. In order for relative imports to work, you need to fully specify the module name (e.g. name = "package1.package2.mymodule").

For example:

runimport.py

import importlib
import os

name = "testpack.inside" # NOT "inside"

spec = importlib.util.spec_from_file_location(name, 
    os.path.join(os.path.dirname(__file__), 'testpack/inside.py'))
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)

testpack/init.py

# empty

testpack/inside.py

from . import otherinside
print('I got', otherinside.data)

testpack/otherinside.py

data = 'other inside'

Now, python3 runimport.py prints "I got other inside". If you replace the name with "inside", it throws the error you describe.

Post a Comment for "Using Importlib To Dynamically Import Module(s) Containing Relative Imports"