我正试图弄清楚在Python中打字,但我遇到了以下代码的问题:
from collections.abc import Iterable
from typing import TypeVar
T = TypeVar('T')
def convert_to_iter(var: T | Iterable[T]) -> Iterable[T]:
if not isinstance(var, Iterable):
return (var, )
return var
我在带有typeCheckingMode: "strict"
的VScode中使用Pylance,在代码的最后一行出现错误:
Return type, "Iterable[Unknown]* | Iterable[T@convert_to_list]", is partially unknown
Pylance(reportUnknownVariableType)
有人能解释一下为什么这是不正确的吗?
本期有关于这个问题的讨论。因此,这种行为可以用类型缩小来解释。现有的消除这种错误的方法之一是使用cast
函数