feat(python): optimize union factory and visit methods to avoid .dict() serialization #11339
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
Refs customer feedback about performance bottlenecks in discriminated union
factoryandvisitmethods.Link to Devin run: https://app.devin.ai/sessions/ac18896281bc4c41a46e21d637ce328f
Requested by: [email protected] (@tjb9dc)
Changes Made
This PR optimizes the
factoryandvisitmethods for discriminated unions to avoid expensive.dict()serialization/deserialization. Previously, these methods would:.dict(exclude_unset=True)on the source model (deep serialization)The new implementation uses shallow field copying via
copy_and_update_model, which:source.__dict__fields_set/__pydantic_fields_set__forexclude_unsetsemanticsconstruct/model_constructto bypass validation (matching original behavior)Files changed:
copy_and_update_modelutility to all 4 pydantic utility variantsdiscriminated_union_with_utils_generator.pyto emit optimized codecore_utilities.pyunionsfixtureUpdates since last revision
no-any-returnerrors by wrapping return values withtyping.cast(Model, ...)in all 4 pydantic utility variantsHuman Review Checklist
copy_and_update_modelcorrectly handlesfields_settracking (lines 288-323 inpydantic_utilities.py)pydantic.v1.BaseModel)discriminated_union_with_utils_generator.py- especially themake_visitor_argument_for_same_propertiesfunction andwrite_copy_and_updateclosureunion_with_base_properties.py) to confirm the optimization is applied correctly_build_urltest additions intest_http_client.py- these appear to be from a merge/rebase and may need to be reviewed separatelyTesting
unionsfixture (all 3 configurations:no-custom-config,union-utils,union-naming-v1)pnpm run check)