[Python] Python type annotation for sequences of strings, but not for strings?

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

  1. Stack

    Stack Membro Participativo

    Is there a Python type hint that matches lists, tuples and possibly other sequential types, but does not match strings?

    The issue is that strings are at the same time sequences of strings of length 1 (e.g. individual characters), so they technically match the Sequence[str], but providing a string to a function expecting a list of strings is an error in maybe 100% cases.

    Is there a way to exclude strings from type annotation to make it something similar to non-existent And[Sequence[str], Not[str]]?

    As for the purpose, I would like to annotate this function:

    PathType = Union[str, os.PathLike]
    def escape_cmdline(argv: Union[List[PathType], Tuple[PathType]]) -> str: ...


    But existing signature looks bloated to me, and does not cover any custom types that are list and tuple compatible. Is there any better way?

    Continue reading...

Compartilhe esta Página