]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-32192: A basic lazy importer example (GH-21330)
authorJoannah Nanjekye <33177550+nanjekyejoannah@users.noreply.github.com>
Mon, 13 Jul 2020 21:31:02 +0000 (18:31 -0300)
committerGitHub <noreply@github.com>
Mon, 13 Jul 2020 21:31:02 +0000 (18:31 -0300)
* Add example on lazy imports

* Use four spaces for indentation

* change to console

Doc/library/importlib.rst

index 99bfeacbbc740711b525f39ee1ee7867df4b2fa3..f7286d2ade8bd1d8c8178bef6bfc3569114eec0e 100644 (file)
@@ -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
 ''''''''''''''''''''''