首页 > 解决方案 > 如何在 Python 3.9 中指定多个参数联合类型作为类型提示

问题描述

例如,如果我的代码在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]or组成的元组的事实tuple[str, TestValue, TestValue]。然而,在 Python 3.9 中,它似乎无法工作。我试着让它成为一个,Union[TestListA, TestListB]但这只会产生很多错误。(TypeError:无法实例化打字。联合)

使用or不会给出任何错误,但我的 linter 似乎无法找到可能的第二种类型。

(*tuples: TestListA or TestListB)

标签: pythonpython-3.xtype-hintingpython-typing

解决方案


Python 3.9 没有这个特性。它是在 Python 3.10 中引入的。


推荐阅读