Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(310): keep the fallback on fields a class inherits from a generat…
…ed class

Every generated class registered its validator under one name, and pydantic
keys inherited validators by name, so a class built on a generated class
replaced the validator covering the fields it inherits. Each class now gets
its own name. Tests cover both builders and three levels of inheritance.
Docs describe the behaviour without release history.
  • Loading branch information
nursnaaz committed Dec 3, 2026
commit e2e0a3542281664c174dd9bc07441dc0059ebfc3
19 changes: 10 additions & 9 deletions docs/docs/Advanced/dynamic-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,13 +260,14 @@ prediction = Invoice(amount="N/A") # builds; amount == "N/A"
Invoice(amount=1234.5).compare_with(prediction)["field_scores"]["amount"] # 0.0
```

A value the numeric type accepts is stored exactly as before, so `"1234.50"` still becomes
`1234.5`. `model_dump()`, `model_dump(mode="json")` and `model_dump_json()` return a kept
string as the string, and validating the dump the way the string was kept builds the same
instance. That means lax validation, or strict validation for a numeric string such as
`"1234.5"` that only strict validation keeps; lax validation reads that one as a number. The field's `FieldInfo.annotation` stays `float` or `int`, so
`to_json_schema()`, `model_json_schema()` and the comparator are unchanged; its
`FieldInfo.metadata` holds the serializer that dumps a kept string as a string.
A value the numeric type accepts is stored as that number, so `"1234.50"` becomes `1234.5`.
`model_dump()`, `model_dump(mode="json")` and `model_dump_json()` return a kept string as the
string, and validating the dump again builds the same instance. A numeric string that only strict
validation keeps, such as `"1234.5"`, needs strict validation again, since lax validation reads it
as a number. The field's `FieldInfo.annotation` is `float` or `int` even when it holds a string,
so `to_json_schema()` and `model_json_schema()` describe a number and the comparator is chosen
as for any number field; its `FieldInfo.metadata` holds the serializer that dumps a kept string
as a string.

What a field accepts as a number depends on its type. An `integer` field keeps `"1e3"`,
`"1.50"` and `"inf"` as strings, because none of them is an integer, and `NumericComparator`
Expand All @@ -277,8 +278,8 @@ is not an integer, such as `12.5`, while the string `"12.5"` is kept.
Strict validation, including `model_validate_json(..., strict=True)`, rejects a numeric
string, so there `"1234.5"` is kept as the string `"1234.5"` rather than raising.

The same applies to a ground truth. One holding `"N/A"` used to fail when it was built; it is now
kept. A ground truth the comparator cannot read, such as `"N/A"`, scores 0.0 against every
The same applies to a ground truth: one holding `"N/A"` builds and keeps the string. A ground
truth the comparator cannot read, such as `"N/A"`, scores 0.0 against every
prediction, `"N/A"` included. One it can read still matches: `"$1,250"` or `"١٢٥٠"` against
`1250` scores 1.0. An empty string is read as absent on either side, as in any field, so `""`
against `""` or `None` matches.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
choose.
"""

import itertools
from typing import Annotated, Any, Dict, List

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the counter below (Must fix 1).

Suggested change
from typing import Annotated, Any, Dict, List
import itertools
from typing import Annotated, Any, Dict, List


from pydantic import ValidationError, field_validator
Expand Down Expand Up @@ -136,10 +137,13 @@ def serialize_by_value(annotation: Any) -> Any:
return Annotated[annotation, _SERIALIZE_BY_VALUE]


# One name per generated class: pydantic keys inherited validators by name, so a
# shared name would let a class built on a generated class replace the
# validator that covers the fields it inherits.
_VALIDATOR_IDS = itertools.count()


def scoreable_number_validators(names: List[str]) -> Dict[str, Any]:
"""The ``__validators__`` that keep a non-numeric string in ``names``."""
return {
"_keep_unparseable_numeric_string": field_validator(*names, mode="wrap")(
_keep_unparseable_string
),
}
name = f"_keep_unparseable_numeric_string_{next(_VALIDATOR_IDS)}"
return {name: field_validator(*names, mode="wrap")(_keep_unparseable_string)}
Original file line number Diff line number Diff line change
Expand Up @@ -677,3 +677,59 @@ def test_a_ground_truth_the_comparator_can_read_still_matches(ground_truth, pred
Model = schema_model("number")
result = Model(amount=ground_truth).compare_with(Model(amount=prediction))
assert result["field_scores"]["amount"] == 1.0


def _child_of(base, builder):
"""A class built on ``base`` by ``builder``, adding an integer ``qty`` field."""
if builder == "stickler_config":
return base.model_from_json(
{
"model_name": "Child",
"fields": {"qty": {"type": "int", "comparator": "NumericComparator"}},
}
)
return base.from_json_schema(
{"type": "object", "title": "Child", "properties": {"qty": {"type": "integer"}}}
)


@pytest.mark.parametrize("builder", ["stickler_config", "json_schema"])
def test_a_class_built_on_a_generated_class_keeps_the_fallback_on_inherited_fields(
builder,
):
"""Each generated class registers its own validator, so a child adds to it.

pydantic keys inherited validators by name. With one shared name, the
child's validator, which lists only the child's own numeric fields,
replaced the parent's, and an inherited field rejected ``"N/A"`` again.
"""
Base = schema_model("number")
Child = _child_of(Base, builder)
with warnings.catch_warnings():
warnings.simplefilter("error")
instance = Child(amount="N/A", qty="n/a")
assert instance.amount == "N/A"
assert instance.qty == "n/a"
assert (
Child(amount=1, qty=2).compare_with(Child(amount="N/A", qty=2))["field_scores"][
"amount"
]
== 0.0
)


@pytest.mark.parametrize("builder", ["stickler_config", "json_schema"])
def test_three_levels_of_generated_classes_keep_every_fallback(builder):
Base = schema_model("number")
Child = _child_of(Base, builder)
Grandchild = Child.from_json_schema(
{
"type": "object",
"title": "Grandchild",
"properties": {"rate": {"type": "number"}},
}
)
with warnings.catch_warnings():
warnings.simplefilter("error")
instance = Grandchild(amount="N/A", qty="n/a", rate="tbd")
assert (instance.amount, instance.qty, instance.rate) == ("N/A", "n/a", "tbd")