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

flynt 1.0.1 doesn't handle backslashes (\) correctly, causes SyntaxError in created f-strings #192

Open
EwoutH opened this issue Nov 8, 2023 · 0 comments

Comments

@EwoutH
Copy link

EwoutH commented Nov 8, 2023

flynt 1.0.1 currently doesn't handle backslashes (\) in the string conversion correctly, which is causing SyntaxErrors in the created f-strings.

Fix a SyntaxError: f-string expression part cannot include a backslash

It mainly occurs with newlines (\n) and double backslashes (\\). However, there was also a case without either of those (see the last case below).

Examples

Here are a few examples of broken conversions by flynt 1.0.1 that cause the SyntaxError:

Old:

'"%s\\n"\n' % line if not line.endswith('\\') or line.endswith('\\\\') else '"%s"\n' % line[:-1]

New and broken:

f'"{line}\\n\"\n' if not line.endswith('\\') or line.endswith('\\\\') else f'"{line[:-1]}\"\n'

Old:

msg = "{}\nPossible solutions:\n{}".format(msg, "\n".join(solutions))

New and broken:

msg = f"{msg}\nPossible solutions:\n{'\\n'.join(solutions)}"

Old:

return '{}({})'.format(node.__class__.__name__, ',\n    '.join(values))

New and broken:

return f"{node.__class__.__name__}({',\\n    '.join(values)})"

Old:

self.assertEqual(len(expected), len(result),
    "Unmatched lines. Got:\n{}\nExpected:\n{}".format("\n".join(expected), "\n".join(result)))

New and broken:

self.assertEqual(len(expected), len(result),
    f"Unmatched lines. Got:\n{'\\n'.join(expected)}\nExpected:\n{'\\n'.join(result)}")

Old:

self.assertEqual(len(result_lines), len(expected_lines),
    "Unmatched lines. Got:\n{}\nExpected:\n{}".format("\n".join(result_lines), expected))

New and broken:

self.assertEqual(len(result_lines), len(expected_lines),
    f"Unmatched lines. Got:\n{'\\n'.join(result_lines)}\nExpected:\n{expected}")

Old:

code.putln('"{}.{}",'.format(self.full_module_name, classname.replace('"', '')))

New and broken:

code.putln(f"\"{self.full_module_name}.{classname.replace('\"', '')}\",")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant