Makes it easy to load subpackages and functions on demand.
Maintained. Last release 2 months ago, commits in 4 of the last 26 weeks. Weaker on commit activity.
pip install lazy-loaderlazy-loader makes it easy to load subpackages and functions on demand.
Motivation
- Allow subpackages to be made visible to users without incurring import costs.
- Allow external libraries to be imported only when used, improving import times.
For a more detailed discussion, see the SPEC.
Installation
pip install -U lazy-loader
We recommend using lazy-loader with Python >= 3.11.
If using Python 3.11, please upgrade to 3.11.9 or later.
If using Python 3.12, please upgrade to 3.12.3 or later.
These versions avoid a known race condition.
Usage
Lazily load subpackages
Consider the __init__.py from scikit-image:
subpackages = [
...,
'filters',
...
]
import lazy_loader as lazy
__getattr__, __dir__, _ = lazy.attach(__name__, subpackages)
You can now do:
import skimage as ski
ski.filters.gaussian(...)
The filters subpackages will only be loaded once accessed.
Lazily load subpackages and functions
Consider skimage/filters/__init__.py:
from ..util import lazy
__getattr__, __dir__, __all__ = lazy.attach(
__name__,
submodules=['rank'],
submod_attrs={
'_gaussian': ['gaussian', 'difference_of_gaussians'],
'edges': ['sobel', 'scharr', 'prewitt', 'roberts',
'laplace', 'farid']
}
)
The above is equivalent to: