Skip to content

Omitting defaults does not work with array-like structs #720

@chuckwondo

Description

@chuckwondo

Description

When setting both omit_defaults and array_like to True, defaults are not omitted.

For example, without array_like=True:

class Position(
    msgspec.Struct,
    frozen=True,
    forbid_unknown_fields=True,
    omit_defaults=True,
):
    longitude: float
    latitude: float
    altitude: float = 0.0

Performing a roundtrip works as expected:

>>> pos = msgspec.json.Decoder(Position).decode('{ "longitude": 1.0, "latitude": 2.0 }')
>>> pos
Position(longitude=1.0, latitude=2.0, altitude=0.0)
>>> msgspec.json.encode(pos)
b'{"longitude":1.0,"latitude":2.0}'

However, adding array_like=True to the Position definition above causes rountripping to fail:

>>> pos = msgspec.json.Decoder(Position).decode('[1.0,2.0]')
>>> pos
Position(longitude=1.0, latitude=2.0, altitude=0.0)
>>> msgspec.json.encode(pos)
b'[1.0,2.0,0.0]'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions