我有一个处理序列的Python函数,并返回相同类型的序列。例如。如果它被输入一个整数列表,它将返回一个整数列表,如果它被输入一个字符串,它将返回一个字符串。
如何为此功能添加类型提示?
以下工作正常,但不是非常严格的类型检查:
from typing import Any, TypeVar, Sequence
_S = Any
def process_sequence(s: _S) -> _S:
return s
def print_str(word: str):
print(word)
def print_sequence_of_ints(ints: Sequence[int]):
for i in ints:
print(i)
a = process_sequence("spam")
print_str(a)
a = process_sequence([1,2,3,42])
print_sequence_of_ints(a)
但是,当我尝试缩小_S
时:
_S = Sequence
或
_S = TypeVar('_S', Sequence, str)
mypy(类型检查代码验证程序)产生以下错误:
error: Argument 1 to "print_str" has incompatible type "Sequence[Any]"; expected "str"
如何在我的函数中添加一个类型提示,表示输入必须是一个序列,输出与输入的类型相同,同时让mypy快乐?
答案 0 :(得分:1)
Sequence[Any]
的类型为str
而不是a
。如果您确定print_str(cast(str, a))
始终是字符串,则可以使用_S = Sequence[Any]
def process_sequence(s: _S) -> _S:
return s
def print_str(word: str):
print(word)
def print_sequence_of_ints(ints: Sequence[int]):
for i in ints:
print(i)
a = process_sequence("spam")
print_str(a) # a is of type Sequence[Any] not str
a = process_sequence([1,2,3,42])
print_sequence_of_ints(a)
转换类型。
T = TypeVar('T')
您也可以使用Sequence[Any]
代替f.input :date, as: :date_select, discard_day: true
,但会丢失一些输入信息和保护。
答案 1 :(得分:1)
我找到了一个解决方案:
dim << chunck_size
在这种情况下,mypy很高兴。显然,在TypeVar声明中,我必须在更通用的from typing import TypeVar, Sequence
_S = TypeVar('_S', str, Sequence)
def process_sequence(s: _S) -> _S:
return s
def print_str(word: str):
print(word)
def print_sequence_of_ints(ints: Sequence[int]):
for i in ints:
print(i)
a = process_sequence("spam")
print_str(a)
b = process_sequence([1,2,3,42])
print_sequence_of_ints(b)
之前定义更具体的str
。 (Sequence
仍然会出错)
我还尝试使用_S = TypeVar('_S', Sequence, str)
评论来教育mypy,但这不起作用。