Skip to content

Fix inspect.type_info crashing on mixed-type Literals#1080

Open
gaoflow wants to merge 2 commits into
msgspec:mainfrom
gaoflow:fix-inspect-mixed-literal
Open

Fix inspect.type_info crashing on mixed-type Literals#1080
gaoflow wants to merge 2 commits into
msgspec:mainfrom
gaoflow:fix-inspect-mixed-literal

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 17, 2026

Copy link
Copy Markdown

Fixes #1018.

Problem

msgspec.inspect.type_info crashes on mixed-type Literals:

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.

gaoflow added 2 commits June 17, 2026 08:53
type_info sorted a Literal's values with a plain sorted(), which raises
TypeError on mixed-type literals such as Literal[1, None] or
Literal[True, "yes"] since Python 3 forbids ordering across types. The
encoder/decoder already support these literals, so type_info crashing on them
is a contract violation. Sort by (type name, value) so same-type ordering is
unchanged and mixed-type literals are grouped deterministically, with a
try/except fallback. Also widen the LiteralType.values annotation to allow
mixed/None members.

Adds test_bool_literal and test_mixed_literal.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

inspect.type_info crashes on mixed-type Literals

1 participant