Sometimes, we want to import a module given the full path in Python.
In this article, we’ll look at how to import a module given the full path in Python.
How to import a module given the full path in Python?
To import a module given the full path in Python, we can use the importlib.util
module.
For instance, if we have the following module:
foo.py
:
def hello():
print('hello')
Then if main.py
is in the same folder and we want to use foo.py
in it.
We write:
import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "./foo.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.hello()
We call importlib.util.spec_from_file_location
with 'module.name'
and './foo.py
‘ to import the module.
Then we call importlib.util.module_from_spec
to import the returned spec
object.
Next, we call spec.loader.exec_module
with the imported foo
module to load it.
And then we call foo.hello
to run the hello
function in foo.py
.
Therefore, 'hello'
should be printed.
Conclusion
To import a module given the full path in Python, we can use the importlib.util
module.