Skip to content

Black --preview mode produces invalid code in the first pass, causing second pass to fail #3117

@yilei

Description

@yilei

Describe the bug

Black's --preview mode produces invalid code in the first pass, causing second pass to fail.

To Reproduce

For example, take this code:

some_dict = {
    "something_something":
        r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t"
        r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t",
}

And run it with these arguments:

$ black --preview file.py

The resulting error is:

error: cannot format filepy: Cannot parse: 5:4:     r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t",

Oh no! 💥 💔 💥
1 file failed to reformat.

Expected behavior

It should succeed.

Environment

  • Black's version: black, 22.3.1.dev43+gf51e537 (compiled: no)
  • OS and Python version: Linux, Python (CPython) 3.9.12

Additional context

  1. Looks like the first _format_str_once call formats the code to:
some_dict = {
    "something_something": (
        r"Lorem ipsum dolor sit amet, an sed convenire eloquentiam \t"
    )
    r"signiferumque, duo ea vocibus consetetur scriptorem. Facer \t",
}
  1. It's only reproducible with r-strings.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C: invalid codeBlack destroyed a valid Python fileF: stringsRelated to our handling of stringsT: bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions