Skip to content

Conversation

@davidhewitt
Copy link
Contributor

@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

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
Contributor 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
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
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).

let type_: Bound<'_, PyString> = schema.get_as_req(intern!(py, "type"))?;
let type_ = type_.to_str()?;

if type_ == "model" || type_ == "dataclass" {
Copy link
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 on lines +102 to +104
print(inner_serializer)
print(outer_serializer)

Copy link
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
Contributor Author

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants