Mypy: tell parameter from elif is None without assert

Viewed 690

I have a function 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

Here's what happens if I run 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)

I can get around this by using 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

However, is there a better way to do this? Ideally, a solution would not use assert not cast

1 Answers

Both x is None and x is not None are very efficient comparisons. Simply invert the comparison to check the desired state, instead of implying it by checking the undesired state.

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
Related