Skip to content

PEP 572 Walrus Operator Regex Assignment in Condition #8447

Closed
sthagen/python-mypy
#32

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.

Activity

  1. JukkaL commented on Feb 28, 2020

    @JukkaL
    Collaborator

    Yeah, type inference doesn't seem to work correctly here.

    As a workaround, you can remove the is not None check, and things should work as expected (when using GitHub master, at least):

    import re
    
    
    TXT = "b"
    if a := re.search(r"a", TXT):   # <<-- removed the None check
        string = a.string  # No error here
        print(f"{string}")
    else:
        print("not in there")
  2. added a commit that references this issue on Feb 28, 2020
    32a0185
  3. hauntsaninja commented on Feb 28, 2020

    @hauntsaninja
    Collaborator

    Same issue as in #8236

  4. added a commit that references this issue on Feb 28, 2020
    1e1b22d
  5. added a commit that references this issue on Mar 9, 2020
    c4d8554
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions