簡體   English   中英

如何在 Python 3.9 中指定多個參數聯合類型作為類型提示

[英]How to specify multiple paramater Union types as type hints in 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]tuple[str, TestValue, TestValue]組成的元組這一事實。 然而,在 Python 3.9 中,它似乎無法工作。 我嘗試將其Union[TestListA, TestListB]但這只會產生很多錯誤。 TypeError:無法實例化打字。聯合)

使用or不會給出任何錯誤,但我的 linter 似乎無法找到可能的第二種類型。

(*tuples: TestListA or TestListB)

Python 3.9 沒有該功能。 它在 Python 3.10 中引入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM