python / python/mypy

generic type assertion is incompatible with generic sorted key

Open
#10,500 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.