![](/img/trans.png)
[英]Checking for Sequence in List: Why does this function returns "False", when the Sequence IS there?
[英]Python type checking on a function that returns str or Sequence
我有一个处理序列的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开心?
a
是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]
,但是会丢失一些键入信息和保护。
我找到了解决方案:
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)
在这种情况下,mypy很高兴。 显然,在TypeVar声明中,我必须在更通用的Sequence
之前定义更具体的str
。 ( _S = TypeVar('_S', Sequence, str)
仍然给出错误)
我还尝试使用# type: str
来教育mypy # type: str
注释,但这没有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.