|
25 | 25 | """ |
26 | 26 |
|
27 | 27 | import functools |
| 28 | +import importlib |
28 | 29 | import sys |
29 | 30 | from collections.abc import Callable, Mapping |
30 | 31 |
|
@@ -58,6 +59,90 @@ class PhysicsCfg(PresetCfg): |
58 | 59 | pass |
59 | 60 |
|
60 | 61 |
|
| 62 | +class _OptionalPreset: |
| 63 | + """Lazy preset alternative backed by an optional import.""" |
| 64 | + |
| 65 | + __slots__ = ("import_path", "install_hint", "kwargs", "preset_name") |
| 66 | + |
| 67 | + def __init__( |
| 68 | + self, |
| 69 | + import_path: str, |
| 70 | + preset_name: str, |
| 71 | + install_hint: str | None = None, |
| 72 | + kwargs: dict[str, object] | None = None, |
| 73 | + ): |
| 74 | + self.import_path = import_path |
| 75 | + self.preset_name = preset_name |
| 76 | + self.install_hint = install_hint |
| 77 | + self.kwargs = kwargs or {} |
| 78 | + |
| 79 | + def __eq__(self, other: object) -> bool: |
| 80 | + return ( |
| 81 | + isinstance(other, _OptionalPreset) |
| 82 | + and self.import_path == other.import_path |
| 83 | + and self.preset_name == other.preset_name |
| 84 | + and self.install_hint == other.install_hint |
| 85 | + and self.kwargs == other.kwargs |
| 86 | + ) |
| 87 | + |
| 88 | + def load(self) -> object: |
| 89 | + module_name, _, attr_name = self.import_path.partition(":") |
| 90 | + try: |
| 91 | + module = importlib.import_module(module_name) |
| 92 | + cfg_cls = getattr(module, attr_name) |
| 93 | + except ModuleNotFoundError as exc: |
| 94 | + raise ModuleNotFoundError(self._format_error(exc)) from exc |
| 95 | + except (AttributeError, ImportError) as exc: |
| 96 | + raise ImportError(self._format_error(exc)) from exc |
| 97 | + return cfg_cls(**self.kwargs) |
| 98 | + |
| 99 | + def _format_error(self, exc: Exception) -> str: |
| 100 | + message = ( |
| 101 | + f"Preset '{self.preset_name}' requires optional config '{self.import_path}', but it could not be imported." |
| 102 | + ) |
| 103 | + if self.install_hint: |
| 104 | + message += f" {self.install_hint}" |
| 105 | + message += f" Original error: {exc}" |
| 106 | + return message |
| 107 | + |
| 108 | + |
| 109 | +def optional_preset( |
| 110 | + import_path: str, |
| 111 | + *, |
| 112 | + preset_name: str | None = None, |
| 113 | + install_hint: str | None = None, |
| 114 | + **kwargs: object, |
| 115 | +) -> _OptionalPreset: |
| 116 | + """Create a lazy preset alternative for an optional package. |
| 117 | +
|
| 118 | + The target class is imported and instantiated only when the preset is selected. |
| 119 | + This lets default task configs advertise optional presets without importing |
| 120 | + optional packages during normal config loading. |
| 121 | +
|
| 122 | + Args: |
| 123 | + import_path: Import path in ``"module:ClassName"`` form. |
| 124 | + preset_name: User-facing preset name for error messages. Defaults to the |
| 125 | + imported class name. |
| 126 | + install_hint: Optional guidance appended to import errors. |
| 127 | + **kwargs: Keyword arguments forwarded to the imported config class. |
| 128 | +
|
| 129 | + Returns: |
| 130 | + A lazy preset alternative that can be used as a :class:`PresetCfg` field. |
| 131 | +
|
| 132 | + Raises: |
| 133 | + ValueError: If :attr:`import_path` is not in ``"module:ClassName"`` form. |
| 134 | + """ |
| 135 | + module_name, sep, attr_name = import_path.partition(":") |
| 136 | + if not sep or not module_name or not attr_name: |
| 137 | + raise ValueError(f"Optional preset import path must use 'module:ClassName' form, got: {import_path!r}.") |
| 138 | + return _OptionalPreset(import_path, preset_name or attr_name, install_hint, kwargs) |
| 139 | + |
| 140 | + |
| 141 | +def _materialize_optional_preset(value) -> object: |
| 142 | + """Instantiate an optional preset if needed.""" |
| 143 | + return value.load() if isinstance(value, _OptionalPreset) else value |
| 144 | + |
| 145 | + |
61 | 146 | def preset(**options) -> PresetCfg: |
62 | 147 | """Create a :class:`PresetCfg` instance from keyword arguments. |
63 | 148 |
|
@@ -179,9 +264,9 @@ def _pick_alternative(preset_obj: PresetCfg, selected: set[str], path: str = "") |
179 | 264 | fields = _preset_fields(preset_obj) |
180 | 265 | for name in selected: |
181 | 266 | if name in fields: |
182 | | - return fields[name] |
| 267 | + return _materialize_optional_preset(fields[name]) |
183 | 268 | if "default" in fields: |
184 | | - return fields["default"] |
| 269 | + return _materialize_optional_preset(fields["default"]) |
185 | 270 | raise ValueError( |
186 | 271 | f"PresetCfg {type(preset_obj).__name__} at '{path}' has no 'default' field " |
187 | 272 | f"and none of the selected presets {selected} match its fields {set(fields.keys())}." |
@@ -522,7 +607,7 @@ def _path_reachable(sec: str, path: str) -> bool: |
522 | 607 | for full_path in sorted(resolved, key=lambda fp: fp.count(".")): |
523 | 608 | sec, path, name = resolved[full_path] |
524 | 609 | if cfgs[sec] is not None and _path_reachable(sec, path): |
525 | | - node = presets[sec][path][name] |
| 610 | + node = _materialize_optional_preset(presets[sec][path][name]) |
526 | 611 | node_dict = ( |
527 | 612 | node.to_dict() if hasattr(node, "to_dict") else dict(node) if isinstance(node, Mapping) else node |
528 | 613 | ) |
|
0 commit comments