Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions src/serializers/type_serializers/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::tools::SchemaDict;
use super::simple::to_str_json_key;
use super::{
infer_json_key, infer_serialize, infer_to_python, BuildSerializer, CombinedSerializer, Extra, IsType, ObType,
SerMode, TypeSerializer,
SerCheck, SerMode, TypeSerializer,
};

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -73,12 +73,18 @@ impl TypeSerializer for FloatSerializer {
let py = value.py();
match extra.ob_type_lookup.is_type(value, ObType::Float) {
IsType::Exact => Ok(value.into_py(py)),
IsType::Subclass => match extra.mode {
SerMode::Json => {
let rust_value = value.extract::<f64>()?;
Ok(rust_value.to_object(py))
IsType::Subclass => match extra.check {
SerCheck::Strict => {
extra.warnings.on_fallback_py(self.get_name(), value, extra)?;
infer_to_python(value, include, exclude, extra)
}
_ => infer_to_python(value, include, exclude, extra),
SerCheck::Lax | SerCheck::None => match extra.mode {
SerMode::Json => {
let rust_value = value.extract::<f64>()?;
Ok(rust_value.to_object(py))
}
_ => infer_to_python(value, include, exclude, extra),
},
},
IsType::False => {
extra.warnings.on_fallback_py(self.get_name(), value, extra)?;
Expand Down
12 changes: 12 additions & 0 deletions tests/serializers/test_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,3 +626,15 @@ def test_union_serializer_picks_exact_type_over_subclass_json(
)
assert s.to_python(input_value, mode='json') == expected_value
assert s.to_json(input_value) == json.dumps(expected_value).encode()


def test_union_float_int() -> None:
s = SchemaSerializer(core_schema.union_schema([core_schema.float_schema(), core_schema.int_schema()]))

assert s.to_python(1) == 1
assert json.loads(s.to_json(1)) == 1

s = SchemaSerializer(core_schema.union_schema([core_schema.int_schema(), core_schema.float_schema()]))

assert s.to_python(1) == 1
assert json.loads(s.to_json(1)) == 1