python / python/mypy

Calls to `.get` on TypeVars bound to TypedDict narrow to `object`

Aperta
#16,872 2 commenti 1 reazione 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

When using dict.get to access specific members of TypeVar entries bound to TypedDict, mypy always narrows the type to object where, without the TypeVar, we expect the union of the underlying type and None.

To Reproduce

from typing import TypedDict, TypeVar

class MyDict(TypedDict):
    my_attributes: list[str]

def take_my_dict(d: MyDict):
    reveal_type(d['my_attributes'])
    reveal_type(d.get('my_attributes'))

MyDictT = TypeVar('MyDictT', bound=MyDict)

def take_my_typevar(d: MyDictT):
    reveal_type(d['my_attributes'])
    reveal_type(d.get('my_attributes'))

Expected Behavior

   main.py:7: note: Revealed type is "builtins.list[builtins.str]"
   main.py:8: note: Revealed type is "Union[builtins.list[builtins.str], None]"
   main.py:13: note: Revealed type is "builtins.list[builtins.str]"
   main.py:14: note: Revealed type is "Union[builtins.list[builtins.str], None]"

Actual Behavior

   main.py:7: note: Revealed type is "builtins.list[builtins.str]"
   main.py:8: note: Revealed type is "Union[builtins.list[builtins.str], None]"
   main.py:13: note: Revealed type is "builtins.list[builtins.str]"
=> main.py:14: note: Revealed type is "builtins.object"

Your Environment

  • Mypy version used: 1.8.0
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.12

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 con il riproduttore main.py ed esegui mypy sui casi TypedDict e TypeVar, confrontando l'output di reveal_type per .get. Traccia il percorso del controllo dei tipi per una chiamata a .get su un TypeVar vincolato a TypedDict; il lavoro è completato quando il caso TypeVar rivela Union[list[str], None] invece di object.

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
Specificata chiaramente
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.