Skip to content

string_processing: Multi-line strings with type ignore pragma get merged into a single line #4510

@AleksMat

Description

@AleksMat

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:

  1. A multi-line string gets first merged into a single-line string which can be arbitrarily long.
  2. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    C: preview styleIssues with the preview and unstable style. Add the name of the responsible feature in the title.F: stringsRelated to our handling of stringsT: bugSomething isn't working
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions