mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Nested if Optional checking for class attributes fails

Open clintlombard opened this issue 3 years ago • 0 comments

Checking optional attributes in a class does not persist in a nested if:

(test.py)

#!/usr/bin/env python3

import typing


class Example:
    def __init__(self):
        self.a: typing.Optional[int]


def check_class(foo: Example, bar: Example):
    reveal_type(foo.a)
    if foo.a is not None:
        reveal_type(foo.a)
        if foo.a > 0:
            reveal_type(foo.a)
            foo = bar
        elif foo.a < 0:
            reveal_type(foo.a)
            foo.a += 1

Output:

$ mypy test.py
test.py:12: note: Revealed type is "Union[builtins.int, None]"
test.py:14: note: Revealed type is "builtins.int"
test.py:16: note: Revealed type is "builtins.int"
test.py:18: error: Unsupported operand types for > ("int" and "None")
test.py:18: note: Left operand is of type "Optional[int]"
test.py:19: note: Revealed type is "Union[builtins.int, None]"
test.py:20: error: Unsupported operand types for + ("None" and "int")
test.py:20: note: Left operand is of type "Optional[int]"

Environment

  • Python 3.9.9
  • mypy == 0.971
  • Linux x86_64
  • No other mypy config

clintlombard avatar Sep 16 '22 08:09 clintlombard