Skip to content

Commit c29e3c7

Browse files
BUG: If a float-specified field holds an integer number, the resulting object is int instead of float
1 parent 5fcaf72 commit c29e3c7

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

openapi_python_client/templates/model.py.jinja

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ from typing import Any, TypeVar, BinaryIO, TextIO, TYPE_CHECKING, Generator
55

66
from attrs import define as _attrs_define
77
from attrs import field as _attrs_field
8+
89
{% if model.is_multipart_body %}
910
import json
1011
from .. import types
@@ -24,6 +25,14 @@ if TYPE_CHECKING:
2425
{% endfor %}
2526

2627

28+
def json_aware_cast(typ, val):
29+
# json does not distinguish between float and int, but the scheme carries this information.
30+
# So cast it here, to actually get correct types.
31+
# https://json-schema.org/understanding-json-schema/reference/numeric
32+
if issubclass(float, typ) and not issubclass(int, typ) and isinstance(val, int):
33+
val = float(val)
34+
return cast(typ, val)
35+
2736
{% if model.additional_properties %}
2837
{% set additional_property_type = 'Any' if model.additional_properties == True else model.additional_properties.get_type_string() %}
2938
{% endif %}

openapi_python_client/templates/property_templates/union_property.py.jinja

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def _parse_{{ property.python_name }}(data: object) -> {{ property.get_type_stri
3333
{% endif %}
3434
{% endfor %}
3535
{% if ns.contains_unmodified_properties %}
36-
return cast({{ property.get_type_string() }}, data)
36+
return json_aware_cast({{ property.get_type_string() }}, data)
3737
{% endif %}
3838

3939
{{ property.python_name }} = _parse_{{ property.python_name }}({{ source }})

0 commit comments

Comments
 (0)