Repository navigation
Only coerce between models when the target is a context - #300
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #300 +/- ##
==========================================
- Coverage 93.63% 93.63% -0.01%
==========================================
Files 205 205
Lines 23158 23203 +45
Branches 1519 1519
==========================================
+ Hits 21683 21725 +42
- Misses 1181 1184 +3
Partials 294 294 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
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:
|
2b01f0d to
fab3dbf
Compare
|
Thanks, I've switched the PR to this approach (fab3dbf).
The full suite passes locally (1636 passed, Python 3.11, pydantic 2.14.4). |
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>
fab3dbf to
931549b
Compare
Test Results 1 files ±0 1 suites ±0 2m 26s ⏱️ -1s Results for commit 931549b. ± Comparison against base commit 424a17f. This pull request skips 1 and un-skips 4 tests.♻️ This comment has been updated with latest results. |
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)