[Python] How to write type hints when you change type of a variable?

Discussão em 'Python' iniciado por Stack, Dezembro 8, 2024.

  1. Stack

    Stack Membro Participativo

    Say that I have

    def foo(x: Union[str, list[str]], y: Union[str, list[str]]) -> tuple[list[str], list[str]]:

    x = cast(Union[list[str], tuple[list[str], ...]], str2list(x))
    y = cast(Union[list[str], tuple[list[str], ...]], str2list(y))

    return x,y

    def str2list(*args: Union[str, list[str]]) -> Union[list[str], tuple[list[str], ...]]:
    vals = []
    for x in args:
    if not isinstance(x, list):
    x = [x]
    vals.append(x)
    if len(args) == 1:
    return vals[0]
    else:
    return tuple(vals)


    x = 'My name is x'
    y = ['First element', 'Second element']

    z = str2list(x,y)


    As you see, there are two cast calls in foo, but still mypy complains that

    error: Incompatible types in assignment (expression has type "Union[List[str], Tuple[List[str], ...]]", variable has type "Union[str, List[str]]") [assignment]


    A workaround could be to define new variables and adjust the return type of foo as it follows

    def foo(
    x: Union[str, list[str]], y: Union[str, list[str]]
    ) -> tuple[
    Union[list[str], tuple[list[str], ...]],
    Union[list[str], tuple[list[str], ...]],
    ]:

    xl = cast(Union[list[str], tuple[list[str], ...]], str2list(x))
    yl = cast(Union[list[str], tuple[list[str], ...]], str2list(y))

    return xl, yl


    But I would prefer to overwrite x and y rather than defining two new variables xl and yl.

    Continue reading...

Compartilhe esta Página