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
1719
1719
spec.loader.exec_module(module)
1720
1720
1721
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
<
4FDB
td data-grid-cell-id="diff-023b9cd2ff76dd1b2a7117a363f1789d5d192c09d632872934b86e8d3fbe5f3e-1721-1743-1" data-selected="false" role="gridcell" style="background-color:var(--diffBlob-additionNum-bgColor, var(--diffBlob-addition-bgColor-num));text-align:center" tabindex="-1" valign="top" class="focusable-grid-cell diff-line-number position-relative left-side">1743
+
1744
+
1722
1745
1723
1746
Setting up an importer
1724
1747
''''''''''''''''''''''
You can’t perform that action at this time.
0 commit comments