Skip to content

A module to enable lazy imports using native python syntax

Notifications You must be signed in to change notification settings

hmiladhia/lazyimports

Repository files navigation

Lazyimports

logo

PyPI PyPI - License PyPI - Wheel Tests Copier Ruff

Overview 🌐

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.

Installation 🔨

Install lazyimports via pip:

pip install auto-lazy-imports

Usage 👍

1. Using a with Statement

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()

2. Configuring via pyproject.toml

Define lazy-loaded modules and objects in pyproject.toml for package-based usage.

Standard configuration:

[project.entry-points.lazyimports]
"lazy_modules" = "package,package.submodule"
"lazy_functions" = "package:hello"
"lazy_objects" = "package:array,package:integer"

Poetry-based configuration:

[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

3. Using an Environment Variable (for Development)

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

About

A module to enable lazy imports using native python syntax

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages