Skip to content

can not parse dict-comprehension with f-string in condition #4600

@15r10nk

Description

@15r10nk

Describe the bug

The following code can not be parsed/formatted by black:

{name_4: name_1 for name_2 in something if f'\\' if {}}
❯ .venv/bin/black -t py312 scripts/min_code.py
error: cannot format scripts/min_code.py: Cannot parse for target version Python 3.12: 1:53: {name_4: name_1 for name_2 in something if f'\\' if {}}

Oh no! 💥 💔 💥
1 file failed to reformat.

but it can be parsed by cpython.

❯ python3.12 scripts/min_code.py
Traceback (most recent call last):
  File "/home/frank/projects/black/scripts/min_code.py", line 1, in <module>
    {name_4: name_1 for name_2 in something if f'\\' if {}}
                                  ^^^^^^^^^
NameError: name 'something' is not defined

(this is not a parsing but an runtime error, which is ok)

Environment

  • Black's version: current main (00c0d6d)
  • OS and Python version: Linux/Python 3.12

Additional context

The bug was found by pysource-codegen (see #3908)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions