0

在对元组解包进行类型检查时,我在该程序上遇到 pylance 错误(基本设置)。这个想法是一个元组可以有 2 或 3 个特定类型的元素。

# pylance typechecking "basic"

from typing import Tuple, Union

TT = Union[Tuple[str,str,float], Tuple[str,str]]

def f(v: TT):
    if len(v) == 3:
        a,b,c = v  # pylance reportGeneralTypeIssues: Tuple size mismatch: expected 3 but received 2
    elif len(v) == 2:
        a,b = v    # pylance reportGeneralTypeIssues: Tuple size mismatch: expected 2 but received 3

我应该如何去说服检查器这是正确的(没有#type ignore)?

4

1 回答 1

0

I believe the solution will come with Python 3.10 by using TypeGuards. See PEP 647, which even includes an example for the number of elements in a tuple.

于 2021-05-18T13:55:29.443 回答