如何输入 Python 签名函数 (T, Sequence[T]) -> int including str?

How to type in Python a function of signature (T, Sequence[T]) -> int including str?

我想输入一个简单的计数函数来计算序列中给定元素的出现次数。这没有给出 mypy 错误,这让我感到惊讶,因为 str 不是 Sequence[str] 或者是 ?

from typing import TypeVar, Sequence

T = TypeVar('T')

def count(x: T, xs: Sequence[T], acc: int = 0) -> int:
    if len(xs) == 0:
        return acc
    else:
        return count(x, xs[1:], acc + (1 if x == xs[0] else 0))


print(count("a", "abracadabra"))
print(count(1, (1,0,1,1,0,1,0,1,1)))
print(count(1, range(10)))
print(count(1, [i for i in range(10)]))

Python 不区分字符和字符串,就像其他类型化语言一样。

字符只是长度为 1 的 str 对象,因此 str 是 Sequence[character] 意义上的 Sequence[str]。