python / python/cpython

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

オープン
#152,708 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

interpreter-core topic-parser type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

issue の ast.parse の例から始め、case +0:case -0:+0-0 に対して生成されるノードを比較します。match-expression がどのように表現されているかを追跡し、+0 パターンが期待される UnaryOp 形式を生成するようにして、AST の出力と ast.parse/unparse のラウンドトリップを検証します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。