04 โ Schema and Payload
Schema declares the allowed shape of a Payload, and is enforced whenever a
State is constructed or forked.
๐ฏ Goal
Validate a document with a nested address object, using unions for optional fields.
๐งฑ The schema
Outer keys inside a Schema tree point at one of:
- a type (
str,int, ...) โ single allowed type - a union (
str | None) โ any of the members - a nested
Schemaโ the value must be a mapping following that sub-schema objectโ unrestricted
โ Valid payloads
๐ฅ Violations
validate_payload raises SchemaError for any of:
| Case | Example | Error |
|---|---|---|
| Undefined key | "phone" not declared |
Invalid path 'phone' not defined in schema |
| Wrong scalar type | "name": 42 |
Path 'user.name' must be str |
| Union violation | "zip": "abc" |
Path 'user.address.zip' must be one of (int, NoneType) |
| Non-container for nested schema | "user": "joe" |
Path 'user' must be a container |
๐ Updates are validated too
State.fork(payload_update=...) calls validate_update, which checks that
every dot-path in the update is declared โ before anything is copied:
๐ Dot-path access
Payload gives typed, immutable access to nested values:
Payload.updateitself is schema-unaware โ the shape check belongs to theState/Schemalayer. UseState.forkwhen you want validation.
๐ก Tips
Schemais immutable and reusable across all state instances.SchemaErrorraised during__post_init__means aStatecan never exist with an invalid payload โ catch it early at construction.- Keep union syntax consistent with your Python version (PEP-604
str | Nonefor 3.10+,Union[str, None]otherwise).