flynt icon indicating copy to clipboard operation
flynt copied to clipboard

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

Open EwoutH opened this issue 7 months ago • 0 comments

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('\"', '')}\",")

EwoutH avatar Nov 08 '23 15:11 EwoutH