Skip to content

Type narrowing not performed in walrus operator conditional #19036

@injust

Description

@injust

Bug Report

Type narrowing is not performed in a conditional containing a walrus operator if:

  • There is another conditional in the same statement (if maybe and), and
  • An attribute access is performed on the value of the walrus operator (foo := Foo(True)).value)

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.13&flags=strict&gist=7e7edfa1d3debec48847590a6c4532c9

class Foo:
    value: bool

    def __init__(self, value: bool) -> None:
        self.thing = value


def bad(maybe: bool) -> None:
    foo = None
    if maybe and (foo := Foo(True)).value:
        reveal_type(foo)


def correct1(maybe: bool) -> None:
    foo = None
    if maybe and (foo := Foo(True)):
        reveal_type(foo)


def correct2(maybe: bool) -> None:
    foo = None
    if maybe:
        if (foo := Foo(True)).value:
            reveal_type(foo)

Expected Behavior

The revealed type is always Foo.

Actual Behavior

main.py:11: note: Revealed type is "Union[__main__.Foo, None]"
main.py:17: note: Revealed type is "__main__.Foo"
main.py:24: note: Revealed type is "__main__.Foo"
Success: no issues found in 1 source file

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags: --strict
  • Python version used: 3.13

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-pep-572PEP 572 (walrus operator)topic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions