Skip to content

Commit 9feab7d

Browse files
committed
lazy imports
1 parent 1bcde58 commit 9feab7d

File tree

3 files changed

+37
-10
lines changed

3 files changed

+37
-10
lines changed

python/opengen/__init__.py

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
1-
from . import (
2-
definitions,
3-
builder,
4-
config,
5-
functions,
6-
constraints,
7-
tcp,
8-
ocp,
9-
)
1+
"""Top-level package for OpEn with lazy submodule imports.
2+
3+
This module defers importing heavy subpackages to attribute access
4+
to avoid circular import problems during package initialization.
5+
6+
Lazy submodule imports defer the loading of Python modules and their
7+
attributes until they are first accessed, reducing startup time and
8+
memory usage. This is achieved using PEP 562 (__getattr__ and __dir__)
9+
to intercept attribute access and load the underlying code only when
10+
necessary.
11+
"""
12+
13+
from importlib import import_module
1014

1115
__all__ = [
1216
"definitions",
@@ -17,3 +21,24 @@
1721
"tcp",
1822
"ocp",
1923
]
24+
25+
26+
def __getattr__(name):
27+
"""Lazily import submodules on attribute access.
28+
29+
Example: accessing ``opengen.builder`` will import
30+
``opengen.builder`` and cache it on the package module.
31+
32+
This defers importing heavy subpackages until they're actually used
33+
(lazy imports), reducing startup cost and helping avoid import-time
34+
circular dependencies.
35+
"""
36+
if name in __all__:
37+
module = import_module(f"{__name__}.{name}")
38+
globals()[name] = module
39+
return module
40+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
41+
42+
43+
def __dir__():
44+
return sorted(list(__all__) + list(globals().keys()))

python/opengen/builder/optimizer_builder.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import subprocess
24
import shutil
35
import yaml

python/test/test_constraints.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -623,7 +623,7 @@ def test_dimension_sphere2(self):
623623
# -----------------------------------------------------------------------
624624

625625
def test_zero_dimension(self):
626-
z = og.opengen.constraints.Zero()
626+
z = og.constraints.Zero()
627627
self.assertIsNone(z.dimension())
628628

629629
if __name__ == '__main__':

0 commit comments

Comments
 (0)