Skip to content

inspect.type_info crashes on mixed-type Literals #1018

Description

@Siyet

`msgspec.inspect.type_info` crashes with `TypeError` when called on a `Literal` type that mixes value types (e.g. `Literal[1, None]` or `Literal[True, "yes"]`).

Reproduction

import msgspec.inspect as mi
from typing import Literal

mi.type_info(Literal[1, None])
# TypeError: '<' not supported between instances of 'NoneType' and 'int'

mi.type_info(Literal[True, "yes"])
# TypeError: '<' not supported between instances of 'str' and 'bool'

Cause

`inspect.py:888` does `LiteralType(tuple(sorted(args)))` which calls `sorted()` on the Literal args. Python 3 does not allow comparison between different types, so mixed-type tuples like `(1, None)` or `(True, "yes")` raise `TypeError`.

Additionally, `LiteralType.values` type annotation (`Union[Tuple[bool, ...], Tuple[str, ...], Tuple[int, ...]]`) does not cover mixed-type tuples.

Suggested fix

  1. Replace `sorted(args)` with a type-aware sort (e.g. `sorted(args, key=lambda x: (type(x).name, x))`) or skip sorting for mixed types.
  2. Widen `LiteralType.values` to `Tuple[Union[bool, str, int, None], ...]` or similar.
  3. Add tests for `type_info(Literal[True])`, `type_info(Literal[True, "yes"])`, `type_info(Literal[1, None])`.

This is a pre-existing issue (not introduced by #1004), but #1004 makes it more likely to encounter since it enables `Literal[True, ...]` combinations.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions