python / python/mypy

incorrect inferred type accessing typed dict with static keys

Open
#19,961 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

mypy does not infer the correct type of a dictionary when constructing a subset of a TypedDict using a constant subset of keys.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=82fc1eb24628e1ba2aed8294b81e2912

from typing import TypedDict, reveal_type


class MyDict(TypedDict):
    key_0: bool
    key_1: int
    key_2: bool


limits: MyDict = {
    'key_0': True,
    'key_1': 1,
    'key_2': False
}

def test_func() -> dict[str, bool]:
    result = {
        label: limits.get(label, False)
        for label in ('key_0', 'key_2')
    }
    reveal_type(limits.get('key_0', False))
    reveal_type(result)
    return result

test_func()

Expected Behavior

In the example above, I expect mypy to accept the return type since both key_0 and key_2 are annotated as bool

Actual Behavior

mypy complains about the return type with

Incompatible return value type (got "dict[str, object]", expected "dict[str, bool]")  [return-value]

After mentioning it in my team chat @LefterisJP noticed that this version works https://mypy-play.net/?mypy=latest&python=3.12&gist=63bece9a183493b170f6f55527fbd7d3

from typing import TypedDict, reveal_type, Literal


class MyDict(TypedDict):
    key_0: bool
    key_1: int
    key_2: bool


limits: MyDict = {
    'key_0': True,
    'key_1': 1,
    'key_2': False
}

def test_func() -> dict[str, bool]:
    keys: tuple[Literal['key_0', 'key_2'], ...] = ('key_0', 'key_2')
    result: dict[str, bool] = {
        label: limits.get(label, False)
        for label in keys
    }
    reveal_type(limits.get('key_0', False))
    reveal_type(result)
    return result

test_func()

In this case, because the keys are explicitly typed as Literals, mypy infers the correct type.
This suggests that mypy is not analyzing constant tuples deeply enough to recognize the accessed keys.

Your Environment

  • Mypy version used: mypy 1.18.2 (compiled: yes)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): I can reproduce it in an environment without any extra configuration.
  • Python version used: 3.11.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

Start by reproducing the reported behavior in the linked mypy-play examples and compare the inferred types for the plain constant tuple and the explicitly Literal-typed tuple. Done means mypy accepts the shown dict[str, bool] return type for the constant-key case without requiring the explicit Literal annotation.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 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.