ssapling 0.1.0__py3-none-any.whl

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.
Files changed (61) hide show
  1. ssapling/__init__.py +12 -0
  2. ssapling/core/__init__.py +53 -0
  3. ssapling/core/_declarations.py +139 -0
  4. ssapling/core/_execution.py +155 -0
  5. ssapling/core/_plain.py +37 -0
  6. ssapling/core/_text.py +42 -0
  7. ssapling/core/errors.py +175 -0
  8. ssapling/core/loading.py +205 -0
  9. ssapling/core/registry.py +345 -0
  10. ssapling/core/settings.py +698 -0
  11. ssapling/core/spec.py +98 -0
  12. ssapling/data/__init__.py +89 -0
  13. ssapling/data/_matching.py +22 -0
  14. ssapling/data/batching.py +166 -0
  15. ssapling/data/collections.py +335 -0
  16. ssapling/data/encoding.py +107 -0
  17. ssapling/data/errors.py +104 -0
  18. ssapling/data/provenance.py +94 -0
  19. ssapling/data/records.py +546 -0
  20. ssapling/data/sampling.py +339 -0
  21. ssapling/data/storage.py +569 -0
  22. ssapling/environments/__init__.py +43 -0
  23. ssapling/environments/contracts.py +168 -0
  24. ssapling/environments/errors.py +53 -0
  25. ssapling/environments/runner.py +153 -0
  26. ssapling/environments/types.py +173 -0
  27. ssapling/evaluate/__init__.py +40 -0
  28. ssapling/evaluate/aggregation.py +173 -0
  29. ssapling/evaluate/assessment.py +429 -0
  30. ssapling/evaluate/measurement.py +165 -0
  31. ssapling/interaction/__init__.py +24 -0
  32. ssapling/interaction/episode.py +713 -0
  33. ssapling/interaction/errors.py +21 -0
  34. ssapling/interaction/hosting.py +287 -0
  35. ssapling/models/__init__.py +44 -0
  36. ssapling/models/buffering.py +189 -0
  37. ssapling/models/contracts.py +181 -0
  38. ssapling/models/errors.py +27 -0
  39. ssapling/models/types.py +75 -0
  40. ssapling/py.typed +0 -0
  41. ssapling/registries.py +37 -0
  42. ssapling/tasks/__init__.py +49 -0
  43. ssapling/tasks/contracts.py +137 -0
  44. ssapling/tasks/errors.py +37 -0
  45. ssapling/tasks/types.py +172 -0
  46. ssapling/teachers/__init__.py +34 -0
  47. ssapling/teachers/contracts.py +145 -0
  48. ssapling/teachers/errors.py +80 -0
  49. ssapling/teachers/runner.py +142 -0
  50. ssapling/teachers/types.py +178 -0
  51. ssapling/train/__init__.py +43 -0
  52. ssapling/train/components.py +194 -0
  53. ssapling/train/context.py +169 -0
  54. ssapling/train/errors.py +24 -0
  55. ssapling/train/procedure.py +316 -0
  56. ssapling/train/runner.py +398 -0
  57. ssapling/train/stages.py +463 -0
  58. ssapling-0.1.0.dist-info/METADATA +113 -0
  59. ssapling-0.1.0.dist-info/RECORD +61 -0
  60. ssapling-0.1.0.dist-info/WHEEL +4 -0
  61. ssapling-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,698 @@
1
+ """Settings: what a component declares it accepts, and how supplied values are checked.
2
+
3
+ A component's settings are a standard-library dataclass. Each field is one
4
+ setting: its annotation is the setting's type, its default is the setting's
5
+ default, and ``setting()`` adds a description and constraints::
6
+
7
+ @dataclass(frozen=True)
8
+ class StepwiseTeacherSettings:
9
+ explain: bool = setting(False, description="Explain each correction.")
10
+ max_interventions: int = setting(10, ge=0, description="Interventions per episode.")
11
+
12
+ def validate(self) -> None: # optional: rules that involve several settings
13
+ ...
14
+
15
+ ``validate_settings`` turns plain values, from Python or a file, into a checked
16
+ instance and reports every problem at once. ``settings_to_dict`` turns an
17
+ instance back into plain values. ``settings_schema`` describes the class as JSON
18
+ Schema. ``check_settings_class`` checks the declaration itself; registries call
19
+ it when a component is registered.
20
+
21
+ Supported setting types are ``bool``, ``int``, ``float``, ``str``, ``None``,
22
+ ``Literal[...]``, unions such as ``int | None``, ``list[T]``, ``tuple[T, ...]``,
23
+ fixed tuples such as ``tuple[int, str]``, ``dict[str, T]``, nested settings
24
+ dataclasses, and ``Any``, which accepts any plain value (``None``, booleans,
25
+ numbers, strings, and lists and string-keyed dicts of plain values). Settings
26
+ hold plain values only, never live objects such as an environment or a model.
27
+ """
28
+
29
+ import dataclasses
30
+ import difflib
31
+ import functools
32
+ import operator
33
+ import re
34
+ import types
35
+ import typing
36
+ from collections.abc import Mapping
37
+ from typing import Any, Literal
38
+
39
+ from ._plain import PLAIN, plain_copy
40
+ from ._text import join_path, show, summary
41
+ from .errors import ConfigError, Problem, SettingsDeclarationError
42
+
43
+ __all__ = [
44
+ "check_settings_class",
45
+ "setting",
46
+ "settings_schema",
47
+ "settings_to_dict",
48
+ "validate_settings",
49
+ ]
50
+
51
+ _METADATA_KEY = "ssapling.setting"
52
+ _MISSING: Any = dataclasses.MISSING
53
+
54
+
55
+ # Declaring settings
56
+
57
+
58
+ @dataclasses.dataclass(frozen=True, slots=True, kw_only=True)
59
+ class _SettingInfo:
60
+ description: str | None = None
61
+ ge: float | None = None
62
+ gt: float | None = None
63
+ le: float | None = None
64
+ lt: float | None = None
65
+ min_length: int | None = None
66
+ max_length: int | None = None
67
+ pattern: str | None = None
68
+
69
+
70
+ def setting(
71
+ default: Any = _MISSING,
72
+ *,
73
+ default_factory: Any = _MISSING,
74
+ description: str | None = None,
75
+ ge: float | None = None,
76
+ gt: float | None = None,
77
+ le: float | None = None,
78
+ lt: float | None = None,
79
+ min_length: int | None = None,
80
+ max_length: int | None = None,
81
+ pattern: str | None = None,
82
+ ) -> Any:
83
+ """Declare one setting: a dataclass field with a description and constraints.
84
+
85
+ Args:
86
+ default: The default value. Omit it, and ``default_factory``, to make
87
+ the setting required.
88
+ default_factory: Builds the default, for mutable defaults such as lists.
89
+ description: A short description, exported in the JSON Schema.
90
+ ge, gt, le, lt: Bounds for a number: ``>=``, ``>``, ``<=``, ``<``.
91
+ min_length, max_length: Bounds on the length of a string, list,
92
+ tuple, or dict.
93
+ pattern: A regular expression a string must match in full.
94
+
95
+ Constraints apply to the setting's own value, not to items inside it, and
96
+ are skipped when the value is ``None``. Rules that need more, such as one
97
+ setting depending on another, belong in the class's ``validate()`` method.
98
+ """
99
+ info = _SettingInfo(
100
+ description=description,
101
+ ge=ge,
102
+ gt=gt,
103
+ le=le,
104
+ lt=lt,
105
+ min_length=min_length,
106
+ max_length=max_length,
107
+ pattern=pattern,
108
+ )
109
+ return dataclasses.field(
110
+ default=default, default_factory=default_factory, metadata={_METADATA_KEY: info}
111
+ )
112
+
113
+
114
+ # Types: how one annotation checks a value and describes itself as JSON Schema.
115
+ #
116
+ # ``check`` returns the value converted to the declared type (for example a
117
+ # list into a tuple) and appends a Problem for everything wrong with it.
118
+
119
+
120
+ class _Type:
121
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
122
+ raise NotImplementedError
123
+
124
+ def schema(self) -> dict[str, Any]:
125
+ raise NotImplementedError
126
+
127
+ def describe(self) -> str:
128
+ raise NotImplementedError
129
+
130
+ def kinds(self) -> set[str]:
131
+ """The JSON kinds of value this type accepts: number, string, array, object, ..."""
132
+ raise NotImplementedError
133
+
134
+ def _fail(self, value: Any, path: str, problems: list[Problem]) -> Any:
135
+ problems.append(Problem(path, f"expected {self.describe()}, got {show(value)}"))
136
+ return value
137
+
138
+
139
+ _SCALAR_NAMES: dict[type, str] = {
140
+ bool: "boolean",
141
+ int: "integer",
142
+ float: "number",
143
+ str: "string",
144
+ type(None): "null",
145
+ }
146
+
147
+
148
+ @dataclasses.dataclass(frozen=True)
149
+ class _Scalar(_Type):
150
+ cls: type
151
+
152
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
153
+ is_bool = isinstance(value, bool)
154
+ if self.cls is bool and is_bool:
155
+ return value
156
+ if self.cls is int and isinstance(value, int) and not is_bool:
157
+ return value
158
+ if self.cls is float and isinstance(value, int | float) and not is_bool:
159
+ return float(value)
160
+ if self.cls is str and isinstance(value, str):
161
+ return value
162
+ if self.cls is type(None) and value is None:
163
+ return value
164
+ return self._fail(value, path, problems)
165
+
166
+ def schema(self) -> dict[str, Any]:
167
+ return {"type": _SCALAR_NAMES[self.cls]}
168
+
169
+ def describe(self) -> str:
170
+ return "None" if self.cls is type(None) else self.cls.__name__
171
+
172
+ def kinds(self) -> set[str]:
173
+ return {"number" if self.cls in (int, float) else _SCALAR_NAMES[self.cls]}
174
+
175
+
176
+ @dataclasses.dataclass(frozen=True)
177
+ class _Literal(_Type):
178
+ values: tuple[Any, ...]
179
+
180
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
181
+ # Compare types too, so that True is not accepted for Literal[1].
182
+ if any(type(value) is type(v) and value == v for v in self.values):
183
+ return value
184
+ return self._fail(value, path, problems)
185
+
186
+ def schema(self) -> dict[str, Any]:
187
+ return {"enum": list(self.values)}
188
+
189
+ def describe(self) -> str:
190
+ return "one of " + ", ".join(repr(v) for v in self.values)
191
+
192
+ def kinds(self) -> set[str]:
193
+ return set().union(*(_Scalar(type(v)).kinds() for v in self.values))
194
+
195
+
196
+ @dataclasses.dataclass(frozen=True)
197
+ class _Union(_Type):
198
+ options: tuple[_Type, ...]
199
+
200
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
201
+ for option in self.options:
202
+ attempt: list[Problem] = []
203
+ converted = option.check(value, path, attempt)
204
+ if not attempt:
205
+ return converted
206
+ # For "X | None" with a value that is not None, X's own problems are
207
+ # more useful than "expected X or None".
208
+ non_null = [o for o in self.options if o != _Scalar(type(None))]
209
+ if value is not None and len(non_null) == 1:
210
+ return non_null[0].check(value, path, problems)
211
+ return self._fail(value, path, problems)
212
+
213
+ def schema(self) -> dict[str, Any]:
214
+ return {"anyOf": [option.schema() for option in self.options]}
215
+
216
+ def describe(self) -> str:
217
+ return " or ".join(option.describe() for option in self.options)
218
+
219
+ def kinds(self) -> set[str]:
220
+ return set().union(*(option.kinds() for option in self.options))
221
+
222
+
223
+ @dataclasses.dataclass(frozen=True)
224
+ class _List(_Type):
225
+ item: _Type
226
+
227
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
228
+ if not isinstance(value, list | tuple):
229
+ return self._fail(value, path, problems)
230
+ return [self.item.check(v, f"{path}[{i}]", problems) for i, v in enumerate(value)]
231
+
232
+ def schema(self) -> dict[str, Any]:
233
+ return {"type": "array", "items": self.item.schema()}
234
+
235
+ def describe(self) -> str:
236
+ return f"list of {self.item.describe()}"
237
+
238
+ def kinds(self) -> set[str]:
239
+ return {"array"}
240
+
241
+
242
+ @dataclasses.dataclass(frozen=True)
243
+ class _Tuple(_Type):
244
+ items: tuple[_Type, ...]
245
+ variadic: bool # tuple[T, ...]: any length, every item a T
246
+
247
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
248
+ if not isinstance(value, list | tuple):
249
+ return self._fail(value, path, problems)
250
+ if self.variadic:
251
+ item = self.items[0]
252
+ return tuple(item.check(v, f"{path}[{i}]", problems) for i, v in enumerate(value))
253
+ if len(value) != len(self.items):
254
+ problems.append(Problem(path, f"expected {len(self.items)} items, got {len(value)}"))
255
+ return value
256
+ return tuple(
257
+ t.check(v, f"{path}[{i}]", problems)
258
+ for i, (t, v) in enumerate(zip(self.items, value, strict=True))
259
+ )
260
+
261
+ def schema(self) -> dict[str, Any]:
262
+ if self.variadic:
263
+ return {"type": "array", "items": self.items[0].schema()}
264
+ return {
265
+ "type": "array",
266
+ "prefixItems": [t.schema() for t in self.items],
267
+ "items": False,
268
+ "minItems": len(self.items),
269
+ "maxItems": len(self.items),
270
+ }
271
+
272
+ def describe(self) -> str:
273
+ if self.variadic:
274
+ return f"tuple of {self.items[0].describe()}"
275
+ return f"tuple of ({', '.join(t.describe() for t in self.items)})"
276
+
277
+ def kinds(self) -> set[str]:
278
+ return {"array"}
279
+
280
+
281
+ @dataclasses.dataclass(frozen=True)
282
+ class _Dict(_Type):
283
+ value_type: _Type
284
+
285
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
286
+ if not isinstance(value, Mapping):
287
+ return self._fail(value, path, problems)
288
+ result = {}
289
+ for key, item in value.items():
290
+ if not isinstance(key, str):
291
+ problems.append(Problem(path, f"keys must be strings, got {show(key)}"))
292
+ continue
293
+ result[key] = self.value_type.check(item, join_path(path, key), problems)
294
+ return result
295
+
296
+ def schema(self) -> dict[str, Any]:
297
+ return {"type": "object", "additionalProperties": self.value_type.schema()}
298
+
299
+ def describe(self) -> str:
300
+ return f"dict of str to {self.value_type.describe()}"
301
+
302
+ def kinds(self) -> set[str]:
303
+ return {"object"}
304
+
305
+
306
+ @dataclasses.dataclass(frozen=True)
307
+ class _Plain(_Type):
308
+ """``Any``: any plain value, so settings never hold live objects."""
309
+
310
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
311
+ return plain_copy(value, path, problems)
312
+
313
+ def schema(self) -> dict[str, Any]:
314
+ return {}
315
+
316
+ def describe(self) -> str:
317
+ return PLAIN
318
+
319
+ def kinds(self) -> set[str]:
320
+ return {"null", "boolean", "number", "string", "array", "object"}
321
+
322
+
323
+ @dataclasses.dataclass(frozen=True)
324
+ class _Nested(_Type):
325
+ cls: type
326
+
327
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
328
+ return _validate_into(self.cls, value, path, problems)
329
+
330
+ def schema(self) -> dict[str, Any]:
331
+ return _object_schema(self.cls)
332
+
333
+ def describe(self) -> str:
334
+ return f"{self.cls.__name__} settings"
335
+
336
+ def kinds(self) -> set[str]:
337
+ return {"object"}
338
+
339
+
340
+ def _parse(annotation: Any, path: str, problems: list[Problem]) -> _Type | None:
341
+ """Turn a field's annotation into a _Type, or record why it is unsupported."""
342
+ origin, args = typing.get_origin(annotation), typing.get_args(annotation)
343
+ if annotation is Any:
344
+ return _Plain()
345
+ if annotation in (bool, int, float, str, type(None)):
346
+ return _Scalar(annotation)
347
+ if annotation is None:
348
+ return _Scalar(type(None))
349
+ if origin is Literal:
350
+ if all(v is None or type(v) in (bool, int, str) for v in args):
351
+ return _Literal(args)
352
+ problems.append(Problem(path, "Literal values must be str, int, bool, or None"))
353
+ return None
354
+ if origin in (typing.Union, types.UnionType):
355
+ options = _parse_all(args, path, problems)
356
+ return _Union(options) if options else None
357
+ if origin is list and len(args) == 1:
358
+ item = _parse(args[0], path, problems)
359
+ return _List(item) if item else None
360
+ if origin is tuple and len(args) == 2 and args[1] is Ellipsis:
361
+ item = _parse(args[0], path, problems)
362
+ return _Tuple((item,), variadic=True) if item else None
363
+ if origin is tuple and args:
364
+ items = _parse_all(args, path, problems)
365
+ return _Tuple(items, variadic=False) if items else None
366
+ if origin is dict and len(args) == 2:
367
+ if args[0] is not str:
368
+ problems.append(Problem(path, "dict keys must be str, as in dict[str, int]"))
369
+ return None
370
+ value_type = _parse(args[1], path, problems)
371
+ return _Dict(value_type) if value_type else None
372
+ if annotation in (list, tuple, dict):
373
+ problems.append(
374
+ Problem(path, f"give the item types, as in list[int], not bare {annotation.__name__}")
375
+ )
376
+ return None
377
+ if isinstance(annotation, type) and dataclasses.is_dataclass(annotation):
378
+ try:
379
+ _compile(annotation)
380
+ except SettingsDeclarationError as error:
381
+ problems += [Problem(join_path(path, p.path), p.message) for p in error.problems]
382
+ return None
383
+ return _Nested(annotation)
384
+ problems.append(
385
+ Problem(
386
+ path,
387
+ f"unsupported setting type {annotation!r}; use bool, int, float, str, None, "
388
+ "Literal, a union, list[T], tuple[...], dict[str, T], a settings dataclass, "
389
+ "or Any",
390
+ )
391
+ )
392
+ return None
393
+
394
+
395
+ def _parse_all(
396
+ annotations: tuple[Any, ...], path: str, problems: list[Problem]
397
+ ) -> tuple[_Type, ...] | None:
398
+ """Parse several annotations; None if any of them is unsupported."""
399
+ parsed = [_parse(a, path, problems) for a in annotations]
400
+ supported = tuple(t for t in parsed if t is not None)
401
+ return supported if len(supported) == len(parsed) else None
402
+
403
+
404
+ # Reading a settings class
405
+
406
+
407
+ @dataclasses.dataclass(frozen=True)
408
+ class _Field:
409
+ name: str
410
+ type: _Type
411
+ info: _SettingInfo
412
+ field: dataclasses.Field[Any]
413
+
414
+ @property
415
+ def required(self) -> bool:
416
+ return self.field.default is _MISSING and self.field.default_factory is _MISSING
417
+
418
+ def default(self) -> Any:
419
+ factory: Any = self.field.default_factory
420
+ return self.field.default if factory is _MISSING else factory()
421
+
422
+ def check(self, value: Any, path: str, problems: list[Problem]) -> Any:
423
+ found: list[Problem] = []
424
+ converted = self.type.check(value, path, found)
425
+ if not found:
426
+ found += [Problem(path, m) for m in _constraint_problems(self.info, converted)]
427
+ problems += found
428
+ return converted
429
+
430
+
431
+ @functools.cache
432
+ def _compile(cls: type) -> tuple[_Field, ...]:
433
+ """Read a settings class once: each field's type, constraints, and default."""
434
+ name = getattr(cls, "__qualname__", repr(cls))
435
+ if not (isinstance(cls, type) and dataclasses.is_dataclass(cls)):
436
+ raise SettingsDeclarationError(name, [Problem("", "settings must be a dataclass")])
437
+ try:
438
+ hints = typing.get_type_hints(cls)
439
+ except NameError as error:
440
+ raise SettingsDeclarationError(
441
+ name, [Problem("", f"annotations could not be resolved: {error}")]
442
+ ) from None
443
+
444
+ problems: list[Problem] = []
445
+ fields = []
446
+ for field in dataclasses.fields(cls):
447
+ if not field.init:
448
+ continue
449
+ info = field.metadata.get(_METADATA_KEY, _SettingInfo())
450
+ found: list[Problem] = []
451
+ setting_type = _parse(hints[field.name], field.name, found)
452
+ if setting_type is not None:
453
+ found += _constraint_declaration_problems(field.name, setting_type, info)
454
+ if setting_type is not None and not found:
455
+ compiled = _Field(field.name, setting_type, info, field)
456
+ if not compiled.required:
457
+ bad_default: list[Problem] = []
458
+ compiled.check(compiled.default(), field.name, bad_default)
459
+ found += [Problem(p.path, f"invalid default: {p.message}") for p in bad_default]
460
+ fields.append(compiled)
461
+ problems += found
462
+ if problems:
463
+ raise SettingsDeclarationError(name, problems)
464
+ return tuple(fields)
465
+
466
+
467
+ def _constraint_declaration_problems(
468
+ path: str, setting_type: _Type, info: _SettingInfo
469
+ ) -> list[Problem]:
470
+ kinds = setting_type.kinds()
471
+ problems = []
472
+ numeric = {"ge": info.ge, "gt": info.gt, "le": info.le, "lt": info.lt}
473
+ for name, bound in numeric.items():
474
+ if bound is not None and "number" not in kinds:
475
+ problems.append(
476
+ Problem(path, f"{name}= applies to numbers, not {setting_type.describe()}")
477
+ )
478
+ lengths = {"min_length": info.min_length, "max_length": info.max_length}
479
+ for name, bound in lengths.items():
480
+ if bound is not None and not kinds & {"string", "array", "object"}:
481
+ problems.append(
482
+ Problem(
483
+ path,
484
+ f"{name}= applies to strings, lists, tuples, and dicts, "
485
+ f"not {setting_type.describe()}",
486
+ )
487
+ )
488
+ if info.pattern is not None:
489
+ if "string" not in kinds:
490
+ problems.append(
491
+ Problem(path, f"pattern= applies to strings, not {setting_type.describe()}")
492
+ )
493
+ else:
494
+ try:
495
+ re.compile(info.pattern)
496
+ except re.error as error:
497
+ problems.append(Problem(path, f"pattern {info.pattern!r} is not valid: {error}"))
498
+ return problems
499
+
500
+
501
+ def _constraint_problems(info: _SettingInfo, value: Any) -> list[str]:
502
+ problems = []
503
+ if isinstance(value, int | float) and not isinstance(value, bool):
504
+ bounds = [
505
+ (">=", operator.ge, info.ge),
506
+ (">", operator.gt, info.gt),
507
+ ("<=", operator.le, info.le),
508
+ ("<", operator.lt, info.lt),
509
+ ]
510
+ for symbol, test, bound in bounds:
511
+ # "not test(...)" rather than a reversed test, so that NaN fails every bound.
512
+ if bound is not None and not test(value, bound):
513
+ problems.append(f"must be {symbol} {bound}, got {value!r}")
514
+ if isinstance(value, str | list | tuple | dict):
515
+ unit = "characters" if isinstance(value, str) else "items"
516
+ if info.min_length is not None and len(value) < info.min_length:
517
+ problems.append(f"must have at least {info.min_length} {unit}, got {len(value)}")
518
+ if info.max_length is not None and len(value) > info.max_length:
519
+ problems.append(f"must have at most {info.max_length} {unit}, got {len(value)}")
520
+ if (
521
+ isinstance(value, str)
522
+ and info.pattern is not None
523
+ and not re.fullmatch(info.pattern, value)
524
+ ):
525
+ problems.append(f"must match the pattern {info.pattern!r}, got {value!r}")
526
+ return problems
527
+
528
+
529
+ def check_settings_class(cls: type) -> None:
530
+ """Check that ``cls`` is a settings dataclass SSAPling can validate.
531
+
532
+ Raises:
533
+ SettingsDeclarationError: Listing every problem: unsupported types,
534
+ constraints that do not fit their setting's type, invalid patterns,
535
+ and defaults that fail their own type or constraints.
536
+ """
537
+ _compile(cls)
538
+
539
+
540
+ # Validation
541
+
542
+
543
+ def validate_settings[S](cls: type[S], values: Mapping[str, Any] | S | None = None) -> S:
544
+ """Check supplied settings values and return an instance of ``cls``.
545
+
546
+ ``values`` is a mapping of setting names to plain values (as written in
547
+ Python or loaded from a file), an existing instance of ``cls`` (checked
548
+ again), or ``None`` for all defaults. Omitted settings take their default.
549
+
550
+ Checking covers types, unknown settings, missing required settings,
551
+ constraints declared with ``setting()``, and the class's own ``validate()``
552
+ method, which runs only once everything else passes. It reports every
553
+ problem it finds, each with its path.
554
+
555
+ Raises:
556
+ ConfigError: The values are invalid.
557
+ SettingsDeclarationError: ``cls`` itself is not a valid settings class.
558
+ """
559
+ check_settings_class(cls)
560
+ problems: list[Problem] = []
561
+ result = _validate_into(cls, {} if values is None else values, "", problems)
562
+ if problems:
563
+ raise ConfigError(f"settings for {cls.__qualname__}", problems)
564
+ return typing.cast(S, result)
565
+
566
+
567
+ def _validate_into(cls: type, values: Any, path: str, problems: list[Problem]) -> Any:
568
+ fields = _compile(cls)
569
+ if isinstance(values, cls):
570
+ values = settings_to_dict(values)
571
+ if not isinstance(values, Mapping):
572
+ problems.append(
573
+ Problem(path, f"expected a mapping of {cls.__name__} settings, got {show(values)}")
574
+ )
575
+ return values
576
+
577
+ count_before = len(problems)
578
+ known = [field.name for field in fields]
579
+ for key in values:
580
+ if not isinstance(key, str):
581
+ problems.append(Problem(path, f"setting names must be strings, got {show(key)}"))
582
+ elif key not in known:
583
+ message = "unknown setting"
584
+ close = difflib.get_close_matches(key, known, n=1)
585
+ if close:
586
+ message += f"; did you mean {close[0]!r}?"
587
+ problems.append(Problem(join_path(path, key), f"{message} (known: {', '.join(known)})"))
588
+
589
+ checked = {}
590
+ for field in fields:
591
+ field_path = join_path(path, field.name)
592
+ if field.name in values:
593
+ checked[field.name] = field.check(values[field.name], field_path, problems)
594
+ elif field.required:
595
+ problems.append(Problem(field_path, "missing required setting"))
596
+ if len(problems) > count_before:
597
+ return values
598
+
599
+ try:
600
+ instance = cls(**checked)
601
+ validate = getattr(instance, "validate", None)
602
+ if callable(validate):
603
+ validate()
604
+ except ValueError as error:
605
+ problems.append(Problem(path, str(error)))
606
+ return values
607
+ return instance
608
+
609
+
610
+ # Conversion and schema
611
+
612
+
613
+ def settings_to_dict(settings: object) -> dict[str, Any]:
614
+ """Turn a settings instance into plain values: dicts, lists, and scalars.
615
+
616
+ Nested settings become dicts and tuples become lists, so the result can be
617
+ written as JSON or YAML. ``validate_settings`` turns it back into an equal
618
+ instance.
619
+ """
620
+ if not dataclasses.is_dataclass(settings) or isinstance(settings, type):
621
+ raise TypeError(f"expected a settings dataclass instance, got {show(settings)}")
622
+ return {
623
+ field.name: _plain(getattr(settings, field.name))
624
+ for field in dataclasses.fields(settings)
625
+ if field.init
626
+ }
627
+
628
+
629
+ def _plain(value: Any) -> Any:
630
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
631
+ return settings_to_dict(value)
632
+ if isinstance(value, list | tuple):
633
+ return [_plain(v) for v in value]
634
+ if isinstance(value, Mapping):
635
+ return {k: _plain(v) for k, v in value.items()}
636
+ return value
637
+
638
+
639
+ def settings_schema(cls: type) -> dict[str, Any]:
640
+ """Describe a settings class as JSON Schema (draft 2020-12).
641
+
642
+ The schema includes each setting's type, description, default, and
643
+ constraints, and rejects unknown settings. Rules in ``validate()`` cannot
644
+ be expressed in the schema, so a value that matches the schema can still
645
+ fail ``validate_settings``.
646
+ """
647
+ return {"$schema": "https://json-schema.org/draft/2020-12/schema", **_object_schema(cls)}
648
+
649
+
650
+ def _object_schema(cls: type) -> dict[str, Any]:
651
+ properties = {}
652
+ for field in _compile(cls):
653
+ schema = field.type.schema()
654
+ info = field.info
655
+ if info.description:
656
+ schema["description"] = info.description
657
+ if not field.required:
658
+ schema["default"] = _plain(field.default())
659
+ schema.update(_constraint_schema(info, field.type.kinds()))
660
+ properties[field.name] = schema
661
+
662
+ result: dict[str, Any] = {"title": cls.__name__}
663
+ description = summary(cls)
664
+ if description:
665
+ result["description"] = description
666
+ result |= {"type": "object", "properties": properties, "additionalProperties": False}
667
+ required = [field.name for field in _compile(cls) if field.required]
668
+ if required:
669
+ result["required"] = required
670
+ return result
671
+
672
+
673
+ def _constraint_schema(info: _SettingInfo, kinds: set[str]) -> dict[str, Any]:
674
+ # JSON Schema keywords apply only to their own kind of value (minLength to
675
+ # strings, minItems to arrays, ...), so each is added for every kind the
676
+ # setting accepts.
677
+ keywords: dict[str, Any] = {}
678
+ for keyword, bound in [
679
+ ("minimum", info.ge),
680
+ ("exclusiveMinimum", info.gt),
681
+ ("maximum", info.le),
682
+ ("exclusiveMaximum", info.lt),
683
+ ]:
684
+ if bound is not None:
685
+ keywords[keyword] = bound
686
+ for kind, low, high in [
687
+ ("string", "minLength", "maxLength"),
688
+ ("array", "minItems", "maxItems"),
689
+ ("object", "minProperties", "maxProperties"),
690
+ ]:
691
+ if kind in kinds:
692
+ if info.min_length is not None:
693
+ keywords[low] = info.min_length
694
+ if info.max_length is not None:
695
+ keywords[high] = info.max_length
696
+ if info.pattern is not None:
697
+ keywords["pattern"] = f"^(?:{info.pattern})$"
698
+ return keywords