Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 982
neves Avatar asked Mar 28 '26 11:03

neves


2 Answers

Edit 2024-05-27: updating for new black and VSCode configurations.

First you must install VSCode Black Extension.

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 --preview.

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

"black-formatter.args": [
    "--line-length",
    "100",
    "--preview"
],

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:

    "flake8.args": [
        "--max-line-length=100",
    ],

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.

like image 145
neves Avatar answered Mar 30 '26 01:03

neves


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

like image 41
bergercookie Avatar answered Mar 30 '26 01:03

bergercookie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!