python / python/mypy

TypedDict totality ignored when unpacked for function call

Offen
#12,754 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-typed-dict
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

When unpacking a typeddict for a function call, mypy doesn't seem to check the totality of the typeddict, and instead assumes the keys are all present.

from typing import TypedDict

def my_function(foo: int, bar: int, baz: str) -> None:
    pass

class MyTypedDict(TypedDict, total=False):
    foo: int
    bar: int
    baz: str
    
    
a: MyTypedDict = {'bar': 1}

my_function(**a) # Should be error here, as a doesn't contain foo or baz

https://mypy-play.net/?mypy=latest&python=3.10&flags=strict&gist=5444e1100000a8f1678fe9cbcfc23921

Expected Behavior

Mypy should not assume that keys are present when the TypedDict has total=False, and treat it as potentially having any combination of they keys present.

Actual Behavior

Mypy allows this, but when executed it gives the following error:

Traceback (most recent call last):
  File "<path>\typeddict1.py", line 17, in <module>
    my_function(**a)  # Should be error here, as a doesn't contain foo or baz
TypeError: my_function() missing 2 required positional arguments: 'foo' and 'baz'

#11753

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, das TypedDict-Beispiel für das Unpacking mit total=False aus dem Issue oder seinem mypy-play-Link nachzustellen, und verfolge dann die Prüfung der Funktionsaufrufargumente für das TypedDict-Unpacking. Fertig ist es, wenn mypy einen Fehler meldet, wenn optionale Schlüssel fehlen können, während gültiges Verhalten für erforderliche Schlüssel erhalten bleibt.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
48/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.