type
type is the runtime that schema-generated models are built on. It provides the base class those models inherit from, TypeBase, and a schema-driven loading pipeline for YAML-backed documents: annotation metadata carried on each generated field drives normalization and validation, so that logic is declared once in a schema rather than written into each model.
Obtaining it
The library is published as the coordinate type:type and is imported as type. Its dependencies arrive with it, so naming the one coordinate is enough.
Schemas are authored, parsed and turned into model classes by the schema library, which is a separate coordinate; type is what those generated classes run on.
Public surface
Everything a caller uses is imported from the package root – from type import TypeBase, from type import load_data_file – and nothing beneath it is part of the surface. The root exports:
- The model base and loading:
TypeBase,AppConfig(an application’s own configuration, “An application’s configuration” below),load,load_data_file,load_migrated,schema_version_of,to_string,render_posix_pathsandsuppress_constructor_pipeline. - The built-in types:
SetOf(a schema’sset[T], “Sets” below),Coordinate,PinnedCoordinate,FloatingCoordinate,IntegerRange,Datespan,Timespan,Datetimespan,Duration,Currency,CurrencyValue,Timezone,Date,TimeandDateTime, withDEFAULT_FORMAT,DEFAULT_UNIT,currency_code,currency_symbol,currency_spec,default_currency,set_default_currency,default_timezone,set_default_timezone,known_timezonesandtzinfo_for. - The rule vocabulary:
is_valid_normalize_rule,is_valid_validate_ruleandis_element_wise_normalize_rule, and the protocols a package-local rule or a per-type hook implements,FieldNormalizer,FieldValidatorandTypeNormalizer. - Field names:
field_spelled_asandfold_field_name. - Limits:
max_content_length,set_max_content_length,max_string_field_lengthandset_max_string_field_length. - Errors:
TypeLoadError,TypeParseError,TypeDeserializationError,TypeSerializationError,TypeNormalizationError,TypeValidationError,FieldNameError,FieldNormalizationErrorandFieldValidationError. - Schema store resolution:
SCHEMA_STORE,SCHEMA_VERSION_SHAPE,SCHEMA_ARTIFACT_FILENAME,parse_coordinate,parse_version,resolve_coordinate,coordinate_floats,registered_versions,latest_version,render_version,version_sort_key,store_dir,store_repo_root,artifact_dir,artifact_dir_in,artifact_pathandartifact_path_in. - Version ranges:
parse_version_range,render_version_rangeandversion_in_range. “Version ranges”, below, says how a range is written and read.
Example YAML schema
A schema definition names its types and declares field-level metadata using x-normalize and x-validate extensions. The example below defines two types where demo owns a list of demoItem objects:
demoItem:
name: demo-item
fields:
label:
type: string
help: What the item is called
x-normalize: trim
x-validate: non-empty
demo:
name: demo
fields:
name:
type: string
help: What the demo is called, in lower case
x-normalize:
- trim
- lower
items:
type:
base: list
item: demoItem
help: The items the demo holds, sorted by label
default: []
x-normalize:
- sort-by:label
x-validate:
- unique-name
The x-normalize and x-validate metadata is carried through into the generated model classes and drives the loader pipeline at runtime:
nameondemois trimmed and lowercased.itemsdefaults to an empty list when absent, is sorted by each item’slabel, and is validated to contain no duplicate names.labelon eachdemoItemis trimmed and must be non-empty.
A file loaded against the demo type might look like this:
name: Hello World
items:
- label: Beta
- label: Alpha
- label: Alpha
After loading: name becomes hello world, items is sorted by label, and the duplicate Alpha entry fails unique-name validation.
Generated types
The schema generator creates a Python model class for each type defined in the schema and places them under a package-specific __types__ module. Each class inherits from TypeBase and carries the schema metadata — including x-normalize and x-validate — directly on its fields via json_schema_extra. For the example schema above, the generated classes look like this:
from pydantic import Field
from type import TypeBase
class DemoItem(TypeBase):
label: str = Field(
json_schema_extra={"x-normalize": "trim", "x-validate": "non-empty"}
)
class Demo(TypeBase):
name: str = Field(
json_schema_extra={"x-normalize": ["trim", "lower"]}
)
items: list[DemoItem] = Field(
default=[],
json_schema_extra={"x-normalize": ["sort-by:label"], "x-validate": ["unique-name"]},
)
Because those classes inherit from TypeBase, they automatically participate in the shared loading pipeline — no additional wiring is required.
An application’s configuration
AppConfig is a TypeBase that holds one field, features: a mapping from a feature flag’s name to true or false, empty by default. Every application’s own configuration is generated on it. A schema names the definitions that are an application’s configuration in metadata.configRoots, and each is generated as a subclass of AppConfig – of it and the definition it extends, where it extends one – so the field is declared in one class and every configuration has it. Code that reads a configuration’s flags can take an AppConfig and read features from it, whatever application it belongs to. Which names a configuration may switch is the application’s declaration, checked where its configuration is composed, not this class’s.
Immutability
Generated models are frozen: field assignment raises after construction, on
top-level and nested models alike. Update a model by building a new one —
model.copy(field=value) (pydantic model_copy) — and, when the model lives
inside a container, reinsert the copy. Containers themselves (lists, dicts)
stay mutable by design: the load pipeline mutates collection
contents, and freezing them would buy little since the models inside are
already immutable.
Two consequences for extension code:
- Per-type normalizers must return a new or copied model, never mutate the input (see the example below).
- The load pipeline’s internal write-backs use
object.__setattr__deliberately; that escape hatch is reserved for the pipeline itself.
Sets
A field a schema declares as set[T] is generated as SetOf[T], which a type
checker reads as frozenset[T]:
from typing import Literal
from type import SetOf, TypeBase
class Turn(TypeBase):
links: SetOf[Literal["commit", "pr"]] = frozenset({"commit", "pr"})
A document writes a set as a sequence. A value written twice is refused where
the document loads, naming the field and the value – (links): holds 'pr' more than once; a set holds each value once – and so is a value that comes
twice once its field’s x-normalize rules have run, since the model is built
again from what they return. Code may hand a model a frozenset or a list.
A loaded set iterates in the order it is written back in: an enum’s values in the order the enum declares them, anything else sorted. A frozenset of strings otherwise iterates in an order no two processes share, so every caller walking a set – to list it, report it or write a file from it – answers the same way on every run, and a document a tool writes stays byte-stable. In every other respect the value is a frozenset: it compares equal to one, hashes as one, and a set operation on it answers a plain frozenset.
Built-in expansion types
Runtime-hosted models a schema names as a field’s base type (the schema
package’s BUILT_IN_TYPES declares each name’s class). Each expands
from a compact wire form at load and serializes back to it:
coordinate→Coordinate,pinnedCoordinate→PinnedCoordinate,floatingCoordinate→FloatingCoordinate: a package reference, one string on the wire –<namespace>:<name>, then@<major>.<minor>.<patch>to pin a version, or nothing or@latestto float – andnamespace,nameandversionapart in memory, withpackage(<namespace>:<name>) andfloats. The three differ in what they take: either form, only a pinned one, only a floating one. A field says which it holds by which it declares, and a string of the wrong kind is refused where the document loads, told what to write. A version is written whole;@1.2is refused by all three.versionSegment→VersionSegment: which of a version’s three numbers a change moves,major,minororpatch. Not a model but the set itself,Literal['major', 'minor', 'patch'], so a value is the word as written and anything else is refused where it loads.integerRange→IntegerRange,datespan→Datespan,timespan→Timespan,datetimespan→Datetimespan: a span from one value to another, one string on the wire with..between the ends –3..9,2026-10-01..2026-10-31,09:00:00..17:30:00– andstart,end,startInclusiveandendInclusivein memory. Each end is written as a value of its kind is anywhere else. What the string means at its ends is the kind’s own: a range of whole numbers and a datespan hold both ends, so3..9holds 9 and a datespan holds its last day; a timespan and a datetimespan hold their start and stop short of their end, so09:00:00..17:30:00does not hold 17:30. A span held otherwise is written with a bracket at each end,[or]holding the end beside it and(or)leaving it out –[3..9),[09:00:00..17:30:00]– and the mapping it expands to is read too,{start: 3, end: 9, endInclusive: false}; every span is written back as one string and reads back from it. Either end may be left off (3..,..2026-10-31), and not both. A span that ends before it starts is refused, and so is one that holds nothing; a timespan whose end is the earlier time crosses midnight, and a datetimespan’s ends each carry their own timezone and are compared as instants. They offer nothing beyond the value yet: no field in the tree is one, so containment, length and overlap have no caller to be written for.regex→Regex: a regular expression in the dialect of Python’sre, one string on the wire and back, a flag written inline ((?i)). A pattern that does not compile is refused where it is read, quoted. Whether it must match a whole value or may be found inside one is the caller’s question:fullmatch(text=...)andsearch(text=...)are both offered and nothing anchors silently;compiledis the compiled pattern.glob→Glob: a tree pattern, one string on the wire and back, read the way a line of an ignore file is. A leading/roots it at the root a path is relative to, and without one it matches at any depth; within a segment*,?and[...]match asfnmatchreads them, with case kept and never across a/; a segment that is exactly**matches any number of segments; a trailing/is not read, and a pattern that matches a directory names everything beneath it.matches(relative_path=...)asks one pattern about a path relative to that root, andmatches_any_glob(relative_path=..., globs=...)asks a list – globs or their spellings – whether any names it, which is how every list of them is read;glob_matcher(globs=...)reads a list once and answers the same question for each path it is handed, for a caller asking about many.beneath(directory=...)is the same glob stated from a root the directory lies beneath, andanchored_spellingsis how a tool that anchors a pattern holding a separator and takes no leading/– ruff’s excludes – reads what the glob names. A pattern that names nothing once its separators are taken off,**inside a segment (where it would read as*) and a[never closed are refused where it is read.duration→Duration: whole microseconds on the wire; every component and per-unit total in memory. It also reads the form it renders –30d,1h30min,500ms, in the abbreviationsABBREVIATIONSdeclares – so a duration can be written by hand or typed on a command line, and one vocabulary is read in both directions rather than a parser elsewhere inventing a second set of unit names.currency→Currency: any spelling the currency table knows — ISO code, symbol, or alias,"$"/"usd"/"USD"— canonicalized to the code. The table is priority-ordered so a shared symbol ($,£,¥,kr…) resolves to its conventional owner;currency_symbol/currency_codeare the two directions through it.currencyValue→CurrencyValue: an amount in a currency. A bare number reads in the default currency (USDglobally;set_default_currencylets a caller choose); a string carries its own label ("$5.00","5.00 EUR"); serializes as the amount and the code,"5.00 USD", with two decimal places at least and as many more as the value carries ("0.0042 USD"), so it reads back as the value it was written from.render()/str()are for a reader: the table’s symbol and per-currency decimals (¥1,234,د.ك1.500).timezone→Timezone: an IANA name, validated against the zoneinfo database (known_timezones()is the union); fixed offsets (+05:30) are accepted for wire interop.date→Date:YYYY-MM-DD.time→Time:HH:MM:SS[.ffffff], optionally with a zone (18:21:05 America/Chicago) or ISO offset (18:21:05+02:00).datetime→DateTime: ISO 8601 with the offset, plus the zone by name (2026-08-26T14:30:05-05:00[America/Chicago]) — the offset pins the instant for any ISO reader, the name keeps conversions (in_timezone) correct across daylight-time boundaries.now()andDate.today()read on the default timezone (UTCglobally;set_default_timezonelets a caller choose).
All calendar and clock arithmetic defers to the standard library’s
datetime + zoneinfo (the tzdata package supplies the database on
Windows); nothing here re-implements daylight time.
Type-loading pipeline
- The shared loader runs the pipeline in this order:
- Parse YAML content into a model instance.
- Apply field-level normalization rules.
- Apply any per-type normalizer.
- Apply field-level validation rules.
- Apply any per-type validator.
Depth-first traversal
Both the normalization and validation stages traverse the model tree depth-first. When a field value is itself a TypeBase — or a list that contains TypeBase instances — the pipeline recurses into that nested model and fully processes it before returning to apply any rules declared on the containing field.
For the two-type example, this means:
- During normalization, each
DemoIteminsidedemo.itemsis normalized first (trimminglabel), and only then are the rules on theitemsfield itself applied (defaulting to an empty list, sorting by label). - During validation, each
DemoItemis validated first (checkinglabelis non-empty), and only then is theitemsfield validated against its own rules (checking for duplicates).
This ordering guarantees that by the time a field-level rule runs on a list or nested model, all inner content has already been fully normalized or validated.
A refused key says what it is spelled as
A field name is a document’s key and the generated model’s attribute name in one breath, so re-spelling one re-spells every document that carries it – and pydantic reports only Extra inputs are not permitted, which names the key that was refused and nothing about what replaced it. Where the model at the error’s location declares a field that folds to the same thing – case and _/- removed – the message says so:
Schema validation failed: (repo_root): Extra inputs are not permitted; the field is spelled 'repoRoot'
The answer comes off the model rather than out of a table of renames kept beside it, so a rename declares itself and there is nothing to keep in step. It is direction-free by consequence: a document written in camelCase against a snake_case field is answered the same way. A key that folds to nothing declared is left exactly as pydantic reported it.
How generated types reach the runtime
The runtime package does not define the schema models by hand. Instead, the schema generator creates Python model classes from schema definitions and places them under package-specific __types__ modules. Those generated classes inherit from TypeBase, so they automatically participate in the shared loading pipeline.
In practice, the flow looks like this:
- A schema source (typically a YAML schema) is loaded by the schema generator step.
- The generator creates Python model classes for the schema types and stores them under a generated package such as
example_schema.__types__. - Each generated model carries the schema metadata used by this package, including
x-normalizeandx-validatefields. - When code calls
ModelClass.load(...), the runtime package resolves that generated model, applies the annotation-driven normalization and validation rules, and then returns the populated model instance.
That means the generation step and the runtime loader are complementary:
- generation supplies the strongly typed schema classes and their metadata
- the type package supplies the shared parsing, normalization, validation, and model-loading behavior
In code organization terms, generation/parsing entry points live under schema.*, while runtime loading entry points live under type.
A package can also add extra behavior by providing a per-type normalizer or validator module that matches the generated model package name. For example, example_schema.normalizer.demo can provide logic for the Demo model, while example_schema.validator.demo can provide schema-specific validation.
Loading a model
The package exposes three loading entry points with different responsibilities:
TypeBase.deserialize(content, format="yml"): parse content only.TypeBase.load(content, format="yml"): parse, normalize, and validate content.type.load_data_file(ModelType, path, format="yml"): read data from disk and then run the shared load pipeline.type.load_migrated(schema_type=ModelType, path=path, version=VERSION): the read a document’s writer makes. One stating another state of the same major and minor – a development marker such as0.0.0-devonce its schema is released as0.0.0– is re-stamped, loaded again against the schema in force and written back; another major or minor, or content the schema cannot read, is refused with the file left as it was.
Constructor-path behavior:
ModelType(...): validates and then runs the same normalize/validate pipeline asload_mappingandload.ModelType.model_validate(...): validates and then runs the same normalize/validate pipeline asload_mappingandload.ModelType.deserialize(...): parse/validate only; skips normalization and runtime validation hooks by design.
The recommended model-level entry point is TypeBase.load(...). It keeps the runtime model API independent from the filesystem while still leaving a separate convenience helper for path-based callers.
Load content directly
Use this when the content already comes from memory, a service response, or any non-filesystem source:
content = """
name: Hello World
items:
- label: Beta
- label: Alpha
"""
model = Demo.load(content)
print(model.name) # hello world
print(model.items) # sorted list of DemoItem instances
Load from a file
Use the separate helper when file I/O is the caller’s responsibility:
from pathlib import Path
from type import load_data_file
model = load_data_file(Demo, Path("demo.yml"))
print(model.name) # hello world
print(model.items) # sorted list of DemoItem instances
If you only need the raw parse step, TypeBase.deserialize(...) skips normalization and validation entirely. In the full load flow, name is normalized to hello world, items are sorted by label, and a duplicate Alpha entry fails validation.
The rule DSL
Rules are declared with x-normalize and x-validate metadata, on a field or
on the type the field is declared as. The rule vocabulary is a closed,
schema-transported DSL: every un-prefixed rule is
structural, built into the type runtime, and depends on nothing outside the
value it operates on. That property makes a schema document self-describing —
any consumer with the type runtime can normalize and validate data against
it without importing Python code from the schema’s producer, which is what
lets one package carry a copy of another’s schema definitions.
The vocabulary is enforced in two places:
- at schema parse time, the
schemaparser rejectsx-normalize/x-validateentries that are not in the vocabulary, on a field and on a definition alike, and - at load time, the pipeline refuses to run a rule outside the vocabulary
(
is_valid_normalize_rule/is_valid_validate_ruleare exported for callers that need the same judgment).
Where a rule is declared
A rule may belong to a field, or to the type every such field is declared as.
A definition carries its own rules beside its shorthand and toString:
definitions:
label:
name: label
x-normalize:
- trim
x-validate:
- non-empty
fields:
value: string
Every field declared type: label then trims and rejects empty values without
saying so. Primitive types carry rules the same way, from a short built-in
table: type: path normalizes with posix-path, so a path field needs no
x-normalize to get path handling.
A guarantee that belongs to the type is stated once and cannot be omitted by a field that simply did not think about it. That is the whole reason the type owns it: a rule that has to be remembered is a rule that is sometimes forgotten, and a field that forgot one looks exactly like a field that deliberately did without.
How a field’s rules combine with its type’s
Union, type first. The type’s rules run, then the field’s own. A field may add to what its type guarantees and can never drop one — an opt-out would reintroduce exactly the silent omission type-level rules exist to end. A field that restates a rule its type already gives does not run it twice; the duplicate is dropped, and order is otherwise as written.
holder:
name: holder
fields:
title:
type: label # x-normalize: [trim]
x-normalize:
- lower
# the generated field carries ['trim', 'lower']
A rule that cannot apply to a field’s shape is rejected where it is written, by the generator, rather than failing on the value it is eventually handed:
- A field whose type is the rule-carrying type inherits everything.
- A list or dict of one inherits only the rules the loader applies
element-wise — the rules whose handler declares
element_wise, which ispath/posix-path, so alistofpathis normalized item by item. Any other rule reaching a field that way would be handed the container itself, and is refused. - A dict keyed by a rule-carrying type is refused: the loader never visits dict keys, so such a rule would have nowhere to run.
- A union (
anyOf) inherits nothing and is refused: a union field has no single type whose rules could apply. Declare them on the field. - A generic definition renders as a frozen dataclass, which carries no field metadata and runs no rules at all; its fields inherit nothing, the same way they may not declare rules of their own.
Built-in normalization rules
trim: remove surrounding whitespace from a stringlower: convert a string to lowercaseposix-path(aliaspath): trim whitespace and normalize backslashes to forward slashessort: sort a list when the values are comparabletrim-items: trim each string in a list
Built-in validation rules
non-empty: reject empty or blank strings, and empty or blank string items in lists and setssays-more-than-name: reject text that only says back the name its model is held under – the model’s key where it is a value of a mapping, its ownnamefield where it is an item of a list – compared with case and punctuation ignored. The meta-schema holds every field’shelpto it. A handler asks for that name by settingneeds_name = True, and is then given it asname; it is None for a model held under neitherunique: reject duplicate string values in a list. A field whose order means nothing is better declared a set, which holds the same to every document without a rule to stateunique-name: reject duplicatenamevalues across a list of modelsabsolute-path/relative-path: require the path formno-periods: reject values containing a periodkebab-label/kebab-name: require lowercase kebab-case values
Parameterized rules
Some rules take an argument after a : separator. Handlers for these are
constructed on demand and cached per rule string:
sort-by:<key>(normalize): sort a list of mappings or models by one key, for examplesort-by:name.pattern:<regex>(validate): the string value must match the regular expression, for examplepattern:^[a-z][a-z0-9-]*$.unique-by:<key>(validate): the<key>value must be unique across a list of mappings or models, for exampleunique-by:code.unique-tree:<key>/<children>(validate): the<key>value must be unique across a list of nodes and, recursively, across each node’s<children>list, for exampleunique-tree:name/submodules.
A malformed argument (for example an invalid regex) is rejected when the rule is first resolved.
Type shorthand expansion
A definition may declare a canonical string form via shorthand in its
schema. The generated model carries the
declaration as a __shorthand__ class attribute, and the runtime expands
matching strings into the mapping form before validation — wherever the type
appears, including nested fields:
class Coordinate(TypeBase):
__shorthand__ = {
"pattern": r"^(?P<namespace>[^:@]+):(?P<name>[^:@]+)@(?P<version>[^@]+)$",
"format": "{namespace}:{name}@{version}",
}
namespace: str
name: str
version: str
Coordinate.load(value="pkg-store:x@1.0.0") # expands to the three fields
Named capture groups map to fields; unmatched optional groups fall back to
field defaults; a non-matching string is a validation error. When a format
template is declared the model also serializes back to its shorthand string,
so the form round-trips, and str() of the model is that string: the format
is declared only where the string is the whole of the value, so it is how the
value is shown as well as how it is written. A path field is rendered into
it with forward slashes on every platform. Expansion is structural and value-only, which keeps
it inside the schema-transported guarantee — no producer Python required.
A format may bracket a stretch of itself. "{name}[@{version}]" renders
the @ and the version together when the version is there, and neither when
it is not, so a component a pattern made optional round-trips as written
rather than interpolating None. Every placeholder inside a bracketed
segment has to resolve for the segment to render, and [ and ] therefore
delimit a segment rather than standing for themselves.
Schema store resolution
A schema is addressed by a coordinate, namespace:name@version, and the
runtime resolves an id: coordinate reference against a schema store: a
directory, .schema/ at a repository’s root, holding each schema document
under its namespace, name and version. SCHEMA_STORE names that directory,
and parse_coordinate, resolve_coordinate, store_dir, artifact_path,
version_sort_key and render_version are how a caller reads it. The
store’s layout is the runtime’s own: SCHEMA_VERSION_SHAPE (major.minor)
governs how parsed versions render back into directory names and index keys,
and SCHEMA_ARTIFACT_FILENAME names the file each version keeps. All of
these are exported from the package root.
A coordinate’s version is optional. acme:thing and acme:thing@latest are
one reference – whichever version the store holds highest – and
registered_versions and latest_version answer that off the store’s own
directories, so an index pointer left behind by a removal does not decide it.
coordinate_floats reports whether a reference names a version, and a
reference inside a loaded document may not float: load_data_file refuses one
as CoordinatePinRequiredError, because a document is read again and
generated from, and a reference that resolves to whatever is highest would let
generated output change for a reason nothing records.
Package-local rules: local:<rule>
The local: prefix is the escape hatch for rules that genuinely cannot be
expressed structurally. A rule such as local:expand-shorthand resolves
against handlers discovered from the owning package — the package root is
derived from the generated model’s __types__ module, and handlers are
imported from <package>.normalizer.handlers and <package>.validator.handlers.
A handler implements the FieldNormalizer / FieldValidator protocol with a
unique un-prefixed rule name:
from type import FieldNormalizer
class TitleFieldNormalizer(FieldNormalizer[str]):
rule = "title"
def normalize(self, *, value: str) -> str:
return value.title()
and is referenced from the schema with the prefix:
name:
type: string
x-normalize:
- trim
- local:title
The prefix is the only way to reach discovered handlers — an un-prefixed
custom rule is rejected at parse time. This keeps the portability boundary
explicit in the schema itself: a document whose rules are all un-prefixed is
fully portable, while a local: rule declares that consumers need the
producer package present. Prefer built-in and parameterized rules; reach for
local: only when the transformation requires knowledge the schema cannot
carry.
Per-type normalizers
Some packages need behavior that is specific to a particular generated model. Those hooks are resolved from modules named after the generated type. For example, example_schema.normalizer.demo can provide a normalizer for Demo.
The module should expose a Normalizer class. A normalizer is the right fit when a rule should run after the field-level normalization metadata has already been applied, but before any later model-level validation. In other words, it is the place for logic that rewrites or enriches a fully built model object in a way that is specific to a schema or repository.
For example, a normalizer that derives a canonical display_name from two sibling fields on Demo:
class Normalizer:
def normalize(self, *, model: Demo) -> Demo:
if model.display_name:
return model
if model.first_name and model.last_name:
display_name = f"{model.first_name} {model.last_name}".strip()
elif model.first_name:
display_name = model.first_name
else:
display_name = model.last_name or ""
# Models are frozen: return an updated copy instead of mutating.
return model.copy(display_name=display_name)
These hooks run after field-level normalization, which keeps the generic transformation rules in the schema metadata while reserving richer repository-specific behavior for dedicated normalizers.
When to use custom normalizers
Custom normalizers are useful when the rule:
- depends on the fully parsed model rather than a single raw field value,
- needs to rewrite the object after field-level normalization has already run,
- is repo- or schema-specific behavior rather than a generic reusable transformation,
- should happen once per model instance rather than once per field.
Good examples include:
- deriving a computed field from sibling values,
- canonicalizing list or nested-model structure,
- applying repository-specific defaults after the generic metadata-driven rules have finished,
- repairing or enriching a model before later validation runs.
By contrast, prefer x-normalize metadata for simple, reusable transformations such as trimming strings, lowercasing values, sorting lists, or normalizing paths.
When not to use custom normalizers
Custom normalizers should not be the first choice for every transformation. Avoid them when the logic is:
- simple enough to express as a field annotation,
- already covered by one of the built-in normalization handlers,
- better represented as schema metadata than as runtime Python logic.
If a rule is still a single-field transformation, a field-level normalization rule keeps the schema easier to read and makes the behavior easier to discover.
Per-type validators
Validators are resolved from modules named after the generated type as well. For example, example_schema.validator.demo can provide a validator for Demo.
The module should expose a Validator class. A validator is the right fit when the rule is meaningful only once the loader has already built and normalized the full model object. It is especially useful when the check:
- depends on multiple fields at once,
- needs access to the fully normalized object rather than just an individual field value,
- is repo- or schema-specific business logic rather than a generic reusable constraint,
- should run after nested models and list contents have already been normalized and validated.
For example, a validator that enforces a relationship between two fields on Demo:
class Validator:
def validate(self, *, model: Demo) -> None:
if model.start_date and model.end_date and model.start_date > model.end_date:
raise ValueError("start_date must not be later than end_date")
When to use custom validators
Custom validators are a good fit for rules such as:
- one field requires another field to be present,
- two or more fields must satisfy a relationship,
- the final object must obey a cross-field invariant,
- a generated model needs a policy that is specific to a repository or deployment.
By contrast, prefer field-level metadata such as x-validate for simple, reusable checks that can be expressed against a single field. Examples include non-empty strings, unique list entries, or path format requirements. Those rules are easier to maintain when they stay close to the schema.
When not to use custom validators
Custom validators should not be the first choice for every rule. Avoid them when the check is:
- simple enough to express as a field annotation,
- already covered by one of the built-in validation handlers,
- better modeled as a schema constraint than as runtime Python logic.
If a rule is still a single-field constraint, a field validator keeps the schema simpler and the validation behavior easier to discover.
Summary
The type package keeps three responsibilities separate:
- parsing and deserialization
- field-level normalization and validation
- higher-level, model-specific behavior
That split makes it straightforward to extend the system with new rules or package-specific policies without scattering the logic across the runtime model classes.
Version ranges
A version range says which versions something is for. It is declared by this library, in the schema type:version-range, so a schema names that document in its externalSchemas with vendor: true and a field of the type <alias>.versionRange takes any of three things, told apart by how each is written:
| Written | Is | Holds |
|---|---|---|
'3.13' |
a version | that version |
['3.11', '3.13'] |
a sequence | every version from its lowest item to its highest, both included |
'>=3.11,<3.14' |
bounds | every version each bound holds |
A single version is a range of one and is written as a version is written anywhere else, with nothing around it.
A version in a range is read as far as it was written. 3.13 is every 3.13.x, not 3.13.0 alone. That is the one way a range’s version differs from the meta-schema’s version, which names one thing and fills an unwritten segment with 0. It carries no suffix either: a -dev mark says a document has moved since its release, and a range holds versions, not documents.
A sequence is a run with nothing left out. ['3.11', '3.13'] holds 3.12, so the first and the last are all it needs; an item written between them is allowed and adds nothing. It is not a list of the versions it holds and no others. An empty sequence is refused.
Bounds take four operators: >=, >, <= and <, one bound or two joined by a comma, and both have to hold. Each reads a short version the way everything else here does: >=3.13 starts at the first 3.13.x, <=3.13 ends at the last, >3.13 starts after the last and <3.13 ends before the first. There is no ==, which a plain version says, and no !=, ~= or ^.
version_in_range(version=..., version_range=...) is the one answer to whether a version is in a range. Every package that names the type is generated its own copy of it, and the copies are distinct classes of one shape, so the function reads the shape: it takes any package’s copy, or a range still written as text. The version asked about is text or any version-shaped model; it is compared over the segments the range’s version wrote, a segment it left out itself is read as 0, and a suffix on it is not read. A range or a version that cannot be read raises ValueError rather than answering False.
from type import parse_version_range, render_version_range, version_in_range
version_in_range(version="3.13.5", version_range="3.13") # True
version_in_range(version="3.12", version_range=["3.11", "3.13"]) # True
version_in_range(version="3.14.0", version_range=">=3.11,<3.14") # False
held = parse_version_range(value=">= 3.11, < 3.14")
render_version_range(version_range=held) # '>=3.11,<3.14'
parse_version_range reads what a document or a literal wrote into the range types and raises ValueError saying what the three spellings are; render_version_range writes a range back the one way, as a string or a list of them.