Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Parsing the with statement with tuple argument and type comment failedΒ #4633

@15r10nk

Description

@15r10nk

Describe the bug

The following code can not be parsed/formatted by black:

with (name_5, something): # type: ignoresome text
    pass

(playground)

black reported the following error:

> black -l 100 -t py312 bug.py
error: cannot format bug.py: INTERNAL ERROR: Black 25.1.1.dev21+g944a38e.d20250317 on Python (CPython) 3
.12.6 produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf
/black/issues.  This diff might be helpful: /tmp/blk_pgrn0rje.log

Oh no! πŸ’₯ πŸ’” πŸ’₯
1 file failed to reformat.

the reported diff in /tmp/blk_pgrn0rje.log is:

--- src
+++ dst
@@ -5,30 +5,29 @@
         Pass(
         )  # /Pass
         items=
         withitem(
             context_expr=
-            Tuple(
+            Name(
                 ctx=
                 Load(
                 )  # /Load
-                elts=
-                Name(
-                    ctx=
-                    Load(
-                    )  # /Load
-                    id=
-                    'name_5',  # str
-                )  # /Name
-                Name(
-                    ctx=
-                    Load(
-                    )  # /Load
-                    id=
-                    'something',  # str
-                )  # /Name
-            )  # /Tuple
+                id=
+                'name_5',  # str
+            )  # /Name
+            optional_vars=
+            None,  # NoneType
+        )  # /withitem
+        withitem(
+            context_expr=
+            Name(
+                ctx=
+                Load(
+                )  # /Load
+                id=
+                'something',  # str
+            )  # /Name
             optional_vars=
             None,  # NoneType
         )  # /withitem
         type_comment=
         'ignoresome text',  # str

but it can be parsed by cpython:

from ast import parse
parse(
    'with (name_5, something): # type: ignoresome text\n'
    '    pass\n'
)

The code can be formatted with black -l 100 -t py312 bug.py --fast:

with name_5, something:  # type: ignoresome text
    pass

Environment

  • Black's version: current main (6144c46)
  • OS and Python version: Linux/Python 3.12.6 (main, Sep 9 2024, 22:11:19) [Clang 18.1.8 ]

Additional context

The bug was found by pysource-codegen (see #3908)
The above problem description was created from a script, let me know if you think it can be improved.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T: bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions