8000 bpo-32192: A basic lazy importer example (GH-21330) · python/cpython@8dd32fe · GitHub
[go: up one dir, main page]

Skip to content

Commit 8dd32fe

Browse files
bpo-32192: A basic lazy importer example (GH-21330)
* Add example on lazy imports * Use four spaces for indentation * change to console
1 parent 4f309ab commit 8dd32fe

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Doc/library/importlib.rst

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1719,6 +1719,29 @@ To import a Python source file directly, use the following recipe
1719 F9EE 1719
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

17231746
Setting up an importer
17241747
''''''''''''''''''''''

0 commit comments

Comments
 (0)
0