Python 3.15+Modules & importsconstruct
lazy import
import
Lazy import: lazy import x and lazy from m import y postpone loading a module until the name is first used. Speeds up program start.
Syntax
lazy import module
lazy from module import name
lazy is a soft keyword: outside an import line it is an ordinary name. Instead of the module, the name immediately gets a lightweight proxy, and the real load happens on first use, so imports can stay at the top of the file without paying for unused ones. The price is that errors move: a typo in the module name raises ModuleNotFoundError not on the import line but where the name is first used (the traceback shows both lines), and an import cycle raises ImportCycleError. lazy is allowed only at module level: inside a function, class or try/except it is a SyntaxError; lazy from m import * and lazy from __future__ are forbidden too. For code that must also run on older versions there is __lazy_modules__ = ['json'], which makes a plain import json lazy.
Examples
import sys
lazy import json
print('json' in sys.modules) # → False — модуль ещё не загружен
print(json.dumps([1, 2])) # → [1, 2]
print('json' in sys.modules) # → True — загрузка случилась при обращении
lazy import no_such_module_here # ошибки нет: модуль ещё не ищется
print('импорт объявлен') # → импорт объявлен
try:
no_such_module_here.x
except ModuleNotFoundError as e:
print(type(e).__name__) # → ModuleNotFoundError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy