Skip to content

State Management

Haiway's state management system is built around the State class, which provides immutable, type-safe data structures with validation. Unlike traditional mutable objects, State instances cannot be modified after creation, ensuring predictable behavior, especially in concurrent environments. This guide explains how to effectively use the State class to manage your application's data.

Defining State Classes

State classes are defined by subclassing the State base class and declaring typed attributes:

from haiway import State
from uuid import UUID
from datetime import datetime

class User(State):
    id: UUID
    name: str
    email: str | None = None
    created_at: datetime

Key features of State class definitions:

  • Type Annotations: All attributes must have type annotations
  • Optional Attributes: Provide default values for optional attributes
  • Immutability: All instances are immutable once created
  • Validation: Values are validated against their type annotations at creation time
  • Metadata Support: Attach aliases, descriptions, specifications, and validators via typing.Annotated

Creating State Instances

State instances are created using standard constructor syntax:

from uuid import uuid4
from datetime import datetime

user = User(
    id=uuid4(),
    name="Alice Smith",
    created_at=datetime.now()
)

All required attributes must be provided, and all values are validated against their type annotations. If a value fails validation, an exception will be raised.

Default Values and Lazy Initialization

Use the Default helpers when a field needs to be computed lazily or resolved from the environment: Default takes a literal or a factory, DefaultFactory calls a function with arguments and DefaultEnv reads an environment variable. Each returns a DefaultValue container that the State runtime resolves while creating each instance. A plain default is one value shared by every instance, so a mutable one - a list, dict, set or bytearray, or a subclass of them, also given as Default([]) - is refused when the class is created: use DefaultFactory(list) or Default(factory=...), or an immutable value ((), frozenset(), Map()):

from datetime import UTC, datetime
from uuid import uuid4
from haiway import Default, DefaultEnv, DefaultFactory, State

class ServiceConfig(State):
    correlation_id: str = Default(factory=lambda: uuid4().hex)
    timeout_seconds: float = Default(1.5)  # literal defaults still work
    started_at: datetime = DefaultFactory(datetime.now, UTC)  # factory with its arguments
    region: str = DefaultEnv("SERVICE_REGION", fallback="local")  # environment variable

config = ServiceConfig()
assert isinstance(config.correlation_id, str)

Factories are called every time a new instance is created, so each ServiceConfig receives its own identifier. DefaultEnv defaults are also read during construction, so tests stay deterministic: set the environment variable before instantiating the state or pass an explicit value in the constructor. An unset variable needs either a fallback (Missing makes the value optional) or required=True, which fails construction naming the variable.

Immutability and Updates

State instances are immutable, so you cannot modify them directly:

user.name = "Bob"  # Raises AttributeError

Instead, create new instances with updated values using the updating method:

updated_user = user.updating(name="Bob Smith")

This creates a new instance with the updated value, leaving the original instance unchanged. The updating method accepts keyword arguments for any attributes you want to change.

Attribute Metadata with typing.Annotated

Haiway uses typing.Annotated to attach field-level metadata that controls how attributes are validated, exposed, and documented. Combine your base type with one or more annotations:

from typing import Annotated
from haiway import Alias, Description, Sensitive, Specification, State, Validator

def ensure_positive(value: int) -> int:
    if value <= 0:
        raise ValueError("value must be positive")
    return value

class Invoice(State):
    # Externally exposed as "customer_id" when encoding/decoding mappings or JSON.
    customer: Annotated[str, Alias("customer_id"), Description("Public customer identifier")]
    total_cents: Annotated[int, Specification({"type": "integer", "minimum": 0}), Validator(ensure_positive)]
    notes: Annotated[str | None, Description("Free-form note about the invoice")] = None
    # Kept out of every rendered representation, including logs.
    payment_token: Annotated[str, Sensitive()] = ""

Supported annotations include:

  • Alias("external_name") — maps the attribute to an alternate key when using to_mapping, from_mapping, JSON helpers, and updating. Both the name and the alias are accepted as input, but giving the same attribute under both of them is refused with a TypeError.
  • Description("text") — surfaces in generated JSON schemas and downstream documentation. To describe the State type itself use the description="..." class keyword (see JSON Schema Generation).
  • Meta.of({...}) — attaches structured metadata that you can later inspect from field definitions.
  • Specification({...}) — overrides the JSON Schema fragment when the inferred schema is insufficient.
  • Validator(callable) — applies additional validation or coercion logic before the base attribute validation runs. It always receives the raw input, including for nested State attributes and for custom classes providing their own validate, which validate the value afterwards.
  • Verifier(callable) — applies an additional check after the base attribute has been validated and typed. It has to return the value - what it returns is what the attribute holds, so a verifier which only checks and returns nothing stores None. Raise to reject.
  • Sensitive — marks the attribute as carrying a secret or personal data. str(), repr(), and format_str render <redacted> instead of the value, which keeps it out of logs and observability backends. The class and Sensitive() mark the attribute alike; pass a custom marker
  • Sensitive(redaction="<api-key>") - when the shape of the omission is worth keeping.

Marking an attribute sensitive covers rendering only: attribute access, to_mapping, to_json, and the generated JSON schema all keep working on the real value, so persistence and outgoing requests are unaffected. Review those call sites separately when handling secrets.

Several Validators, or several Verifiers, of one attribute compose in the order they are declared: each is given what the previous one returned, and a failure of any stops the rest and is reported at the position of the attribute. Validators all run before the base validation, verifiers all after it - writing a verifier before a validator changes nothing. Declarations nested through Annotated or a type alias read inner first: given type Checked = Annotated[int, Validator(a)], Annotated[Checked, Validator(b)] runs a and then b.

typing.NotRequired[T] belongs to TypedDict definitions embedded in State fields. It is refused with a TypeError on an attribute of a State itself, which has no default - validation would still require the value, so the annotation would promise what the class does not do. Give the attribute a default, or accept Missing (int | Missing), to make it optional.

typing.ReadOnly (PEP 705) is accepted in a TypedDict and on an attribute and is resolved as the type it qualifies - it only matters to a type checker, as State attributes are immutable anyway.

Structured Metadata with Meta

Use the Meta container when you need immutable, JSON-compatible metadata on either a field itself or on the annotations that describe it. Prefer Meta.of(...), Meta.from_mapping(...), or Meta.from_json(...) when constructing metadata: those entry points validate values, convert sequences to tuples, and convert nested mappings to immutable Map instances. Meta also exposes convenience accessors such as .kind, .tags, .has_tags(...), and .with_identifier(...).

from typing import Annotated
from haiway import Description, Meta, State

class Dataset(State):
    meta: Meta = Meta.of(kind="dataset", tags=("exports",))
    export_path: Annotated[
        str,
        Description("S3 key for the generated export"),
        Meta.of(tags=("pii", "s3")),
    ]

Meta.of(...) accepts either an existing mapping or keyword arguments, and you can combine builders. For example, Meta.of(kind="dataset").with_last_updated(timestamp) returns a new instance with the timestamp recorded. When no metadata is provided, Haiway uses the shared Meta.empty, so Meta.of(None) is Meta.empty.

To inspect metadata added through annotations, read it from the resolved attribute definition:

fields = Dataset.__SELF_ATTRIBUTE__.attributes
path_meta = fields["export_path"].meta
assert path_meta.has_tags(("pii",))

Metadata values are limited to strings, numbers, booleans, None, sequences, and nested mappings. Passing unsupported objects through the validating constructors raises a TypeError, which keeps emitted schemas and observability events consistent. Direct Meta({...}) construction preserves the underlying dict behavior and does not perform recursive validation on its own, so use the factory helpers when the input is external or mutable.

Generic State Classes

State supports generic type parameters, allowing you to create reusable containers:

from typing import TypeVar
from haiway import State

T = TypeVar('T')

class Container[T](State):
    value: T

# Create specialized instances
int_container = Container[int](value=42)
str_container = Container[str](value="hello")

The type parameter is enforced during validation:

int_container.updating(value="string")  # Raises ValidationError

Each specialization is a distinct class - Container[int] is not Container[str] - while the relation between the arguments is preserved: Container[Dog] is a subclass of Container[Animal] when Dog inherits from Animal, also through nested arguments such as Container[Container[Dog]]. isinstance(Container(value=1), Container[int]) checks the held values of an unspecialized instance against the arguments. The relation is the one validation keeps, not the one of the language: a bool is no int and a datetime no date to an annotation, so Container[bool] is not a subclass of Container[int] and Container(value=True) is no instance of it.

Bounds and constraints of the type parameters are checked when the class is specialized. A class which is not specialized takes a parameter for its bound, or for any one of its constraints (class Con[T: (int, str)] accepts an int or a str and refuses 1.5):

class Shelf[T: Animal](State):
    item: T

Shelf[Dog]  # fine
Shelf[int]  # raises TypeError - T is bound to Animal

Defaults of type parameters

A type parameter may declare a default (PEP 696). Leaving the argument out of a specialization uses it, and the variant is the same class however it is spelled:

class Pair[A, B = str](State):
    first: A
    second: B

assert Pair[int] is Pair[int, str]

An unspecialized generic stands for its defaults, so Pair(first=1, second=2) fails validation because second is a str. A parameter without a default stands for its bound, or for any value.

Variadic parameters and parameter specifications

A TypeVarTuple binds the arguments the other parameters leave over, and each position of a tuple[*Ts] attribute is validated against its own argument. A ParamSpec is given the signature it stands for, written as a list of types or as ..., and a Callable[P, R] attribute then has to be given a callable taking those arguments - Handler[[int], bool](call=lambda: True) is refused as Callable[[int], bool] is:

class Row[*Ts](State):
    cells: tuple[*Ts]

Row[int, str](cells=(1, "a"))  # validated position by position

class Handler[**P, R](State):
    call: Callable[P, R]

Handler[[int], bool](call=lambda value: value > 0)

A tuple may hold one unbounded part, written *tuple[X, ...] or as an unspecialized or open-specialized *Ts, with elements before and after it - tuple[Leaf, *tuple[int, ...], str] takes a Leaf, any number of integers and a str. The elements around it are validated by position, counting from the end for those which follow it, and the ones in between against X (any value for an unspecialized *Ts). An unpacked fixed tuple such as *tuple[int, str], or a type alias of one, is spliced in. A second unbounded part is refused, and so is ... as an argument of a TypeVarTuple: Row[int, ...] is spelled Row[*tuple[int, ...]]. A default such as *Ts = *tuple[int, ...] binds as an argument does.

Recursive generics

A generic refers to itself with its own parameters, in the order they are declared - Tree[V] within Tree[V] is the class itself, as Self is, and so are Pair[K, V], Row[*Ts] and Handler[P, R] given theirs. Any other specialization of it within its own declaration, such as Pair[B, A] within Pair[A, B] or Tree[int] within Tree[V], is refused with a TypeError - the class does not exist yet. A recursive State can also refer to itself through a type alias, either a plain one or a generic one whose type parameters stand for the own parameters of the class, as in the snippet below. The other parameters of a generic alias are not bound to the arguments it is given - one is looked up by its name among the parameters of the class using the alias, standing for anything where the class has none of that name - so such an alias should not be relied on to constrain them:

from collections.abc import Sequence

class Tree[V](State):
    value: V
    children: Sequence[Tree[V]] = ()  # the same as Sequence[Self]

Tree[int](value=1, children=({"value": 2},))  # the child is a Tree[int]
Tree(value="a", children=({"value": 1},))  # not specialized, it is a Tree of anything

type Forest[V] = Sequence[Node[V]]

class Node[V](State):
    value: V
    children: Forest[V] = ()

Variance

Whether Box[Dog] is a subclass of Box[Animal] follows the variance of the parameter. A declared one is honored, so a TypeVar("T", contravariant=True) reverses the relation. A parameter whose variance is inferred, as in class Box[T], is worked out from the attributes using it: read from only, it is covariant, which is all an immutable State can do with a value. Used as an argument of a callable attribute it is contravariant, and used both ways it is invariant - neither variant is a subclass of the other.

State Classes Are Final

A State class that declares attributes cannot be inherited from:

class User(State):
    name: str

class Admin(User):  # TypeError - User declares attributes
    privileges: Sequence[str]

Nor can a State have more than one base. State is for passing state around, not for building objects out of mixins, so a class inherits from a single State - plus Generic, which a class declaring type parameters gets - and anything else is refused:

class Named:
    def label(self) -> str: ...

class Item(State, Named):  # TypeError - a State inherits from a single State
    name: str

The values of a State live inline in the instance, right after its header, so a base which brings slots, a __dict__ or a layout of its own (as int does) could never be combined with it safely anyway.

Slots, defaults, annotations, and type arguments are all resolved once, when the class is created, and the nominal identity that equality, instance checks, and schema generation rely on assumes they describe the whole class. There are three ways to get what inheritance would have given you:

# 1. parametrize a generic State to type a variant of it
class Container[T](State):
    value: T

IntContainer = Container[int]

# 2. inherit from an attribute-less base to share behavior - this is what
#    `Configuration` is, and why configuration classes may still subclass it
class Behavior(State):
    def described(self) -> str:
        return f"{self.__class__.__name__}"

class Concrete(Behavior):
    value: int

# 3. hold an instance as an attribute to reuse its attributes
class Admin(State):
    user: User
    privileges: Sequence[str]

A specialization such as Container[int] declares the attributes of its origin, so it is final too - it names a typed variant rather than opening a base to derive from.

Copying, Pickling and Representation

copy.copy returns the same instance, copy.deepcopy creates an equal one, and copy.replace (or updating) produces a validated variant. A deep copy is built once its values are copied, so the code copying them never sees an instance with some of its attributes missing, while a value referring back to the instance - through a list held in an Any attribute, say - refers to the copy in turn. pickle is deliberately not supported and raises a TypeError pointing at to_json / to_basic_object - rebuilding a State would have to skip validation, and a specialized variant such as Box[int] has no importable name. This also applies to values crossing a process pool.

str(state) renders values as they read (User(name: Alice)), while repr(state) spells each value with its own repr (User(name: 'Alice')) so a string and a number can be told apart. Attributes marked Sensitive render their redaction in both. inspect.signature(User) lists the attributes as keyword-only parameters.

Conversion to Mappings and JSON

You can convert a State instance to a dictionary using the to_mapping method:

user_dict = user.to_mapping()
# {"id": UUID('...'), "name": "Alice Smith", "email": None, "created_at": datetime(...)}

# Only the State itself is converted, the nested ones are kept as they are
user_dict = user.to_mapping(recursive=False)

