Lazy Imports
lazy-imports is a Python library (current version 1.2.0) designed to facilitate lazy loading of modules and symbols, primarily to reduce application startup times. It provides decorators and functions to defer the actual import process until the imported object is first accessed. The library is actively maintained with updates released as needed.
Warnings
- gotcha Lazy imports can interfere with IDE auto-completion, refactoring tools, and static analysis (e.g., MyPy), potentially leading to 'unresolved reference' warnings or missing type hints.
- gotcha Debugging code with lazy imports can be challenging as the actual module import happens at the point of first access, not at the `lazy_import` definition, which can lead to unexpected exceptions or load delays at runtime.
- gotcha While lazy imports can defer the *resolution* of circular dependencies, they do not fundamentally solve circular import *design* issues and can sometimes mask them, leading to runtime errors if not handled carefully.
- gotcha Lazy imports introduce a small, one-time runtime overhead when the imported object is first accessed, as the module must then be loaded. For very frequently accessed or extremely small modules, this overhead might outweigh startup time benefits.
Install
-
pip install lazy-imports
Imports
- lazy_import
from lazy_imports import lazy_import
- lazy_module
from lazy_imports import lazy_module
- lazy_import_all
from lazy_imports import lazy_import_all
Quickstart
from lazy_imports import lazy_import
# Defer import of 'json' module's 'loads' function
# The 'json' module will only be loaded when 'loads' is first called.
loads = lazy_import("json", "loads")
print("json.loads not yet imported...")
data = loads('{"key": "value"}') # The actual 'json' import happens here
print(f"Data loaded: {data}")
# Example with a module (using the decorator)
# from lazy_imports import lazy_module
# @lazy_module("os")
# def get_path_sep():
# return os.path.sep
# print(f"Path separator: {get_path_sep()}")