psf / black

The uncompromising Python code formatter
https://black.readthedocs.io/en/stable/
MIT License
39.2k stars 2.48k forks source link

Error formatting f-string with `# fmt: off` inside a pair of brackets #4511

Open Azureblade3808 opened 1 week ago

Azureblade3808 commented 1 week ago

Describe the bug

If there is a f-string (single-line or multi-line) following a # fmt: off (with or without a pairing # fmt: on) and both the f-string and # fmt: off are inside a pair of brackets ((), [], {}), the code cannot be formatted.

The error reported is something like:

error: cannot format ???.py: {' ', 'r', 'f', 'o', ':', 'm', 't', '#', '\n'} is NOT a subset of {'U', 'r', 'f', 'u', 'F', 'R', 'b', 'B'}.

To Reproduce

Sample:

(
# fmt: off
f"""
"""
# fmt: on
)

Expected behavior

No error is reported and the code is formatted as if the f-string is a normal string.

Environment

Additional context

None

MeGaGiGaGon commented 1 week ago

This is fixed by #3978, though with interesting results. I'd instinctively say that # fmt: skip/off/on comments should never be moved by black, though I don't know if that's every been formalized/is possible thanks to issues with indented comments.

Output with #3978:

(
    # fmt: off
f"""
"""
    # fmt: on
)