pre-alpha

5.4 · Reference

Schemas

hinoki.schema.Schema

Base class for schemas.

class PostCreate(Schema): title: str becomes a frozen, keyword-only dataclass. PostCreate.validate(data) checks decoded JSON strictly: no coercion, unknown keys refused by default, and every problem reported with its path.

__hinoki_schema__ class-attribute

__hinoki_schema__: bool = True

__specs__ class-attribute

__specs__: dict[str, FieldSpec] | None = None

__assigned_field_info__ class-attribute

__assigned_field_info__: dict[str, FieldInfo] = {}

__native__ class-attribute

__native__: CompiledSchema | None = None

__native_dump__ class-attribute

__native_dump__: bool = True

__checks__ class-attribute

__checks__: tuple[
    tuple[str, tuple[str, ...], str], ...
] = ()

__normalizers__ class-attribute

__normalizers__: tuple[tuple[str, str], ...] = ()

__before__ class-attribute

__before__: tuple[str, ...] = ()

__declared_forms__ class-attribute

__declared_forms__: (
    tuple[tuple[str, FieldInfo], ...] | None
) = None

__float_fields__ class-attribute

__float_fields__: (
    tuple[tuple[str, FieldType], ...] | None
) = None

__graph_normalizers__ class-attribute

__graph_normalizers__: bool | None = None

__graph_before__ class-attribute

__graph_before__: bool | None = None

__source__ class-attribute

__source__: dict[str, Any] = {}

__derivation__ class-attribute

__derivation__: tuple[Any, ...] | None = None

__derived_model__ class-attribute

__derived_model__: type | None = None

__schema_config__ class-attribute

__schema_config__: SchemaConfig = SchemaConfig()

__computed_specs__ class-attribute

__computed_specs__: dict[str, ComputedSpec] = {}

__computed_checked__ class-attribute

__computed_checked__: bool = False

__init_subclass__

__init_subclass__(
    model: object = _NO_MODEL,
    config: SchemaConfig | _ConfigOmitted = _CONFIG_UNSET,
    **kwargs: object,
) -> None

is_generic classmethod

is_generic() -> bool

True while type parameters are still open (Envelope).

__class_getitem__

__class_getitem__(args: object) -> Any

computed_fields classmethod

computed_fields() -> dict[str, ComputedSpec]

The read-only values this schema adds to its output, by name.

apply_default classmethod

apply_default(name: str) -> None

Turn a Field(default_factory=...) attribute into a dataclass default.

specs classmethod

specs() -> dict[str, FieldSpec]

Field descriptions, resolving forward references on first use.

build_specs classmethod

build_specs(final: bool = False) -> dict[str, FieldSpec]

validate_normalizers classmethod

validate_normalizers(specs: dict[str, FieldSpec]) -> None

Check that registered normalizers have a precise typed target.

native_schema classmethod

native_schema() -> core.CompiledSchema

The Rust validator for this schema and everything it refers to, compiled on first use and cached on the class.

validate classmethod

validate(data: object) -> Self

Build an instance from decoded JSON or raise ValidationError (validated in Rust).

_validate_prepared classmethod

_validate_prepared(data: object) -> Self

validate_text classmethod

validate_text(data: object) -> Self

Like validate for data that is all text, such as form fields ({"count": ["2"]}) or a parsed XML tree: text is first converted, in Rust, to the int, float and bool the fields declare. Anything that does not convert is left for validate to refuse. Before hooks see the raw text (each form value is a list of strings) and run first.

_validate_instance classmethod

_validate_instance(
    instance: Schema,
    *,
    allow_naive_datetime: bool = False,
    skip_fields: set[str] | None = None,
    use_aliases: bool = False,
    path_prefix: str = "",
) -> None

Validate final Python values on a manually constructed instance.

fields classmethod

fields() -> dict[str, FieldSpec]

Immutable description shared by binding, docs and rules.

to_dict

to_dict(*, exclude: Iterable[str] = ()) -> dict[str, Any]

The field values as Python objects (UUID, datetime stay what they are), nested schemas converted too. Fields left UNSET are omitted, so the result is exactly "what the client sent" for a partial update.

replace

replace(**changes: Any) -> Self

A copy with changes (Python field names) applied. Every value is validated again, normalised and checked like a new instance, so the copy is as trustworthy as any other; fields that were never supplied stay unsupplied for dump(exclude_unset=True).

from_models classmethod

from_models(
    rows: Iterable[object], **extra: Any
) -> list[Self]

Build a list from a synchronous iterable of model rows.

Each row follows from_model exactly. The iterable is consumed once, eagerly; this reads already-loaded attributes and never performs I/O.

from_model classmethod

from_model(row: object, **extra: Any) -> Self

Build this schema from a model instance: every field is read from the attribute of the same name, extra supplies or overrides values (for computed fields). Nested models become nested schemas. A field the row lacks is an error, and an unloaded relation still raises RelationNotLoaded: nothing here does I/O.

dump

dump(
    *,
    include: Iterable[str] | None = None,
    exclude: Iterable[str] = (),
    exclude_unset: bool = False,
    by_alias: bool = True,
) -> dict[str, Any]

Return JSON-compatible data with optional projection controls.

Selectors use Python field names. exclude_unset omits defaulted fields not supplied at construction. HTTP responses use default options.

hinoki.schemaconfig.SchemaConfig dataclass

Immutable class-level Schema behavior configuration.

hinoki.schemaconfig.SchemaExtra

Bases: StrEnum

Policy for unknown string keys in decoded Schema input.

hinoki.fields.Field

Field(
    *,
    default_factory: Callable[[], T],
    alias: str | None = None,
) -> T
Field(
    *,
    alias: str,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    ge: float | Decimal | None = None,
    le: float | Decimal | None = None,
    gt: float | Decimal | None = None,
    lt: float | Decimal | None = None,
    one_of: Sequence[Any] | None = None,
    max_digits: int | None = None,
    decimal_places: int | None = None,
    multiple_of: int | Decimal | None = None,
    strip: bool | None = None,
    lower: bool | None = None,
    upper: bool | None = None,
    format: str | None = None,
    discriminator: str | None = None,
    description: str | None = None,
    examples: Sequence[Any] | None = None,
    deprecated: bool | None = None,
) -> Any
Field(
    *,
    min_length: int | None = None,
    max_length: int | None = None,
    pattern: str | None = None,
    ge: float | Decimal | None = None,
    le: float | Decimal | None = None,
    gt: float | Decimal | None = None,
    lt: float | Decimal | None = None,
    one_of: Sequence[Any] | None = None,
    max_digits: int | None = None,
    decimal_places: int | None = None,
    multiple_of: int | Decimal | None = None,
    strip: bool | None = None,
    lower: bool | None = None,
    upper: bool | None = None,
    format: str | None = None,
    alias: str | None = None,
    discriminator: str | None = None,
    description: str | None = None,
    examples: Sequence[Any] | None = None,
    deprecated: bool | None = None,
) -> FieldInfo
Field(**options: Any) -> Any

Declare constraints (inside Annotated) or a default factory.

tags: list[str] = Field(default_factory=list) gives a per-instance default; title: Annotated[str, Field(min_length=1)] adds constraints.

hinoki.schema.Invalid

Bases: Exception

Raised by a check to refuse a value: a stable code, a readable message and optionally the path it concerns (default: the field the check is attached to, or the object itself).

hinoki.schema.Unset

Type of UNSET: a field that was absent from the input (PATCH).

hinoki.schema.field_check

field_check(*names: str) -> Callable[[F], F]

Mark a method as a check on one or more fields: def ok(self, value).

It runs after the structural validation succeeded, so value already has the declared type, and may read the other fields through self. Raise Invalid(code, message) to refuse; it never changes the value. Checks are synchronous and must not do I/O: a rule that needs the database belongs in an operation, not in a schema.

hinoki.schema.field_normalize

field_normalize(name: str) -> Callable[[F], F]

Mark a typed field canonicalizer: def trim(self, value: str) -> str.

Methods run synchronously after structural validation and return a replacement string; raise Invalid only from a check hook to reject.

hinoki.schema.object_check

object_check(function: F) -> F

Mark a method as a check on the whole object: def ok(self). Runs after every field check passed or failed (all problems are reported together).

hinoki.errors.ValidationError

Bases: Exception

Input does not match a schema. details lists every problem found.

hinoki.fields.UNSET module-attribute

UNSET = Unset()

hinoki.derive.derive

derive(
    model: type[Model] | None = None,
    *,
    only: tuple[str, ...] | None = None,
    exclude: tuple[str, ...] | None = None,
    partial: bool | tuple[str, ...] = False,
) -> Callable[[type[S]], type[S]]

Derive selected fields from model into a Schema subclass.

The keyword-only form is retained for one compatibility cycle and is deprecated; it requires the legacy model= Schema class keyword.