python / python/cpython

Specialize syntax error for assignment expressions in invalid places

Open
#146,601 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
35.9k
PR merge metrics
PR metrics pending

Description

Feature or enhancement

Proposal:

There are a few places where (unparenthesized) assignment expressions are not accepted but users might think of using them. For example:

>>> func(arg=x := foo())
  File "<python-input-0>", line 1
    func(arg=x := foo())
               ^^
SyntaxError: invalid syntax

I find this error pretty confusing. It's not clear why this is a syntax error or what users should do it fix it (i.e. add parentheses).

I propose adding a specialized syntax error to point users in the right direction, similar to what's currently done for assert:

>>> assert x := 1
  File "<python-input-12>", line 1
    assert x := 1
           ^^^^^^
SyntaxError: cannot use named expression without parentheses here

Refs #138716, #146260

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

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 reproducing the examples in the issue and reading CPython's syntax-error handling for assignment expressions, comparing it with the existing specialized diagnostic for assert. Done means invalid unparenthesized assignment expressions receive a clear message directing users toward parentheses, while valid forms retain their existing behavior.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
58/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.