Skip to content

Type narrowing not performed in walrus operator conditional #19036

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
injust opened this issue May 5, 2025 · 0 comments · May be fixed by #19038
Open

Type narrowing not performed in walrus operator conditional #19036

injust opened this issue May 5, 2025 · 0 comments · May be fixed by #19038
Labels
bug mypy got something wrong topic-pep-572 PEP 572 (walrus operator) topic-type-narrowing Conditional type narrowing / binder

Comments

@injust
Copy link

injust commented May 5, 2025

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
@injust injust added the bug mypy got something wrong label May 5, 2025
@sterliakov sterliakov added topic-pep-572 PEP 572 (walrus operator) topic-type-narrowing Conditional type narrowing / binder labels May 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-pep-572 PEP 572 (walrus operator) topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants