black
black copied to clipboard
Crash on formatting `case case` syntax when line length set to be small
Describe the bug
When using the match-case
block with a case case
statement (syntax allowed since Python 3.10), Black fails to parse the code if the line length is set to a small number.
To Reproduce
Consider the following code:
match test:
case case if True:
pass
This code can be correctly formatted by Black when the line length is reduced to 14, as shown below (playground link)
match test:
case (
case
) if True:
pass
However, when the line length is further decreased to 13 or below, Black will not be able to parse the code, (see playground link)
This issue can also be reproduced locally:
PS > cat temp.py
match test:
case case if True:
pass
PS > python -m black temp.py --line-length 13
error: cannot format temp.py: Cannot parse: 5:8: if True
Oh no! 💥 💔 💥
1 file failed to reformat.
PS > python -m black temp.py --line-length 1
error: cannot format temp.py: Cannot parse: 3:8: if True
Oh no! 💥 💔 💥
1 file failed to reformat.
Expected behavior
With line length set to be lower than 13, the output format should remain as
match test:
case (
case
) if True:
pass
Environment
- Local environment: Windows
PS > black --version
black, 24.2.0 (compiled: yes)
Python (CPython) 3.10.7
- Black Playground version: current stable v24.1.0
Thanks for the issue! It looks like this is already fixed in preview style, by https://github.com/psf/black/pull/4214
Hm actually no that's not quite right, https://github.com/psf/black/pull/4214 just reduces the line length at which this crashes. Black wants to do something like:
match test:
case case (
if True
):
pass