black icon indicating copy to clipboard operation
black copied to clipboard

fmt: skip on a bracketed ternary turns the tuple into a call

Open jiteshgulati opened this issue 2 months ago • 0 comments

Describe the bug

if you put # fmt: skip after an element inside brackets and that element is a ternary like a + b if c else d black drops the comma after it

with default settings it fails with INTERNAL ERROR (not equivalent to the source) so the file cant be formatted at all with --fast its worse, black writes the file and the tuple turns into a call so the code throws a TypeError once that line runs

To Reproduce

take this code

x = (
    a + b if c else d,  # fmt: skip
    (e),
)

and run it with default args

$ black file.py

the resulting error is

error: cannot format file.py: INTERNAL ERROR: Black 26.5.1 on Python (CPython) 3.14.4 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_....log

with black --fast file.py it writes this instead

x = (
    (
        a + b if c else d,  # fmt: skip
    )(e),
)

with a = b = 1, c = True, d = 0, e = 5 the original gives (2, 5) and the formatted one raises TypeError: 'tuple' object is not callable

same thing happens with a.b if c else d or f(x) if c else d or a comparison in the first branch, and inside lists sets dict values call args subscripts and return (...) too. a couple of those (a dict value, or when the next element isnt wrapped in parens) give unparseable output instead of the call

plain a if c else d works fine and so does a + b, # fmt: skip without the ternary

Expected behavior

the skipped line stays as it is and the tuple stays a tuple

Environment

  • Black's version: 26.5.1 (compiled: yes) from pypi, also reproduces on main at a7c2368
  • OS and Python version: Linux (WSL2) / Python 3.14.4

Additional context

looks like _generate_ignored_nodes_from_fmt_skip in src/black/comments.py collapses a + b into its arith_expr parent but stops one level before the ternary (test) node, so the ignored list ends up holding the children of test plus the comma from the outer tuple. the standalone comment then gets inserted inside test and the comma is gone from the tuple, and visit_test later wraps that node in invisible parens which become the )(

it also reproduces on the commit right before #5429 so its not from that change. i have a fix with a regression test and will open a PR for it

jiteshgulati avatar Oct 01 '26 15:10 jiteshgulati