Skip to content

False positive when accessing a TypedDict in a list comprehension #19317

Open
@fishikles

Description

@fishikles

Bug Report

When using a TypedDict in list comprehension

To Reproduce

from typing import TypedDict

class Data (TypedDict):
    field1:int
    field2:str
    field3:str

data:Data = {
    'field1':1,
    'field2':'string',
    'field3':'string'
}

stringValues = [value for value in ("field1", "field2", "field3") if type(data[value]) is str] # error here

Expected Behavior

Works as the non list comprehension verson:

from typing import TypedDict

class Data (TypedDict):
    field1:int
    field2:str
    field3:str

data:Data = {
    'field1':1,
    'field2':'string',
    'field3':'string'
}
for value in ("field1", "field2", "field3"):
    if type(data[value]) is str:
        print(f"{value} is a string")

Actual Behavior

mypy complains about the typing of value in the list comprehension. Error reported is

error: TypedDict key must be a string literal; expected one of ("field1", "field2", "field3")  [literal-required]

Your Environment

  • Mypy version used: mypy 1.16.0 (compiled: yes)
  • Mypy command-line flags: NA
  • Mypy configuration options from mypy.ini (and other config files): NA
  • Python version used: 3.13.5

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions