Search code examples
pythonpython-typing

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


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?


Solution

  • Apparently, this is not possible with type hints. PEP 484 can not distinguish between Sequence[str], Iterable[str] and str according to Guido van Rossum.

    Source: https://github.com/python/mypy/issues/1965 and https://github.com/python/typing/issues/256