marshmallow_dataclass
marshmallow_dataclass copied to clipboard
When using Literal type provide a way to detect the field type instead of defaulting to Raw
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'}))