Skip to content

[3.12] gh-105800: Issue SyntaxWarning in f-strings for invalid escape sequences (GH-105801) #105806

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

Merged
merged 1 commit into from
Jun 15, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Lib/test/test_fstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -907,6 +907,9 @@ def test_backslashes_in_string_part(self):
with self.assertWarns(DeprecationWarning): # invalid escape sequence
value = eval(r"f'\{6*7}'")
self.assertEqual(value, '\\42')
with self.assertWarns(SyntaxWarning): # invalid escape sequence
value = eval(r"f'\g'")
self.assertEqual(value, '\\g')
self.assertEqual(f'\\{6*7}', '\\42')
self.assertEqual(fr'\{6*7}', '\\42')

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Correctly issue :exc:`SyntaxWarning` in f-strings if invalid sequences are
used. Patch by Pablo Galindo
6 changes: 3 additions & 3 deletions Parser/action_helpers.c
Original file line number Diff line number Diff line change
Expand Up @@ -1231,7 +1231,7 @@ _PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq
// Fstring stuff

static expr_ty
_PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant) {
_PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant, Token* token) {
assert(PyUnicode_CheckExact(constant->v.Constant.value));

const char* bstr = PyUnicode_AsUTF8(constant->v.Constant.value);
Expand All @@ -1247,7 +1247,7 @@ _PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant) {
}

is_raw = is_raw || strchr(bstr, '\\') == NULL;
PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, NULL);
PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
if (str == NULL) {
_Pypegen_raise_decode_error(p);
return NULL;
Expand Down Expand Up @@ -1321,7 +1321,7 @@ _PyPegen_joined_str(Parser *p, Token* a, asdl_expr_seq* raw_expressions, Token*b
for (Py_ssize_t i = 0; i < n_items; i++) {
expr_ty item = asdl_seq_GET(expr, i);
if (item->kind == Constant_kind) {
item = _PyPegen_decode_fstring_part(p, is_raw, item);
item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
if (item == NULL) {
return NULL;
}
Expand Down