Skip to content

Commit 5840a15

Browse files
committed
fix: handle mixed-type Literals in inspect.type_info
`type_info()` crashes with `TypeError` on `Literal` types that mix value types (e.g. `Literal[1, None]`) because `sorted()` in Python 3 cannot compare values of different types. Use a type-aware sort key that groups by type name, with `None` always sorting first. Also update the `LiteralType.values` annotation to reflect that mixed-type tuples are valid. Closes msgspec#1018
1 parent 88ce26d commit 5840a15

2 files changed

Lines changed: 30 additions & 4 deletions

File tree

‎src/msgspec/inspect.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -315,11 +315,11 @@ class LiteralType(Type):
315315
Parameters
316316
----------
317317
values: tuple
318-
A tuple of possible values for this literal instance. Only `str` or
319-
`int` literals are supported.
318+
A tuple of possible values for this literal instance. Values may be
319+
``None``, ``int``, or ``str`` literals.
320320
"""
321321

322-
values: Union[Tuple[str, ...], Tuple[int, ...]]
322+
values: Tuple[Union[None, int, str], ...]
323323

324324

325325
class CustomType(Type):
@@ -885,7 +885,14 @@ def _translate_inner(
885885
args = tuple(self.translate(a) for a in args if a is not _UnsetType)
886886
return args[0] if len(args) == 1 else UnionType(args)
887887
elif t is Literal:
888-
return LiteralType(tuple(sorted(args)))
888+
return LiteralType(
889+
tuple(
890+
sorted(
891+
args,
892+
key=lambda x: ("", 0) if x is None else (type(x).__name__, x),
893+
)
894+
)
895+
)
889896
elif _is_enum(t):
890897
return EnumType(t)
891898
elif is_struct_type(t):

‎tests/unit/test_inspect.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,25 @@ def test_str_literal():
350350
assert mi.type_info(Literal["c", "a", "b"]) == mi.LiteralType(("a", "b", "c"))
351351

352352

353+
def test_none_literal():
354+
assert mi.type_info(Literal[None]) == mi.LiteralType((None,))
355+
356+
357+
def test_mixed_int_none_literal():
358+
result = mi.type_info(Literal[1, None])
359+
assert result == mi.LiteralType((None, 1))
360+
361+
362+
def test_mixed_str_int_literal():
363+
result = mi.type_info(Literal[1, "a"])
364+
assert result == mi.LiteralType((1, "a"))
365+
366+
367+
def test_mixed_none_int_str_literal():
368+
result = mi.type_info(Literal["b", 1, None, "a"])
369+
assert result == mi.LiteralType((None, 1, "a", "b"))
370+
371+
353372
def test_int_enum():
354373
class Example(enum.IntEnum):
355374
B = 3

0 commit comments

Comments
 (0)