Mypy:告诉来自 elif 的参数是 None 没有断言

Mypy: tell parameter from elif is None without assert

我有一个函数t.py:

from typing import Optional

def f(a: Optional[int], b: Optional[int]):
    if a is None and b is None:
        c: int = 3
    elif a is None:
        c = b
    elif b is None:
        c = a
    else:
        c = 0

如果我 运行 mypy:

会发生什么
$ mypy t.py 
t.py:7: error: Incompatible types in assignment (expression has type "Optional[int]", variable has type "int")
Found 1 error in 1 file (checked 1 source file)

我可以使用 assert:

来解决这个问题
from typing import Optional

def f(a: Optional[int], b: Optional[int]):
    if a is None and b is None:
        c: int = 3
    elif a is None:
        assert b is not None
        c = b
    elif b is None:
        c = a
    else:
        c = 0

但是,有更好的方法吗?理想情况下,解决方案不会使用 assert 而不是 cast

x is Nonex is not None都是非常有效的比较。只需反转比较以检查所需状态,而不是通过检查不需要的状态来暗示它。

def f(a: Optional[int], b: Optional[int]):
    if a is None and b is None:
        c: int = 3
    elif b is not None:  # check for b in branch using b
        c = b
    elif a is not None:  # check for a in branch using a
        c = a
    else:
        c = 0