Skip to content

Commit f7b1e46

Browse files
bpo-38964: Print correct filename on a SyntaxError in an fstring (GH-20399)
When a `SyntaxError` in the expression part of a fstring is found, the filename attribute of the `SyntaxError` is always `<fstring>`. With this commit, it gets changed to always have the name of the file the fstring resides in. Co-authored-by: Pablo Galindo <[email protected]>
1 parent 2602d97 commit f7b1e46

File tree

3 files changed

+16
-5
lines changed

3 files changed

+16
-5
lines changed

Lib/test/test_fstring.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,12 @@
88
# Unicode identifiers in tests is allowed by PEP 3131.
99

1010
import ast
11+
import os
1112
import types
1213
import decimal
1314
import unittest
15+
from test.support import temp_cwd, use_old_parser
16+
from test.support.script_helper import assert_python_failure
1417

1518
a_global = 'global variable'
1619

@@ -1044,6 +1047,16 @@ def test_errors(self):
10441047
r"f'{1000:j}'",
10451048
])
10461049

1050+
@unittest.skipIf(use_old_parser(), "The old parser only supports <fstring> as the filename")
1051+
def test_filename_in_syntaxerror(self):
1052+
# see issue 38964
1053+
with temp_cwd() as cwd:
1054+
file_path = os.path.join(cwd, 't.py')
1055+
with open(file_path, 'w') as f:
1056+
f.write('f"{a b}"') # This generates a SyntaxError
1057+
_, _, stderr = assert_python_failure(file_path)
1058+
self.assertIn(file_path, stderr.decode('utf-8'))
1059+
10471060
def test_loop(self):
10481061
for i in range(1000):
10491062
self.assertEqual(f'i:{i}', 'i:' + str(i))
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
When there's a :exc:`SyntaxError` in the expression part of an fstring, the filename attribute of the :exc:`SyntaxError` gets correctly set to the name of the file the fstring resides in.

Parser/pegen/parse_string.c

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -606,11 +606,8 @@ fstring_compile_expr(Parser *p, const char *expr_start, const char *expr_end,
606606
if (tok == NULL) {
607607
return NULL;
608608
}
609-
tok->filename = PyUnicode_FromString("<fstring>");
610-
if (!tok->filename) {
611-
PyTokenizer_Free(tok);
612-
return NULL;
613-
}
609+
Py_INCREF(p->tok->filename);
610+
tok->filename = p->tok->filename;
614611

615612
Parser *p2 = _PyPegen_Parser_New(tok, Py_fstring_input, p->flags, p->feature_version,
616613
NULL, p->arena);

0 commit comments

Comments
 (0)