TypedDict 'in' narrowing w/o @final
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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).
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue names no files or tests; start by reviewing the existing key in Union[TypedDict, ...] narrowing added in #13838 and reproduce the examples above. Define done as allowing narrowing without @final while treating TypedDicts structurally, then add regression coverage for the shown cases and verify the incorrect assertions are rejected.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100