Calls to `.get` on TypeVars bound to TypedDict narrow to `object`
Open
Nobody has claimed this yet.
bug
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When using dict.get to access specific members of TypeVar entries bound to TypedDict, mypy always narrows the type to object where, without the TypeVar, we expect the union of the underlying type and None.
To Reproduce
from typing import TypedDict, TypeVar
class MyDict(TypedDict):
my_attributes: list[str]
def take_my_dict(d: MyDict):
reveal_type(d['my_attributes'])
reveal_type(d.get('my_attributes'))
MyDictT = TypeVar('MyDictT', bound=MyDict)
def take_my_typevar(d: MyDictT):
reveal_type(d['my_attributes'])
reveal_type(d.get('my_attributes'))
Expected Behavior
main.py:7: note: Revealed type is "builtins.list[builtins.str]"
main.py:8: note: Revealed type is "Union[builtins.list[builtins.str], None]"
main.py:13: note: Revealed type is "builtins.list[builtins.str]"
main.py:14: note: Revealed type is "Union[builtins.list[builtins.str], None]"
Actual Behavior
main.py:7: note: Revealed type is "builtins.list[builtins.str]"
main.py:8: note: Revealed type is "Union[builtins.list[builtins.str], None]"
main.py:13: note: Revealed type is "builtins.list[builtins.str]"
=> main.py:14: note: Revealed type is "builtins.object"
Your Environment
- Mypy version used: 1.8.0
- Mypy command-line flags: n/a
- Mypy configuration options from
mypy.ini(and other config files): n/a - Python version used: 3.12
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 with the main.py reproducer and run mypy against the TypedDict and TypeVar cases, comparing the reveal_type output for .get. Trace the type-checking path for a .get call on a TypeVar bound to TypedDict; done means the TypeVar case reveals Union[list[str], None] rather than object.
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
- Clearly specified
- Newbie friendliness
- 45/100