Skip to content

Looping through literals not typed correctly #9230

Description

@rggjan

Iterating through a fixed Tuple of strings ("foo", "bar") makes the loop variable a str instead of Union[Literal["foo"], Literal["bar"]]. This makes it difficult to loop through indices of a TypedDict

https://mypy-play.net/?mypy=latest&python=3.8&gist=17fe6a875f727a01fe3a5c6dca13dba2

fromtypingimportTypedDictclassFooDict(TypedDict):
foo: intbar: intfoo=FooDict(foo=3, bar=3)
print(foo["foo"]) # Worksprint(foo["bar"]) # Worksreveal_type(("foo", "bar")) # Revealed type is 'Tuple[Literal['foo']?, Literal['bar']?]'forkeyin ("foo", "bar"):
reveal_type(key) # Revealed type is 'builtins.str'print(foo[key]) # TypedDict key must be a string literal; expected one of ('foo', 'bar')

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions