Walrus operator for match in if

Python pattern

Use the walrus operator for snippets with a match followed by an if.

Limitations:

  • If the match function is imported with an alias (e.g. from re import match as m), it will not be transformed.
  • When re.match is used, we do not check that re comes from import re.

Simple match and if

BEFORE
match = re.match("hello")
if match:
    print("there is a match")
elif x > 10:
    print("no match")
else:
    print("no match")
AFTER
if match := re.match("hello"):
    print("there is a match")
elif x > 10:
    print("no match")
else:
    print("no match")

It also applies to search and fullmatch

BEFORE
match = re.fullmatch("hello")
if match:
    pass

match = re.search("hello")
if match:
    pass
AFTER
if match := re.fullmatch("hello"):
    pass

if match := re.search("hello"):
    pass

It only applies to functions in re

BEFORE
# search is re.search and thus is transformed
from re import search
match = search("hello")
if match:
    pass

# match is not re.match and thus is not transformed
match = lambda s: False
match = match("hello")
if match:
    pass
AFTER
# search is re.search and thus is transformed
from re import search

if match := search("hello"):
    pass

# match is not re.match and thus is not transformed
match = lambda s: False
match = match("hello")
if match:
    pass

It does not apply to other re functions or from other modules

PYTHON
# re.sub is not transformed
sub = re.sub("hello", "bye")
if sub:
    pass

# regex.fullmatch is not transformed
match = regex.fullmatch("hello")
if match:
    pass