Argument "key" to "sorted" has incompatible type "Callable…"
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
I believe that I've found a bug in mypy, the following MRE should as far as I can tell not result in any typing errors at all, but it reports an error (and I've found two simple workarounds for which no error is reported, strengthening my belief that this is a bug and not intended behaviour).
To Reproduce
#!/usr/bin/python3
from collections.abc import Iterable
from typing import cast
def unproblematic(iter: Iterable[int]) -> None:
print(iter)
def problematic(iter: Iterable[int | str]) -> None:
print(iter)
def key(item: int) -> int:
return -item
def main() -> None:
items: list[int] = [3, 4, 1, 2]
unproblematic(sorted(items, key=key)) # Works.
problematic(sorted(items, key=key)) # Fails mypy arg-type.
workaround = sorted(items, key=key)
problematic(workaround) # Works.
problematic(cast(Iterable[int], sorted(items, key=key))) # Works.
if __name__ == '__main__':
main()
Actual Behavior
$ mypy mre.py
mre.py:23: error: Argument "key" to "sorted" has incompatible type "Callable[[int], int]"; expected "Callable[[int | str], SupportsDunderLT[Any] | SupportsDunderGT[Any]]" [arg-type]
Your Environment
$ mypy --version
mypy 1.16.0 (compiled: yes)
$ python3 --version
Python 3.13.3
(If anyone can't trivially reproduce this, I'd be happy to provide more details about my environment.)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the report from the MRE in mre.py with mypy 1.16.0 and Python 3.13.3, then compare the direct sorted(items, key=key) call with the two workarounds. Done means the direct call no longer reports the incompatible key argument while the example remains correctly typed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100