例如,如果我的代码在Python 3.10中是这样的:
from typing import Union
class TupleInvalid(Exception):
pass
TestValue = Union[int, str, float]
TestListA = tuple[str, TestValue]
TestListB = tuple[str, TestValue, TestValue]
def two_or_three(*tuples: TestListA | TestListB) -> str:
for x in tuples:
if isinstance(x[0], str):
if len(x) == 2:
return 'two'
elif len(x) == 3:
return 'three'
else:
raise TupleInvalid('Tuple should be 2 or 3 long')
else:
raise TupleInvalid(
'Tuple should be (<str>, <int | float | str>, \
<int | float | str> (optional)')
print(two_or_three(("test", 3, 4.5)))
print(two_or_three(("testing", 'hi')))
我的linter将能够理解这样一个事实:参数*tuples
应该是由tuple[str, TestValue]
或tuple[str, TestValue, TestValue]
组成的元组。然而,在Python3.9中,它似乎无法工作。我试着把它变成一个Union[TestListA, TestListB]
,但那只会产生很多错误。(TypeError:无法实例化typing.Union)
使用or
不会给出任何错误,但是我的linter似乎无法找到可能的第二种类型
(*tuples: TestListA or TestListB)
Python3.9没有这个特性。它是在Python3.10中引入的
相关问题 更多 >
编程相关推荐