Skip to content

Commit 923b28f

Browse files
committed
lazy loading of modules and exposed utility functions
1 parent fb85f5e commit 923b28f

1 file changed

Lines changed: 44 additions & 8 deletions

File tree

lumispy/__init__.py

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

1919

20+
import importlib
21+
2022
from importlib.metadata import version
2123
from pathlib import Path
22-
23-
from lumispy.utils.axes import nm2eV, eV2nm, nm2invcm, invcm2nm, join_spectra
24-
from lumispy.utils.io import to_array, savetxt
25-
26-
from lumispy import signals, components, utils
27-
28-
from lumispy.utils import crop_edges
24+
from typing import Any
2925

3026

27+
# rresolve version
3128
__version__ = version("lumispy")
3229

3330
# For development version, `setuptools_scm` will be used at build time
@@ -61,5 +58,44 @@
6158
]
6259

6360

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

0 commit comments

Comments
 (0)