python / python/mypy

Nested if Optional checking for class attributes fails

Open
#13,670 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied test.py example with mypy and inspect the reveal_type output and reported errors in the nested branches. The work is done when the intended non-None narrowing is handled consistently there without introducing incorrect narrowing after foo is reassigned.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.