Skip to content

Validation errors for Literal types incorrectly say 'enum value' #1009

@Siyet

Description

@Siyet

Description

When validation fails for a typing.Literal type, msgspec raises a ValidationError with the message Invalid enum value <val>. This is misleading because the user is not using enum.Enum, they are using typing.Literal.

Reproduction

import msgspec
from typing import Literal

msgspec.json.decode(b'4', type=Literal[1, 2, 3])
# msgspec.ValidationError: Invalid enum value 4

msgspec.json.decode(b'"bad"', type=Literal["one", "two"])
# msgspec.ValidationError: Invalid enum value 'bad'

msgspec.json.decode(b'false', type=Literal[True])
# msgspec.ValidationError: Invalid enum value False

Expected

A wording that does not reference enum, since the type is not an enum. For example:

Invalid value 4
Invalid value 'bad'
Invalid value False

Or, even more useful, a message that lists the allowed literals:

Invalid value 4, expected one of (1, 2, 3)

Notes

  • This affects all decode paths (JSON, MsgPack, convert).
  • The same error path (_Lookup_OnMissing) is shared between Enum and Literal, so the fix needs to differentiate between the two cases (when lookup->cls != NULL it is an Enum, otherwise it is a Literal).
  • Bool literals (added in Support Literal[True] and Literal[False] types #1004) use a separate code path but produce the same misleading wording.

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