Skip to content

Improve syntax error when brackets (parentheses) are mismatched #98278

@stevendaprano

Description

@stevendaprano

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 '['

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions