Skip to content

Commit 30a0b5f

Browse files
authored
[3.15] gh-142349: Fill gaps in lazy import documentation (GH-162386) (#162811)
Backport the lazy import documentation and API help to Python 3.15. (cherry picked from commit 9d66e0c)
1 parent 6f23185 commit 30a0b5f

18 files changed

Lines changed: 275 additions & 101 deletions

File tree

‎Doc/builtins/functions.rst‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2346,14 +2346,17 @@ are always available. They are listed here in alphabetical order.
23462346
This is an advanced function that is not needed in everyday Python
23472347
programming, unlike :func:`importlib.import_module`.
23482348

2349-
This function is invoked by the :keyword:`import` statement. It can be
2350-
replaced (by importing the :mod:`builtins` module and assigning to
2351-
``builtins.__import__``) in order to change semantics of the
2352-
:keyword:`!import` statement, but doing so is **strongly** discouraged as it
2353-
is usually simpler to use import hooks (see :pep:`302`) to attain the same
2354-
goals and does not cause issues with code which assumes the default import
2355-
implementation is in use. Direct use of :func:`__import__` is also
2356-
discouraged in favor of :func:`importlib.import_module`.
2349+
Eager :keyword:`import` statements call this function.
2350+
For :ref:`lazy imports <lazy-imports>`, Python calls this function at
2351+
resolution.
2352+
2353+
You can replace :func:`__import__` through an assignment to
2354+
``builtins.__import__``. :ref:`Import hooks <import-hooks>` usually provide a
2355+
simpler way to customize imports. A replacement can cause problems for code
2356+
that expects the default import implementation.
2357+
Do not replace :func:`__import__` unless import hooks cannot supply the
2358+
required behavior.
2359+
To import a module by name, use :func:`importlib.import_module`.
23572360

23582361
The function imports the module *name*, potentially using the given *globals*
23592362
and *locals* to determine how to interpret the name in a package context.

‎Doc/c-api/import.rst‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -371,12 +371,13 @@ Importing Modules
371371
372372
.. c:function:: int PyImport_SetLazyImportsFilter(PyObject *filter)
373373
374-
Sets the current lazy imports filter. The *filter* should be a callable that
375-
will receive ``(importing_module_name, imported_module_name, [fromlist])``
376-
when an import can potentially be lazy. The ``imported_module_name`` value
377-
is the resolved module name, so ``lazy from .spam import eggs`` passes
378-
``package.spam``. The callable must return ``True`` if the import should be
379-
lazy and ``False`` otherwise.
374+
Set the lazy import filter for the current interpreter.
375+
The *filter* must be a callable, ``NULL``, or :c:data:`Py_None`.
376+
Use ``NULL`` or :c:data:`Py_None` to clear the filter.
377+
The callable receives three positional arguments:
378+
``(importing_module_name, imported_module_name, fromlist)``.
379+
See :func:`sys.set_lazy_imports_filter` for the arguments and filter
380+
behavior.
380381
381382
Return ``0`` on success and ``-1`` with an exception set otherwise.
382383
@@ -388,11 +389,13 @@ Importing Modules
388389
389390
.. c:enumerator:: PyImport_LAZY_NORMAL
390391
391-
Respect the ``lazy`` keyword in source code. This is the default mode.
392+
Respect :keyword:`lazy` and :attr:`module.__lazy_modules__`.
393+
This is the default mode.
392394
393395
.. c:enumerator:: PyImport_LAZY_ALL
394396
395-
Make all imports lazy by default.
397+
Make eligible module-scope imports lazy by default.
398+
See the :ref:`lazy import restrictions <lazy-imports>`.
396399
397400
.. versionadded:: 3.15
398401

‎Doc/c-api/init_config.rst‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1598,9 +1598,11 @@ PyConfig
15981598
15991599
Control :ref:`lazy imports <lazy-imports>`.
16001600
1601-
A value of ``-1`` keeps the default behaviour, where only imports marked
1602-
with the ``lazy`` keyword are lazy. A value of ``1`` makes every import
1603-
lazy. ``0`` is rejected.
1601+
A value of ``-1`` selects the default behavior, which respects
1602+
:keyword:`lazy` and :attr:`module.__lazy_modules__`.
1603+
A value of ``1`` makes eligible module-scope imports lazy by default.
1604+
The :ref:`lazy import restrictions <lazy-imports>` apply in both modes.
1605+
A value of ``0`` is invalid.
16041606
16051607
Configured by the :option:`-X lazy_imports <-X>` command line option or
16061608
the :envvar:`PYTHON_LAZY_IMPORTS` environment variable.

‎Doc/glossary.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -929,6 +929,11 @@ Glossary
929929
which is evaluated when the function is called. The syntax to create
930930
a lambda function is ``lambda [parameters]: expression``
931931

932+
lazy import
933+
An import that delays module search and execution until the first use
934+
of the imported name. A proxy represents the imported object until
935+
resolution. See :ref:`lazy-imports`.
936+
932937
LBYL
933938
Look before you leap. This coding style explicitly tests for
934939
pre-conditions before making calls or lookups. This style contrasts with

‎Doc/library/ast.rst‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1127,9 +1127,11 @@ described in other sections.
11271127
Imports
11281128
~~~~~~~
11291129

1130-
.. class:: Import(names)
1130+
.. class:: Import(names, is_lazy)
11311131

11321132
An import statement. ``names`` is a list of :class:`alias` nodes.
1133+
``is_lazy`` is ``1`` for ``lazy import`` and ``0`` for ``import``.
1134+
The field records the source syntax and does not reflect runtime controls.
11331135

11341136
.. doctest::
11351137

@@ -1144,12 +1146,22 @@ Imports
11441146
is_lazy=0)])
11451147

11461148

1147-
.. class:: ImportFrom(module, names, level)
1149+
.. versionchanged:: 3.15
1150+
Added ``is_lazy`` for :ref:`lazy imports <lazy-imports>`.
1151+
1152+
1153+
.. class:: ImportFrom(module, names, level, is_lazy)
11481154

11491155
Represents ``from x import y``. ``module`` is a raw string of the 'from' name,
11501156
without any leading dots, or ``None`` for statements such as ``from . import foo``.
11511157
``level`` is an integer holding the level of the relative import (0 means
11521158
absolute import).
1159+
``is_lazy`` is ``1`` for ``lazy from ... import`` and ``0`` for
1160+
``from ... import``.
1161+
1162+
The ``is_lazy`` field records the source syntax. It does not reflect
1163+
runtime controls such as :func:`sys.set_lazy_imports` or
1164+
:attr:`module.__lazy_modules__`.
11531165

11541166
.. doctest::
11551167

@@ -1166,6 +1178,10 @@ Imports
11661178
is_lazy=0)])
11671179

11681180

1181+
.. versionchanged:: 3.15
1182+
Added ``is_lazy`` for :ref:`lazy imports <lazy-imports>`.
1183+
1184+
11691185
.. class:: alias(name, asname)
11701186

11711187
Both parameters are raw strings of the names. ``asname`` can be ``None`` if

‎Doc/library/dis.rst‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1349,10 +1349,22 @@ iterations of the loop.
13491349

13501350
.. opcode:: IMPORT_NAME (namei)
13511351

1352-
Imports the module ``co_names[namei]``. ``STACK[-1]`` and ``STACK[-2]`` are
1353-
popped and provide the *fromlist* and *level* arguments of :func:`__import__`.
1354-
The module object is pushed onto the stack. The current namespace is not affected: for a proper import statement, a subsequent :opcode:`STORE_FAST` instruction
1355-
modifies the namespace.
1352+
Imports the module ``co_names[namei >> 2]``. ``STACK[-1]`` and
1353+
``STACK[-2]`` supply the *fromlist* and *level* arguments of the import.
1354+
The instruction removes both values from the stack.
1355+
The result is a module object or a
1356+
:class:`lazy import proxy <types.LazyImportType>`.
1357+
The instruction pushes the result onto the stack.
1358+
1359+
The instruction does not change the current namespace.
1360+
For ``import spam``, a subsequent store instruction binds the result.
1361+
1362+
The two lowest bits of *namei* control :ref:`lazy imports <lazy-imports>`.
1363+
Bit ``0`` marks an explicit lazy import. Bit ``1`` forces an eager import.
1364+
If both bits are zero, the runtime lazy import controls apply.
1365+
1366+
.. versionchanged:: 3.15
1367+
The two lowest bits encode lazy import flags.
13561368

13571369

13581370
.. opcode:: IMPORT_FROM (namei)
@@ -1361,6 +1373,12 @@ iterations of the loop.
13611373
The resulting object is pushed onto the stack, to be subsequently stored by a
13621374
:opcode:`STORE_FAST` instruction.
13631375

1376+
For a :class:`lazy import proxy <types.LazyImportType>`, the result can
1377+
be another proxy that represents the requested attribute.
1378+
1379+
.. versionchanged:: 3.15
1380+
Added support for lazy import proxies.
1381+
13641382

13651383
.. opcode:: JUMP_FORWARD (delta)
13661384

‎Doc/library/importlib.rst‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1467,7 +1467,13 @@ To import a Python source file directly from a path, use the following recipe::
14671467
Implementing lazy imports
14681468
'''''''''''''''''''''''''
14691469

1470-
The example below shows how to implement lazy imports::
1470+
Use the :keyword:`lazy` keyword for an explicit :ref:`lazy import <lazy-imports>`.
1471+
Python delays the module search and execution until the first use of the
1472+
imported name.
1473+
1474+
The :class:`importlib.util.LazyLoader` example below does the module search
1475+
immediately and delays only module execution. It creates a module object in
1476+
:data:`sys.modules` before execution::
14711477

14721478
>>> import importlib.util
14731479
>>> import sys

‎Doc/library/sys.rst‎

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -924,11 +924,11 @@ always available. Unless explicitly noted otherwise, all variables are read-only
924924

925925
Returns the current lazy imports mode as a string.
926926

927-
* ``"normal"``: Only imports explicitly marked with the ``lazy`` keyword
928-
are lazy
929-
* ``"all"``: All top-level imports are potentially lazy
927+
* ``"normal"``: Respect :keyword:`lazy` and
928+
:attr:`module.__lazy_modules__`. This is the default mode.
929+
* ``"all"``: Make all eligible module-scope imports potentially lazy.
930930

931-
See also :func:`set_lazy_imports` and :pep:`810`.
931+
See also :func:`set_lazy_imports` and :ref:`lazy-imports`.
932932

933933
.. versionadded:: 3.15
934934

@@ -1512,7 +1512,7 @@ always available. Unless explicitly noted otherwise, all variables are read-only
15121512
In future versions of Python, these may be removed, and/or additional
15131513
extras may be added.
15141514

1515-
See also :func:`set_lazy_imports` and :pep:`810`.
1515+
See also :func:`set_lazy_imports` and :ref:`lazy-imports`.
15161516

15171517
.. versionadded:: 3.15
15181518

@@ -1803,12 +1803,16 @@ always available. Unless explicitly noted otherwise, all variables are read-only
18031803

18041804
.. function:: set_lazy_imports(mode)
18051805

1806-
Sets the global lazy imports mode. The *mode* parameter must be one of
1807-
the following strings:
1806+
Set the lazy import mode for the current interpreter.
1807+
The *mode* parameter must be one of these strings:
18081808

1809-
* ``"normal"``: Only imports explicitly marked with the ``lazy`` keyword
1810-
are lazy
1811-
* ``"all"``: All top-level imports become potentially lazy
1809+
* ``"normal"``: Respect :keyword:`lazy` and
1810+
:attr:`module.__lazy_modules__`. This is the default mode.
1811+
* ``"all"``: Make all eligible module-scope imports potentially lazy.
1812+
1813+
The :ref:`lazy import restrictions <lazy-imports>` also apply in
1814+
``"all"`` mode. A mode change applies to subsequent import statements.
1815+
It does not resolve lazy import proxies from earlier statements.
18121816

18131817
This function is intended for advanced users who need to control lazy
18141818
imports across their entire application. Library developers should
@@ -1818,7 +1822,7 @@ always available. Unless explicitly noted otherwise, all variables are read-only
18181822
In addition to the mode, lazy imports can be controlled via the filter
18191823
provided by :func:`set_lazy_imports_filter`.
18201824

1821-
See also :func:`get_lazy_imports` and :pep:`810`.
1825+
See also :func:`get_lazy_imports` and :ref:`lazy-imports`.
18221826

18231827
.. versionadded:: 3.15
18241828

@@ -1832,12 +1836,13 @@ always available. Unless explicitly noted otherwise, all variables are read-only
18321836
determine whether it should actually be lazy. It should have the following
18331837
signature::
18341838

1835-
def filter(importing_module: str, imported_module: str,
1839+
def filter(importing_module: str | None, imported_module: str,
18361840
fromlist: tuple[str, ...] | None) -> bool
18371841

18381842
The function is called with three positional arguments:
18391843

1840-
* *importing_module* is the name of the module doing the import
1844+
* *importing_module* is the name of the module that executes the import,
1845+
or ``None`` if its globals do not contain ``__name__``
18411846
* *imported_module* is the resolved name of the module being imported
18421847
(for example, ``lazy from .spam import eggs`` passes
18431848
``package.spam``)
@@ -1847,10 +1852,14 @@ always available. Unless explicitly noted otherwise, all variables are read-only
18471852
The filter should return ``True`` to allow the import to be lazy, or
18481853
``False`` to force an eager import.
18491854

1855+
The filter runs when the import statement executes, before proxy creation.
1856+
If the filter raises an exception, the exception propagates from that
1857+
statement. The filter cannot make an otherwise eager import lazy.
1858+
18501859
This is an advanced feature intended for specialized users who need
18511860
fine-grained control over lazy import behavior.
18521861

1853-
See also :func:`get_lazy_imports_filter` and :pep:`810`.
1862+
See also :func:`get_lazy_imports_filter` and :ref:`lazy-imports`.
18541863

18551864
.. versionadded:: 3.15
18561865

‎Doc/library/types.rst‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -345,19 +345,38 @@ Standard names are defined for the following types:
345345

346346
.. class:: LazyImportType
347347

348-
The type of lazy import proxy objects. These objects are created when a
349-
module is lazily imported and serve as placeholders until the module is
350-
actually accessed. This type can be used to detect lazy imports
351-
programmatically.
348+
The type of :ref:`lazy import proxies <lazy-imports>`.
349+
A proxy represents a module or an imported attribute until resolution.
350+
You cannot create instances of this type directly.
351+
352+
A direct read of an imported global name resolves its proxy.
353+
Access through :func:`globals` or
354+
:attr:`module.__dict__` returns the proxy itself::
355+
356+
import types
357+
lazy import json
358+
359+
isinstance(globals()["json"], types.LazyImportType) # True
360+
json.dumps({"key": "value"}) # Resolves the import.
361+
isinstance(globals()["json"], types.LazyImportType) # False
352362

353363
.. versionadded:: 3.15
354364

355-
.. seealso:: :pep:`810`
365+
.. seealso:: :ref:`lazy-imports`
356366

357367
.. method:: resolve()
358368

359-
Reify the lazy import and return the "real" object being imported.
369+
Resolve the lazy import and return the imported module or attribute.
370+
This method can leave the proxy in its namespace.
371+
To replace the proxy explicitly, assign the result to the imported name::
372+
373+
lazy import json
374+
json = globals()["json"].resolve()
360375

376+
Each call to :func:`!resolve` call does a fresh import.
377+
The proxy itself does not store :func:`!resolve`'s result,
378+
relying on the import mechanism to use :attr:`sys.modules`
379+
to reuse modules that have already been imported.
361380

362381
.. class:: GetSetDescriptorType
363382

‎Doc/reference/datamodel.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1158,6 +1158,11 @@ Module objects also have the following special read-only attribute:
11581158
listed here, :attr:`!__dict__` cannot be accessed as a global variable from
11591159
within a module; it can only be accessed as an attribute on module objects.
11601160

1161+
Dictionary access does not resolve :ref:`lazy import proxies <lazy-imports>`.
1162+
This also applies to the dictionary that :func:`globals` returns.
1163+
See :class:`types.LazyImportType` for proxy detection and explicit
1164+
resolution.
1165+
11611166
.. impl-detail::
11621167

11631168
Because of the way CPython clears module dictionaries, the module

0 commit comments

Comments
 (0)