Ensure custom __init__() is called when using model_validate_strings()#12897
Merged
Viicos merged 2 commits intopydantic:mainfrom Mar 25, 2026
Merged
Conversation
davidhewitt
previously requested changes
Mar 9, 2026
Collaborator
davidhewitt
left a comment
There was a problem hiding this comment.
Thanks, implementation seems correct however I would like the test to be unified with existing one please.
__init__() is called when using model_validate_strings()
Merging this PR will improve performance by 5.22%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_complete_core_isinstance |
1.6 ms | 1.5 ms | +5.22% |
| ⚡ | test_complete_core_error |
1.6 ms | 1.5 ms | +5.12% |
Comparing siewcapital:fix-model-validate-strings-custom-init (16dafbf) with main (0574aaa)
Contributor
Viicos
approved these changes
Mar 25, 2026
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.
Summary
model_validate_strings()currently skips the custom__init__path for models becauseStringMappingalways returnsNonefromInput::as_kwargs().This causes behavior differences compared to
model_validate()/model_validate_json()for models that override__init__, and is the root issue reported in #12718.Changes
StringMapping::as_kwargs()when the input is a mapping.Nonefor non-mapping (String) values.model_validate_strings()invokes a custom__init__and forwards string mapping values.Tests
uv run pytest tests/test_edge_cases.py -k "custom_init or model_validate_strings_custom_init_called or init_inspection"uv run pytest tests/test_main.py -k "model_validate_strings"Closes #12718