cpython
cpython copied to clipboard
Improve syntax error when brackets (parentheses) are mismatched
The syntax error for mismatched brackets uses a caret to point to the closing bracket. But sometimes it is the opening bracket which is wrong. We should point a caret at both.
For example, this simple expression points to the closing square bracket:
>>> obj{"some long expression"]
File "<stdin>", line 1
obj{"some long expression"]
^
SyntaxError: closing parenthesis ']' does not match opening parenthesis '{'
But the real cause of the issue is the opening brace. It would be helpful to point at that as well:
obj{"some long expression"]
^ ^
SyntaxError: closing parenthesis ']' does not match opening parenthesis '{'
This is especially helpful in complex expressions with many mixed parentheses:
>>> obj[func(x[store[arg, a[i], b[j])])[y]]
File "<stdin>", line 1
obj[func(x[store[arg, a[i], b[j])])[y]]
^
SyntaxError: closing parenthesis ')' does not match opening parenthesis '['
The reader has to carefully match up brackets by hand to see where the opening bracket is. A second caret would make that instantaneous:
obj[func(x[store[arg, a[i], b[j])])[y]]
^ ^
SyntaxError: closing parenthesis ')' does not match opening parenthesis '['
In your first example, shouldn't it even only point to the {
and not look further? That's also what Python 3.8 still did.