Infer that `a or `b, when one of them is not `None`, isn't `None`

Question:

Here’s an example:

a: int | None
b: int | None
assert (a is not None) or (b is not None)
reveal_type(a or b)

If one of a and b is not None, then a or b must be not None.

But mypy reveals the type to be

main.py:4: note: Revealed type is "Union[builtins.int, None]"

Why is that? How can I get it to infer that a or b isn’t None?

https://mypy-play.net/?mypy=latest&python=3.10&gist=f5f8f94d89204920e9543ff52fcaf6ab

Asked By: ignoring_gravity

||

Answers:

Consider what happens when a == 0 and b is None. The assert isn’t triggered, but since 0 is falsy, the result of 0 or None is None.

Answered By: yuri kilochek
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.