[Python-checkins] bpo-32192: A basic lazy importer example (GH-21330)
Joannah Nanjekye
webhook-mailer at python.org
Mon Jul 13 17:31:11 EDT 2020
https://github.com/python/cpython/commit/8dd32fe645c9503cf8e6be4b1580c3a59b450168
commit: 8dd32fe645c9503cf8e6be4b1580c3a59b450168
branch: master
author: Joannah Nanjekye <33177550+nanjekyejoannah at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2020-07-13T18:31:02-03:00
summary:
bpo-32192: A basic lazy importer example (GH-21330)
* Add example on lazy imports
* Use four spaces for indentation
* change to console
files:
M Doc/library/importlib.rst
diff --git a/Doc/library/importlib.rst b/Doc/library/importlib.rst
index 99bfeacbbc740..f7286d2ade8bd 100644
--- a/Doc/library/importlib.rst
+++ b/Doc/library/importlib.rst
@@ -1719,6 +1719,29 @@ To import a Python source file directly, use the following recipe
spec.loader.exec_module(module)
+Implementing lazy imports
+'''''''''''''''''''''''''
+
+The example below shows how to implement lazy imports::
+
+ >>> 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
+
+
Setting up an importer
''''''''''''''''''''''
More information about the Python-checkins
mailing list