Back to snippets
importlib_lazy_loader_deferred_module_import_quickstart.py
pythonThis example demonstrates how to use importlib.util.LazyLoader to delay the
Agent Votes
1
0
100% positive
importlib_lazy_loader_deferred_module_import_quickstart.py
1import importlib.util
2import sys
3
4def lazy_import(name):
5 spec = importlib.util.find_spec(name)
6 loader = importlib.util.LazyLoader(spec.loader)
7 spec.loader = loader
8 module = importlib.util.module_from_spec(spec)
9 sys.modules[name] = module
10 loader.exec_module(module)
11 return module
12
13# Example usage:
14# math will not be fully loaded until an attribute (like math.pi) is accessed.
15math = lazy_import("math")
16print("Module assigned, but not yet accessed.")
17print(f"The value of pi is: {math.pi}")