我如何告诉mypy条件得到保证?

问题描述 投票:1回答:1

我的实际情况比较复杂,但是MVCE是

from typing import List


def find_largest(numbers: List[int]) -> List[int]:
    """
    >>> find_largest([3, 4, 5, 5, 3, 1, -2, 4, 3, 3])
    [5, 5]
    """
    assert len(numbers) > 0  # guaranteed by caller
    largest_numbers = None
    value = None
    for number in numbers:
        if value is None or number > value:
            largest_numbers = [number]
            value = number
        elif number == value:
            largest_numbers.append(number)
    return largest_numbers


if __name__ == '__main__':
    import doctest
    doctest.testmod()

当我对此执行mypy时,我得到:

mytest.py:18: error: Incompatible return value type (got "Optional[List[int]]", expected "List[int]")
Found 1 error in 1 file (checked 1 source file)

但是mypy未捕获的限制保证不返回None。我该如何向mypy提示? (无法用其他方式初始化)

python-3.6 mypy
1个回答
1
投票

根据Mypy,您的代码仍然可以返回None,并且它认为键入是正确的。

假设您无法解决此问题,也可以使用以下命令强制返回值始终具有值:

assert largest_numbers
return largest_numbers
© www.soinside.com 2019 - 2024. All rights reserved.