Text of peps.python.org › pep-0690 as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

PEP 690 – Lazy Imports | peps.python.org

PEP 690 – Lazy Imports PEP 690 – Lazy Imports Author : Germán Méndez Bravo <german.mb at gmail.com>, Carl Meyer <carl at oddbird.net> Sponsor : Barry Warsaw <barry at python.org> Discussions-To : Discourse thread Status : Rejected Type : Standards Track Created : 29-Apr-2022 Python-Version : 3.12 Post-History : 03-May-2022 , 03-May-2022 Resolution : Discourse message Table of Contents Abstract Motivation Rationale Specification Example Intended usage Implementation Debugging Per-module opt-out Testing C API Backwards Compatibility Import Side Effects Dynamic Paths Deferred Exceptions Drawbacks Security Implications Performance Impact How to Teach This Reference Implementation Rejected Ideas Wrapping deferred exceptions Per-module opt-in Explicit syntax for individual lazy imports Environment variable to enable lazy imports Removing the -L flag Half-lazy imports Lazy dynamic imports Deep eager-imports override Making lazy imports the default behavior Copyright Abstract This PEP proposes a feature to transparently defer the finding and execution of imported modules until the moment when an imported object is first used.

Since Python programs commonly import many more modules than a single invocation of the program is likely to use in practice, lazy imports can greatly reduce the overall number of modules loaded, improving startup time and memory usage. Lazy imports also mostly eliminate the risk of import cycles. Motivation Common Python code style prefers imports at module level, so they don’t have to be repeated within each scope the imported object is used in, and to avoid the inefficiency of repeated execution of the import system at runtime.

This means that importing the main module of a program typically results in an immediate cascade of imports of most or all of the modules that may ever be needed by the program. Consider the example of a Python command line program (CLI) with a number of subcommands. Each subcommand may perform different tasks, requiring the import of different dependencies. But a given invocation of the program will only execute a single subcommand, or possibly none (i.e. if just --help usage info is requested).

Top-level eager imports in such a program will result in the import of many modules that will never be used at all; the time spent (possibly compiling and) executing these modules is pure waste. To improve startup time, some large Python CLIs make imports lazy by manually placing imports inline into functions to delay imports of expensive subsystems. This manual approach is labor-intensive and fragile; one misplaced import or refactor can easily undo painstaking optimization work.

The Python standard library already includes built-in support for lazy imports, via importlib.util.LazyLoader . There are also third-party packages such as demandimport . These provide a “lazy module object” which delays its own import until first attribute access. This is not sufficient to make all imports lazy: imports such as from foo import a, b will still eagerly import the module foo since they immediately access an attribute from it.

It also imposes noticeable runtime overhead on every module attribute access, since it requires a Python-level __getattr__ or __getattribute__ implementation. Authors of scientific Python packages have also made extensive use of lazy imports to allow users to write e.g. import scipy as sp and then easily access many different submodules with e.g. sp.linalg , without requiring all the many submodules to be imported up-front.

SPEC 1 codifies this practice in the form of a lazy_loader library that can be used explicitly in a package __init__.py to provide lazily accessible submodules. Users of static typing also have to import names for use in type annotations that may never be used at runtime (if PEP 563 or possibly in future PEP 649 are used to avoid eager runtime evaluation of annotations). Lazy imports are very attractive in this scenario to avoid overhead of unneeded imports.

This PEP proposes a more general and comprehensive solution for lazy imports that can encompass all of the above use cases and does not impose detectable overhead in real-world use. The implementation in this PEP has already demonstrated startup time improvements up to 70% and memory-use reductions up to 40% on real-world Python CLIs. Lazy imports also eliminate most import cycles. With eager imports, “false cycles” can easily occur which are fixed by simply moving an import to the bottom of a module or inline into a function, or switching from from foo import bar to import foo .

With lazy imports, these “cycles” just work. The only cycles which will remain are those where two modules actually each use a name from the other at module level; these “true” cycles are only fixable by refactoring the classes or functions involved. Rationale The aim of this feature is to make imports transparently lazy. “Lazy” means that the import of a module (execution of the module body and addition of the module object to sys.modules ) should not occur until the module (or a name imported from it) is actually referenced during execution.

“Transparent” means that besides the delayed import (and necessarily observable effects of that, such as delayed import side effects and changes to sys.modules ), there is no other observable change in behavior: the imported object is present in the module namespace as normal and is transparently loaded whenever first used: its status as a “lazy imported object” is not directly observable from Python or from C extension code.

The requirement that the imported object be present in the module namespace as usual, even before the import has actually occurred, means that we need some kind of “lazy object” placeholder to represent the not-yet-imported object. The transparency requirement dictates that this placeholder must never be visible to Python code; any reference to it must trigger the import and replace it with the real imported object.

Given the possibility that Python (or C extension) code may pull objects directly out of a module __dict__ , the only way to reliably prevent accidental leakage of lazy objects is to have the dictionary itself be responsible to ensure resolution of lazy objects on lookup. When a lookup finds that the key references a lazy object, it resolves the lazy object immediately before returning it. To avoid side effects mutating dictionaries midway through iteration, all lazy objects in a dictionary are resolved prior to starting an iteration; this could incur a performance penalty when using bulk iterations ( iter(dict) , reversed(dict) , dict.__reversed__() , dict.keys() , iter(dict.keys()) and reversed(dict.keys()) ).

To avoid this performance penalty on the vast majority of dictionaries, which never contain any lazy objects, we steal a bit from the dk_kind field for a new dk_lazy_imports flag to keep track of whether a dictionary may contain lazy objects or not. This implementation comprehensively prevents leakage of lazy objects, ensuring they are always resolved to the real imported object before anyone can get hold of them for any use, while avoiding any significant performance impact on dictionaries in general.

Specification Lazy imports are opt-in, and they can be globally enabled either via a new -L flag to the Python interpreter, or via a call to a new importlib.set_lazy_imports() function. This function takes two arguments, a boolean enabled and an excluding container. If enabled is true, lazy imports will be turned on from that point forward. If it is false, they will be turned off from that point forward. (Use of the excluding keyword is discussed below under “Per-module opt-out.”) When the flag -L is passed to the Python interpreter, a new sys.flags.lazy_imports is set to True , otherwise it exists as False .

This flag is used to propagate -L to new Python subprocesses. The flag in sys.flags.lazy_imports does not necessarily reflect

The rest of this page is on the live site.