如何在Python 3.9中指定多个paramater联合类型作为类型提示

2024-06-25 06:01:45 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,如果我的代码在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)

Tags: ortypingiffloatintthreeuniontwo