Python 字符串序列的类型注释,而不是字符串?

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

是否有 Python 匹配列表、元组和其他可能的顺序类型但不匹配字符串的类型提示?

问题是字符串同时是长度为 1 的字符串序列(例如单个字符),因此它们在技术上匹配 Sequence[str],但向需要字符串列表的函数提供字符串在可能 100% 的情况下是一个错误。

有没有办法从类型注释中排除字符串,使其类似于不存在的东西And[Sequence[str], Not[str]]

至于用途,我想注释一下这个函数:

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

但现有签名在我看来显得臃肿,并且不涵盖任何与列表和元组兼容的自定义类型。有没有更好的办法?

我找不到关于类型 exclusion 或类型 negation 的任何信息,似乎当前版本 Python 3. 因此,我想到的字符串的唯一显着特征是字符串是不可变的。也许它会有所帮助:

from typing import Union
from collections.abc import MutableSequence


MySequenceType = Union[MutableSequence, tuple, set]
def foo(a: MySequenceType):
    pass

foo(["09485", "kfjg", "kfjg"]) # passed
foo(("09485", "kfjg", "kfjg")) # passed
foo({"09485", "kfjg", "kfjg"}) # passed
foo("qwerty") # not passed

我可能不完全理解你的问题,但在我看来你正在寻找以下快捷方式:

for object in data:
    if not isinstance(object, type):
        your code functions + list...
        .... etc.

而类型是 strobject 来自您的 原始数据 通过 listtuple 提供的变量项目。如果我误解了你的问题,用更多细节加深你的问题可能会有帮助?或者上面的答案足以让你继续吗?然后一点点反馈就好了;-)

显然,这对于类型提示是不可能的。根据 Guido van Rossum 的说法,PEP 484 无法区分 Sequence[str]Iterable[str]str

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