Types¶
Haiway's types package contains the low-level primitives that support State, schema generation,
metadata handling, and immutable value objects. Most applications use these types indirectly through
State, but understanding them helps when you need custom metadata, three-state optional values, or
standalone immutable containers.
Overview¶
The package groups into four areas:
- JSON-like value aliases:
RawValue,BasicValue,BasicObject,FlatObject - Sentinel and defaults:
Missing,Default,DefaultFactory,DefaultEnv,DefaultValue - Immutable containers:
Map,Meta - Annotation metadata:
Alias,Description,Specification,TypeSpecification
All of them are exported from haiway.
JSON-Compatible Value Aliases¶
Use the aliases from haiway.types.basic when you need precise public types for JSON-like payloads:
RawValueisstr | float | int | bool | NoneBasicValueis recursive: raw values, nested mappings, and nested sequencesBasicObjectisMapping[str, BasicValue]FlatObjectisMapping[str, RawValue]
FlatObject is useful for headers, message attributes, and similar payloads where nested structures
are intentionally forbidden.
Converting to Basic Values¶
State.to_basic_object(), State.to_json(), and Meta validation all share one conversion into
this representation. Each leaf is encoded to the spelling the matching attribute validation reads
back, so a converted value can be validated into the type it came from - with two exceptions: the
mapping keys which spell alike once encoded, see the limitation below, and a union with an
alternative taking the encoded value as it is, which wins whatever its position. str | UUID
holding a UUID reads back the str it is written as, and so does a datetime, Path or bytes
next to str; through JSON, str | Color reads Color.RED back as the str "red" and
int | Num an IntEnum member as its int:
| Type | Basic value |
|---|---|
str, int, float, bool |
unchanged |
None, StrEnum, IntEnum |
unchanged |
UUID |
str(value) |
datetime, date, time |
value.isoformat() |
Path |
value.as_posix() |
bytes, bytearray, memoryview |
base64 encoded str |
Nested State instances, dataclasses, mappings, sequences and sets are converted as the value graph
is traversed, into Map and tuple instances. Mapping keys go through the same table and are then
spelled the way JSON spells them - a str result is used as is, int and float become the number
as json.dumps writes it (int.__repr__, float.__repr__), and bool and None become "true",
"false" and "null". That is the spelling json.dumps gives those keys on its own, so payloads
which already encoded keep the output they had - except for infinite and NaN float keys, written
as "inf", "-inf" and "nan" where json.dumps writes "Infinity", "-Infinity" and "NaN".
Only "inf", "-inf" and "nan" are read back. Two keys which are spelled the same -
{1: "a", "1": "b"} - raise ValueError.
Float values are not converted: to_basic_object keeps an infinite or NaN float as it is, and
from_mapping reads it back. JSON has no spelling for it, so to_json raises ValueError and
from_json refuses the constants NaN, Infinity and -Infinity and a number such as 1e400
beyond what a float holds.
from collections.abc import Mapping
from datetime import UTC, datetime
from uuid import UUID
from haiway import State
class Event(State):
identifier: UUID
created: datetime
class Journal(State):
events: Mapping[UUID, Event]
event = Event(identifier=UUID(int=1), created=datetime(2026, 1, 2, tzinfo=UTC))
event.to_basic_object()
# {"identifier": "00000000-0000-0000-0000-000000000001", "created": "2026-01-02T00:00:00+00:00"}
# keys are converted too, so a mapping json could not key encodes now
Journal(events={UUID(int=1): event}).to_json()
# '{"events":{"00000000-0000-0000-0000-000000000001":{"identifier":"000...",...}}}'
Keys spelled alike, such as None and "null" or 1 and "1", raise ValueError as described
above. A JSON document which repeats a key - {"a": 1, "a": 2} - is read as json.loads reads it,
the last one winning.
Anything else - a plain Enum, a Decimal, Missing held within a value - has no basic spelling
the validation would read back. Rather than encoding it into a value which could only fail on the
way in, to_basic_object raises TypeError naming the path and the type, never the value.
to_json leaves such values unchanged instead, so a custom encoder_class still gets to handle
them. An attribute of a State set to Missing is different: it is left out of the result
altogether.
Missing Values with Missing¶
Missing is Haiway's explicit "not provided" sentinel. It is different from None:
Nonemeans a value was provided and that value is nullMissingmeans no value was provided at all
Like None, Missing is both the value and its type - a builtin PEP 661 sentinel. A parameter
which may be left out is annotated int | Missing and defaults to Missing. It is the one instance
there is, kept as itself when copied or pickled, and is always compared by identity:
value is Missing. Unlike None it is truthy, so never test it with if value:.
from haiway import Missing
def normalize(value: str | Missing) -> str:
if value is Missing:
return "fallback"
return value.upper() # narrowed to `str` by the identity check alone
assert normalize(Missing) == "fallback"
Use Missing in state field types when you need three states: present, null, and omitted:
from haiway import Missing, State
class Patch(State):
name: str | Missing = Missing
note: str | Missing | None = Missing
assert Patch(note=None).to_mapping() == {"note": None} # `name` was never provided
Within a match statement refer to it through a module - case haiway.Missing: - since a bare
case Missing: is a capture pattern, binding the value to a new variable named Missing.
Defaults with Default¶
Default(...) is a typed wrapper used by State fields.
from uuid import uuid4
from haiway import Default, State
class RequestContext(State):
request_id: str = Default(factory=lambda: uuid4().hex)
retries: int = Default(3)
DefaultFactory(fn, *args, **kwargs) calls fn with the given arguments for every new instance, so
no lambda is needed:
from datetime import UTC, datetime
from haiway import DefaultFactory, State
class Audit(State):
created_at: datetime = DefaultFactory(datetime.now, UTC)
DefaultEnv reads a default from an environment variable. What happens when it is not set has to be
stated: fallback is the value used instead (Missing makes it optional) and required=True
raises instead. mapping converts the raw string to the type of the field:
from haiway import DefaultEnv, State, parse_bool
class ServiceConfig(State):
host: str = DefaultEnv("SERVICE_HOST", fallback="localhost")
port: int = DefaultEnv("SERVICE_PORT", mapping=int, fallback=8080)
tracing: bool = DefaultEnv("SERVICE_TRACING", mapping=parse_bool, fallback=False)
token: str = DefaultEnv("SERVICE_TOKEN", required=True)
Important behavior:
- Literal defaults are reused as-is
- Factories are called for each new instance
- Environment-backed defaults are read during instance construction, not at import time, so
load_env()applies regardless of import order - A
required=Truevariable that is not set fails construction, naming the variable Default(...)is a field specifier, not a runtime descriptor
Frozen records¶
Haiway has no separate frozen-record base class - a value which has to be validated, compared and
serialized is a State. A small record which has to hold what it is given as it is - callables,
clients, anything a State would validate or copy - is a final, slotted class which binds its
values once and refuses to rebind or delete them:
from collections.abc import Callable
from typing import Any, NoReturn, final
@final
class RetryPolicy:
attempts: int
backoff_seconds: float
on_retry: Callable[[int], None] | None
__slots__ = ("attempts", "backoff_seconds", "on_retry")
def __init__(
self,
*,
backoff_seconds: float,
attempts: int = 3,
on_retry: Callable[[int], None] | None = None,
) -> None:
object.__setattr__(self, "attempts", attempts)
object.__setattr__(self, "backoff_seconds", backoff_seconds)
object.__setattr__(self, "on_retry", on_retry)
def __setattr__(self, name: str, value: Any) -> NoReturn:
raise AttributeError(f"Can't modify immutable RetryPolicy, attribute - '{name}'")
def __delattr__(self, name: str) -> NoReturn:
raise AttributeError(f"Can't modify immutable RetryPolicy, attribute - '{name}'")
Equality and hashing stay by identity, so a record holding a callable or a mutable value still
hashes. Nothing is validated or copied - a list it was given stays mutable. Note that
object.__setattr__ can still rebind an attribute of such a class, which a State refuses. An
object whose internals change after it is made, like a client opening its connection or a response
caching its body, is a plain class with __slots__.
Map¶
Map[K, V] is an immutable mapping with JSON helpers. It subclasses the builtin frozendict, so it
can't be mutated through the dict methods either. It is therefore not a dict, and {} | map is
a plain dict (Meta is built the same way and behaves the same, {} | meta included):
from haiway import Map
mapping = Map({"a": 1})
merged = mapping | {"b": 2}
assert isinstance(merged, Map)
assert merged == {"a": 1, "b": 2}
Mutation methods such as update, pop, and item assignment raise AttributeError.
Map.to_json() writes compact JSON, with no space after , and :, and raises ValueError for an
infinite or NaN float value. Map.from_json() refuses the constants NaN, Infinity and
-Infinity and a number such as 1e400 beyond what a float holds, as State does. The keys are
written by json.dumps as they are, so unlike the keys of a State they are not checked for two
spelled alike, and an infinite float key raises.
Use Map when you want an immutable mapping outside State, or when you want to document that a
function returns a read-only mapping value concretely.
Meta¶
Meta is a specialized immutable metadata mapping built on the same JSON-compatible value model. It
adds:
- validation and normalization through
Meta.of(...),Meta.from_mapping(...), andMeta.from_json(...) - convenience accessors such as
.kind,.name,.description,.identifier,.error,.created,.last_updated, and.tags - typed getters for arbitrary keys -
.get_str(...),.get_int(...),.get_float(...),.get_bool(...),.get_uuid(...), and.get_datetime(...)- each raisingTypeErrorwhen the stored value has a different type - builder-style methods such as
.with_tags(...),.with_error(...),.with_created(...),.merged_with(...), and.excluding(...)
from haiway import Meta
meta = Meta.of(
kind="dataset",
tags=("exports", "pii"),
payload={"owner": "ops", "versions": [1, 2]},
)
assert meta.tags == ("exports", "pii")
assert meta["payload"]["versions"] == (1, 2)
Normalization rules:
- lists become tuples
- nested mappings become
Map - values with a basic spelling are coerced to it - a
datetimebecomes its ISO string, aUUIDbecomesstr(value)- see Converting to Basic Values - values without one raise
TypeError - keys stay strictly
str, there is no spelling to coerce them to
Meta.empty is a shared empty instance returned by Meta.of(None).
Accessors normalize on read rather than storing rich types: .error stores the stringified message
under "error" and returns it wrapped in a plain Exception, so the original exception type does
not survive a round trip.
meta = Meta.empty.with_error(ValueError("quota exceeded"))
assert meta["error"] == "quota exceeded"
assert isinstance(meta.error, Exception)
Meta.to_json() and Meta.from_json() are as strict as the ones of Map: compact output, no
infinite or NaN float written and none of NaN, Infinity, -Infinity or 1e400 read.
One subtlety matters: direct Meta({...}) construction does not recursively validate or normalize
values on its own. Use the factory helpers when the input comes from user code, JSON, or mutable
objects.
Annotation Metadata¶
Haiway consumes several types through typing.Annotated[...] when resolving State fields:
Alias("external_name")changes the externally exposed field nameDescription("...")adds human-readable schema/documentation text to an attribute; thedescription="..."class keyword ofStatedoes the same for the type itselfSpecification({...})provides a manual JSON-schema-like overrideMeta.of(...)attaches structured metadata to the resolved attribute definitionValidator(callable)applies an additional validation or coercion step before the base type validation runsVerifier(callable)applies an additional check after the base type has been validated; it has to return the value, which is what the attribute then holds. Several validators, or several verifiers, of one attribute compose in the order they are declared
from typing import Annotated
from haiway import Alias, Description, Meta, Specification, State
class Invoice(State):
customer_id: Annotated[
str,
Alias("customer"),
Description("Public customer identifier"),
Meta.of(tags=("billing",)),
Specification({"type": "string"}),
]
These annotations feed both runtime validation metadata and generated state schemas.
Type Specifications¶
TypeSpecification is a typed union of JSON-schema-like TypedDict shapes. Specification is a
thin typed wrapper around one of those shapes so it can be attached inside typing.Annotated[...].
This is intentionally lightweight:
- Haiway keeps the structure typed
- schema fragments are composed by the attribute system
Specification(...)does not deeply validate every schema keyword
Use it when inference is insufficient or when a type is intentionally represented differently in the generated schema.