[Python] How to correctly type hint a mapping (dict) with Literal keys?

Discussão em 'Python' iniciado por Stack, Agosto 19, 2025.

  1. Stack

    Stack Membro Participativo

    I want to type hint a dictionary (or equivalent object) that maps from a set of Literal choices to some outputs. I'm using pytype as my type checker.

    The ideal behaviour would be something like:

    from typing import Literal

    SupportedKey = Literal["one", "two"]
    d : dict[SupportedKey, int] = {"one": 1, "two": 2}


    However, pytype doesn't recognise that "one" and "two" are in fact SupportedKeys, and so fails with

    Type annotation for d does not match type of assignment [annotation-type-mismatch]
    Annotation: dict[Literal['one', 'two'], int]
    Assignment: dict[str, Literal[1, 2]]


    Note that the mismatch in type assignment only matters in the keys, as:

    • str is not assignable to Literal['one', 'two']
    • Literal[1, 2] is assignable to int

    I tried a more explicit method, where the keys are constructed with appropriate typing:

    from typing import Literal, Final

    SupportedKey = Literal["one", "two"]
    KEY_ONE: Final[SupportedKey] = "one"
    KEY_TWO: Final[SupportedKey] = "two"
    d : dict[SupportedKey, int] = {KEY_ONE: 1, KEY_TWO: 2}


    However, this fails in a similar way - the keys are still inferred as the more general str rather than Literal:

    Type annotation for d does not match type of assignment [annotation-type-mismatch]
    Annotation: dict[Literal['one', 'two'], int]
    Assignment: dict[str, int]


    What's the best way of achieving a correctly typed mapping with Literals as the keys?

    Continue reading...

Compartilhe esta Página