Skip to content

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

Description

@fishikles

Bug Report

When using a TypedDict in list comprehension

To Reproduce

fromtypingimportTypedDictclassData (TypedDict):
field1:intfield2:strfield3:strdata:Data= {
'field1':1,
'field2':'string',
'field3':'string'
}
stringValues= [valueforvaluein ("field1", "field2", "field3") iftype(data[value]) isstr] # error here

Expected Behavior

Works as the non list comprehension verson:

fromtypingimportTypedDictclassData (TypedDict):
field1:intfield2:strfield3:strdata:Data= {
'field1':1,
'field2':'string',
'field3':'string'
}
forvaluein ("field1", "field2", "field3"):
iftype(data[value]) isstr:
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