Skip to content

Argument "key" to "sorted" has incompatible type "Callable…" #19259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
roubert opened this issue Jun 9, 2025 · 1 comment
Open

Argument "key" to "sorted" has incompatible type "Callable…" #19259

roubert opened this issue Jun 9, 2025 · 1 comment
Labels
bug mypy got something wrong topic-type-context Type context / bidirectional inference

Comments

@roubert
Copy link

roubert commented Jun 9, 2025

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.)

@roubert roubert added the bug mypy got something wrong label Jun 9, 2025
@sterliakov sterliakov added the topic-type-context Type context / bidirectional inference label Jun 9, 2025
@sterliakov
Copy link
Collaborator

That's yet another case where applying return type context and args context separately causes overly broad inference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-type-context Type context / bidirectional inference
Projects
None yet
Development

No branches or pull requests

2 participants