Skip to content

False positive when combining walrus operator and regex #8260

Closed
@coiax

Description

@coiax

I think I've discovered the following bug, involving the walrus operator, and regular expressions, although I'm sure it's not exclusive to regex.

import re


def foo1(bar: str):
    if match := re.match(r'a(.*)', bar):
        group1 = match.group(1)

def foo2(bar: str):
    if (match := re.match(r'b(.*)', bar)) is not None:
        group2 = match.group(1)

def foo3(bar: str):
    if match := re.match(r'c(.*)', bar) and match is not None:
        group3 = match.group(1)

def foo4(bar: str):
    if match := re.match(r'd(.*)', bar):
        if match is not None:
            group4 = match.group(1)

def foo5(bar: str):
    if match := re.match(r'e(.*)', bar):
        if match:
            group5 = match.group(1)
  • What is the actual behavior/output?
bad.py:6: error: Item "None" of "Optional[Match[str]]" has no attribute "group"  [union-attr]
bad.py:10: error: Item "None" of "Optional[Match[str]]" has no attribute "group"  [union-attr]
bad.py:13: error: Cannot determine type of 'match'  [has-type]
bad.py:14: error: Item "None" of "Union[Match[str], None, bool]" has no attribute "group"  [union-attr]
bad.py:14: error: Item "bool" of "Union[Match[str], None, bool]" has no attribute "group"  [union-attr]
Found 5 errors in 1 file (checked 1 source file)
  • What is the behavior/output you expect?
    I expect all functions to pass type checking.
    All MatchObjects are always true, so all of the if blocks will only be entered if a match is found, but mypy complains about foo1, foo2, and foo3. foo4 and foo5 pass.

  • What are the versions of mypy and Python you are using?
    Python 3.8.1
    mypy 0.761

  • Do you see the same issue after installing mypy from Git master?
    Yes. git master version was mypy 0.770+dev.35b50397cabd36066d2dd92b979794b94f1741d3

  • What are the mypy flags you are using? (For example --strict-optional)
    No flags.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions