-
Notifications
You must be signed in to change notification settings - Fork 312
add polymorphic_serialization for models and dataclasses
#1881
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
cb281b5
add `polymorphic_serialization` config for models and dataclasses
davidhewitt f590f21
configure global runtime override for `polymorphic_serialization`
davidhewitt 9d0079b
test when `config` not set
davidhewitt 9d9cc75
lint fixes
davidhewitt 53da883
test fixes
davidhewitt f4fc147
fix rust tests
davidhewitt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| use std::{borrow::Cow, sync::Arc}; | ||
|
|
||
| use pyo3::{prelude::*, types::PyType}; | ||
|
|
||
| use crate::serializers::{ | ||
| errors::unwrap_ser_error, | ||
| extra::SerCheck, | ||
| infer::call_pydantic_serializer, | ||
| shared::{serialize_to_json, serialize_to_python, DoSerialize, TypeSerializer}, | ||
| CombinedSerializer, SerializationState, | ||
| }; | ||
|
|
||
| /// The polymorphism trampoline detects subclasses of its target type and dispatches to their | ||
| /// `__pydantic_serializer__` serializer for serialization. | ||
| /// | ||
| /// This exists as a separate structure to allow for cases such as model serializers where the | ||
| /// inner serializer may just be a function serializer and so cannot handle polymorphism itself. | ||
| #[derive(Debug)] | ||
| pub struct PolymorphismTrampoline { | ||
| class: Py<PyType>, | ||
| /// Inner serializer used when the type is not a subclass (responsible for any fallback etc) | ||
| pub(crate) serializer: Arc<CombinedSerializer>, | ||
| /// Whether polymorphic serialization is enabled from config | ||
| enabled_from_config: bool, | ||
| } | ||
|
|
||
| impl_py_gc_traverse!(PolymorphismTrampoline { class, serializer }); | ||
|
|
||
| impl PolymorphismTrampoline { | ||
| pub fn new(class: Py<PyType>, serializer: Arc<CombinedSerializer>, enabled_from_config: bool) -> Self { | ||
| Self { | ||
| class, | ||
| serializer, | ||
| enabled_from_config, | ||
| } | ||
| } | ||
|
|
||
| fn is_subclass(&self, value: &Bound<'_, PyAny>) -> PyResult<bool> { | ||
| Ok(!value.get_type().is(&self.class) && value.is_instance(self.class.bind(value.py()))?) | ||
| } | ||
|
|
||
| fn serialize<'py, T, E: From<PyErr>>( | ||
| &self, | ||
| value: &Bound<'py, PyAny>, | ||
| state: &mut SerializationState<'_, 'py>, | ||
| do_serialize: impl DoSerialize<'py, T, E>, | ||
| ) -> Result<T, E> { | ||
| let runtime_polymorphic = state.extra.polymorphic_serialization; | ||
| if state.check != SerCheck::Strict // strict disables polymorphism | ||
| && runtime_polymorphic.unwrap_or(self.enabled_from_config) | ||
| && self.is_subclass(value)? | ||
| { | ||
| call_pydantic_serializer(value, state, do_serialize) | ||
| } else { | ||
| do_serialize.serialize_no_infer(&self.serializer, value, state) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl TypeSerializer for PolymorphismTrampoline { | ||
| fn to_python<'py>( | ||
| &self, | ||
| value: &Bound<'py, PyAny>, | ||
| state: &mut SerializationState<'_, 'py>, | ||
| ) -> PyResult<Py<PyAny>> { | ||
| self.serialize(value, state, serialize_to_python()) | ||
| } | ||
|
|
||
| fn json_key<'a, 'py>( | ||
| &self, | ||
| key: &'a Bound<'py, PyAny>, | ||
| state: &mut SerializationState<'_, 'py>, | ||
| ) -> PyResult<Cow<'a, str>> { | ||
| // json key serialization for models and dataclasses was always polymorphic anyway | ||
| // FIXME: make this consistent with the other cases? | ||
| self.serializer.json_key(key, state) | ||
| } | ||
|
|
||
| fn serde_serialize<'py, S: serde::ser::Serializer>( | ||
| &self, | ||
| value: &Bound<'py, PyAny>, | ||
| serializer: S, | ||
| state: &mut SerializationState<'_, 'py>, | ||
| ) -> Result<S::Ok, S::Error> { | ||
| self.serialize(value, state, serialize_to_json(serializer)) | ||
| .map_err(unwrap_ser_error) | ||
| } | ||
|
|
||
| fn get_name(&self) -> &str { | ||
| self.serializer.get_name() | ||
| } | ||
|
|
||
| fn retry_with_lax_check(&self) -> bool { | ||
| self.serializer.retry_with_lax_check() | ||
| } | ||
| } |
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
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
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).