Skip to content

bpo-38964: Print correct filename on a SyntaxError in an fstring #20399

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 5 commits into from
May 26, 2020
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
13 changes: 13 additions & 0 deletions Lib/test/test_fstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@
# Unicode identifiers in tests is allowed by PEP 3131.

import ast
import os
import types
import decimal
import unittest
from test.support import temp_cwd, use_old_parser
from test.support.script_helper import assert_python_failure

a_global = 'global variable'

Expand Down Expand Up @@ -1044,6 +1047,16 @@ def test_errors(self):
r"f'{1000:j}'",
])

@unittest.skipIf(use_old_parser(), "The old parser only supports <fstring> as the filename")
def test_filename_in_syntaxerror(self):
# see issue 38964
with temp_cwd() as cwd:
file_path = os.path.join(cwd, 't.py')
with open(file_path, 'w') as f:
f.write('f"{a b}"') # This generates a SyntaxError
_, _, stderr = assert_python_failure(file_path)
self.assertIn(file_path, stderr.decode('utf-8'))

def test_loop(self):
for i in range(1000):
self.assertEqual(f'i:{i}', 'i:' + str(i))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +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.
7 changes: 2 additions & 5 deletions Parser/pegen/parse_string.c
Original file line number Diff line number Diff line change
Expand Up @@ -606,11 +606,8 @@ fstring_compile_expr(Parser *p, const char *expr_start, const char *expr_end,
if (tok == NULL) {
return NULL;
}
tok->filename = PyUnicode_FromString("<fstring>");
if (!tok->filename) {
PyTokenizer_Free(tok);
return NULL;
}
Py_INCREF(p->tok->filename);
tok->filename = p->tok->filename;

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