Skip to content

Type of LHS of walrus operator not correctly inferred #14407

@turlando

Description

@turlando

Bug Report

The type of the LHS of an assignment performed using the walrus operator is not correctly inferred.
This issue can lead to insidious bugs where the user forgets to add a pair of brackets around the assignment.

To Reproduce

FOO: dict[str, int] = {
    'a': 1,
    'b': 2
}


def foo(a: str) -> int:
    if x := FOO.get(a) is not None:
        return x
    return -1


if __name__ == '__main__':
    print(foo('a'))
% python ~/testcase.py
True

Expected Behavior

mypy should report that it is not possible to unify int (coming from the return type of foo) and bool (coming from the is operator).

This can lead to bugs where the user does not realize that they should have really written if (x := FOO.get(a)) is not None.

Actual Behavior

% mypy ~/testcase.py  
Success: no issues found in 1 source file

Your Environment

  • Mypy version used: mypy 0.991 (compiled: yes)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: Python 3.10.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions