Iterating over TypedDict's keys
Asked Answered
E

1

6

Here's an example:

from typing import TypedDict

class Foo(TypedDict):
    a: str
    b: int

foo = Foo(a='2', b=4)

for key in foo:
    print(foo[key])

I get

main.py:10: note: Revealed type is 'Any'
main.py:10: error: TypedDict key must be a string literal; expected one of ('a', 'b')
Found 1 error in 1 file (checked 1 source file)

I find this surprising - isn't it known that key is one of foo's keys, and hence that foo[key] should be valid?


Playground URL: https://mypy-play.net/?mypy=latest&python=3.9&gist=8972284897f25314f9c790eab4cb8548

Ensue answered 15/6, 2021 at 17:51 Comment(1)
Not strictly related, but in case you didn't know, you can do for key, value in foo.items() which entirely bypasses the issue. Though it of course doesn't address the limitation of mypy.Hystero
C
6

I think it's known issue which was discussed here. If you want it to work now, just try # type: ignore which should overwritten the warning.

from typing import TypedDict

class Foo(TypedDict):
    a: str
    b: int

foo = Foo(a='2', b=4)

for key in foo:
    print(foo[key]) # type: ignore

playground URL:https://mypy-play.net/?mypy=latest&python=3.9&gist=85e30e0187088219797a283c31d7ec7c

Candace answered 15/6, 2021 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.