Skip to content

Commit 1287d22

Browse files
Allow case where __pydantic_extra__ is None, even if extra='allow' (#1236)
Co-authored-by: David Hewitt <[email protected]>
1 parent abaab10 commit 1287d22

File tree

2 files changed

+38
-8
lines changed

2 files changed

+38
-8
lines changed

src/serializers/fields.rs

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,13 +132,7 @@ impl GeneralFieldsSerializer {
132132

133133
fn extract_dicts<'a>(&self, value: &Bound<'a, PyAny>) -> Option<(Bound<'a, PyDict>, Option<Bound<'a, PyDict>>)> {
134134
match self.mode {
135-
FieldsMode::ModelExtra => {
136-
if let Ok((main_dict, extra_dict)) = value.extract() {
137-
Some((main_dict, Some(extra_dict)))
138-
} else {
139-
None
140-
}
141-
}
135+
FieldsMode::ModelExtra => value.extract().ok(),
142136
_ => {
143137
if let Ok(main_dict) = value.downcast::<PyDict>() {
144138
Some((main_dict.clone(), None))

tests/serializers/test_other.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import pytest
22

3-
from pydantic_core import SchemaSerializer, core_schema
3+
from pydantic_core import SchemaSerializer, SchemaValidator, core_schema
44

55
from ..conftest import plain_repr
66

@@ -60,3 +60,39 @@ def test_lax_or_strict_custom_ser():
6060
assert s.to_python('abc') == ' abc '
6161
assert s.to_python('abc', mode='json') == ' abc '
6262
assert s.to_json('abc') == b'" abc "'
63+
64+
65+
def test_serialize_with_extra_on_superclass() -> None:
66+
class Parent:
67+
x: int
68+
69+
class Other(Parent):
70+
y: str
71+
72+
Parent.__pydantic_core_schema__ = core_schema.model_schema(
73+
Parent,
74+
core_schema.model_fields_schema(
75+
{
76+
'x': core_schema.model_field(core_schema.int_schema()),
77+
}
78+
),
79+
config=core_schema.CoreConfig(extra_fields_behavior='allow'),
80+
)
81+
Parent.__pydantic_validator__ = SchemaValidator(Parent.__pydantic_core_schema__)
82+
Parent.__pydantic_serializer__ = SchemaSerializer(Parent.__pydantic_core_schema__)
83+
84+
Other.__pydantic_core_schema__ = core_schema.model_schema(
85+
Other,
86+
core_schema.model_fields_schema(
87+
{
88+
'x': core_schema.model_field(core_schema.int_schema()),
89+
'y': core_schema.model_field(core_schema.str_schema()),
90+
}
91+
),
92+
config=core_schema.CoreConfig(extra_fields_behavior='forbid'),
93+
)
94+
Other.__pydantic_validator__ = SchemaValidator(Other.__pydantic_core_schema__)
95+
Other.__pydantic_serializer__ = SchemaSerializer(Other.__pydantic_core_schema__)
96+
97+
other = Other.__pydantic_validator__.validate_python({'x': 1, 'y': 'some string'})
98+
assert Parent.__pydantic_serializer__.to_python(other) == {'x': 1}

0 commit comments

Comments
 (0)