Skip to content

Repository files navigation

lazyimports

A backport of Python 3.15's lazy import statement for older Python versions.

On Python 3.15+, you can write:

lazyimportnumpylazyfromos.pathimportjoin

This package provides the same deferred-import behaviour on every supported Python version (3.6 through 3.15) via a small, focused API.

Why?

Deferring heavy imports until they are actually needed can noticeably speed up module load times and reduce memory usage — useful for CLIs, plugins, and any code path that imports optional dependencies.

Installation

pip install python-lazyimports

Usage

Lazy import

fromlazyimportsimportlazy_importnp=lazy_import("numpy") # not imported yetpd=lazy_import("pandas") # not imported yet# ``numpy`` is loaded on first attribute access:arr=np.array([1, 2, 3])

Lazy from X import Y

fromlazyimportsimportlazy_fromjoin, basename=lazy_from("os.path", "join", "basename")
result=join("a", "b") # os.path is imported here

Grouping with lazy()

fromlazyimportsimportlazy, lazy_importwithlazy():
np=lazy_import("numpy")
pd=lazy_import("pandas")
tf=lazy_import("tensorflow")
# None of the modules are imported until first use.

Inspecting and forcing load

fromlazyimportsimportis_lazy, force_loadproxy=lazy_import("json")
assertis_lazy(proxy)
assertnotis_lazy(json) # False for already-imported modulesreal=force_load(proxy) # resolve now and return the real module

API

See the main documentation

Python 3.15+ native syntax

When you are running on Python 3.15+, you may prefer the native syntax. The package's own API still works identically, so you can use either:

# Native (Python 3.15+ only):lazyimportnumpy# Cross-version equivalent via this package:fromlazyimportsimportlazy_importnumpy=lazy_import("numpy")

Compatibility

  • Python 3.6 through 3.15
  • No third-party dependencies — uses only the standard library (contextlib, importlib, sys, types)

Running the tests

python -m unittest test_lazyimports -v

Retired

This project will reach its end-of-life around October 1, 2031 — the official EOL date of Python 3.15 — and the exact timeline could be slightly delayed. We plan to ship the final stable release in November 2031. After this release, all support will cease and the repository will be officially archived, as this library is developed solely to bring lazy import compatibility to Python 3.15 and older versions.

License

MIT

About

Backport of Python 3.15's lazy import statement

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages