Skip to content

Commit 638c2ba

Browse files
[3.12] gh-105800: Issue SyntaxWarning in f-strings for invalid escape sequences (GH-105801) (#105806)
Co-authored-by: Pablo Galindo Salgado <[email protected]>
1 parent 52a2bbd commit 638c2ba

File tree

3 files changed

+8
-3
lines changed

3 files changed

+8
-3
lines changed

Lib/test/test_fstring.py

+3
Original file line numberDiff line numberDiff line change
@@ -907,6 +907,9 @@ def test_backslashes_in_string_part(self):
907907
with self.assertWarns(DeprecationWarning): # invalid escape sequence
908908
value = eval(r"f'\{6*7}'")
909909
self.assertEqual(value, '\\42')
910+
with self.assertWarns(SyntaxWarning): # invalid escape sequence
911+
value = eval(r"f'\g'")
912+
self.assertEqual(value, '\\g')
910913
self.assertEqual(f'\\{6*7}', '\\42')
911914
self.assertEqual(fr'\{6*7}', '\\42')
912915

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Correctly issue :exc:`SyntaxWarning` in f-strings if invalid sequences are
2+
used. Patch by Pablo Galindo

Parser/action_helpers.c

+3-3
Original file line numberDiff line numberDiff line change
@@ -1231,7 +1231,7 @@ _PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq
12311231
// Fstring stuff
12321232

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

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

12491249
is_raw = is_raw || strchr(bstr, '\\') == NULL;
1250-
PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, NULL);
1250+
PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
12511251
if (str == NULL) {
12521252
_Pypegen_raise_decode_error(p);
12531253
return NULL;
@@ -1321,7 +1321,7 @@ _PyPegen_joined_str(Parser *p, Token* a, asdl_expr_seq* raw_expressions, Token*b
13211321
for (Py_ssize_t i = 0; i < n_items; i++) {
13221322
expr_ty item = asdl_seq_GET(expr, i);
13231323
if (item->kind == Constant_kind) {
1324-
item = _PyPegen_decode_fstring_part(p, is_raw, item);
1324+
item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
13251325
if (item == NULL) {
13261326
return NULL;
13271327
}

0 commit comments

Comments
 (0)