【问题标题】:Can mypy handle list comprehensions?mypy 可以处理列表推导吗?
【发布时间】:2018-02-27 12:27:38
【问题描述】:
from typing import Tuple
def test_1(inp1: Tuple[int, int, int]) -> None:
    pass

def test_2(inp2: Tuple[int, int, int]) -> None:
    test_tuple = tuple(e for e in inp2)
    reveal_type(test_tuple)
    test_1(test_tuple)

在上述代码上运行 mypy 时,我得到:

error: Argument 1 to "test_1" has incompatible type "Tuple[int, ...]"; expected "Tuple[int, int, int]"

test_tuple 是否不能保证有 3 个 int 元素? mypy 不处理这样的列表推导还是有另一种在这里定义类型的方法?

【问题讨论】:

    标签: python python-3.x type-hinting mypy python-typing


    【解决方案1】:

    从 0.600 版开始,mypy 在这种情况下不会推断类型。正如GitHub 所建议的那样,这将很难实施。

    相反,我们可以使用cast(参见mypy docs):

    from typing import cast, Tuple
    
    def test_1(inp1: Tuple[int, int, int]) -> None:
        pass
    
    def test_2(inp2: Tuple[int, int, int]) -> None:
        test_tuple = cast(Tuple[int, int, int], tuple(e for e in inp2))
        reveal_type(test_tuple)
        test_1(test_tuple)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 2015-10-14
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      相关资源
      最近更新 更多