python / python/mypy

error: "key" to "max" has incompatible type

Open
#21,104 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-context
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

mypy fails to typecheck set(max(S, key=len)) in the below code. Splitting it into first computing X = max(S, key=len) and then computing set(X) passes the type checks. The problem persists when providing type annotations.

To Reproduce

S = [[1, 2], [3]]

X = max(S, key=len)
Y = set(X)
Z = set(max(S, key=len))

print(Y, Z)

L : list[list[int]] = [[1, 2], [3]]

A : list[int] = max(L, key=len)
B : set[int] = set(A)
C : set[int] = set(max(L, key=len))

print(B, C)

Running with Python 3.14.3 gives the correct output

{1, 2} {1, 2}
{1, 2} {1, 2}

Running with mypy 3.19.1 reports the following errors for the lines computing Z and C.

mypy_max.py:5: error: Argument "key" to "max" has incompatible type "Callable[[Sized], int]"; expected "Callable[[Iterable[int]], SupportsDunderLT[Any] | SupportsDunderGT[Any]]"  [arg-type]
mypy_max.py:13: error: Argument "key" to "max" has incompatible type "Callable[[Sized], int]"; expected "Callable[[Iterable[int]], SupportsDunderLT[Any] | SupportsDunderGT[Any]]"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

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 running the supplied reproduction with mypy 3.19.1 and compare the failing inline calls with the accepted intermediate-variable form. Trace the type checking of max(..., key=len) and add a regression test covering both Z and C; done means the reproduction passes without the reported arg-type errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
58/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.