python / python/mypy

Invalid type inference for generic typed dicts

Open
#18,804 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-typed-dict
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When we try to assert the type of an object obtained from get with default value from generic object bound to typed dict, then mypy shows next error:

error: Incompatible types in assignment (expression has type "object", variable has type "int")  [assignment]

To Reproduce

from typing import NotRequired, TypedDict, TypeVar


class A(TypedDict):
    i: NotRequired[int]


ParamsT = TypeVar('ParamsT', bound=A)


def foo(params: ParamsT) -> None:
    i: int = params.get('i', 0)


foo(A())

Gist: https://gist.github.com/mypy-play/effc3f0d297540be8ca1bad7b08c5902
Play: https://mypy-play.net/?mypy=latest&python=3.12&gist=effc3f0d297540be8ca1bad7b08c5902

Expected Behavior

It is expected that result of expression params.get('i', 0) would be of type int since typed dict attribute is annotated as <int> and the default value type is <int> as well.

Actual Behavior

Mypy reports that result of expression params.get('i', 0) has type <object>.

Your Environment

  • Mypy version used: mypy 1.15.0 (compiled: yes)
  • Python version used: 3.13

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

No repository file or test path is named; start by running the provided Python reproduction with mypy 1.15.0 and inspect the inferred type for params.get('i', 0). Done means this expression is inferred as int rather than object, with regression coverage for the generic TypedDict case.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.