File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed
Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change @@ -1719,6 +1719,29 @@ To import a Python source file directly, use the following recipe
17191719 spec.loader.exec_module(module)
17201720
17211721
1722+ Implementing lazy imports
1723+ '''''''''''''''''''''''''
1724+
1725+ The example below shows how to implement lazy imports::
1726+
1727+ >>> import importlib.util
1728+ >>> import sys
1729+ >>> def lazy_import(name):
1730+ ... spec = importlib.util.find_spec(name)
1731+ ... loader = importlib.util.LazyLoader(spec.loader)
1732+ ... spec.loader = loader
1733+ ... module = importlib.util.module_from_spec(spec)
1734+ ... sys.modules[name] = module
1735+ ... loader.exec_module(module)
1736+ ... return module
1737+ ...
1738+ >>> lazy_typing = lazy_import("typing")
1739+ >>> #lazy_typing is a real module object,
1740+ >>> #but it is not loaded in memory yet.
1741+ >>> lazy_typing.TYPE_CHECKING
1742+ False
1743+
1744+
17221745
17231746Setting up an importer
17241747''''''''''''''''''''''
You can’t perform that action at this time.
0 commit comments