Generic TypedDict and inferring return value
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
I was working on some code that needs to be passed a generic TypedDict, like this:
from typing import TypeVar, TypedDict, Generic
T = TypeVar("T")
ReturnValue = TypeVar("ReturnValue")
class Option(TypedDict, Generic[ReturnValue]):
name: str
value: ReturnValue
class Menu:
def ask(self, text: str, options: list[Option[T]]) -> T:
return options[0]["value"]
And the usage would be this:
value = Menu().ask("text", [{"value": 123, "name": "abc"}])
reveal_type(value)
In this case the value type should int, but unfortunately I get this error:
main.py:18: error: Need type annotation for "value" [var-annotated]
main.py:18: error: Argument 2 to "ask" of "Menu" has incompatible type "list[dict[str, int]]"; expected "list[Option[Never]]" [arg-type]
Playground: https://mypy-play.net/?mypy=latest&python=3.12&flags=verbose%2Cstrict&gist=9a8643b51a69f6d60ab5b0b482e10865
This seems to be working well in pyright 😊
Also I didn't find yet a workaround, changing the class to this:
class Menu:
def ask(self, text: str, options: list[dict[str, T]]) -> T:
return options[0]["value"]
Almost works, but for example in the case above it would infer the type as object 😊
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia con l’esempio Python minimo e la riproduzione collegata su mypy-play per confermare gli errori attuali di inferenza. Traccia l’inferenza dei tipi coinvolta negli argomenti TypedDict generici, quindi verifica che l’esempio inferisca value come int senza richiedere un’annotazione né segnalare un errore relativo a un argomento incompatibile.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- tooling
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 42/100