[Python] Proper Python type hinting for this function in 2025

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using VS Code with Pylance, and having problems correctly writing type hints for the following function. To me, the semantics seem clear, but Pylance disagrees. How can I fix this without resorting to cast() or # type ignore? Pylance warnings are given in the comments.

    I am fully committed to typing in Python, but it is often a struggle.

    T = TypeVar("T")

    def listify(item: T | list[T] | tuple[T] | None) -> list[T]:
    if item is None:
    return []
    elif isinstance(item, list):
    return item # Return type, "List[Unknown]* | List[T@listify]",
    # is partially unknown
    elif isinstance(item, tuple):
    return list(item) # Return type, "List[Unknown]* | List[T@listify]",
    # is partially unknown
    else:
    return [item]

    Continue reading...

Compartilhe esta Página