I'm having a hard time understanding the python importlib library. I've seen 2 implementations to dynamically import modules:
1.
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
importlib.import_module(name)
So which one is the correct one? And what differences happen here? Thanks in advance.
Both work, both give same results..
The first snippet tries to create a module from a specific file that may be in a folder not on the import path. It will execute the code in the file, regardless of whether that code has already been executed, and it will create a new module object, even if a module object has already been created for that file previously. It will not insert the module into sys.modules
.
If you need to load code from files not on the import path, this code may be a way to do that. However, if that code has dependencies on other code that's also not on the import path, the code won't be able to find those dependencies, so this code may not be enough. You should also be careful about trying to load the same file twice.
The second snippet just loads a module the same way the usual import
statement does, going through all the usual machinery with sys.modules
and sys.path
and all that, but letting you specify the name of the module to load dynamically. import foo
and foo = importlib.import_module('foo')
are mostly equivalent, but importlib.import_module
lets you do mod = importlib.import_module(some_name_computed_at_runtime)
.
Due to weird implementation details, if you import a package with importlib.import_module
, importlib.import_module
will also initialize any submodules named in the package's __all__
list. This usually isn't a big deal.
If your situation is "I would use import
, but I don't know the module name yet when I'm writing my code", importlib.import_module
is the way to go.