Skip to content

Commit

Permalink
bpo-32192: A basic lazy importer example (pythonGH-21330)
Browse files Browse the repository at this point in the history
* Add example on lazy imports

* Use four spaces for indentation

* change to console
  • Loading branch information
nanjekyejoannah authored Jul 13, 2020
1 parent 4f309ab commit 8dd32fe
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Doc/library/importlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
''''''''''''''''''''''
Expand Down

0 comments on commit 8dd32fe

Please sign in to comment.