`.get(key)` should narrow final TypedDicts
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
in keyword narrowing was implemented for TypedDicts, but not .get(). I understand that it may be hard to implement for arbitrary default arguments of .get(key, default), but the .get(key) variable, without a default value, can be useful as well.
Bug Report
To Reproduce
import typing
@typing.final
class Node(typing.TypedDict):
name: str
children: list[typing.Union['Node', 'Leaf']]
@typing.final
class Leaf(typing.TypedDict):
name: str
x: Node | Leaf
### INCORRECT ERROR
if x.get('children'):
x['children'] # error: TypedDict "Leaf" has no key "children"
### CORRECT
if 'children' in x:
x['children']
Expected Behavior
No error
Actual Behavior
error: TypedDict "Leaf" has no key "children" [typeddict-item]
Your Environment
- Mypy version used: 1.9.0
- Mypy command-line flags: non
- Mypy configuration options from
mypy.ini(and other config files):
warn_redundant_casts = True
warn_unused_ignores = True
warn_no_return = False
warn_return_any = True
disallow_untyped_defs = True
disallow_any_generics = True
- Python version used:
Python 3.12.1
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
Start by running the Python reproduction and locating the existing TypedDict narrowing behavior for the in operator. No source file or test is named in the report; done means that the .get('children') check narrows x so the subsequent x['children'] produces no error, while the default-argument case remains scoped separately.
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
- 45/100