python / python/mypy

TypedDict.setdefault gives error when type is a TypeVar

Open
#17,674 0 comments 1 reaction 0 assignees View on GitHub

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.