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

When using Literal type provide a way to detect the field type instead of defaulting to Raw #154

Open
mark-akeero opened this issue Jul 19, 2021 · 0 comments

Comments

@mark-akeero
Copy link

When you use the Literal type in your dataclass it defaults the Marshmallow field to be Raw. Would it be possible to make a change to allow detection of the type used in the Literal and set the correct Marshmallow field.

What the code currently does when it detects a Literal

    if typing_inspect.is_literal_type(typ):
        arguments = typing_inspect.get_args(typ)
        return marshmallow.fields.Raw(
            validate=(
                marshmallow.validate.Equal(arguments[0])
                if len(arguments) == 1
                else marshmallow.validate.OneOf(arguments)
            ),
            **metadata,
        )

If you are using Apispec to generate Api docs this causes issues in the OpenApi doc as there is no "type" value set causing it to not render the choices in the enum value

I can workaround this by supplying the value via Marshmallow Metadata as in the example below, so not a huge issue at the moment for me.

from dataclasses import field
from typing import Literal
from marshmallow_dataclass import dataclass

@dataclass
class Status:
    status: Literal["done", "todo"] = field(metadata=dict(metadata={'type': 'string'}))
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

No branches or pull requests

1 participant