black
black copied to clipboard
Cannot format code with local variable name `match` in same line as match pattern matching expression
Describe the bug
Take this code:
import re
match = re.match(r"(?P<grade>LD|MD|HD)(?P<material>AL|SS)", "HDSS")
match (match.group("grade"), match.group("material")):
case ("MD" | "HD", "SS" as code):
print("You will get here")
And run it with these arguments:
$ black file.py --target-version py310 # or --target-version py311
The resulting error is:
cannot format foo.py: Cannot parse: 3:0: match (match.group("grade"), match.group("material")):
Expected behavior
Sure, the local variable name should be something else, but it's valid python and Python will run it perfectly fine. If Python is cool with it, then black should support it. (Even if it's poor taste in variable names; valid Python should not break black)
Environment
- Black's version: 22.12.0
- OS and Python version:
docker run -it --rm python:3.11 bash
Workarounds
Black works if you use a different variable name:
the_match = re.match(r"(?P<grade>LD|MD|HD)(?P<material>AL|SS)", "HDSS")
match (the_match.group("grade"), the_match.group("material")):
case _:
pass
This simply proves the issue is with the variable name being match
.
Black works also if you refactor the code to separate the local variable match
and the keyword match
:
match = re.match(r"(?P<grade>LD|MD|HD)(?P<material>AL|SS)", "HDSS")
grade, material = match.group("grade"), match.group("material")
match (grade, material): # local variable `match` not used here
case _:
pass
An interesting case where Black works with match
in the same line is:
match re.match(r"(?P<grade>LD|MD|HD)(?P<material>AL|SS)", "HDSS").groups():
case _:
pass
cc @isidentical
I think #3950 fixed this. I'll send a PR with a regression test.