[Python] Tell mypy that all elements of list are of same type

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    Say we have

    from typing import List

    a: List[int] | List[str]

    if all(isinstance(i, int) for i in a):
    reveal_type(a)


    This gives us

    main.py:6: note: Revealed type is "Union[builtins.list[builtins.int], builtins.list[builtins.str]]"


    Is there a way to get mypy to recognise that a is a list of integers, or is the only solution here to use cast?

    Continue reading...

Compartilhe esta Página