Skip to content

How can I import a module dynamically given the full path?

You can use the importlib.util.spec_from_file_location and importlib.util.module_from_spec functions to import a module dynamically given a full file path. For example:

Import a module dynamically given the full path to the module in Python

python
import importlib.util

module_path = '/path/to/module.py'
module_name = 'module'

spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

This will import the module located at /path/to/module.py, and the module will be bound to the module variable.

You can then use module just like any other module that you imported using the import statement.

Import a module dynamically given the full path to the module in Python and running a function inside the module

python
import importlib.util

module_path = '/path/to/module.py'
module_name = 'module'

spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

x = module.some_function()

Note that spec_from_file_location requires the module_name as a string and the module_path as the absolute or relative file path to the module.

Dual-run preview — compare with live Symfony routes.