python / python/cpython

ast.parse creates only Constant(value=0) nodes for a `case +0:` pattern, which is inconsistent.

Open
#152,708 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core topic-parser type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

I found the following asymmetry in the generated ast while I was working with the new cpython 3.15.

c="""
match 0:
    case +0:
        pass
    case -0:
        pass
+0
-0
"""

import ast

print(ast.dump(ast.parse(c),indent=2))

output (Python 3.15.0b3+dev):

Module(
  body=[
    Match(
      subject=Constant(value=0),
      cases=[
        match_case(
          pattern=MatchValue(
            value=Constant(value=0)),
          body=[
            Pass()]),
        match_case(
          pattern=MatchValue(
            value=UnaryOp(
              op=USub(),
              operand=Constant(value=0))),
          body=[
            Pass()])]),
    Expr(
      value=UnaryOp(
        op=UAdd(),
        operand=Constant(value=0))),
    Expr(
      value=UnaryOp(
        op=USub(),
        operand=Constant(value=0)))])

+0 is parsed to Constant(value=0) instead of UnaryOp(op=UAdd(),operand=Constant(value=0)) when it is used as a match-expression.

This was really unexpected for me and can maybe produce some problems with ast.parse/unparse roundtripps or code which works with the ast and require workarounds (like in my case)

Is it possible to implement this in a way that it generates UnaryOp(...)?

@johnslavik you implemented this #148566, maybe you can help me here.

CPython versions tested on:

3.15

Operating systems tested on:

No response

Linked PRs
  • gh-152712

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 with the ast.parse example in the issue and compare the generated nodes for case +0:, case -0:, +0, and -0. Trace how the match-expression is represented, then make the +0 pattern produce the expected UnaryOp form and verify the AST output and ast.parse/unparse round trip.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.