python / python/mypy

generic type assertion is incompatible with generic sorted key

Aperta
#10,500 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia riproducendo l’esempio con mypy 0.800 e ispeziona la firma sovraccaricata di sorted nel file builtins.pyi di typeshed collegato. Il lavoro è completato quando la lambda key accetta un input str | None, unwrap(x) viene inferito come str e l’errore sull’attributo upper scompare.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.