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 parse a complex conditional list comprehension inside of an f-string #4166

Closed
aphexcx opened this issue Jan 24, 2024 · 2 comments
Closed
Labels
T: bug Something isn't working

Comments

@aphexcx
Copy link

aphexcx commented Jan 24, 2024

Describe the bug

Black unexpectedly can't parse complex conditional list comprehensions inside of f-strings. Check out the example below.

To Reproduce

For example, take this code:

subdirs = ["foodir", "bardir", "tests"]

subdir_options = f" ({", ".join([dir for dir in subdirs if dir != "tests"])})" if subdirs else ""

And run it with these arguments:

$ black file.py --target-version py312

The resulting error is:

Cannot parse: 128:71: subdir_options = f" ({", ".join([dir for dir in subdirs if dir != "tests"])})" if subdirs else ""

Expected behavior

Black should parse this valid python.

Environment

  • Black's version: 23.12.1
  • OS and Python version: 3.12.1

Workaround

This does work if I change the f-string to use single quotes!:

subdir_options = f' ({", ".join([dir for dir in subdirs if dir != "tests"])})' if subdirs else ""

Black succeeds in formatting it to:

subdir_options = (
    f' ({", ".join([dir for dir in subdirs if dir != "tests"])})' if subdirs else ""
)
@aphexcx aphexcx added the T: bug Something isn't working label Jan 24, 2024
@JelleZijlstra
Copy link
Collaborator

Duplicate of #3746. (Note this syntax only works in Python 3.12 and higher.)

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Jan 24, 2024
@aphexcx
Copy link
Author

aphexcx commented Jan 24, 2024

Thanks! I found a workaround, see above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
T: bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants