Skip to content

TypedDict 'in' narrowing w/o @final #15697

Open
@ikonst

Description

@ikonst

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).

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions