[Python] How to annotate mutable structures for Mypy

Discussão em 'Python' iniciado por Stack, Maio 31, 2025.

  1. Stack

    Stack Membro Participativo

    I have this code:

    def my_foo(x: dict[str, int | float], some_condition: bool) -> None:
    if some_condition:
    x['the_int'] = 1
    else:
    x['the_float'] = 1.0

    my_dict = {'some_int': 2}

    my_foo(my_dict, True)


    Mypy (understandably) complains


    error: Argument 1 to "my_foo" has incompatible type "dict[str, int]"; expected "dict[str, int | float]" [arg-type] note: "Dict" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance src\type_test.py:23: note: Consider using "Mapping" instead, which is covariant in the value type
    ​

    I tried do type-hint using MutableMapping but to no avail:


    error: Argument 1 to "my_foo" has incompatible type "dict[str, int]"; expected "MutableMapping[str, int | float]"
    ​

    Continue reading...

Compartilhe esta Página