Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1660f6f

Browse files
committed
bpo-24612: Improve syntax error for 'not' after an operator
1 parent 6beaf2f commit 1660f6f

File tree

4 files changed

+690
-418
lines changed

4 files changed

+690
-418
lines changed

Grammar/python.gram

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,7 @@ bitwise_and[expr_ty]:
722722
shift_expr[expr_ty]:
723723
| a=shift_expr '<<' b=sum { _PyAST_BinOp(a, LShift, b, EXTRA) }
724724
| a=shift_expr '>>' b=sum { _PyAST_BinOp(a, RShift, b, EXTRA) }
725+
| invalid_arithmetic
725726
| sum
726727

727728
# Arithmetic operators
@@ -1249,3 +1250,6 @@ invalid_kvpair:
12491250
RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError, a->lineno, a->end_col_offset - 1, a->end_lineno, -1, "':' expected after dictionary key") }
12501251
| expression ':' a='*' bitwise_or { RAISE_SYNTAX_ERROR_STARTING_FROM(a, "cannot use a starred expression in a dictionary value") }
12511252
| expression a=':' {RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "expression expected after dictionary key and ':'") }
1253+
1254+
invalid_arithmetic:
1255+
| sum ('+'|'-'|'*'|'/'|'~'|'%'|'//'|'@') a='not' b=inversion { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "'not' after an operator must be parenthesized") }

Lib/test/test_syntax.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,6 +1194,29 @@
11941194
Traceback (most recent call last):
11951195
SyntaxError: only single target (not list) can be annotated
11961196
1197+
# 'not' after operators:
1198+
1199+
>>> 3 + not 3
1200+
Traceback (most recent call last):
1201+
SyntaxError: 'not' after an operator must be parenthesized
1202+
1203+
>>> 3 * not 3
1204+
Traceback (most recent call last):
1205+
SyntaxError: 'not' after an operator must be parenthesized
1206+
1207+
>>> 3 ~ not 3
1208+
Traceback (most recent call last):
1209+
SyntaxError: 'not' after an operator must be parenthesized
1210+
1211+
# Check that we don't introduce misleading errors
1212+
>>> not 1 */ 2
1213+
Traceback (most recent call last):
1214+
SyntaxError: invalid syntax
1215+
1216+
>>> not 1 +
1217+
Traceback (most recent call last):
1218+
SyntaxError: invalid syntax
1219+
11971220
Corner-cases that used to fail to raise the correct error:
11981221
11991222
>>> def f(*, x=lambda __debug__:0): pass
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve the :exc:`SyntaxError` that happens when 'not' appears after an
2+
operator. Patch by Pablo Galindo

0 commit comments

Comments
 (0)