PyDocs

Nav

Importing Modules

find_spec

importlib.util

function · Added in 3.4 (source)
  • find_spec(name, package=None)
Return the spec for the specified module.

First, sys.modules is checked to see if the module was already imported. If
so, then sys.modules[name].__spec__ is returned. If that happens to be
set to None, then ValueError is raised. If the module is not in
sys.modules, then sys.meta_path is searched for a suitable spec with the
value of 'path' given to the finders. None is returned if no spec could
be found.

If the name is for submodule (contains a dot), the parent module is
automatically imported.

The name and package arguments work the same as importlib.import_module().
In other words, relative module names (with leading dots) work.
Changed in 3.7
  • 3.7: Raises ModuleNotFoundError instead of AttributeError if package is in fact not a package (i.e. lacks a __path__ attribute).
1 Example
>>> import importlib.util
>>> import sys
>>> def lazy_import(name):
...     spec = importlib.util.find_spec(name)
...     loader = importlib.util.LazyLoader(spec.loader)
...     spec.loader = loader
...     module = importlib.util.module_from_spec(spec)
...     sys.modules[name] = module
...     loader.exec_module(module)
...     return module
...
>>> lazy_typing = lazy_import("typing")
>>> #lazy_typing is a real module object,
>>> #but it is not loaded in memory yet.
>>> lazy_typing.TYPE_CHECKING
False
from the Python docs
See Also
No see-alsos for importlib.util/find_spec
0 Notes
No notes for find_spec