Skip to content

Commit 39a6b10

Browse files
Fix float serialization behavior in strict mode (#1400)
1 parent 7368c1f commit 39a6b10

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

src/serializers/type_serializers/float.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@ use crate::tools::SchemaDict;
1212
use super::simple::to_str_json_key;
1313
use super::{
1414
infer_json_key, infer_serialize, infer_to_python, BuildSerializer, CombinedSerializer, Extra, IsType, ObType,
15-
SerMode, TypeSerializer,
15+
SerCheck, SerMode, TypeSerializer,
1616
};
17+
use crate::serializers::errors::PydanticSerializationUnexpectedValue;
1718

1819
#[derive(Debug)]
1920
pub struct FloatSerializer {
@@ -73,12 +74,15 @@ impl TypeSerializer for FloatSerializer {
7374
let py = value.py();
7475
match extra.ob_type_lookup.is_type(value, ObType::Float) {
7576
IsType::Exact => Ok(value.into_py(py)),
76-
IsType::Subclass => match extra.mode {
77-
SerMode::Json => {
78-
let rust_value = value.extract::<f64>()?;
79-
Ok(rust_value.to_object(py))
80-
}
81-
_ => infer_to_python(value, include, exclude, extra),
77+
IsType::Subclass => match extra.check {
78+
SerCheck::Strict => Err(PydanticSerializationUnexpectedValue::new_err(None)),
79+
SerCheck::Lax | SerCheck::None => match extra.mode {
80+
SerMode::Json => {
81+
let rust_value = value.extract::<f64>()?;
82+
Ok(rust_value.to_object(py))
83+
}
84+
_ => infer_to_python(value, include, exclude, extra),
85+
},
8286
},
8387
IsType::False => {
8488
extra.warnings.on_fallback_py(self.get_name(), value, extra)?;

tests/serializers/test_union.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,18 @@ def test_union_serializer_picks_exact_type_over_subclass_json(
628628
assert s.to_json(input_value) == json.dumps(expected_value).encode()
629629

630630

631+
def test_union_float_int() -> None:
632+
s = SchemaSerializer(core_schema.union_schema([core_schema.float_schema(), core_schema.int_schema()]))
633+
634+
assert s.to_python(1) == 1
635+
assert json.loads(s.to_json(1)) == 1
636+
637+
s = SchemaSerializer(core_schema.union_schema([core_schema.int_schema(), core_schema.float_schema()]))
638+
639+
assert s.to_python(1) == 1
640+
assert json.loads(s.to_json(1)) == 1
641+
642+
631643
def test_custom_serializer() -> None:
632644
s = SchemaSerializer(
633645
core_schema.union_schema(

0 commit comments

Comments
 (0)