Lazy import#
HyperSpy uses lazy imports to reduce the initial import time and memory footprint, as described in SPEC.
The following patterns are used in HyperSpy for lazy imports:
Libraries such as
scipy,scikit-imageare imported using, for example,import scipyinstead offrom scipy import ndimageto avoid loading submodules until they are needed.Deferring expensive imports, such as
dask,matplotliborpintuntil they are needed inside functions or methods.__getattr__and__dir__are used to implement lazy imports of HyperSpy objects, as described in PEP 562.Lazily the import of signals and define lazy signals in separate modules from their non-signal counterparts to import dask only when needed, for example:
In the module
my_new_signal.pyfrom hyperspy import signals class MyNewSignal(signals.BaseSignal): # all of my great functions.
In the module
lazy_my_new_signal.pyfrom hyperspy import signals from my_package.my_new_signal import MyNewSignal class LazyMyNewSignal(MyNewSignal, signals.LazySignal): """ Lazy signal for my new signal class"""