Search code examples
pythonpython-typingmypytypeddict

Iterating over TypedDict's keys


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


Solution

  • 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