Trace Explicit Lazy Import Loading
Core idea
Python 3.15 adds the soft keyword lazy to module-level imports. In normal mode, a lazy import binds a proxy and postpones loading until the name is used. Errors and module initialization side effects can move to the first use. This is a startup optimization, not a guarantee of faster total execution. Python 3.15 was released on 2026-10-09; the target example below is documented but not executed locally.
import sysfrom pathlib import Pathfrom tempfile import TemporaryDirectorytemp = TemporaryDirectory()root = temp.namePath(root, 'bm_migration_demo.py').write_text("print('module loaded')\nvalue = 7\n", encoding='utf-8')sys.path.insert(0, root)# Only fixed, trusted teaching source is imported.lazy import bm_migration_demotry: print('before use') print(bm_migration_demo.value)finally: sys.path.remove(root) sys.modules.pop('bm_migration_demo', None) temp.cleanup()The synthetic module prints its marker at initialization, after the first print. This fixture assumes the normal lazy-import policy and a fresh interpreter.
Documented expected output (target runtime not tested locally):
before usemodule loaded7Use an older on-demand import
def decode(text): import json return json.loads(text)print('before use')print(decode('[3, 5]'))On older interpreters, moving an ordinary import into a function explicitly delays that import statement. It is not the same mechanism as a lazy proxy.
Expected output:
before use[3, 5]Common mistake
Do not place explicit lazy imports inside functions, class bodies or try blocks, and do not use lazy star or future imports. Do not hide required startup checks behind deferred loading. For mixed-version source, use ordinary imports and consider the documented lazy_modules mechanism on 3.15; older parsers cannot parse explicit lazy syntax.
Practice
On 3.15, create a disposable module that emits a fixed marker and compare eager versus lazy loading in two fresh processes. Test a missing optional dependency at first use and record the exception separately from startup.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Python 3.15 lazy imports
Check your understanding of python 3.15 lazy imports.
On Python 3.15 (documented expectation; target runtime not tested locally), what is printed?
lazy import jsonprint(json.loads('[1, 2]'))What is printed?
def f(): import math return math.isqrt(16)print(f())When can a missing lazily imported module first raise an error?
Where can explicit lazy syntax be placed?