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

list[enum] ignores "by_value": True flag #255

Open
rayrapetyan opened this issue Mar 9, 2024 · 1 comment
Open

list[enum] ignores "by_value": True flag #255

rayrapetyan opened this issue Mar 9, 2024 · 1 comment

Comments

@rayrapetyan
Copy link

Sample code:

from dataclasses import field
from enum import StrEnum
from typing import (
    ClassVar,
    List,
    Type,
)

from marshmallow import Schema
from marshmallow_dataclass import dataclass


class Color(StrEnum):
    RED = "red"
    GREEN = "green"
    BLUE = "blue"


@dataclass
class Thing:
    color: Color = field(metadata={"by_value": True})
    color_list: List[Color] = field(default_factory=list, metadata={"by_value": True})
    Schema: ClassVar[Type[Schema]] = Schema  # pylint: disable=invalid-name


thing = Thing(color=Color.RED, color_list=[Color.RED, Color.GREEN, Color.BLUE])  # Example data
serialized_thing = Thing.Schema().dump(thing)
print(serialized_thing)

Actual result:

{'color': 'red', 'color_list': ['RED', 'GREEN', 'BLUE']}

Expected result:

{'color': 'red', 'color_list': ['red', 'green', 'blue]}
@ddorian
Copy link

ddorian commented May 24, 2024

Does this work:

from dataclasses import field
from enum import StrEnum
from typing import ClassVar, List, Type

from marshmallow_dataclass import dataclass

class Color(StrEnum):
    RED = "red"
    GREEN = "green"
    BLUE = "blue"

from marshmallow import Schema, fields

@dataclass
class Thing:
    color: Color = field(metadata={"by_value": True})
    color_list: List[Color] = field(
        default_factory=list, metadata=dict(cls_or_instance=fields.Enum(Color, by_value=True))
    )
    # Schema: ClassVar[Type["Schema"]] = Schema  # pylint: disable=invalid-name

thing = Thing(color=Color.RED, color_list=[Color.RED, Color.GREEN, Color.BLUE])  # Example data
serialized_thing = Thing.Schema().dump(thing)
print(serialized_thing)

You have to change this line https://github.com/lovasoa/marshmallow_dataclass/blob/master/marshmallow_dataclass/__init__.py#L654 to

            return list_type(**metadata)

You need a way to set the metadata for the cls_or_instance attribute. Maybe it can do a `cls_or_instance_metadata = metadata.pop("cls_or_instance_metadata") inside so you can provide as:

    color_list: List[Color] = field(
        default_factory=list, metadata=dict(cls_or_instance_metadata=dict(enum=Color, by_value=True))
    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants