python / python/cpython

Improve syntax error when brackets (parentheses) are mismatched

Open
#98,278 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core topic-parser type-feature
Dominant language
Python
Stars
77.2k
Forks
36k
Avg merge
1d 9h
Merged PRs (30d)
558

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the parser or syntax-error diagnostic code that handles mismatched brackets, then find its existing tests for the reported examples. Update the behavior so the diagnostic points to both the opening and closing brackets, and confirm the displayed caret positions for mixed parentheses.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.