hydra-qol 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,132 @@
1
+ Metadata-Version: 2.4
2
+ Name: hydra-qol
3
+ Version: 0.1.0
4
+ Summary: Quality-of-life helpers for Hydra: register dataclass configs and check that all YAML config files are valid.
5
+ Keywords: hydra,config,configuration,dataclass,omegaconf
6
+ Author: Thomas M Kehrenberg
7
+ Author-email: Thomas M Kehrenberg <tmke8@posteo.net>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Typing :: Typed
21
+ Requires-Dist: hydra-core>=1.4.0rc1
22
+ Requires-Dist: omegaconf>=2.4
23
+ Requires-Python: >=3.11
24
+ Project-URL: Repository, https://github.com/tmke8/hydra-qol
25
+ Project-URL: Issues, https://github.com/tmke8/hydra-qol/issues
26
+ Description-Content-Type: text/markdown
27
+
28
+ # hydra-qol
29
+
30
+ Quality-of-life helpers for [Hydra](https://hydra.cc): register dataclass-based configs
31
+ in one call, prepare composed configs for logging, and check that *all* YAML config
32
+ files in a project are valid without running any experiments.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ uv add hydra-qol
38
+ # or
39
+ pip install hydra-qol
40
+ ```
41
+
42
+ Requires Python 3.11+, `hydra-core` 1.4+ (a pre-release at the time of writing) and
43
+ `omegaconf` 2.4+.
44
+
45
+ ## What's in the box
46
+
47
+ | Function | Purpose |
48
+ | --- | --- |
49
+ | `register_hydra_config(Config, groups, schema_name=...)` | Stores the main config class and all config-group options in Hydra's `ConfigStore`, after checking the classes for common mistakes. |
50
+ | `prepare_for_logging(hydra_config)` | Turns a composed config into a plain dict (enums → strings, interpolations resolved, subconfigs tagged with their type), ready for `wandb.init(config=...)`. |
51
+ | `check_configs(Config, groups, config_name=..., config_dir=...)` | Composes every YAML file in `config_dir` and instantiates `Config` from it; prints a report and returns an exit code. |
52
+ | `validate_configs(...)` | Same as `check_configs`, but returns a list of `CheckResult` objects instead of printing. Handy in a test suite. |
53
+
54
+ ## Quick start
55
+
56
+ ```python
57
+ # main.py
58
+ import hydra
59
+ from omegaconf import DictConfig, OmegaConf
60
+ from hydra_qol import prepare_for_logging, register_hydra_config
61
+
62
+ from my_project.config import CONFIG_GROUPS, Config
63
+
64
+
65
+ @hydra.main(config_path="configs", config_name="main_config")
66
+ def main(hydra_config: DictConfig) -> None:
67
+ config = OmegaConf.to_object(hydra_config)
68
+ assert isinstance(config, Config)
69
+ config_for_logging = prepare_for_logging(hydra_config)
70
+ ...
71
+
72
+
73
+ if __name__ == "__main__":
74
+ register_hydra_config(Config, CONFIG_GROUPS, schema_name="main_config")
75
+ main()
76
+ ```
77
+
78
+ ```python
79
+ # check_configs.py
80
+ import sys
81
+
82
+ from hydra_qol import check_configs
83
+
84
+ from my_project.config import CONFIG_GROUPS, Config
85
+
86
+ if __name__ == "__main__":
87
+ sys.exit(
88
+ check_configs(
89
+ Config, CONFIG_GROUPS, config_name="main_config", config_dir="configs"
90
+ )
91
+ )
92
+ ```
93
+
94
+ ```
95
+ $ python check_configs.py
96
+ OK dm/celeba_male_smiling.yaml (dm=celeba_male_smiling)
97
+ OK good_run.yaml (--config-name good_run)
98
+ FAIL model/single_linear_layer.yaml (model=single_linear_layer)
99
+ Traceback (most recent call last):
100
+ ...
101
+ hydra.errors.ConfigCompositionException: Could not override 'model.num_hiden'.
102
+
103
+ 1 config file(s) are invalid:
104
+ - model/single_linear_layer.yaml (model=single_linear_layer)
105
+ ```
106
+
107
+ A complete, annotated example project that uses these functions can be found at
108
+ [wearepal/hydra-example](https://github.com/wearepal/hydra-example).
109
+ The full documentation lives in [`docs/`](docs/) and is built with Sphinx:
110
+
111
+ ```bash
112
+ uv sync --group docs
113
+ uv run sphinx-build -b html docs docs/_build/html
114
+ ```
115
+
116
+ ## Development
117
+
118
+ ```bash
119
+ uv sync # installs test, lint and docs dependencies
120
+ uv run pytest
121
+ uv run ruff check && uv run ruff format --check
122
+ uv run ty check
123
+ ```
124
+
125
+ ## Acknowledgements
126
+
127
+ `register_hydra_config` and `prepare_for_logging` originate from
128
+ [ranzen](https://github.com/wearepal/ranzen) (Apache 2.0).
129
+
130
+ ## License
131
+
132
+ Apache 2.0, see [LICENSE](LICENSE).
@@ -0,0 +1,105 @@
1
+ # hydra-qol
2
+
3
+ Quality-of-life helpers for [Hydra](https://hydra.cc): register dataclass-based configs
4
+ in one call, prepare composed configs for logging, and check that *all* YAML config
5
+ files in a project are valid without running any experiments.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ uv add hydra-qol
11
+ # or
12
+ pip install hydra-qol
13
+ ```
14
+
15
+ Requires Python 3.11+, `hydra-core` 1.4+ (a pre-release at the time of writing) and
16
+ `omegaconf` 2.4+.
17
+
18
+ ## What's in the box
19
+
20
+ | Function | Purpose |
21
+ | --- | --- |
22
+ | `register_hydra_config(Config, groups, schema_name=...)` | Stores the main config class and all config-group options in Hydra's `ConfigStore`, after checking the classes for common mistakes. |
23
+ | `prepare_for_logging(hydra_config)` | Turns a composed config into a plain dict (enums → strings, interpolations resolved, subconfigs tagged with their type), ready for `wandb.init(config=...)`. |
24
+ | `check_configs(Config, groups, config_name=..., config_dir=...)` | Composes every YAML file in `config_dir` and instantiates `Config` from it; prints a report and returns an exit code. |
25
+ | `validate_configs(...)` | Same as `check_configs`, but returns a list of `CheckResult` objects instead of printing. Handy in a test suite. |
26
+
27
+ ## Quick start
28
+
29
+ ```python
30
+ # main.py
31
+ import hydra
32
+ from omegaconf import DictConfig, OmegaConf
33
+ from hydra_qol import prepare_for_logging, register_hydra_config
34
+
35
+ from my_project.config import CONFIG_GROUPS, Config
36
+
37
+
38
+ @hydra.main(config_path="configs", config_name="main_config")
39
+ def main(hydra_config: DictConfig) -> None:
40
+ config = OmegaConf.to_object(hydra_config)
41
+ assert isinstance(config, Config)
42
+ config_for_logging = prepare_for_logging(hydra_config)
43
+ ...
44
+
45
+
46
+ if __name__ == "__main__":
47
+ register_hydra_config(Config, CONFIG_GROUPS, schema_name="main_config")
48
+ main()
49
+ ```
50
+
51
+ ```python
52
+ # check_configs.py
53
+ import sys
54
+
55
+ from hydra_qol import check_configs
56
+
57
+ from my_project.config import CONFIG_GROUPS, Config
58
+
59
+ if __name__ == "__main__":
60
+ sys.exit(
61
+ check_configs(
62
+ Config, CONFIG_GROUPS, config_name="main_config", config_dir="configs"
63
+ )
64
+ )
65
+ ```
66
+
67
+ ```
68
+ $ python check_configs.py
69
+ OK dm/celeba_male_smiling.yaml (dm=celeba_male_smiling)
70
+ OK good_run.yaml (--config-name good_run)
71
+ FAIL model/single_linear_layer.yaml (model=single_linear_layer)
72
+ Traceback (most recent call last):
73
+ ...
74
+ hydra.errors.ConfigCompositionException: Could not override 'model.num_hiden'.
75
+
76
+ 1 config file(s) are invalid:
77
+ - model/single_linear_layer.yaml (model=single_linear_layer)
78
+ ```
79
+
80
+ A complete, annotated example project that uses these functions can be found at
81
+ [wearepal/hydra-example](https://github.com/wearepal/hydra-example).
82
+ The full documentation lives in [`docs/`](docs/) and is built with Sphinx:
83
+
84
+ ```bash
85
+ uv sync --group docs
86
+ uv run sphinx-build -b html docs docs/_build/html
87
+ ```
88
+
89
+ ## Development
90
+
91
+ ```bash
92
+ uv sync # installs test, lint and docs dependencies
93
+ uv run pytest
94
+ uv run ruff check && uv run ruff format --check
95
+ uv run ty check
96
+ ```
97
+
98
+ ## Acknowledgements
99
+
100
+ `register_hydra_config` and `prepare_for_logging` originate from
101
+ [ranzen](https://github.com/wearepal/ranzen) (Apache 2.0).
102
+
103
+ ## License
104
+
105
+ Apache 2.0, see [LICENSE](LICENSE).
@@ -0,0 +1,143 @@
1
+ [project]
2
+ name = "hydra-qol"
3
+ version = "0.1.0"
4
+ description = "Quality-of-life helpers for Hydra: register dataclass configs and check that all YAML config files are valid."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = [
10
+ "hydra-core>=1.4.0rc1",
11
+ "omegaconf>=2.4",
12
+ ]
13
+ keywords = [
14
+ "hydra",
15
+ "config",
16
+ "configuration",
17
+ "dataclass",
18
+ "omegaconf",
19
+ ]
20
+ classifiers = [
21
+ "Development Status :: 4 - Beta",
22
+ "Intended Audience :: Developers",
23
+ "Intended Audience :: Science/Research",
24
+ "Operating System :: OS Independent",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Programming Language :: Python :: 3.13",
29
+ "Programming Language :: Python :: 3.14",
30
+ "Topic :: Software Development :: Libraries",
31
+ "Typing :: Typed",
32
+ ]
33
+
34
+ [[project.authors]]
35
+ name = "Thomas M Kehrenberg"
36
+ email = "tmke8@posteo.net"
37
+
38
+ [project.urls]
39
+ Repository = "https://github.com/tmke8/hydra-qol"
40
+ Issues = "https://github.com/tmke8/hydra-qol/issues"
41
+
42
+ [dependency-groups]
43
+ test = ["pytest>=8"]
44
+ lint = [
45
+ "ruff>=0.14",
46
+ "ty",
47
+ ]
48
+ docs = [
49
+ "sphinx>=8",
50
+ "furo",
51
+ ]
52
+
53
+ [[dependency-groups.dev]]
54
+ include-group = "test"
55
+
56
+ [[dependency-groups.dev]]
57
+ include-group = "lint"
58
+
59
+ [[dependency-groups.dev]]
60
+ include-group = "docs"
61
+
62
+ [build-system]
63
+ requires = ["uv_build>=0.9,<0.14"]
64
+ build-backend = "uv_build"
65
+
66
+ [tool.pytest.ini_options]
67
+ testpaths = ["tests"]
68
+ addopts = "-ra"
69
+
70
+ [tool.ty.src]
71
+ include = [
72
+ "src",
73
+ "tests",
74
+ ]
75
+
76
+ [tool.ty.rules]
77
+ disjoint-cast = "warn"
78
+ possibly-missing-attribute = "warn"
79
+ possibly-missing-import = "warn"
80
+ possibly-unresolved-reference = "warn"
81
+ truthiness-test-of-none-union = "warn"
82
+ unsound-assignment = "warn"
83
+ unsound-return-statement = "warn"
84
+
85
+ [tool.ruff]
86
+ line-length = 88
87
+ target-version = "py311"
88
+
89
+ [tool.ruff.format]
90
+ quote-style = "preserve"
91
+
92
+ [tool.ruff.lint]
93
+ select = [
94
+ "ARG",
95
+ "B",
96
+ "C4",
97
+ "E",
98
+ "F",
99
+ "FBT",
100
+ "I",
101
+ "INP",
102
+ "N",
103
+ "PLC",
104
+ "PLE",
105
+ "PLR",
106
+ "PLW",
107
+ "PTH",
108
+ "SIM",
109
+ "UP",
110
+ "W",
111
+ ]
112
+ ignore = [
113
+ "E501",
114
+ "N812",
115
+ "PLR0402",
116
+ "PLR2004",
117
+ "PLR0913",
118
+ "PLW2901",
119
+ "PLC0105",
120
+ "W191",
121
+ ]
122
+
123
+ [tool.ruff.lint.per-file-ignores]
124
+ "__init__.py" = [
125
+ "F403",
126
+ "PLC0414",
127
+ ]
128
+ "docs/conf.py" = ["INP"]
129
+ "tests/**" = ["INP"]
130
+
131
+ [tool.ruff.lint.isort]
132
+ known-third-party = ["hydra"]
133
+ extra-standard-library = ["typing_extensions"]
134
+ no-lines-before = [
135
+ "future",
136
+ "standard-library",
137
+ ]
138
+ force-sort-within-sections = true
139
+ split-on-trailing-comma = false
140
+
141
+ [tool.ruff.lint.pylint]
142
+ max-statements = 60
143
+ max-branches = 13
@@ -0,0 +1,111 @@
1
+ [project]
2
+ name = "hydra-qol"
3
+ version = "0.1.0"
4
+ description = "Quality-of-life helpers for Hydra: register dataclass configs and check that all YAML config files are valid."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Thomas M Kehrenberg", email = "tmke8@posteo.net" }]
9
+ requires-python = ">=3.11"
10
+ dependencies = ["hydra-core>=1.4.0rc1", "omegaconf>=2.4"]
11
+ keywords = ["hydra", "config", "configuration", "dataclass", "omegaconf"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "Intended Audience :: Science/Research",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Programming Language :: Python :: 3.14",
22
+ "Topic :: Software Development :: Libraries",
23
+ "Typing :: Typed",
24
+ ]
25
+
26
+ [project.urls]
27
+ Repository = "https://github.com/tmke8/hydra-qol"
28
+ Issues = "https://github.com/tmke8/hydra-qol/issues"
29
+
30
+ [dependency-groups]
31
+ dev = [{ include-group = "test" }, { include-group = "lint" }, { include-group = "docs" }]
32
+ test = ["pytest>=8"]
33
+ lint = ["ruff>=0.14", "ty"]
34
+ docs = ["sphinx>=8", "furo"]
35
+
36
+ [build-system]
37
+ requires = ["uv_build>=0.9,<0.14"]
38
+ build-backend = "uv_build"
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+ addopts = "-ra"
43
+
44
+ [tool.ty.src]
45
+ include = ["src", "tests"]
46
+
47
+ [tool.ty.rules]
48
+ disjoint-cast = "warn"
49
+ possibly-missing-attribute = "warn"
50
+ possibly-missing-import = "warn"
51
+ possibly-unresolved-reference = "warn"
52
+ truthiness-test-of-none-union = "warn"
53
+ unsound-assignment = "warn"
54
+ unsound-return-statement = "warn"
55
+
56
+ [tool.ruff]
57
+ line-length = 88
58
+ target-version = "py311"
59
+
60
+ [tool.ruff.format]
61
+ quote-style = "preserve"
62
+
63
+ [tool.ruff.lint]
64
+ select = [
65
+ "ARG", # flake8-unused-args
66
+ "B", # bugbear
67
+ "C4", # flake8-comprehensions
68
+ "E", # pycodestyle
69
+ "F", # pyflakes
70
+ "FBT", # boolean trap
71
+ "I", # isort
72
+ "INP", # implicit namespace package
73
+ "N", # pep8-naming
74
+ "PLC", # pylint convention
75
+ "PLE", # pylint error
76
+ "PLR", # pylint refactor
77
+ "PLW", # pylint warning
78
+ "PTH", # flake8-use-pathlib
79
+ "SIM", # flake8-simplify
80
+ "UP", # pyupgrade
81
+ "W",
82
+ ]
83
+ ignore = [
84
+ "E501", # line too long (conflicts with formatter)
85
+ "N812", # case of import alias
86
+ "PLR0402", # useless import alias
87
+ "PLR2004", # magic number comparison
88
+ "PLR0913", # too many arguments
89
+ "PLW2901", # overwriting loop variables
90
+ "PLC0105", # mark variance in typevar name
91
+ "W191", # tab indentation (conflicts with formatter)
92
+ ]
93
+
94
+ [tool.ruff.lint.per-file-ignores]
95
+ "__init__.py" = [
96
+ "F403",
97
+ "PLC0414", # reexporting
98
+ ]
99
+ "docs/conf.py" = ["INP"]
100
+ "tests/**" = ["INP"]
101
+
102
+ [tool.ruff.lint.isort]
103
+ known-third-party = ["hydra"]
104
+ extra-standard-library = ["typing_extensions"]
105
+ no-lines-before = ["future", "standard-library"]
106
+ force-sort-within-sections = true
107
+ split-on-trailing-comma = false
108
+
109
+ [tool.ruff.lint.pylint]
110
+ max-statements = 60 # default: 50
111
+ max-branches = 13 # default: 12
@@ -0,0 +1,30 @@
1
+ """Quality-of-life helpers for `Hydra <https://hydra.cc>`_.
2
+
3
+ The package has two parts:
4
+
5
+ * :func:`register_hydra_config` and :func:`prepare_for_logging` help with setting up
6
+ a dataclass-based configuration (registering the schema and the config groups in
7
+ Hydra's ``ConfigStore``, and turning a composed config into a plain dictionary for
8
+ logging).
9
+ * :func:`check_configs` and :func:`validate_configs` compose every YAML file in a config
10
+ directory and instantiate the config object from it, so that broken config files are
11
+ caught without running any experiments.
12
+ """
13
+
14
+ from .checking import CheckResult as CheckResult
15
+ from .checking import check_configs as check_configs
16
+ from .checking import construct_override as construct_override
17
+ from .checking import to_object as to_object
18
+ from .checking import validate_configs as validate_configs
19
+ from .formatting import prepare_for_logging as prepare_for_logging
20
+ from .registration import register_hydra_config as register_hydra_config
21
+
22
+ __all__ = [
23
+ "CheckResult",
24
+ "check_configs",
25
+ "construct_override",
26
+ "prepare_for_logging",
27
+ "register_hydra_config",
28
+ "to_object",
29
+ "validate_configs",
30
+ ]
@@ -0,0 +1,249 @@
1
+ """Checking that all YAML config files in a directory are valid.
2
+
3
+ YAML config files are not checked by the type checker, so if, for example, a field in
4
+ one of the config dataclasses is renamed, a YAML file that still uses the old name would
5
+ only fail once someone tries to use it. The functions in this module catch that without
6
+ running any experiments: they compose every config file with Hydra (which validates keys
7
+ and value types against the registered dataclasses) and then instantiate the main config
8
+ object from the result.
9
+ """
10
+
11
+ from collections.abc import Sequence
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ import sys
15
+ import traceback
16
+ from typing import Any, TextIO
17
+
18
+ from hydra import compose, initialize_config_dir
19
+ from omegaconf import DictConfig, OmegaConf, open_dict
20
+
21
+ from .registration import register_hydra_config
22
+
23
+ __all__ = [
24
+ "CheckResult",
25
+ "check_configs",
26
+ "construct_override",
27
+ "to_object",
28
+ "validate_configs",
29
+ ]
30
+
31
+ _MISSING = object()
32
+
33
+
34
+ @dataclass(frozen=True, kw_only=True)
35
+ class CheckResult:
36
+ """Outcome of checking a single YAML config file."""
37
+
38
+ path: Path
39
+ """Path of the config file, relative to the config directory."""
40
+ cmdline_arg: str
41
+ """The command-line argument that would select this config file.
42
+
43
+ This is ``--config-name <name>`` for primary configs and ``<group>=<option>`` or
44
+ ``+<group>=<option>`` for config-group options.
45
+ """
46
+ error: Exception | None = None
47
+ """The exception that was raised while composing or instantiating the config, if
48
+ any."""
49
+ traceback: str | None = None
50
+ """The formatted traceback of :attr:`error`, if any."""
51
+
52
+ @property
53
+ def ok(self) -> bool:
54
+ """Whether the config file is valid."""
55
+ return self.error is None
56
+
57
+ @property
58
+ def description(self) -> str:
59
+ """Short, human-readable description of the config file."""
60
+ return f"{self.path.as_posix()} ({self.cmdline_arg})"
61
+
62
+
63
+ def validate_configs(
64
+ main_cls: type,
65
+ groups: dict[str, dict[str, type]],
66
+ *,
67
+ config_name: str,
68
+ config_dir: Path | str,
69
+ ) -> list[CheckResult]:
70
+ """Compose and instantiate every YAML config file in ``config_dir``.
71
+
72
+ First, ``main_cls`` and ``groups`` are registered with
73
+ :func:`~hydra_qol.register_hydra_config` (with ``replace=True``, so that it doesn't
74
+ matter whether the main script already registered them). Then, every ``.yaml``/``.yml`` file below
75
+ ``config_dir`` is composed with Hydra: files at the top level of ``config_dir`` are
76
+ treated as primary configs (``--config-name <name>``), all other files are treated
77
+ as options of a config group (``<group>=<option>``). Finally, the composed config is
78
+ converted to an instance of ``main_cls`` with :func:`to_object`. Any exception
79
+ raised along the way is recorded in the corresponding :class:`CheckResult`.
80
+
81
+ :param main_cls: The main config class; has to be a dataclass.
82
+ :param groups: The config groups, in the same format as expected by
83
+ :func:`~hydra_qol.register_hydra_config`.
84
+ :param config_name: Name of the main schema. This has to match both the
85
+ ``schema_name`` passed to :func:`~hydra_qol.register_hydra_config` and the
86
+ ``config_name`` passed to ``@hydra.main()`` in the main script.
87
+ :param config_dir: The directory containing the YAML config files; the same
88
+ directory as the ``config_path`` passed to ``@hydra.main()``.
89
+ :returns: One :class:`CheckResult` per config file, sorted by path.
90
+ :raises ValueError: If the config classes themselves are malformed (see
91
+ :func:`~hydra_qol.register_hydra_config`).
92
+ """
93
+ config_dir = Path(config_dir).resolve()
94
+ register_hydra_config(main_cls, groups, schema_name=config_name, replace=True)
95
+
96
+ results: list[CheckResult] = []
97
+ with initialize_config_dir(config_dir=str(config_dir)):
98
+ # Groups that are already in the defaults list are overridden with
99
+ # `group=option`, all others have to be appended with `+group=option`.
100
+ base_cfg = compose(config_name, return_hydra_config=True)
101
+ groups_in_defaults = set(base_cfg.hydra.runtime.choices)
102
+
103
+ for path in sorted(config_dir.rglob("*.y*ml")):
104
+ # For each YAML file, we construct an override like `group=sub/config`.
105
+ rel_path = path.relative_to(config_dir)
106
+ name_parts = rel_path.with_suffix("").parts
107
+
108
+ if len(name_parts) == 1:
109
+ # A config at the top level is a primary config.
110
+ primary_config = name_parts[0]
111
+ overrides: list[str] = []
112
+ cmdline_arg = f"--config-name {primary_config}"
113
+ else:
114
+ # Any other config is an option in a config group.
115
+ override = construct_override(name_parts, groups_in_defaults)
116
+ primary_config = config_name
117
+ overrides = [override]
118
+ cmdline_arg = override
119
+
120
+ try:
121
+ cfg = compose(
122
+ primary_config, overrides=overrides, return_hydra_config=True
123
+ )
124
+ config_obj = to_object(cfg)
125
+ if not isinstance(config_obj, main_cls):
126
+ raise TypeError(
127
+ f"Config was not instantiated as `{main_cls.__name__}`, but as "
128
+ f"`{type(config_obj).__name__}`. (Does the primary config "
129
+ f"inherit from `{config_name}` in its defaults list?)"
130
+ )
131
+ except Exception as exc:
132
+ results.append(
133
+ CheckResult(
134
+ path=rel_path,
135
+ cmdline_arg=cmdline_arg,
136
+ error=exc,
137
+ traceback=traceback.format_exc(),
138
+ )
139
+ )
140
+ else:
141
+ results.append(CheckResult(path=rel_path, cmdline_arg=cmdline_arg))
142
+ return results
143
+
144
+
145
+ def check_configs(
146
+ main_cls: type,
147
+ groups: dict[str, dict[str, type]],
148
+ *,
149
+ config_name: str,
150
+ config_dir: Path | str,
151
+ file: TextIO | None = None,
152
+ ) -> int:
153
+ """Check all YAML config files in ``config_dir`` and print a report.
154
+
155
+ This is a thin wrapper around :func:`validate_configs` that prints one line per
156
+ config file (plus the traceback for every failure) and returns an exit code, so
157
+ that it can be used directly in a script::
158
+
159
+ if __name__ == "__main__":
160
+ sys.exit(
161
+ check_configs(
162
+ Config, CONFIG_GROUPS, config_name="main_config", config_dir="configs"
163
+ )
164
+ )
165
+
166
+ :param main_cls: The main config class; has to be a dataclass.
167
+ :param groups: The config groups, in the same format as expected by
168
+ :func:`~hydra_qol.register_hydra_config`.
169
+ :param config_name: Name of the main schema; see :func:`validate_configs`.
170
+ :param config_dir: The directory containing the YAML config files.
171
+ :param file: Where to print the report to; defaults to ``sys.stdout``.
172
+ :returns: ``0`` if all config files are valid, ``1`` otherwise.
173
+ """
174
+ out = sys.stdout if file is None else file
175
+ results = validate_configs(
176
+ main_cls, groups, config_name=config_name, config_dir=config_dir
177
+ )
178
+
179
+ failures = [result for result in results if not result.ok]
180
+ for result in results:
181
+ if result.ok:
182
+ print(f"OK {result.description}", file=out)
183
+ else:
184
+ print(f"FAIL {result.description}", file=out)
185
+ print(result.traceback, file=out)
186
+
187
+ if failures:
188
+ print(f"\n{len(failures)} config file(s) are invalid:", file=out)
189
+ for failure in failures:
190
+ print(f" - {failure.description}", file=out)
191
+ return 1
192
+ print("\nAll config files are valid.", file=out)
193
+ return 0
194
+
195
+
196
+ def construct_override(name_parts: Sequence[str], groups_in_defaults: set[str]) -> str:
197
+ """Construct the command-line override that selects a config-group option.
198
+
199
+ Groups can be nested (e.g. ``hydra/launcher``) and options can contain slashes
200
+ (e.g. ``experiment=cmnist/cnn``), so we pick the longest known group that is a
201
+ prefix of the path and fall back to the top-level directory.
202
+
203
+ :param name_parts: The parts of the path of the config file, relative to the config
204
+ directory and without the file extension; e.g. ``("hydra", "launcher", "slurm")``
205
+ for ``configs/hydra/launcher/slurm.yaml``.
206
+ :param groups_in_defaults: The groups that are already in the defaults list. Options
207
+ of these groups can be selected with ``group=option``; all other groups have to
208
+ be added with ``+group=option``.
209
+ :returns: The override string, e.g. ``"hydra/launcher=slurm"`` or ``"+opt=adamw"``.
210
+ """
211
+ split = next(
212
+ (
213
+ i
214
+ for i in range(len(name_parts) - 1, 0, -1)
215
+ if "/".join(name_parts[:i]) in groups_in_defaults
216
+ ),
217
+ 1,
218
+ )
219
+ group = "/".join(name_parts[:split])
220
+ option = "/".join(name_parts[split:])
221
+ prefix = "" if group in groups_in_defaults else "+"
222
+ return f"{prefix}{group}={option}"
223
+
224
+
225
+ def to_object(cfg: DictConfig) -> Any:
226
+ """Instantiate the config object from a composed config.
227
+
228
+ This mimics what ``@hydra.main()`` does before calling the decorated function
229
+ (removing the ``hydra`` node) and then calls ``OmegaConf.to_object()``. In addition,
230
+ the keys listed under ``hydra.sweeper.params`` are checked for existence, because
231
+ they are just strings in the sweeper config and would otherwise only fail once a
232
+ sweep is started.
233
+
234
+ :param cfg: A config as returned by ``compose(..., return_hydra_config=True)``.
235
+ :returns: The instantiated config object (an instance of the registered schema
236
+ class, if the config was composed from it).
237
+ :raises KeyError: If a key in ``hydra.sweeper.params`` does not exist in the config.
238
+ """
239
+ # Keys that are swept over by the sweeper are just strings in the sweeper config,
240
+ # so we check here that they actually exist in the config.
241
+ if (params := OmegaConf.select(cfg, "hydra.sweeper.params")) is not None:
242
+ for key in params:
243
+ if OmegaConf.select(cfg, key, default=_MISSING) is _MISSING:
244
+ raise KeyError(f"Swept-over key '{key}' does not exist in the config.")
245
+
246
+ # Remove the hydra node (as `@hydra.main` does) and instantiate the dataclasses.
247
+ with open_dict(cfg):
248
+ del cfg["hydra"]
249
+ return OmegaConf.to_object(cfg)
@@ -0,0 +1,53 @@
1
+ """Turning a composed Hydra config into something that is nice to log."""
2
+
3
+ from typing import Any, cast
4
+
5
+ from omegaconf import DictConfig, OmegaConf
6
+
7
+ __all__ = ["prepare_for_logging"]
8
+
9
+
10
+ def prepare_for_logging(
11
+ hydra_config: DictConfig, *, enum_to_str: bool = True
12
+ ) -> dict[str, Any]:
13
+ """Take a Hydra config and make it prettier for logging.
14
+
15
+ Things this function does: turn enums into strings, resolve any interpolations, and
16
+ mark subconfigs with their type. The last point is the main reason to use this
17
+ function: if an entry of the config is a config group with several options (say, a
18
+ ``model`` entry that can be ``fcn`` or ``cnn``), the key of that entry in the
19
+ returned dictionary becomes ``"model/FcnFactory"`` or ``"model/SimpleCNNFactory"``,
20
+ so that the chosen option is visible in the logs.
21
+
22
+ :param hydra_config: The config object as received by the function decorated with
23
+ ``@hydra.main()`` (or as returned by :func:`hydra.compose`).
24
+ :param enum_to_str: Whether to convert enum values to strings (their ``name``).
25
+ :returns: A plain (nested) dictionary with resolved values.
26
+ :raises omegaconf.MissingMandatoryValue: If the config contains an entry that is
27
+ still ``MISSING`` (``???``).
28
+
29
+ :example:
30
+ .. code-block:: python
31
+
32
+ @hydra.main(config_path="configs", config_name="main_config")
33
+ def main(hydra_config: DictConfig) -> None:
34
+ config_for_logging = prepare_for_logging(hydra_config)
35
+ wandb.init(config=config_for_logging)
36
+ """
37
+ raw_config = OmegaConf.to_container(
38
+ hydra_config, throw_on_missing=True, enum_to_str=enum_to_str, resolve=True
39
+ )
40
+ assert isinstance(raw_config, dict)
41
+ raw_config = cast(dict[str, Any], raw_config)
42
+ return {
43
+ f"{key}/{_type_name(dict_)}"
44
+ if isinstance(dict_ := hydra_config[key], DictConfig)
45
+ else key: value
46
+ for key, value in raw_config.items()
47
+ }
48
+
49
+
50
+ def _type_name(cfg: DictConfig) -> str:
51
+ """Name of the dataclass backing a config node (or of the node itself if untyped)."""
52
+ typ = OmegaConf.get_type(cfg)
53
+ return str(typ.__name__) if typ is not None else type(cfg).__name__
File without changes
@@ -0,0 +1,163 @@
1
+ """Registering dataclass-based configs with Hydra's ``ConfigStore``."""
2
+
3
+ import dataclasses
4
+ from dataclasses import MISSING, is_dataclass
5
+ from typing import Any, Final, get_args, get_type_hints
6
+
7
+ from hydra.core.config_store import ConfigStore
8
+
9
+ __all__ = ["register_hydra_config"]
10
+
11
+ _NEED: Final = "there should be"
12
+ _IF: Final = "if an entry has"
13
+
14
+
15
+ def register_hydra_config(
16
+ main_cls: type,
17
+ groups: dict[str, dict[str, type]],
18
+ schema_name: str = "config_schema",
19
+ *,
20
+ replace: bool = False,
21
+ ) -> None:
22
+ """Check the given config classes and store everything in Hydra's ``ConfigStore``.
23
+
24
+ This function performs two tasks: 1) make the necessary calls to ``ConfigStore``
25
+ and 2) run some checks over the given config classes and, if there are problems,
26
+ try to give a nice error message.
27
+
28
+ The checks are based on the following rules:
29
+
30
+ * An entry of type ``Any`` has to have registered variants (an entry in ``groups``)
31
+ and may not have a default value.
32
+ * An entry whose type is a dataclass and which has no default value has to have
33
+ registered variants, and all variants have to be subclasses of the entry's type.
34
+ * An entry whose type is a dataclass and which has a default value may not have
35
+ registered variants.
36
+ * An entry with registered variants has to have a dataclass type or ``Any``
37
+ (unions of dataclasses are not supported by Hydra).
38
+ * Variants may not have generic base classes.
39
+
40
+ :param main_cls: The main config class; has to be a dataclass.
41
+ :param groups: A dictionary that defines all the variants. The keys of the top level
42
+ of the dictionary should correspond to the group names (which are also the
43
+ names of the entries in ``main_cls``), and the keys in the nested dictionaries
44
+ should correspond to the names of the options.
45
+ :param schema_name: Name under which the main schema is stored. This name has to
46
+ be passed as ``config_name`` to ``@hydra.main()`` (or it has to appear in the
47
+ defaults list of a YAML file that is used as the primary config).
48
+ :param replace: What to do if a config with the same name is already registered in
49
+ the ``ConfigStore`` (this happens, for example, if this function is called
50
+ twice). ``False`` (the default) raises a :class:`ValueError`, ``True`` replaces
51
+ the existing config silently. For a normal Hydra app, the default is the right
52
+ choice, because a collision usually means that something is registered twice by
53
+ accident.
54
+ :raises ValueError: If the config is malformed in some way, or on a collision
55
+ with ``replace=False``.
56
+ :raises RuntimeError: If Hydra itself is throwing an error.
57
+
58
+ :example:
59
+ .. code-block:: python
60
+
61
+ @dataclass
62
+ class DataModule:
63
+ root: Path = Path()
64
+
65
+ @dataclass
66
+ class LinearModel:
67
+ dim: int = 256
68
+
69
+ @dataclass
70
+ class CNNModel:
71
+ kernel: int = 3
72
+
73
+ @dataclass
74
+ class Config:
75
+ dm: DataModule = field(default_factory=DataModule)
76
+ model: Any
77
+
78
+ groups = {"model": {"linear": LinearModel, "cnn": CNNModel}}
79
+ register_hydra_config(Config, groups, schema_name="main_config")
80
+ """
81
+ assert isinstance(main_cls, type), "`main_cls` has to be a type."
82
+ if not is_dataclass(main_cls):
83
+ raise ValueError(f"The config class {main_cls.__name__} should be a dataclass.")
84
+ entries = dataclasses.fields(main_cls)
85
+ try:
86
+ types = get_type_hints(main_cls)
87
+ except NameError as exc:
88
+ raise ValueError(
89
+ f"Can't resolve type hints from the config class: `{main_cls.__name__}`."
90
+ ) from exc
91
+
92
+ for entry in entries:
93
+ has_default = (
94
+ entry.default is not MISSING or entry.default_factory is not MISSING
95
+ )
96
+ _check_entry(
97
+ entry.name, types[entry.name], has_default=has_default, groups=groups
98
+ )
99
+
100
+ cs = ConfigStore.instance()
101
+ cs.store(node=main_cls, name=schema_name, replace=replace)
102
+ for group, variants in groups.items():
103
+ for var_name, var_type in variants.items():
104
+ bases = getattr(var_type, "__orig_bases__", None)
105
+ if bases is not None and len(bases) > 0 and len(get_args(bases[0])) > 0:
106
+ raise ValueError(
107
+ f"Can't register a dataclass with generic base class: `{var_type.__name__}`"
108
+ f" with base class `{bases[0].__name__}`."
109
+ )
110
+ try:
111
+ cs.store(node=var_type, name=var_name, group=group, replace=replace)
112
+ except ValueError:
113
+ # A collision with `replace=False`; the message is already descriptive.
114
+ raise
115
+ except Exception as exc:
116
+ raise RuntimeError(
117
+ f"{main_cls=}, {var_type=}, {var_name=}, {group=}"
118
+ ) from exc
119
+
120
+
121
+ def _check_entry(
122
+ name: str, typ: Any, *, has_default: bool, groups: dict[str, dict[str, type]]
123
+ ) -> None:
124
+ """Check a single field of the main config class against the registered variants."""
125
+ group = groups.get(name)
126
+ if typ == Any:
127
+ if group is None:
128
+ raise ValueError(f"{_IF} type `Any`, {_NEED} variants: `{name}`")
129
+ for var_name, var_class in group.items():
130
+ if not is_dataclass(var_class):
131
+ raise ValueError(
132
+ f"All variants should be dataclasses: type `{var_class.__name__}` "
133
+ f"of variant `{name}={var_name}` is not a dataclass."
134
+ )
135
+ if has_default:
136
+ raise ValueError(f"{_IF} type `Any`, {_NEED} no default value: `{name}`")
137
+ elif is_dataclass(typ):
138
+ if has_default:
139
+ if group is not None:
140
+ raise ValueError(
141
+ f"Can't have both a default value and variants: `{name}`."
142
+ )
143
+ elif group is not None:
144
+ for var_name, var_class in group.items():
145
+ if not issubclass(var_class, typ):
146
+ raise ValueError(
147
+ f"All variants should be subclasses of their entry's type: type"
148
+ f" `{var_class.__name__}` of variant `{name}={var_name}` "
149
+ f"is not a subclass of `{typ.__name__}`."
150
+ )
151
+ else:
152
+ raise ValueError(
153
+ f"{_IF} a dataclass type, "
154
+ f"{_NEED} a default value or registered variants: `{name}`. "
155
+ "You can specify a default value with `field(default_factory=...)`."
156
+ )
157
+ elif group is not None:
158
+ raise ValueError(
159
+ f"Entry `{name}` has registered variants, but its type annotation, "
160
+ f"`{getattr(typ, '__name__', str(typ))}`, is not a dataclass. "
161
+ "(Note that unions of dataclasses are not allowed either.) "
162
+ "You can always use `Any` for the type annotation."
163
+ )