Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
gvashishtha opened this issue Apr 16, 2024 · 2 comments
Closed

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

gvashishtha opened this issue Apr 16, 2024 · 2 comments
Labels
duplicate This issue or pull request already exists

Comments

@gvashishtha
Copy link

gvashishtha commented Apr 16, 2024

  • mashumaro version: 3.11
  • Python version: 3.10.12
  • Operating System: MacOS 14.4.1 ARM64

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"}'

@gvashishtha gvashishtha changed the title Union type of [int | float] not serialized/deserialized correctly Union type of [int | float] not serialized correctly Apr 16, 2024
@Fatal1ty
Copy link
Owner

This is fixed in #194 and will be available in the next release.

@Fatal1ty Fatal1ty added the duplicate This issue or pull request already exists label Apr 16, 2024
@Fatal1ty
Copy link
Owner

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}
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

2 participants