How to automatically break long string constants in Python code using Black formatter?

Question:

Python formatting guidelines, the famous PEP8 recommends no line longer than 79 chars.

I can easily auto-format my code to a max line length with the Black Formatter, but it does not break long strings. The linter will still complain about a long URL in your code and Black won’t help.

Is it possible to automatically break long strings with Black formatter?

Asked By: neves

||

Answers:

Yes it is possible due to a new feature.

First make sure that you have a very recent Black formatter installed. Now just run black with the option --experimental-string-processing.

In VSCode you can configure it in your settings.json file:

"python.formatting.blackArgs": [
    "--line-length",
    "99",
    "--experimental-string-processing"
],

After you edit settings.json, restart Black server for the change to take effect: Cmd/Ctrl + Shift + P -> Black Formatter: Restart Server.

BTW, if you want to increase the default line length, it is a good idea to also change to the same value in your linter:

"python.linting.flake8Args": [
        "--max-line-length=99",
],

Some teams really prefer longer lines, don’t let them use this as a reason for not automatically formatting.

BTW, PEP8 support greater line length:

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 99 characters, provided that comments and docstrings are still wrapped at 72 characters.

Answered By: neves

With newer versions of black (e.g., 22.1.0) this functionality is now part of the --preview flag.

Answered By: bergercookie