对绑定到 TypedDict 的 TypeVars 的 `.get` 调用被限定为 `object`
作者: chadhpaine创建于 2024年2月5日更新于 2026年9月21日
标签bug
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
内容来源: python/mypy