The conversion is recursive by default (recursive=True): nested States and the States within collections become mappings as well, while the values which are not States - UUID, datetime, bytes - are kept as they are. This is useful for serialization or when you need to work with plain dictionaries.

When working with external payloads, use the complementary helpers:

  • State.from_mapping(value, /, *, ignore_extra=False) — accepts both attribute names and aliases. A key which is neither is refused, in nested States and TypedDicts as well; see ignore_extra below. A State refuses such a key the same way wherever it is given - the constructor, updating(), validate and the decoding helpers - with Unexpected attribute 'x' for Name (Unexpected attributes 'a', 'b' for Name for several of them in the constructor and updating()).
  • State.from_json(value, /, decoder=json.JSONDecoder, *, ignore_extra=False) / State.from_json_array(...) of the same parameters — decode a JSON str or bytes into a State instance (or a sequence of instances). decoder is a json.JSONDecoder class, and a custom one is read through the standard library. Validation errors are converted into informative exceptions.
  • state.to_json(indent=2) — encode a State instance to JSON using the same alias behaviour as to_mapping. Without indent the JSON is compact, with no space after , and :.
  • The JSON State writes and reads is strict. A float value which is infinite or NaN is not JSON, so to_json raises ValueError for it wherever it is - an attribute, an Any, a nested container - and from_json and from_json_array refuse the constants NaN, Infinity and -Infinity, and a number beyond what a float holds (1e400), wherever they are, a key skipped by ignore_extra included. A custom decoder is given the parse_float and parse_constant which refuse them - it has to accept both and leave them as they are, and one which overrides decode refuses them itself or not at all. Float mapping keys keep the spelling "inf", "-inf" and "nan", and refuse a number beyond what a float holds as well. to_mapping, to_basic_object and from_mapping work on Python values and keep such floats.
  • state.to_basic_object() — convert to a mapping of JSON-compatible values, in memory. Where to_mapping keeps the live UUID, datetime or bytes values, this encodes every leaf and key to the spelling validation reads back, so the result round trips through from_mapping - bar the mapping keys which spell alike once encoded, which can't be told apart afterwards. An attribute with no basic spelling - a plain Enum, a Decimal - raises TypeError naming the path and the type. See Converting to Basic Values, also for the limitation.
  • State.validate(value) — coerce an instance or compatible mapping into the target State type. This is handy when accepting heterogeneous inputs.

By default the decoding helpers refuse a key which is not an attribute: TypeError at the top level of from_mapping and validate, and ValueError from from_json. For a key within a nested State or TypedDict from_mapping and validate raise a ValidationError naming the path, while from_json and from_json_array raise a ValueError with that ValidationError as its __cause__. When the payload comes from a producer you do not control, from_mapping, from_json and from_json_array take a keyword-only ignore_extra flag which skips such keys instead:

from haiway import State


class Account(State):
    id: int
    name: str


payload = '{"id": 42, "name": "Alice", "plan": "pro", "profile": {"theme": "dark"}}'

account = Account.from_json(payload, ignore_extra=True)  # `plan` and `profile` are skipped
account = Account.from_mapping(
    {"id": 42, "name": "Alice", "plan": "pro"},
    ignore_extra=True,
)

The flag applies to that one decode and reaches every nested plain State, sequence, mapping, tuple, union and TypedDict of it. It stops below a class with its own __init__ or validate: those decide for themselves, and what they nest is validated without the flag. A State with a validate of its own is handed the value as it is, so what it does with extra keys is up to it - it may still raise TypeError for them - and one with an __init__ of its own is called without the skipped keys. Missing required attributes and invalid values of known keys still fail. The constructor, updating() and validate keep refusing unknown keys, and a validator which decodes on its own does not inherit the flag. TypedDicts refuse keys they do not declare unless the flag is set, which drops them.

In a union an alternative which takes the value exactly as it is wins first, flag or not: TypedDict | Mapping[str, Any] given {"a": 1, "x": 2} is read as the mapping, with every key. Among the rest the first alternative which validates wins, and with the flag an alternative which fits only because its unknown keys are skipped can drop data - one with nothing but defaults, listed first, matches an object holding nothing but unknown keys and discards them all, though it still refuses an invalid value of a key it knows. List the most specific alternative first, or tell them apart with a Literal attribute.

Aliases apply consistently across these helpers. For example, the Invoice.customer field above accepts customer or customer_id when instantiating, and invoice.to_mapping() emits {"customer_id": "...", ...}.

Type Validation

State classes perform thorough type validation for all supported Python types:

  • Basic Types: int, str, bool, float, bytes
  • bool accepts True/False, the ints 0 and 1, the floats 0.0, -0.0 and 1.0 and the strings "true"/"false" in any case; any other int (2, -1), any other float, any other string ("1", "yes") is refused.
  • int accepts an int (not a bool) and a float which is a whole number up to 2**53 (read as an int); strings are never parsed, and non-integral floats, NaN, infinities and larger floats are refused. float accepts an int (not a bool) and a float, and refuses strings.
  • StrEnum/IntEnum read a member, then the raw value (a str; an int which is not a bool, or for an IntEnum a float which is a whole number up to 2**53, read as that int), then the name of a member - so a value always wins over a name. A numeric string is no value of an IntEnum.
  • Literal of ints reads the same whole float as the int it equals (Literal[1] given 1.0 is 1); a float never matches a bool literal. In a union the alternative which takes the value as it is wins first, so float | IntEnum given 1.0 stays a float.
  • Mapping keys are strings in JSON, so they are read from the spelling they are written as, and from no other: int keys as canonical decimal integers ("-12", not "+1", "01", " 1", "1_0"), float keys as JSON numbers or as "inf", "-inf" and "nan" (the spelling float.__repr__ gives them, which json.dumps spells "Infinity", "-Infinity" and "NaN" for a key - those are refused), bool keys as "true"/"false", None as "null", Literal keys as the spelling of the literal, enum keys as a value, a number or a name. Two keys which convert to the same one are refused (Mapping[int, str] given {"1": "a", 1: "b"}), and so are two keys which are written the same by to_json and to_basic_object ({1: "a", "1": "b"} raises ValueError).
  • Container Types:
  • Sequence[T]: sequence-like inputs are normalized to immutable tuples
  • Mapping[K, V]: mappings are validated recursively and converted to immutable Map values
  • Set[T]: sets and sequences (a list or tuple, which is what a JSON array is) are normalized to immutable frozensets - a mapping, a dict view, a generator, an iterator and str/bytes are refused
  • tuple[T, ...]: Fixed or variable-length tuples
  • Special Types: UUID, datetime, date, time, timedelta, Path - a datetime is not accepted for date; for datetime | date an ISO string is read as the first alternative which reads it (datetime.fromisoformat reads a date alone), so declare date | datetime to get a date back. timezone and re.Pattern are accepted as well, but have no JSON form and no JSON Schema: a State holding one is not serializable (to_json raises, json_schema() raises TypeError)
  • Union Types: str | None, int | float
  • Literal Types: Literal["a", "b", "c"] - a value has to be of the type of the literal it is equal to, so Literal[1] refuses True, while a whole float such as 1.0 is read as the int it holds. A plain str or int and a StrEnum or IntEnum member equal to it stand for each other, and the literal itself is what gets stored: Literal[Color.RED] reads "red" as Color.RED, Literal["red"] reads Color.RED as "red"
  • Enum Types: Enum, StrEnum, and IntEnum
  • Callable Types: Function types and Protocol interfaces
  • TypedDict: Validates structure with Required/NotRequired fields. A key the TypedDict does not declare is refused (Unexpected key 'x' for Name), unless decoding with ignore_extra=True, which drops it. closed and extra_items of PEP 728 are not honoured: undeclared keys are refused or dropped, never kept or validated against extra_items
  • Nested State Classes: Validates recursively including generic State types
  • Any Type: Accepts any value without validation

Important Typing Requirements

Prefer abstract collection types in public State definitions:

# ✅ Correct - Use abstract types
from collections.abc import Sequence, Mapping, Set

class Config(State):
    items: Sequence[str]        # Not list[str]
    data: Mapping[str, int]     # Not dict[str, int]
    tags: Set[str]              # Not set[str]

# Lists and sets are accepted at runtime and normalized
config = Config(
    items=["a", "b", "c"],      # Becomes ("a", "b", "c")
    data={"key": 1},            # Becomes immutable Map
    tags={"tag1", "tag2"}       # Becomes frozenset({"tag1", "tag2"})
)

# Concrete collection annotations also work, but are less flexible for public APIs
class ConcreteConfig(State):
    items: list[str]
    data: dict[str, int]
    tags: set[str]

This keeps interfaces flexible while preserving predictable runtime behavior. Sequences and sets are wrapped in immutable containers, and mappings are converted to immutable Map objects, so treat them as read-only once they cross a State boundary.

A few validation details matter in practice:

  • Plain Enum fields accept enum members and do not coerce from raw values.

  • StrEnum and IntEnum fields accept both enum members and matching raw string or integer forms.

  • A function field takes a callable only when it can be called the way its annotation says. A Callable[[A, B], R] is called with two arguments by position, so a function taking one, or requiring a third, is refused when the state is created rather than when it is called. A protocol whose only member is __call__ describes a function by that signature: every call it allows - each argument by position or by name where it may be, each default given or left out - has to be one the value takes, so the names of what may be given by name have to match, and a parameter the protocol lets be left out needs a default.

from typing import Protocol

from haiway import State


class Handler(Protocol):
    def __call__(self, request: str, /, retries: int, *, timeout: float = 1.0) -> str: ...


class Service(State):
    handler: Handler


def handle(request: str, /, retries: int, *, timeout: float = 1.0) -> str:
    return request


Service(handler=handle)  # accepted
Service(handler=lambda request, attempts: request)  # refused - `retries` may be given by name

Arguments left open - ..., a ParamSpec, what follows Concatenate[A, P] or *Ts - are not checked, and neither are the types of arguments nor the result. Functions, bound methods, partials and objects with __call__ are read natively; a callable without a signature to read, such as some builtins, is accepted. A partial is checked as the call it makes in the end: what it gives by position and by name is left out, and each functools.Placeholder is an argument the caller gives first, by position only.

from collections.abc import Callable
from functools import Placeholder, partial

from haiway import State


class Scaling(State):
    scale: Callable[[float], float]


def multiply(value: float, factor: float, /) -> float:
    return value * factor


Scaling(scale=partial(multiply, Placeholder, 2.0))  # accepted - called with the value
Scaling(scale=partial(multiply, 2.0, 3.0))  # refused - takes no more arguments
  • Callable and protocol fields do not produce JSON Schema specifications.

  • Validation failures are wrapped in ValidationError, which includes a precise nested path.

JSON Schema Generation

A State with a JSON schema exposes it through the __SPECIFICATION__ attribute, and one without raises a TypeError on reading it. Call State.json_schema(indent=2) when you need a ready-to-serialize schema definition:

schema = Invoice.json_schema(indent=2)

Besides the primitives, the schema covers the standard value types: UUID and date (strings with a format), datetime, time and timedelta (strings with a pattern of their spelling), Path (a plain string), bytes (a base64 string, contentEncoding and a pattern) and sets (arrays). A timedelta is spelled as an ISO 8601 duration such as P1DT2H3M4.5S, with a leading - when negative; years and months are refused because their length depends on the calendar date. Aliases and descriptions propagate into the schema automatically, and any custom Specification overrides are respected. If a State cannot be represented as JSON Schema (for example, when it holds callables), json_schema(required=True) raises a TypeError so you can detect unsupported shapes early.

The schema is strict: it describes the form the State writes, regardless of what decoding is lenient about. It accepts every document the State writes, and refuses what the State refuses wherever JSON Schema can say so. Where it can't, it is the looser of the two - a document which passes the schema can still fail validation, and that is what validation is for. The other way around, the State reads spellings besides the one it writes, which the schema leaves out: a bool from 0, 1 or "true"/"false" in any case, an enum member from its name, the Python names of aliased attributes, and the other forms of a UUID and a date. A bool is {"type": "boolean"} and an enum lists its values alone. What it leaves unsaid is on purpose:

  • Every object of a State or a TypedDict is closed (additionalProperties: false), nested ones too, as strict structured outputs expect. A Mapping is the open object its keys make it, with additionalProperties holding the schema of its values, and Any or object accepts any JSON value - a State holding one can't be used where every object has to be closed.
  • An attribute is required when it can't be left out: it has no default and doesn't accept Missing. An attribute annotated Any, object or X | Missing can be omitted from the input, and is not listed - unless a Validator or a Verifier is declared on it, which may refuse Missing.
  • Missing has no JSON value, so it is not an alternative of a union - int | Missing is an integer, which may be left out of the object.
  • A format is only claimed when everything written fits it - not for datetime and time, which are written without an offset when they have none, and not for timedelta, which is written with a sign when negative and with a fraction of a second. A pattern of the written spelling stands in for it: 2026-01-02T03:04:05 with microseconds and an offset when there are any, 03:04:05 likewise, and the duration P1DT2H3M4.5S with a leading - when negative. bytes is a padded base64 pattern besides contentEncoding, which validators don't check, and a UUID the lowercase hyphenated pattern besides its format.
  • Sets don't claim uniqueItems - elements which differ may be written the same way, and a repeated one is read as a set all the same.
  • A fixed tuple has exactly its length (minItems and maxItems). A tuple with an unbounded part has minItems for the elements around it, and takes what follows its leading elements as any of the types after them, as a schema can't tell the elements at the end from those in the middle.
  • JSON Schema compares numbers by value, so it can't tell 1 from 1.0, and the State reads a whole float as the int it equals for an int, an IntEnum and an int Literal. What remains is the bound: the int schema accepts whole floats beyond 2**53, which the State refuses, and so do the schemas of an IntEnum or a Literal holding a value beyond it. A number beyond what a float holds (1e400) passes a number schema, and the pattern of a float key, while the State refuses it.
  • A UUID and a date are read with UUID(...) and date.fromisoformat, which take more spellings than the uuid and date formats: hex digits without hyphens, braces or the urn:uuid: prefix for a UUID, the basic (20240102) and week (2025-W01-1) forms for a date. The schema refuses those, the State writes the canonical form alone - and so it does for a datetime given as a date alone or a time without seconds, which the State reads.
  • The keys of a mapping which are not strings constrain propertyNames to the way they are spelled where that can be told - int, float, bool, None, UUID, enum and Literal keys - with the exact spellings written, so an enum key is spelled as its values.
  • A Literal of enum members is written as their values, and one of values with no JSON form (a plain Enum member, bytes) leaves the State without a schema.
  • Both the name of an attribute and its alias are accepted as input, while the schema names the alias alone, as additionalProperties is off. A document using the Python names of aliased attributes passes validation and not the schema.

A State can describe itself with the description class keyword. It is kept on the type as __DESCRIPTION__ and written into its schema, so it survives python -OO (which strips docstrings) and a State nested in another one describes itself there as well. A Description on the attribute holding it takes precedence, and a specialization of a generic keeps the description of its origin:

class AssistantConfig(State, description="Settings of the assistant"):
    model: str = "claude-sonnet-5-5"


AssistantConfig.__DESCRIPTION__  # "Settings of the assistant"

When serialization must be guaranteed, mark the class as serializable to enforce schema generation at definition time:

class SerializableInvoice(State, serializable=True):
    id: str
    total: int

Best Practices

  1. Use Immutability: Embrace the immutable nature of State - never try to modify instances.
  2. Make Small States: Keep State classes focused on a single concern.
  3. Provide Defaults: Use default values for optional attributes to make creation easier.
  4. Use Type Annotations: Always provide accurate type annotations for all attributes.
  5. Consistent Updates: Always use updating (or helper functions that call it) for changes.
  6. Composition: Compose complex states from simpler ones.

Path-Based Updates and Requirements

Every State subclass exposes an AttributePath builder via the class attribute _. Paths let you read or update deeply nested values without manually rebuilding intermediate objects, and they work with the same validation rules as regular constructors: an update which validation refuses raises ValidationError naming the whole path from the root (.profile.name, .roles[0]).

from collections.abc import Mapping, Sequence

from haiway import AttributeRequirement, State

class Profile(State):
    name: str
    preferences: Mapping[str, str]

class User(State):
    profile: Profile
    roles: Sequence[str]

user = User(
    profile=Profile(name="Alice", preferences={"locale": "en"}),
    roles=("admin",),
)

# Read a nested value
assert User._.profile.name(user) == "Alice"

# Produce a new instance with an updated nested value
renamed = User._.profile.name(user, "Alicia")
assert renamed.profile.name == "Alicia"

# Combine with AttributeRequirement to assert invariants
AttributeRequirement.equal(
    "admin",
    path=User._.roles[0],
).check(renamed)

AttributeRequirement instances raise a ValueError when a check fails, which makes them useful in tests or guard clauses. Use paths for bulk updates in performance-sensitive code—they only rebuild the segments that actually change.

Paths support nested attribute traversal, indexing into sequences and tuples, mapping access for str and int keys, and optional container access for unions shaped like T | None.

path.components and str(path) use Python attribute names. Fields declared with an Alias are stored under the alias by to_mapping, so queries and filters against stored data should use serialized_components instead. It resolves aliases at every level, keeps mapping keys as strings and sequence indices as integers:

from collections.abc import Sequence
from typing import Annotated

from haiway import Alias, State

class Item(State):
    title: Annotated[str, Alias("t")]

class Order(State):
    items: Annotated[Sequence[Item], Alias("lines")]

path = Order._.items[0].title
assert path.components == ("items", "[0]", "title")
assert path.serialized_components == ("lines", 0, "t")

# the same components locate the value in the serialized form
order = Order(items=(Item(title="Book"),))
stored = order.to_mapping()
assert stored["lines"][0]["t"] == "Book"

located = stored
for component in path.serialized_components:
    located = located[component]
assert located == "Book"

Resolution works through nested State fields, T | None unions, sequences, tuples, mappings, Annotated types, TypedDict and type aliases. A field without an alias keeps its Python name. Mapping keys are always returned as strings, so a Mapping[int, T] key 3 becomes "3", matching the JSON object keys.

Example: Complex State Management

Here's a more complete example showing complex state management:

from haiway import State
from uuid import UUID, uuid4
from datetime import datetime
from collections.abc import Sequence

class Address(State):
    street: str
    city: str
    country: str = "USA"

class Contact(State):
    email: str
    phone: str | None = None

class User(State):
    id: UUID
    name: str
    address: Address
    contact: Contact
    roles: Sequence[str] = ()
    active: bool = True
    created_at: datetime
    updated_at: datetime

# Create an instance
user = User(
    id=uuid4(),
    name="Alice Smith",
    address=Address(
        street="123 Main St",
        city="Springfield",
    ),
    contact=Contact(
        email="alice@example.com",
    ),
    created_at=datetime.now(),
    updated_at=datetime.now(),
)

# Update a simple attribute
user1 = user.updating(name="Alice Johnson")

# Update multiple attributes
user3 = user.updating(
    active=False,
    updated_at=datetime.now(),
)

# Update a nested attribute directly
new_address = user.address.updating(street="456 Oak Ave")
user4 = user.updating(address=new_address)

Native Storage

A compiled extension stores the attributes of a State inline in the instance, validates every built-in annotation, and converts to mappings and JSON natively. It calls into Python for a few values it doesn't make itself: decoding bytes from base64, parsing a timedelta or an ISO datetime, date or time, constructing a UUID or a Path, and validating Meta. The immutability is real - an attribute can't be rebound through object.__setattr__ either, and an instance has no __dict__ or __weakref__. Calling __init__ a second time on an instance raises. The class is just as fixed: once it is created, assigning or deleting one of its attributes raises TypeError, so neither a method nor the descriptor of an attribute can be replaced. Declare everything in the class body - __init_subclass__ of an attribute-less base still runs in time to add to a class. An instance takes the memory a __slots__ object of the same attributes would. One holding nothing which can be part of a reference cycle - which is what validated values are, being made of tuples, frozensets, Maps and other instances - is left out of the collections of the garbage collector, together with those containers, and is reclaimed by reference counting alone. Keeping many instances alive therefore adds nothing for the collector to walk. One holding a mutable value, such as a list in an Any attribute, stays tracked, so a cycle through it is still collected.

An instance whose __init__ did not run - made with __new__, or by a constructor of the class which never delegated - holds no values at all, which is not the same as holding Missing. Reading an attribute of it raises AttributeError, while to_mapping, to_basic_object, to_json, hash, == of two instances, copy.deepcopy and updating raise TypeError saying the instance is not initialized, rather than leaving the attributes out. An instance another thread is initializing is read either whole or not at all, so to_json of it never returns some of the attributes only.

Two instances which are equal have the same hash, for the containers the language compares equal to one of another kind: a Map, a UserDict or a mapping proxy equal to the dict of its items, a frozenset or a dict view equal to a set, a UserList equal to a list, bytes, a bytearray and a memoryview equal to each other, held alone or within tuples, lists and mappings. The hash of such a container is that of the hashable it is rebuilt as, so it changes when a list, dict, set or bytearray an instance holds is mutated - a set or dict holding the instance no longer finds it. A mutable value is only held by an Any, an object or a custom attribute; a typed attribute (Sequence, Mapping, Set) converts it to an immutable tuple, Map or frozenset, so prefer those, or immutable values. Any other value with no hash of its own (__hash__ is None) is left out of the hash, which can only be consistent with its equality if nothing equal to it is hashed; any other failure to hash a value is raised as it is. Comparing with something which is no State leaves the answer to it (instance == mock.ANY is true); another State class is never equal.

Apart from the values it doesn't make itself, what runs Python is the code of the user: a Validator, a Verifier, a class validating itself, a default factory, an __init__ of the class itself. ValidationError reports a failure at its position the same way for every kind. When reading JSON, such code runs only once the whole document has been read - an attribute which can run it, whatever it nests it in (a tuple, a set, a TypedDict, a union or a sequence), is kept as the document spells it until then, while everything which runs none of it is checked on the way. A document which is not JSON never runs it. One which is accepted runs it exactly once, in the order of the attributes, which is not always the order of the keys. One which is refused runs exactly what validating the same document as a mapping runs, cls.validate(json.loads(text)), and never any more: the code which ran before the first failure is not run again by the document being read once more. The failure is reported at its position, the way validating the instance reports it.

to_json, from_json and from_json_array read and write the JSON natively, without the intermediate Python objects - for the default json.JSONEncoder and json.JSONDecoder, and with no indent. A document which is not the usual case, or a value with no native spelling, is read or written through the standard library instead, which is also what reports an error of the document itself. Passing an encoder_class, a decoder or an indent uses the standard library directly. With ignore_extra=True the native reader walks over the values of keys which are not attributes without building them, and the same document is refused for the same reasons as without it - a malformed value of a skipped key is an error too. A custom decoder, or a document the native reader declines, goes through json.loads, which builds every value before validation drops those of unknown keys.

Calling a class with keyword arguments, Point(x=1, y=2), and updating, point.updating(x=3), are the fastest ways to build and change an instance. To build an instance from a mapping use Point.validate(values) rather than unpacking it into the call, Point(**values).

A class whose instances have to change after they are made - a client opening a connection, a response caching its body - is a plain class with __slots__ instead. After changing the C source run make native, as uv sync does not recompile it.

Performance Considerations

While State instances are immutable, creating new instances for updates has minimal overhead as only the changed paths are reconstructed. The validation system is optimized to be fast for typical use cases.

For high-performance scenarios:

  • Keep State classes relatively small and focused
  • Consider using path-based updates for nested changes
  • If needed, batch multiple updates into a single updating call

Integration with Haiway Context

State classes are designed to work seamlessly with Haiway's context system:

from haiway import ctx, State

class AppConfig(State):
    debug: bool = False
    log_level: str = "INFO"

async def main():
    # Provide state to context
    async with ctx.scope("main", AppConfig(debug=True)):
        # Access state from context
        config = ctx.state(AppConfig)

        # Create updated state in nested context
        async with ctx.scope("debug", config.updating(log_level="DEBUG")):
            # Use updated state
            debug_config = ctx.state(AppConfig)
            assert debug_config.log_level == "DEBUG"

This pattern enables effective dependency injection and state propagation throughout your application.