black
black copied to clipboard
Multi-line strings with type ignore pragma get merged into a single line
Describe the bug
There is a clash between the process of reflowing multi-line strings and the rule that prevents formatting lines with # type: ignore pragma at the end. Here is what happens:
- A multi-line string gets first merged into a single-line string which can be arbitrarily long.
- Because of the pragma comment at the end of the line, the line is considered unsafe to split. Hence the final result is a single huge line.
To Reproduce
Here is a simple example:
(
"A very very very very very very very very very very very very long string "
"annotated with a type ignore pragma gets merged into a single very long line "
"which is against the line length rule."
) # type: ignore
Running black --unstable example.py produces:
("A very very very very very very very very very very very very long string annotated with a type ignore pragma gets merged into a single very long line which is against the line length rule.") # type: ignore
Expected behavior
Probably the best option would be that the multi-line string wouldn't be reflown at all in cases there is a type ignore comment at the end. But the formatting definitely shouldn't produce code that breaks the line length rule.
Environment
- Black's version:
24.10.0 - OS and Python version: Linux, Python 3.11.9
Additional context
In practice this issue can appear if users do some f-string operations inside a multi-line string and want to suppress type checking. E.g. the following line also gets incorrectly reflown into a single huge line:
message = (
"This is an error message that also does an f-string operation for which "
f"type checks might have to be ignored: {value1 + value2} ") # type: ignore
Another issue related to string_processing, linking this to #4208 for tracking
Also, would this be better also categorized under 'preview style'? @JelleZijlstra