python / python/mypy

Misleading error message with `dict.get` like method. (polymorphic function with conflicting context)

Aperta
#20,576 4 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

Consider this example that emulates dict.get: (https://mypy-play.net/?mypy=latest&python=3.12)

from typing import Any, reveal_type

class Map[K, V]:
    def set(self, key: K, value: V) -> None: ...
    def get[T](self, key: Any, default: T, /) -> V | T: ...

d_any: Map[str, Any] = Map()

reveal_type(d_any.get("key", None))  # Any | None  ✅️

result: str = reveal_type(d_any.get("key", None))  # Any | str ❌️
# error: Argument 2 to "get" of "Map" has incompatible type "None"; expected "str" 

mypys error message is misleading. None is a perfectly reasonable argument for the default value of d_any.get. The problem is that the return type Any | None is not assignable to str. It would make more sense if either:

  1. mypy reports that Any | None cannot be assigned to str.
    (e.g. by a two step approach: first try to solve with context and if that fails, use the return type that is inferred from the arguments alone)[^1]
  2. mypy reports that it cannot find a solution for the type variable T.
    (e.g. single step that considers both constraints from arguments and context)

[^1]: In certain special cases like tuple/list/set/dict-comprehensions, the current behavior that inverts the priority seems fine

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 nel mypy playground collegato e confronta la diagnosi con i due risultati proposti. Traccia l'inferenza dei tipi generici di mypy e il comportamento del tipaggio contestuale per la chiamata polimorfica a get. Il lavoro è completo quando la diagnosi non attribuisce più erroneamente la colpa a None e un test di regressione copre questo esempio.

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

Valutazione

Stack tecnologico
python
Ambito
compilers
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.