Every Python developer who has glued two services together has met jsonschema at the worst possible moment: a config file passes one check, an OpenAPI document passes another, and then production rejects a payload with a ValidationError that mentions a oneOf branch five levels deep in the schema. The library has been the de facto JSON Schema implementation in Python for years — when that error arrives, you are staring at the wrong end of a lot of machinery.

The frustration is usually the same three issues. First, error messages from combinator keywords like anyOf and oneOf pile up every branch’s failures, and picking the one that matters feels like guesswork. Second, formats are treacherous: a schema that says "format": "uri" quietly passes strings no HTTP client would accept, unless you know the opt-in. Third, type checks surprise people — in Python, True is an instance of int, and if a validator does not defend against that, "type": "integer" happily accepts booleans.

The cure for all three is reading the source. This tour walks the real tree of the default branch (main) of python-jsonschema/jsonschema: twelve modules where a single factory manufactures every draft validator, keyword logic lives in plain generator functions, and error ranking is a sort key away. Two diagrams map the territory: an overview, then a detail view of the internals.

Overview architecture of python-jsonschema: public API, validator factory, draft classes, keyword validators, types, formats and errors

Overview of python-jsonschema: the public API re-exports a factory that mints per-draft validator classes, which dispatch to keyword generator functions backed by swappable type and format checkers.

Reading the overview from left to right: the package’s __init__.py is deliberately thin, the weight sits in validators.py, and everything the factory needs is injected from small focused modules. The load-bearing pieces, each verified against the current tree:

  • create(), L140 — one function defines a brand-new class per draft, closing over a meta-schema, a keyword mapping, a type checker and a format checker. There is no inheritance hierarchy between drafts at all.
  • Draft202012Validator, L814 — the newest draft is just create() called with 36 keyword-to-callable entries; the oldest, Draft3Validator, does the same with 21.
  • iter_errors(), L352 — validation is a lazy generator over a precompiled list of keyword validators, so the first hard failure can end work early.
  • descend(), L399 — every applicator (properties, items, allOf, $ref, …) funnels subschema checks through this one method, which keeps instance and schema paths correct.
  • validator_for(), L1345 — resolves the $schema URI against a registry of meta-schemas and falls back to the latest draft when the keyword is missing or unknown.
  • additionalProperties, L39 — computes the extras as a set difference, then descends into each one or produces the memorable “not match any of the regexes” message when patternProperties is present.
  • multipleOf, L170 — fast float division first, and an exact fractions.Fraction fallback so enormous integers or Decimals cannot overflow the quotient.
  • oneOf, L352 — after finding a first valid branch, it re-checks the remaining branches just to tell you the instance matched several schemas.
  • best_match, L482 — the error picker behind top-level validate(): shorter instance paths and non-combinator keywords win, then it descends into context to find the deepest relevant cause.

The detail diagram zooms into those internals: the factory’s precompiled keyword list, each draft’s keyword table, and where the type, format and error modules plug in.

Detailed architecture of python-jsonschema: create() factory internals, draft validators, keyword generator functions, legacy behavior, TypeChecker, FormatChecker and the error model

Detail view: the factory builds one attrs-based class per draft; keyword generators, legacy hooks, the frozen type table, the format registry and the ranking-aware error model all meet inside it.

A Factory, Not a Class Hierarchy

The defining design decision in validators.py is that draft classes are manufactured, not subclassed. create() (L140) builds an attrs class inside its own body (L227), with VALIDATORS, META_SCHEMA, TYPE_CHECKER, FORMAT_CHECKER and ID_OF installed as class attributes. Instantiating Draft202012Validator runs __attrs_post_init__ (L285), which walks the schema once and precompiles self._validators — a list of (callable, keyword, value) triples filtered to keywords the class implements (L296). Later calls to iter_errors() never re-parse the schema; they replay that list, and the True/False schema shortcuts bypass it entirely (L372-382).

Registration is equally mechanical. The validates() decorator (L81) drops each manufactured class into a _VALIDATORS dict and its meta-schema URI into _META_SCHEMAS, a _utils.URIDict that normalizes URI scheme and host so lookups survive case differences (defined at _utils.py L13). validator_for() (L1345) reads $schema, and if the URI is unknown it warns and returns _LATEST_VERSION (L862), which points at the 2020-12 draft.

validate() (L1275) is then almost trivial: pick a class with validator_for, call cls.check_schema(schema) to validate the schema against its meta-schema (raising SchemaError via create_from, L310-319), instantiate, and raise only exceptions.best_match(...) of the streamed errors rather than the first one produced. That single choice — best-match instead of first-match — is why the top-level API’s messages are usually the useful ones.

One more piece worth noticing: the public __init__.py does its magic with a module-level __getattr__ (L28). Importing jsonschema.RefResolver or jsonschema.ErrorTree still works, but the shim serves them lazily with a DeprecationWarning, keeping the import graph clean while old names wind down.

Keyword Validators: Generators All the Way Down

Open _keywords.py and the specification becomes greppable. Every keyword is a plain function with the signature (validator, keyword_value, instance, schema) that yields ValidationError objects; applicators call validator.descend(...) to recurse, leaf keywords yield directly. additionalProperties (L39) leans on find_additional_properties() from _utils.py (L75) for the diff, and its error message even enumerates the patternProperties regexes that failed to match (L49-55).

Combinators show the design’s economy. anyOf (L338) collects errors per branch and breaks at the first clean one, falling through to a for/else that yields one aggregate error carrying every branch’s failures as context. oneOf (L352) goes further: once a first valid branch is found, it keeps checking the remaining branches so it can complain that the instance matched several schemas (L367-375) — a distinction most hand-rolled validators never bother with. The 2019-09+ unevaluatedProperties (L412) is the subtlest: it asks _utils.find_evaluated_property_keys_by_schema (L324) which keys sibling keywords already touched, then descends only into the leftovers.

References are delegated, not reimplemented. ref (L275) and dynamicRef (L279) both hand off to validator._validate_reference, which resolves through the referencing library’s registry by default, or through the deprecated _RefResolver (L865) when a legacy resolver object was passed in. The old resolver keeps a scope stack and an lru_cache-backed URL store; its removal path is signposted: automatic remote retrieval now warns users toward referencing.Registry (L111-137).

Types and Formats: Immutable Tables and Optional Checks

_types.py is small — 205 lines — but it encodes the sharpest edge in JSON Schema typing. The TypeChecker is an attrs frozen class (L64) whose state is a rpds.HashTrieMap from keyword name to predicate function (L86); redefine and remove never mutate, they return a new checker (L123, L157). The per-draft chain reads like a changelog: draft 3 allows "any", draft 4 removes it, draft 6 redefines integer to admit integral floats via a lambda on float.is_integer() (L196-202).

The bool trap is defended in plain sight. is_integer (L34) and is_number (L45) both begin with if isinstance(instance, bool): return False, because Python’s bool subclasses int and a naive isinstance check would let True validate as an integer. When you need a custom JSON type, build a new checker with redefine and pass it to create() or extend() — no monkey-patching anywhere.

_format.py plays the opposite trick: formats are strictly optional. The FormatChecker (L21) answers True for any format it does not know (L138-139). Individual checks are registered with the checks decorator (L57), and _checks_drafts (L194) fans a single function out across the six per-draft checkers with historically correct names — the same function becomes ip-address in draft 3 and ipv4 from draft 4 onward (L248-260). Optional dependencies arrive inside contextlib.suppress(ImportError) blocks: fqdn for hostnames, idna for internationalized names, rfc3987/rfc3986_validator for URIs, rfc3339_validator for date-time, plus jsonpointer, uri_template, isoduration and webcolors; uuid needs nothing external (L536-544).

From 21 Keywords to 36: Errors That Know How to Rank

The build facts show a library modernizing in place. Between Draft3Validator (L603, 21 keyword entries) and Draft202012Validator (L814, 36 entries) the keyword surface doubled, and the draft classes themselves became data: the same factory call with a bigger table. The Python floor moved too — pyproject.toml declares requires-python = ">=3.12", spent on PEP 695 generic syntax: def checks[F: _FormatCheckCallable] in _format.py (L57) and def _most_relevant[E: _Error] in exceptions.py (L554). Runtime dependencies stay lean: attrs>=22.2.0, jsonschema-specifications>=2023.03.6, referencing>=0.28.4 and rpds-py>=0.25.0 (pyproject L39-43).

The error model is where the polish shows. The _Error base (L56) keeps path and schema_path as deques so parents can prepend segments cheaply (L87), links context errors back to their parent (L98-99), and its verbose __str__ pretty-prints both the failing schema fragment and the offending instance (L104-134). Ranking lives in two functions: by_relevance (L439) builds a sort key that prefers shorter instance paths, non-weak keywords, and type-consistent errors — with WEAK_MATCHES = frozenset(["anyOf", "oneOf"]) (L30) deliberately demoting combinator failures — and best_match (L482) repeatedly descends into context, grouping sub-errors by the subschema that produced them and stopping when ranks tie (L527-551). ErrorTree (L336) remains the batch-inspection tool, bucketing errors by instance path.

Testing culture is visible too: jsonschema/benchmarks/ runs performance suites with pyperf, including one that validates every valid example in the official JSON-Schema-Test-Suite (benchmarks/json_schema_test_suite.py L8). And a typing protocol — protocols.py’s runtime_checkable Validator (L46-47) — documents the full validator surface for static checkers; the repo even ships a test asserting every concrete validator matches it, the kind of discipline that pays off when you wire validators into mypy-checked codebases. Property-based fans get the mirror image: given a schema, generators built on hypothesis can sample instances it accepts, and the benchmarks directory shows the maintainers care about both directions of that loop.

Weighing this library against the model-based approach is instructive rather than tribal: pydantic’s ecosystem validates Python objects with Python types, while jsonschema validates raw JSON documents against a portable standard — the machinery we walked through in pydantic-ai-source sits on the former, and anything that must speak JSON Schema (OpenAPI documents, LLM structured-output contracts, config validation) lands here.

Honest Limits

  • Format validation is opt-in and incomplete by design: unknown formats always pass, and many checkers only activate with their optional package installed.
  • best_match is explicitly documented as a heuristic whose output may change between versions; do not depend on a specific error being picked.
  • oneOf “matched several schemas” checking costs extra validation passes on wide combinator schemas.
  • The legacy RefResolver and the deprecated CLI (now just a pointer to the external check-jsonschema tool, cli.py L20-28) remain for compatibility but are on their way out.
  • Remote $ref retrieval is deprecated; new code should supply a referencing.Registry instead of relying on network fetches.
  • Line numbers reflect the main tree as of this writing; they will drift, so treat them as coordinates, not anchors.
Watch PyShine on YouTube

Contents