schema
Schema validation using dataclasses.
This module provides structured config validation using Python dataclasses. Define configuration schemas with type hints, then validate your YAML configs against them at runtime.
Example
from dataclasses import dataclass
from typing import Optional
from sparkwheel import Config
from sparkwheel.schema import validate
@dataclass
class OptimizerConfig:
lr: float
momentum: float = 0.9
weight_decay: Optional[float] = None
@dataclass
class ModelConfig:
hidden_size: int
num_layers: int
dropout: float
optimizer: OptimizerConfig
# Load and validate config
config = Config.load("config.yaml")
validate(config.get(), ModelConfig) # Raises error if invalid
# Or validate during load
config = Config.load("config.yaml", schema=ModelConfig)
ValidationError
Bases: BaseError
Raised when configuration validation fails.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
Error description |
|
field_path |
Dot-separated path to the invalid field (e.g., "model.optimizer.lr") |
|
expected_type |
The type that was expected |
|
actual_value |
The value that failed validation |
|
source_location |
Optional location in source file where error occurred |
Source code in src/sparkwheel/schema.py
__init__(message, field_path='', expected_type=None, actual_value=None, source_location=None)
Initialize validation error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Human-readable error message |
required |
field_path
|
str
|
Dot-separated path to invalid field |
''
|
expected_type
|
type | None
|
Expected type for the field |
None
|
actual_value
|
Any
|
The actual value that failed validation |
None
|
source_location
|
SourceLocation | None
|
Source location where the invalid value was defined |
None
|
Source code in src/sparkwheel/schema.py
_MissingSentinel
_find_discriminator(union_types)
Find discriminator field in a Union of dataclasses.
A discriminator is a field that: - Exists in all dataclass types in the Union - Has Literal type annotation - Has unique values per type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
union_types
|
tuple[Any, ...]
|
Types in the Union |
required |
Returns:
| Type | Description |
|---|---|
tuple[bool, str | None]
|
(has_discriminator, field_name) |
Source code in src/sparkwheel/schema.py
_format_union_type(types_tuple)
Format a tuple of types as Union[...] for error messages.
Source code in src/sparkwheel/schema.py
_get_source_location(metadata, field_path)
Get source location from metadata registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
Any
|
MetadataRegistry instance |
required |
field_path
|
str
|
Dot-separated field path to look up |
required |
Returns:
| Type | Description |
|---|---|
SourceLocation | None
|
SourceLocation if found, None otherwise |
Source code in src/sparkwheel/schema.py
_get_validators(schema_type)
Get all validator methods from a dataclass.
Source code in src/sparkwheel/schema.py
_is_union_type(origin)
Check if origin is a Union type (handles both typing.Union and types.UnionType).
Source code in src/sparkwheel/schema.py
_run_validators(config, schema, field_path='', metadata=None)
Run all @validator methods on a dataclass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Configuration dict |
required |
schema
|
type
|
Dataclass type |
required |
field_path
|
str
|
Path to this config |
''
|
metadata
|
Any
|
Optional metadata |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If validation fails |
Source code in src/sparkwheel/schema.py
_validate_discriminated_union(value, union_types, discriminator_field, field_path, metadata=None)
Validate a discriminated union by checking the discriminator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to validate (must be dict) |
required |
union_types
|
tuple[Any, ...]
|
Types in the Union |
required |
discriminator_field
|
str
|
Name of discriminator field |
required |
field_path
|
str
|
Path to field |
required |
metadata
|
Any
|
Optional metadata |
None
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If validation fails |
Source code in src/sparkwheel/schema.py
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | |
_validate_field(value, expected_type, field_path, metadata=None, allow_missing=False)
Validate a single field value against its expected type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The value to validate |
required |
expected_type
|
type
|
The expected type (may be generic like list[int]) |
required |
field_path
|
str
|
Dot-separated path to this field |
required |
metadata
|
Any
|
Optional metadata registry for source locations |
None
|
allow_missing
|
bool
|
If True, allow MISSING sentinel values for partial configs |
False
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If validation fails |
Source code in src/sparkwheel/schema.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | |
validate(config, schema, field_path='', metadata=None, allow_missing=False, strict=True)
Validate configuration against a dataclass schema.
Performs recursive type checking to ensure the configuration matches the structure and types defined in the dataclass schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Configuration dictionary to validate |
required |
schema
|
type
|
Dataclass type defining the expected structure |
required |
field_path
|
str
|
Internal parameter for tracking nested field paths |
''
|
metadata
|
Any
|
Optional metadata registry for source locations |
None
|
allow_missing
|
bool
|
If True, allow MISSING sentinel values for partial configs |
False
|
strict
|
bool
|
If True, reject unexpected fields. If False, ignore them. |
True
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If validation fails |
TypeError
|
If schema is not a dataclass |
Example
Source code in src/sparkwheel/schema.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | |
validator(func)
Decorator to mark a method as a validator.
Validators run after type checking and can validate single fields or relationships between fields. Raise ValueError on failure.
Example
@dataclass class Config: lr: float start: int end: int
@validator
def check_lr(self):
if not (0 < self.lr < 1):
raise ValueError("lr must be between 0 and 1")
@validator
def check_range(self):
if self.end <= self.start:
raise ValueError("end must be > start")