Skip to content

PEP 572 Walrus Operator Regex Assignment in Condition #8447

Closed
sthagen/python-mypy
#32
@NickHackman

Description

@NickHackman

Mypy version: 0.761
Python version: 3.8.1

#6899 implements PEP 572, or at least parts of it, as mentioned in the PR assignments can occur anywhere. Fails with an example similar to here with regex.

Minimal Example:

import re


TXT = "b"
if (a := re.search(r"a", TXT)) is not None:
    string = a.string
    print(f"{string}")
else:
    print("not in there") #=> not in there

mypy message:

~ λ mypy test.py
test.py:8: error: Item "None" of "Optional[Match[str]]" has no attribute "string"
Found 1 error in 1 file (checked 1 source file)

but the type of a is not Optional[Match[str]] it's Match[str] as a result of the if check.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions