@@ -920,6 +920,56 @@ See :pep:`810` for the full specification of lazy imports.
920920
921921.. versionadded :: 3.15
922922
923+ .. _lazy-modules-compat :
924+
925+ Compatibility via ``__lazy_modules__ ``
926+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
927+
928+ .. index ::
929+ single: __lazy_modules__
930+
931+ As an alternative to using the :keyword: `lazy ` keyword, a module can opt
932+ into lazy loading for specific imports by defining a module-level
933+ :attr: `~module.__lazy_modules__ ` variable. When present, it must be a
934+ container of fully qualified module name strings. Any regular (non-``lazy ``)
935+ :keyword: `import ` statement at module scope whose target appears in
936+ :attr: `!__lazy_modules__ ` is treated as a lazy import, exactly as if the
937+ :keyword: `lazy ` keyword had been used.
938+
939+ This provides a way to enable lazy loading for specific dependencies without
940+ changing individual ``import `` statements. This is useful when supporting
941+ Python versions older than 3.15 while using lazy imports in 3.15+::
942+
943+ __lazy_modules__ = ["json", "pathlib"]
944+
945+ import json # loaded lazily (name is in __lazy_modules__)
946+ import os # loaded eagerly (name not in __lazy_modules__)
947+
948+ import pathlib # loaded lazily
949+
950+ Relative imports are resolved to their absolute name before the lookup, so
951+ :attr: `!__lazy_modules__ ` must always contain fully qualified module names.
952+
953+ For ``from ``-style imports, the relevant name is the module following
954+ ``from ``, not the names of its members::
955+
956+ # In mypackage/mymodule.py
957+ __lazy_modules__ = ["mypackage", "mypackage.sub.utils"]
958+
959+ from . import helper # loaded lazily: . resolves to mypackage
960+ from .sub.utils import func # loaded lazily: .sub.utils resolves to mypackage.sub.utils
961+ import json # loaded eagerly (not in __lazy_modules__)
962+
963+ Imports inside functions, class bodies, or
964+ :keyword: `try `/:keyword: `except `/:keyword: `finally ` blocks are always eager,
965+ regardless of :attr: `!__lazy_modules__ `.
966+
967+ Setting ``-X lazy_imports=none `` (or the :envvar: `PYTHON_LAZY_IMPORTS `
968+ environment variable to ``none ``) overrides :attr: `!__lazy_modules__ ` and
969+ forces all imports to be eager.
970+
971+ .. versionadded :: 3.15
972+
923973.. _future :
924974
925975Future statements
0 commit comments