Skip to content

Formatter can insert mysterious extraneous parentheses in with statements #14001

@lpulley

Description

@lpulley

My ruff --version is 0.7.1.

I've encountered a case where ruff format adds nesting parentheses for seemingly no reason:

with (
    open(
        "some/path.txt",
        "rb",
    )
    if True
    else open("other/path.txt")
    # Bar
):
    pass
➜ ruff format --diff up034.py
--- up034.py
+++ up034.py
@@ -1,10 +1,12 @@
 with (
-    open(
-        "some/path.txt",
-        "rb",
+    (
+        open(
+            "some/path.txt",
+            "rb",
+        )
+        if True
+        else open("other/path.txt")
     )
-    if True
-    else open("other/path.txt")
     # Bar
 ):
     pass

1 file would be reformatted

i.e. it wants this:

with (
    (
        open(
            "some/path.txt",
            "rb",
        )
        if True
        else open("other/path.txt")
    )
    # Bar
):
    pass

UP034 complains about this, for good reason.

If the # Bar comment is removed, the formatter makes no changes. More curiously, if I keep # Bar but add as _, the formatter makes no changes. (I also checked that Black does not do this.)

I've resolved the issue in the meantime by moving the # Bar comment to a different line, but this seems like a formatter bug.

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingformatterRelated to the formatter

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions