Repository navigation
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #300 +/- ##
==========================================
- Coverage 93.89% 93.63% -0.27%
==========================================
Files 205 205
Lines 23126 23171 +45
Branches 1517 1517
==========================================
- Hits 21715 21696 -19
- Misses 1119 1183 +64
Partials 292 292 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Collaborator
|
Alternative proposal: only coerce between models when the target is a context. if isinstance(v, PydanticBaseModel) and issubclass(cls, ContextBase):
v = v.model_dump(exclude={"type_"})Contexts are frozen value objects, so treating "any model whose fields fit" as a valid input is like pydantic accepting Behaviour change:
|
BaseModel validation coerced an instance of any model into any other model whose fields fit, by dumping it and re-validating the result. Inside a union, pydantic tries each member in turn, so this ran for every member ahead of the one that matched: it built objects that were then discarded, ran their validators on the coerced data, and an error other than a ValidationError in one of them aborted the whole union. With union_mode="left_to_right", it also returned the coerced object instead of the instance passed in. Coercion now only applies when the target is a context. Contexts are frozen value objects, so any model whose fields fit is a valid input, and CallableModel relies on this to convert one context type into another. Other models reject instances of unrelated models, as in pydantic, so their unions behave like pydantic's, including in TypeAdapter and plain pydantic models. Signed-off-by: Hin Tse <5867507+hintse@users.noreply.github.com>
hintse
force-pushed
the
fix/union-model-coercion-last
branch
from
November 26, 2026 04:35
2b01f0d to
fab3dbf
Compare
Collaborator
Author
|
Thanks, I've switched the PR to this approach (fab3dbf).
The full suite passes locally (1636 passed, Python 3.11, pydantic 2.14.4). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
BaseModel._base_model_validatorcoerced an instance of any model into any other model whose fields fit, by dumping it and re-validating the dict. Inside a union, pydantic tries the members in order, so this coercion ran for every member ahead of the one that matched:Problems with this:
ValidationError, the whole union failed, even though a later member was an exact match.union_mode="left_to_right", the field got the coercedAinstead of theBpassed in.Change
Following the suggestion in the review, coercion between models now only applies when the target is a context:
Contexts are frozen value objects, so any model whose fields fit is a valid input, and
CallableModelrelies on this to convert one context type into another. Other models reject instances of unrelated models, as in pydantic.Comparison with plain pydantic
With
AandBunrelated non-context models that have the same fields, and an instance ofBpassed in (measured on pydantic 2.14.4):A | B(smart mode, the default)Bpassed in, noAbuiltBpassed in, but anAis built from it and discardedBpassed in, noAbuiltA | Bwithunion_mode="left_to_right"Bpassed in, noAbuiltAbuilt from theBBpassed in, noAbuiltA | BinTypeAdapteror a plain pydantic modelBpassed in, noAbuiltBpassed in, but anAis built from it and discardedBpassed in, noAbuiltA(not a union)model_typeerror)Abuilt from theBValidationError)Contexts behave as before: a context still validates from any model whose fields fit, including inside unions.
Behaviour changes
ValidationError.union_mode="left_to_right", an instance of a later union member now comes back unchanged instead of being coerced into an earlier member.Docs
docs/wiki/reference/Contexts-and-Results.mdnow describes context coercion, and notes that context validators should have no side effects, since validation may build a context more than once (for example while trying the members of a union) and discard it.Type of Change
Checklist
ruff check,ruff format --check,mdformat --check,codespellon the changed doc)