[Python] Make pylance ignore type error that I'm already accounting for

Discussão em 'Python' iniciado por Stack, Julho 25, 2025.

  1. Stack

    Stack Membro Participativo

    Is there a way to have pylance ignore a type-hint based issue that I'm already accounting for using try-except?

    I have a method that can take two different types of input. It then tries to handle the first one, and catches an exception if it doesn't work and pivots to the other. Similar to the snippet below. Pylance gives an error on the first arg.lower() as follows: Cannot access attribute "lower" for class "list[str]". Attribute "lower" is unknown. My code will catch that issue.

    def my_method(arg: Union[str, list[str]]) -> str:
    try:
    return arg.lower()
    except AttributeError:
    return arg[0].lower()


    I could pivot to explicitly checking types, and that satisfies Pylance. However, this seems to be not-pythonic (Better to ask forgiveness than permission) and it also gets more complicated in some cases. For example, if you had multiple possible input types and more than 1 can be handled the same way, you'd have to check explicitly for each.

    def my_other_method(arg: Union[str, list[str]]) -> str:
    if isinstance(arg, str):
    return arg.lower()
    else:
    return arg[0].lower()

    Continue reading...

Compartilhe esta Página