【问题标题】:Unpacking tuple gives tuple size mismatch error解包元组会导致元组大小不匹配错误
【发布时间】:2021-02-17 12:37:40
【问题描述】:

在对元组解包进行类型检查时,我在该程序上遇到 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)?

【问题讨论】:

  • Tuple[int, ...] 有效吗?
  • 看起来你真的无能为力。只是类型检查器在这些情况下有点糟糕

标签: python visual-studio-code tuples typechecking pylance


【解决方案1】:

我相信 Python 3.10 会使用 TypeGuards 来解决这个问题。请参阅 PEP 647,其中甚至包括元组中元素数量的示例。

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 2015-01-28
    • 1970-01-01
    • 2020-09-18
    • 2023-02-20
    • 1970-01-01
    相关资源
    最近更新 更多