An import statement runs as soon as it is reached. The module is located, executed and placed in sys.modules, and the cost is paid whether or not the program ever uses what it imported. For a command-line tool that imports a large library for a single subcommand, every invocation pays for a module that most runs never touch.
For example, importing a module makes it available immediately and also loads it immediately:
import sys
import json
print('json' in sys.modules) # True
print(json.dumps({'a': 1})) # {"a": 1}
The module appears in sys.modules straight after the import statement, before any of its contents are used.
Since Python 3.15, placing the lazy keyword before an import defers the work until the imported name is first accessed.
import sys
lazy import json
print('json' in sys.modules) # False
print(json.dumps({'a': 1})) # {"a": 1}
print('json' in sys.modules) # True
The statement binds a placeholder to the name without loading anything, which is why the first check reports False. Calling json.dumps triggers the import, and from that point the module behaves exactly as a normally imported one, as the final check shows.
There are some notes for lazy imports:
- The
fromform is also supported, written aslazy from json import dumps, loads. Accessing any one of the imported names loads the module. - Lazy imports are permitted only at module level. Using the keyword inside a function, a class body or a
tryblock raisesSyntaxError. - Global lazy loading can be enabled without modifying source code by using
-X lazy_importscommand-line option or thePYTHON_LAZY_IMPORTSenvironment variable. Both support two values:all, which makes all imports lazy by default, andnormal(the default), which respects thelazykeyword in source code.
Leave a Comment
Cancel reply