generic type assertion is incompatible with generic sorted key
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
I have a function that removes the nullability of a value, so it takes T | None and returns T. This function doesn't seem to work in functions that have overloaded generic function args, like sorted.
If I create my own sorted function without an overload, this issue doesn't occur.
def my_sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsLessThan], reverse: bool = ...) -> List[_T]: ...
To Reproduce
from __future__ import annotations
from typing import TypeVar
T = TypeVar("T")
def unwrap(val: T | None) -> T:
assert val is not None
return val
x: list[str | None]
sorted(x, key=lambda x: unwrap(x).upper())
# <nothing> has no attribute "upper" [attr-defined]
Expected Behavior
unwrap(x) should return str.
Actual Behavior
unwrap(x) returns <nothing>.
Your Environment
- Mypy version used: 0.800
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 example with mypy 0.800 and inspect the overloaded sorted signature in the linked typeshed builtins.pyi. Done means the key lambda accepts str | None input, unwrap(x) is inferred as str, and the upper attribute error disappears.
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
- Mostly clear
- Newbie friendliness
- 35/100