Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot format code with local variable name match in same line as match pattern matching expression #3487

Closed
CelestialGuru opened this issue Jan 9, 2023 · 2 comments · Fixed by #3993
Labels
C: parser How we parse code. Or fail to parse it. T: bug Something isn't working

Comments

@CelestialGuru
Copy link

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
@CelestialGuru CelestialGuru added the T: bug Something isn't working label Jan 9, 2023
@JelleZijlstra
Copy link
Collaborator

cc @isidentical

@JelleZijlstra JelleZijlstra added the C: parser How we parse code. Or fail to parse it. label Jan 9, 2023
@JelleZijlstra
Copy link
Collaborator

I think #3950 fixed this. I'll send a PR with a regression test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C: parser How we parse code. Or fail to parse it. T: bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants