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

Incorrect flake8-comprehension fixits (C401,C402) in fstring #2770

Closed
Skylion007 opened this issue Feb 11, 2023 · 4 comments · Fixed by #2806
Closed

Incorrect flake8-comprehension fixits (C401,C402) in fstring #2770

Skylion007 opened this issue Feb 11, 2023 · 4 comments · Fixed by #2806
Labels
bug Something isn't working

Comments

@Skylion007
Copy link

Skylion007 commented Feb 11, 2023

One annoying false positive change in this flake8-comprehensions are set/dict conversions to literals in f'strings.

b = list(range(10))
print(f'{set(a if a < 6 else 0  for a in b)}')

which prints: {0, 1, 2, 3, 4, 5}

becomes

b = list(range(10))
print(f'{{a if a < 6 else 0  for a in b}}')

which is actually wrong if it's in a fstring since it actually just escapes the innermost curly brace. This results in the printing of {a if a < 6 else 0 for a in b}

It should fixit as

b = list(range(10))
print(f'{ {a if a < 6 else 0  for a in b} }')

The space will prevent the curly brace from being escaped and is deleted when the fstring resolves which should provide identical behavior to the original code snippit. See this Stackoverflow post: https://stackoverflow.com/questions/49120113/dictionary-set-comprehensions-inside-of-f-string

I suspect you wound find similar behavior for C402 with dict comprehensions.

Command, Version Info, and Settings

ruff --select C401,C402 example.py --fix
ruff 0.0.244
no ruff pyproject.toml ruff settings specified
@charliermarsh charliermarsh added the bug Something isn't working label Feb 11, 2023
@charliermarsh
Copy link
Member

Ahh thank you! Good catch. I guess arguably we should avoid flagging this at all in f-strings.

@charliermarsh
Copy link
Member

\cc @sbrugman if you're interested.

@Skylion007
Copy link
Author

@charliermarsh It's not a bad change in fstrings, and it is potentially more performant, just need to be careful to do it properly :P . Another option is just to add an extra space around the inserted braces unconditionally and let black or whatever formatter you use deal with it.

@charliermarsh
Copy link
Member

Yeah I could see either being "correct". Regardless sorry for the breakage!

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

Successfully merging a pull request may close this issue.

2 participants