【发布时间】:2021-06-13 03:35:05
【问题描述】:
我有带有这些类型注释的 python 函数
def func_1() -> Optional[Sequence[str, List[str], str]]:
# do stuff
def func_2(a: str, b: List[str], c: str) -> None:
# do other stuff
为什么下面的代码在我调用 func_2 的那一行给出警告“Expected type list[str, Any]' got 'str' instead”?
result = func_1()
func_2(result[0], result[1], result[2])
这是否意味着我的类型检查器有问题,或者我的代码有问题?
【问题讨论】:
-
我得到的错误远不止这些,包括 syntax 错误。请仔细检查这是minimal reproducible example。
-
This:
List[str, ...]不是一个有效的注释,据我所知......与Sequence[str, List[str, ...] str]相同......你想在那里表达什么? -
请逐字发布警告并提供
result的值。result[1]很可能是str而不是list,但从您提供的内容中不确定。 -
提供代码只是为了显示我使用的两种类型注释。当然缺少函数实现和导入,但是如果 func_1 保证返回带注释的类型(因为该注释没有给出警告),那么 result[1] 怎么可能是字符串而不是 List[str, 。 ..]?根据 PEP 484 List[str, ...] 是用于长度不确定的字符串列表的注释。我确实提供了 PyCharm 给出的警告。这不是关于特定执行的问题,而是关于类型警告的问题,因此结果没有值。
-
@J.Grohmann 没有。这是不正确的。
Sequence和List一样,采用单个类型变量。
标签: python python-3.x types type-annotation