Python lazy imports you can use today | PythonTest
Briefly

Python lazy imports you can use today | PythonTest
"There's a proposal, PEP 810 Explicit lazy imports for Python to natively support lazy importing starting in Python 3.15. However, it has not been accepted yet, and even if it is accepted, 3.15 is a year away. What do we do now? The techniques covered in this post that allow you to use lazy importing NOW with Python 3.13, Python 3.12, , really every version of Python."
"The module mycode.py needs to call a_function from somelib. In order to do so, mycode needs to import somelib. We traditionally put imports at the top of a file at the top level (not in a function). The import somelib will do whatever Python does to import something, and end up with somelib as a name in the global scope of mycode."
Top-level imports execute at module import time, causing heavy initialization and side effects before program logic runs. Example: importing mycode triggers somelib import that sleeps and prints, so somelib runs before main(). Deferring imports into functions delays module loading until the functionality is actually needed. Practical techniques include moving imports inside functions, using importlib.import_module to import on demand, creating lazy proxy modules or import hooks to defer attribute access, and adopting PEP 810 when available. These approaches work on Python 3.13, 3.12, and earlier versions to improve startup latency and avoid unwanted import-time work.
Read at pythontest.com
Unable to calculate read time
[
|
]