TypedDict 'in' narrowing w/o @final
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
We shouldn't require @final decoration for TypedDicts to narrow them based on the 'in' operator.
Why?
Basically @erictraut's comment.
In #13838, we've added "key in Union[TypedDict, ...]" narrowing for TypedDicts that are marked @final. The reason was to prevent this:
class Mammal(TypedDict):
mammary_glands: int
class Bird(TypedDict):
eggs: int
class Echidna(Mammal):
eggs: int
animal: Mammal | Bird
if 'eggs' in animal:
assert_type(animal, Bird) # WRONG! Could still be a Mammal (a Echidna)
if 'eggs' in animal and 'mammary_glands' in animal:
assert_never(animal) # WRONG! Could still be a Mammal (a Echidna)
However, per @erictraut's comment, due to TypedDict being a structural type, we shouldn't consider the class hierarchy when type-matching.
This will be consistent with pyright and TypeScript (Playground Link).
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Das Issue nennt keine Dateien oder Tests; beginne damit, das bestehende Narrowing von key in Union[TypedDict, ...] zu prüfen, das in #13838 hinzugefügt wurde, und reproduziere die oben gezeigten Beispiele. Definiere als erledigt, dass Narrowing ohne @final ermöglicht wird und TypedDicts strukturell behandelt werden; füge anschließend Regressionstests für die gezeigten Fälle hinzu und verifiziere, dass die falschen Assertions zurückgewiesen werden.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Feature
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100