There was an error while loading. Please reload this page.
1 parent 4f309ab commit 8dd32feCopy full SHA for 8dd32fe
1 file changed
Doc/library/importlib.rst
@@ -1719,6 +1719,29 @@ To import a Python source file directly, use the following recipe
1719
spec.loader.exec_module(module)
1720
1721
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
1745
1746
Setting up an importer
1747
''''''''''''''''''''''
0 commit comments