python / python/mypy

Mypy should warn when comparing lists that hold a union of incomparable types

Open
#14,227 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

As of mypy 0.991 on Python 3.11.0, mypy --strict doesn't report any problems on this code:

from typing import List, Union
a: List[Union[int, str]] = ['a']
b: List[Union[int, str]] = [1]
result = a < b

Despite mypy passing, actually running this results in TypeError: '<' not supported between instances of 'str' and 'int'. I think ideally mypy would catch this.

Pitch

While the problem was much less obvious, this affected a real project at https://github.com/certbot/certbot/issues/9481 so I think it'd be useful if mypy could help stop bugs like this from slipping through.

My knowledge of mypy and especially its internals is pretty limited, but is there a sane way to do this? Would it be possible to do something like write the annotation of list.__lt__ in the typeshed so it only accepts another list whose elements are of a type that can be compared with its own?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the reported Python 3.11 example with mypy --strict and confirm the runtime TypeError. Investigate how list.lt is typed and whether typeshed can express comparable element types. Done means mypy reports the unsafe comparison without rejecting valid comparable-list comparisons.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.