Skip to content

Commit 92ab68f

Browse files
committed
lazy loading of modules and exposed utility functions
1 parent fb85f5e commit 92ab68f

1 file changed

Lines changed: 44 additions & 10 deletions

File tree

lumispy/__init__.py

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,13 @@
1717
# along with LumiSpy. If not, see <https://www.gnu.org/licenses/#GPL>.
1818

1919

20-
from importlib.metadata import version
20+
import importlib
2121
from pathlib import Path
22+
from typing import Any
2223

23-
from lumispy.utils.axes import nm2eV, eV2nm, nm2invcm, invcm2nm, join_spectra
24-
from lumispy.utils.io import to_array, savetxt
2524

26-
from lumispy import signals, components, utils
27-
28-
from lumispy.utils import crop_edges
29-
30-
31-
__version__ = version("lumispy")
25+
# rresolve version
26+
__version__ = importlib.metadata.version("lumispy")
3227

3328
# For development version, `setuptools_scm` will be used at build time
3429
# to get the dev version, in case of missing vcs information (git archive,
@@ -61,5 +56,44 @@
6156
]
6257

6358

59+
# Map exported names that will be resolved lazily
60+
_lazy_modules = {
61+
"signals": "lumispy.signals",
62+
"components": "lumispy.components",
63+
"utils": "lumispy.utils",
64+
}
65+
66+
# Map top-level utility names to their submodule and attribute name
67+
_lazy_attributes = {
68+
# name: (module, attribute)
69+
"nm2eV": ("lumispy.utils.axes", "nm2eV"),
70+
"eV2nm": ("lumispy.utils.axes", "eV2nm"),
71+
"nm2invcm": ("lumispy.utils.axes", "nm2invcm"),
72+
"invcm2nm": ("lumispy.utils.axes", "invcm2nm"),
73+
"join_spectra": ("lumispy.utils.axes", "join_spectra"),
74+
"to_array": ("lumispy.utils.io", "to_array"),
75+
"savetxt": ("lumispy.utils.io", "savetxt"),
76+
}
77+
78+
79+
def __getattr__(name: str) -> Any:
80+
"""Lazy-load subpackages and selected attributes on demand."""
81+
# Lazy subpackages
82+
if name in _lazy_modules:
83+
mod = importlib.import_module(_lazy_modules[name])
84+
globals()[name] = mod
85+
return mod
86+
87+
# Lazy attributes (forward from submodules)
88+
if name in _lazy_attributes:
89+
mod_name, attr = _lazy_attributes[name]
90+
mod = importlib.import_module(mod_name)
91+
val = getattr(mod, attr)
92+
globals()[name] = val
93+
return val
94+
95+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
96+
97+
6498
def __dir__():
65-
return sorted(__all__)
99+
return sorted(list(__all__) + list(_lazy_attributes.keys()))

0 commit comments

Comments
 (0)