`TypedDict` not considered as matching `dict()` pattern in match
- Dominant language
- Python
- Stars
- 15.6k
- Forks
- 1.8k
- Avg merge
- 12h 13m
- Merged PRs (30d)
- 52
Description
**Describe the bug**
Since documentation for `TypedDict` says
> "Values that [inhabit](https://typing.python.org/en/latest/spec/glossary.html#term-inhabit) a TypedDict type must be instances of dict itself"
... values of type `TypedDict` should liklely match a `case dict():` branch in a match statement.
**Code or Screenshots**
```python
from typing import reveal_type
from typing import NotRequired, TypedDict
class DictPattern(TypedDict):
role: NotRequired[int]
type Pattern = (
tuple[int, str] # just role and name
| DictPattern
| None
)
def foo(pattern_item: Pattern) -> None:
reveal_type(pattern_item)
match pattern_item:
case [*_] | dict():
reveal_type(pattern_item)
print("seq or dict")
case None:
print("None")
case _:
reveal_type(pattern_item)
assert False, "unrecognized pattern element %s" % (pattern_item,)
foo({"role": 1})
```
Running the script confirms that the dict does take the `case [*_] | dict():`
```
$ python3 typecheck.py
Runtime type is 'dict'
Runtime type is 'dict'
seq or dict
```
But `pyright` assumes only tuples can match this branch:
```
typecheck.py:14:17 - information: Type of "pattern_item" is "tuple[int, str] | DictPattern | None"
typecheck.py:18:25 - information: Type of "pattern_item" is "tuple[int, str]"
typecheck.py:25:25 - information: Type of "pattern_item" is "DictPattern"
```
If the branch is changed to be just `case dict():`, the following `reveal_type()` is just ignored by pyright as dead code.
Contributor guide
Research direction
Run pyright against the shown typecheck.py example and inspect how TypedDict values are narrowed for a match dict() pattern. Done means the revealed type in the case [*_] | dict(): branch includes DictPattern, with subsequent narrowing matching the runtime behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100