Skip to content

Mypy could not do condition inference #19029

Closed as duplicate of#9229
Closed as duplicate of#9229
@kaelzhang

Description

@kaelzhang

Bug Report

To Reproduce

The min sample:

class MyClass:
    a_property: int = 1

    def do_something (
        self,
        source: Optional['MyClass'] = None
    ):
        is_not_none = source is not None

        if is_not_none:
            # My ass even knows that `source` must be a `MyClass` instance here.
            self.a_property = source.a_property

Expected Behavior

It should pass the test

Actual Behavior

Item "None" of "MyClass | None" has no attribute "a_property"  [union-attr]

The only way to avoid this error output is to replace each is_not_none with source is not None. It makes the code silly sometimes, and forces me to revamp the logic just for mypy which is a totally waste of my time.

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags: mypy foo.py
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.12.7

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions