Skip to content
This repository was archived by the owner on Apr 11, 2026. It is now read-only.

add polymorphic_serialization for models and dataclasses#1881

Closed
davidhewitt wants to merge 6 commits intomainfrom
dh/polymorphic-serialization
Closed

add polymorphic_serialization for models and dataclasses#1881
davidhewitt wants to merge 6 commits intomainfrom
dh/polymorphic-serialization

Conversation

@davidhewitt
Copy link
Copy Markdown
Collaborator

@davidhewitt davidhewitt commented Nov 2, 2025

Change Summary

Introduced as a possible solution to pydantic/pydantic#12382; the theory is that most uses of serialize_as_any are because users want to respect subtyping properly.

This PR introduces a configuration option and runtime flag polymorphic_serialization which is used to enable serializing subclasses of models and dataclasses as the subclass, not as the base class.

To maintain backwards compatibility, the default is False - models and dataclasses will be serialized as the exact type in the schema.

When the config is set to True, then models and dataclasess will be serialized as their runtime type. This also respects any model serializer the subclass may be using.

Users can also pass polymorphic_serialization as a runtime option to the serialization functions; doing so will override the config value (i.e. can be globally enabled or disabled).


Not explored yet in this PR, an additional / alternative possibility could be to expose this as some kind of wrapper so that for foreign types one can use Annotated[ForeignBaseModel, PolymorphicSerialization] to enable this even when the type didn't opt in.

(An Annotated form may remove the need for the global runtime override.)

Related issue number

pydantic/pydantic#12382

Checklist

  • Unit tests for the changes exist
  • Documentation reflects the changes where applicable
  • Pydantic tests pass with this pydantic-core (except for expected changes)
  • My PR is ready to review, please add a comment including the phrase "please review" to assign reviewers

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Nov 2, 2025

CodSpeed Performance Report

Merging #1881 will not alter performance

Comparing dh/polymorphic-serialization (f4fc147) with main (20d576b)

Summary

✅ 163 untouched


@pytest.mark.parametrize('input_value', [ModelA(b'bite', 2.3456), SubclassA(b'bite', 2.3456)])
def test_model_a(model_serializer: SchemaSerializer, input_value):
print(model_serializer, input_value)
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Suggested change
print(model_serializer, input_value)

@davidhewitt davidhewitt marked this pull request as ready for review November 2, 2025 14:08
Copy link
Copy Markdown
Member

@Viicos Viicos left a comment

Choose a reason for hiding this comment

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

Great work!

fallback: A function to call when an unknown value is encountered,
if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization: Whether to override configured model and dataclass polymorphic serialization for this call.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe we should follow the existing pattern for the description? (That is, other parameters don't mention this "override" behavior of the configuration. Maybe in the actual docstring of the method, mention that these parameters override the corresponding configuration or similar).

Comment thread src/serializers/shared.rs
let type_: Bound<'_, PyString> = schema.get_as_req(intern!(py, "type"))?;
let type_ = type_.to_str()?;

if type_ == "model" || type_ == "dataclass" {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
if type_ == "model" || type_ == "dataclass" {
// Note: it could make sense to generalize this behavior for any type that may have subclasses,
// but apart from models and dataclasses, that would be for arbitrary types where custom serialization
// has to be defined already.
if type_ == "model" || type_ == "dataclass" {

Comment thread tests/test_prebuilt.py
Comment on lines +102 to +104
print(inner_serializer)
print(outer_serializer)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
print(inner_serializer)
print(outer_serializer)

@davidhewitt
Copy link
Copy Markdown
Collaborator Author

Thanks, I also added to the OP a note on an idea like Annotated[ForeignBaseModel, PolymorphicSerialization], not explored that yet.

@davidhewitt
Copy link
Copy Markdown
Collaborator Author

Moved to pydantic/pydantic#12518

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants