Skip to content

Commit ecf2282

Browse files
authored
Fix inspect.type_info crashing on mixed-type Literals (msgspec#1080)
Fixes msgspec#1018. ### Problem `msgspec.inspect.type_info` crashes on mixed-type `Literal`s: ```python msgspec.inspect.type_info(Literal[1, None]) # TypeError: '<' not supported between instances of 'NoneType' and 'int' msgspec.inspect.type_info(Literal[True, "yes"]) # same ``` `type_info` does `tuple(sorted(args))` on the literal's values, and Python 3 forbids `<` between values of different types. The encoder/decoder already handle these mixed-type literals fine (e.g. `Literal[1, None]` decodes `1`/`null` and rejects `2`), so `type_info` failing on them is a contract violation. ### Fix Sort the literal values with a `(type name, value)` key instead. This keeps existing same-type ordering identical (`Literal[3,1,2]` → `(1,2,3)`, `Literal[True,False]` → `(False,True)`) while grouping mixed-type literals deterministically rather than crashing, and a `try/except TypeError` falls back to the original order as a safety net. The `LiteralType.values` annotation is widened to allow mixed and `None` members. ### Tests Added `test_mixed_literal` (`Literal[1, None]`, `Literal[True, "yes"]`) and `test_bool_literal`. Without the fix `test_mixed_literal` raises the `TypeError`; with it the full `test_inspect.py`/`test_schema.py` pass (276 passed, 13 skipped). I'll add a `docs/changelog.md` entry referencing this PR number in a follow-up commit. Disclosure: I used AI assistance (Claude) to help locate and draft this fix, under my direction and review.
1 parent 956a7a4 commit ecf2282

5 files changed

Lines changed: 41 additions & 4 deletions

File tree

‎docs/changelog.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
- Fix reference leaks in `typenode_collect_literal`, `Meta.__rich_repr__`,
1818
`ms_decode_bigint`, and `Encoder.__init__` ({pr}`1021`, {pr}`1022`,
1919
{pr}`1023`, {pr}`1040`).
20+
- Fix `msgspec.inspect.type_info` and `msgspec.json.schema` crashing on mixed-type `Literal`s such as `Literal[1, None]` ({pr}`1080`).
2021
- Fix missing GC traversal and clearing of some module state members ({pr}`1060`).
2122
- Ensure an exception is always set on allocation failures ({pr}`1044`).
2223
- Fix compilation warnings on Python 3.15 ({pr}`1077`).

‎src/msgspec/_json_schema.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,11 @@ def to_schema(self, t: mi.Type, check_ref: bool = True) -> dict[str, Any]:
364364
else:
365365
schema["anyOf"] = options
366366
elif isinstance(t, mi.LiteralType):
367-
schema["enum"] = sorted(t.values)
367+
# `t.values` may mix types (e.g. `Literal[1, None]`), which a plain
368+
# `sorted` can't order; reuse the same type-aware sort as
369+
# `inspect.type_info` so the two entry points agree and neither
370+
# crashes.
371+
schema["enum"] = list(mi._sort_literal_args(t.values))
368372
elif isinstance(t, mi.EnumType):
369373
schema.setdefault("title", t.cls.__name__)
370374
if doc := _get_doc(t):

‎src/msgspec/inspect.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -308,10 +308,11 @@ class LiteralType(Type):
308308
----------
309309
values: tuple
310310
A tuple of possible values for this literal instance. Only `bool`,
311-
`str`, or `int` literals are supported.
311+
`str`, `int`, or `None` literals are supported, and a single literal
312+
may mix these types (e.g. ``Literal[1, None]``).
312313
"""
313314

314-
values: tuple[bool, ...] | tuple[str, ...] | tuple[int, ...]
315+
values: tuple[bool | str | int | None, ...]
315316

316317

317318
class CustomType(Type):
@@ -694,6 +695,18 @@ def _origin_args_metadata(t):
694695
return origin, args, tuple(metadata)
695696

696697

698+
def _sort_literal_args(args):
699+
# `Literal` may mix value types (e.g. `Literal[1, None]`), which a plain
700+
# `sorted` can't order since Python 3 forbids comparing across types. Sort
701+
# by type name first so members of the same type stay ordered as before,
702+
# while mixed-type literals are grouped deterministically instead of
703+
# crashing.
704+
try:
705+
return tuple(sorted(args, key=lambda x: (type(x).__name__, x)))
706+
except TypeError:
707+
return tuple(args)
708+
709+
697710
def _is_enum(t):
698711
return type(t) is enum.EnumMeta
699712

@@ -909,7 +922,7 @@ def _translate_inner(
909922
args = tuple(self.translate(a) for a in args if a is not _UnsetType)
910923
return args[0] if len(args) == 1 else UnionType(args)
911924
elif t is Literal:
912-
return LiteralType(tuple(sorted(args)))
925+
return LiteralType(_sort_literal_args(args))
913926
elif _is_enum(t):
914927
return EnumType(t)
915928
elif is_struct_type(t):

‎tests/unit/test_inspect.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,18 @@ def test_str_literal():
370370
assert mi.type_info(Literal["c", "a", "b"]) == mi.LiteralType(("a", "b", "c"))
371371

372372

373+
def test_bool_literal():
374+
assert mi.type_info(Literal[True]) == mi.LiteralType((True,))
375+
assert mi.type_info(Literal[True, False]) == mi.LiteralType((False, True))
376+
377+
378+
def test_mixed_literal():
379+
# Literals may mix value types; `type_info` shouldn't crash trying to sort
380+
# values of incomparable types (gh#1018).
381+
assert mi.type_info(Literal[1, None]) == mi.LiteralType((None, 1))
382+
assert mi.type_info(Literal[True, "yes"]) == mi.LiteralType((True, "yes"))
383+
384+
373385
def test_int_enum():
374386
class Example(enum.IntEnum):
375387
B = 3

‎tests/unit/test_schema.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,13 @@ def test_str_literal():
315315
assert msgspec.json.schema(Literal["c", "a", "b"]) == {"enum": ["a", "b", "c"]}
316316

317317

318+
def test_mixed_literal():
319+
# A Literal may mix value types; building its schema must not crash trying
320+
# to sort values of incomparable types (gh#1018).
321+
assert msgspec.json.schema(Literal[1, None]) == {"enum": [None, 1]}
322+
assert msgspec.json.schema(Literal[True, "yes"]) == {"enum": [True, "yes"]}
323+
324+
318325
def test_struct_object():
319326
class Point(msgspec.Struct, forbid_unknown_fields=True):
320327
x: int

0 commit comments

Comments
 (0)