diff options
author | Joannah Nanjekye <33177550+nanjekyejoannah@users.noreply.github.com> | 2020-07-13 21:31:02 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-07-13 21:31:02 (GMT) |
commit | 8dd32fe645c9503cf8e6be4b1580c3a59b450168 (patch) | |
tree | 34aeabcd35eed132bd93c736a92c276d17560091 /Doc/library/importlib.rst | |
parent | 4f309abf55f0e6f8950ac13d6ec83c22b8d47bf8 (diff) | |
download | cpython-8dd32fe645c9503cf8e6be4b1580c3a59b450168.zip cpython-8dd32fe645c9503cf8e6be4b1580c3a59b450168.tar.gz cpython-8dd32fe645c9503cf8e6be4b1580c3a59b450168.tar.bz2 |
bpo-32192: A basic lazy importer example (GH-21330)
* Add example on lazy imports
* Use four spaces for indentation
* change to console
Diffstat (limited to 'Doc/library/importlib.rst')
-rw-r--r-- | Doc/library/importlib.rst | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/Doc/library/importlib.rst b/Doc/library/importlib.rst index 99bfeac..f7286d2 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 '''''''''''''''''''''' |