Fatal1ty / mashumaro

Fast and well tested serialization library
Apache License 2.0
751 stars 44 forks source link

Union type of [int | float] not serialized correctly #213

Closed gvashishtha closed 4 months ago

gvashishtha commented 4 months ago

Description

I am trying to get mashumaro to correctly handle a union type that can be either int or float. But when I call to_json() the value is automatically cast to an integer

What I Did

from mashumaro.mixins.json import DataClassJSONMixin
from dataclasses import dataclass, field
import json

@dataclass
class Foo(DataClassJSONMixin):
    x: int | float
    _x: str = field(init=False, repr=False)
    @property
    def x(self) -> int | float:
        return json.loads(self._x)
    @x.setter
    def x(self, x: int | float) -> None:
        self._x = json.dumps(x)

test1=Foo(7.8)
print(test1.to_json())  # prints '{"x": 7, "_x": "7.8"}'  instead of '{"x": 7.8, "_x": "7.8"}'
Fatal1ty commented 4 months ago

This is fixed in https://github.com/Fatal1ty/mashumaro/pull/194 and will be available in the next release.

Fatal1ty commented 4 months ago

Until a new version released, a workaround is to register pass_through serialization strategy:

@dataclass
class Foo(DataClassJSONMixin):
    x: int | float
    _x: str = field(init=False, repr=False)

    class Config(BaseConfig):
        serialization_strategy = {
            int: {"serialize": pass_through},
            float: {"serialize": pass_through}
        }