代码之家  ›  专栏  ›  技术社区  ›  Emile

解包元组时出现元组大小不匹配错误

  •  0
  • Emile  · 技术社区  · 4 年前

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

    0 回复  |  直到 4 年前
        1
  •  0
  •   Emile    4 年前

    我相信Python 3.10将通过使用TypeGuards来提供解决方案。参见PEP 647,其中甚至包括一个元组中元素数量的示例。

    推荐文章