Lazyimports is a Python module that enables lazy imports using native Python syntax, reducing startup time and improving performance by delaying module loading until needed.
Install lazyimports
via pip:
pip install auto-lazy-imports
Wrap imports in a with
statement to enable lazy loading:
import lazyimports
with lazyimports.lazy_imports():
from package import submodule
submodule.hello()
Note: By default, all modules under the with statement will be lazily loaded. However, you can also explicitly specify which packages to load lazily by providing them as arguments. This is especially useful, if you want to use lazy objects
import lazyimports
with lazyimports.lazy_imports("package:function", "package.subpackage"):
import package.subpackage
from package import function
package.subpackage.hello()
function()
Define lazy-loaded modules and objects in pyproject.toml for package-based usage.
[project.entry-points.lazyimports]
"lazy_modules" = "package,package.submodule"
"lazy_functions" = "package:hello"
"lazy_objects" = "package:array,package:integer"
[tool.poetry.plugins.lazyimports]
"lazy_modules" = "package,package.submodule"
"lazy_functions" = "package:hello"
"lazy_objects" = "package:array,package:integer"
💡 The keys (lazy_modules, lazy_functions, etc.) can be listed in any order, using comma-separated values.
The previous example is also equivalent to:
[project.entry-points.lazyimports]
"custom_key" = "package,package.submodule,package:hello,package:array,package:integer"
After defining the configuration, import modules as usual—no code modifications needed:
from package import submodule
from package import hello
Dynamically enable lazy imports by setting an environment variable:
export PYTHON_LAZY_IMPORTS="package,package.submodule,package:array,package:integer,package:hello"
python script.py