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

Improve f-string expression detection regex so ... #2437

Merged
merged 1 commit into from Aug 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.md
Expand Up @@ -7,6 +7,8 @@
- Add support for formatting Jupyter Notebook files (#2357)
- Move from `appdirs` dependency to `platformdirs` (#2375)
- Present a more user-friendly error if .gitignore is invalid (#2414)
- The failsafe for accidentally added backslashes in f-string expressions has been
hardened to handle more edge cases during quote normalization (#2437)

### Integrations

Expand Down
4 changes: 2 additions & 2 deletions src/black/strings.py
Expand Up @@ -190,9 +190,9 @@ def normalize_string_quotes(s: str) -> str:
if "f" in prefix.casefold():
matches = re.findall(
r"""
(?:[^{]|^)\{ # start of the string or a non-{ followed by a single {
(?:(?<!\{)|^)\{ # start of the string or a non-{ followed by a single {
([^{].*?) # contents of the brackets except if begins with {{
\}(?:[^}]|$) # A } followed by end of the string or a non-}
\}(?:(?!\})|$) # A } followed by end of the string or a non-}
""",
new_body,
re.VERBOSE,
Expand Down
10 changes: 10 additions & 0 deletions tests/data/string_quotes.py
Expand Up @@ -51,6 +51,11 @@
'\'{z}\' {y * " "}'
'{y * x} \'{z}\''

# We must bail out if changing the quotes would introduce backslashes in f-string
# expressions. xref: https://github.com/psf/black/issues/2348
f"\"{b}\"{' ' * (long-len(b)+1)}: \"{sts}\",\n"
f"\"{a}\"{'hello' * b}\"{c}\""

# output

""""""
Expand Down Expand Up @@ -100,3 +105,8 @@
f"{y * x} '{z}'"
"'{z}' {y * \" \"}"
"{y * x} '{z}'"

# We must bail out if changing the quotes would introduce backslashes in f-string
# expressions. xref: https://github.com/psf/black/issues/2348
f"\"{b}\"{' ' * (long-len(b)+1)}: \"{sts}\",\n"
f"\"{a}\"{'hello' * b}\"{c}\""