Skip to content

Commit 08e4e11

Browse files
[3.11] gh-111380: Show SyntaxWarnings only once when parsing if invalid syntax is encouintered (GH-111381) (#111383)
gh-111380: Show SyntaxWarnings only once when parsing if invalid syntax is encouintered (GH-111381) (cherry picked from commit 3d2f1f0) Co-authored-by: Pablo Galindo Salgado <[email protected]>
1 parent c66f0be commit 08e4e11

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

Lib/test/test_string_literals.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,18 @@ def test_eval_str_invalid_escape(self):
131131
self.assertEqual(exc.lineno, 1)
132132
self.assertEqual(exc.offset, 1)
133133

134+
# Check that the warning is raised ony once if there are syntax errors
135+
136+
with warnings.catch_warnings(record=True) as w:
137+
warnings.simplefilter('always', category=DeprecationWarning)
138+
with self.assertRaises(SyntaxError) as cm:
139+
eval("'\\e' $")
140+
exc = cm.exception
141+
self.assertEqual(len(w), 1)
142+
self.assertEqual(w[0].category, DeprecationWarning)
143+
self.assertRegex(str(w[0].message), 'invalid escape sequence')
144+
self.assertEqual(w[0].filename, '<string>')
145+
134146
def test_eval_str_invalid_octal_escape(self):
135147
for i in range(0o400, 0o1000):
136148
with self.assertWarns(DeprecationWarning):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a bug that was causing :exc:`SyntaxWarning` to appear twice when parsing
2+
if invalid syntax is encountered later. Patch by Pablo galindo

Parser/string_parser.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@
1111
static int
1212
warn_invalid_escape_sequence(Parser *p, const char *first_invalid_escape, Token *t)
1313
{
14+
if (p->call_invalid_rules) {
15+
// Do not report warnings if we are in the second pass of the parser
16+
// to avoid showing the warning twice.
17+
return 0;
18+
}
1419
unsigned char c = *first_invalid_escape;
1520
int octal = ('4' <= c && c <= '7');
1621
PyObject *msg =

0 commit comments

Comments
 (0)