TypedDict.setdefault gives error when type is a TypeVar
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 a function argument is annotated using a TypeVar with a bound that is a TypedDict, using setdefault on it leads to an error.
To Reproduce
from typing import TypedDict, TypeVar
class TD(TypedDict, total=False):
foo: int
bar: bool
_T = TypeVar("_T", bound=TD)
def func(td: _T) -> None:
td.setdefault("bar", True)
Actual Behavior
testit.py:10: error: Argument 1 to "setdefault" of "TypedDict" has incompatible type "str"; expected "Never" [arg-type]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: mypy 1.11.1 (compiled: yes)
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): no config file - Python version used: 3.12.3
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 provided TypedDict and TypeVar example with mypy 1.11.1 and confirm the incorrect Never argument error. Trace TypedDict method checking for TypeVar-bound TypedDict values, then add a regression test showing that td.setdefault("bar", True) is accepted.
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