In Python, how to tweak Black formatter, if possible?
Asked Answered
A

7

80

I know that Black is an opinionated formatter, but I love everything it does except one major thing. When I have a function with multiple arguments, instead of displaying it like this:

def example_function(arg_1: str, arg_2: bool, arg_3: int = 0, arg_4: int = 1, arg_5: float = 0.0):
    pass

I'd rather display it as follows for readability:

def example_function(
    arg_1: str, 
    arg_2: bool, 
    arg_3: int = 0, 
    arg_4: int = 1, 
    arg_5: float = 0.0
):

Is this achievable with Black or some other formatter? I have this problem several times and it makes me consider not to use Black, either something else or nothing at all.

Any ideas or comments?

Avantgarde answered 4/12, 2019 at 20:1 Comment(2)
Maybe blue supports this: blue.readthedocs.io/en/latestFunctionalism
You could set #fmt: off at the begining of your snippet and then #fmt: on at the end. The formatter will skip it.Balinese
S
95

This is due to the default line length for black being longer than you'd like – 88 characters per line.

To decrease the line length, you can use the --line-length flag as documented here:

https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html

For example:

$ black --line-length 80 example.py

Black explains the --line-length setting in more detail here:

https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#line-length

Line length

You probably noticed the peculiar default line length. Black defaults to 88 characters per line, which happens to be 10% over 80. This number was found to produce significantly shorter files than sticking with 80 (the most popular), or even 79 (used by the standard library). In general, 90-ish seems like the wise choice.

If you're paid by the line of code you write, you can pass --line-length with a lower number. Black will try to respect that. However, sometimes it won't be able to without breaking other rules. In those rare cases, auto-formatted code will exceed your allotted limit.

You can also increase it, but remember that people with sight disabilities find it harder to work with line lengths exceeding 100 characters. It also adversely affects side-by-side diff review on typical screen resolutions. Long lines also make it harder to present code neatly in documentation or talk slides.

Emphasis on the final paragraph.

I'd recommend just keeping the default settings. The beauty of Black is that it chooses for you, and therefor preempts any arguments about which way is "best".

Spirillum answered 4/12, 2019 at 20:52 Comment(7)
Thanks, I ended up decreasing it to 60 since I usually work on VScode with split windows, that fits nicely. Great answer! I also enjoyed the video about the 90ish, good watch. +1Avantgarde
There is a alias named -lSensitize
The other problem with changing the line length falls on the next guy running Black. He has to know what you chose or many many lines will be modified.Commercialism
@Commercialism You can just set your preferred line length in pyproject.toml.Spector
Isn't PEP8's recommended value 79?Worldweary
@RTD they talk about that in the quoted text "or even 79 (used by the standard library)…" The reasoning behind 79 characters is based on having side-by-side editors, on monitors without modern screen resolutions. Today, you can fit a lot more characters on a single line comfortably, and 88 chars avoids having to awkwardly split lines that run a few characters longer without being too long to follow.Spirillum
The great thing about standards is there's so many to choose from.Shrike
K
58

This is now possible by adding a trailing comma to your last argument.

In your example you would write instead:

def example_function(
    arg_1: str, 
    arg_2: bool, 
    arg_3: int = 0, 
    arg_4: int = 1, 
    arg_5: float = 0.0, # <-- Notice the trailing comma
):
Kutenai answered 11/2, 2021 at 13:32 Comment(2)
Too bad there is not an option to add this extra comma every time and have the 1 argument/line as well instead of tweaking the line length Prettier handles that way better for NodeJs TS env and I think black could be inspired from this toolOrrin
Nice, thats exactly what I was looking forUndersexed
D
8

For those using visual studio code (add two lines one for --line-length other for the length: 119):

enter image description here

Disproportionate answered 27/2 at 21:23 Comment(0)
P
4

When using the Black playground at https://black.now.sh, I found that your function was reformatted exactly like that when the line length was short enough (in particular, at 78 characters).

It might be nice if there were a special configuration option that controlled the line length specifically for function parameter lines. BUT to seems to me that Black's configuration-free approach means that there is no way to control this with any more tailored option.

Pavkovic answered 4/12, 2019 at 20:16 Comment(1)
Thanks for the links, I tried black.now.sh a bit, worth it! I appreciate your answer. +1Avantgarde
M
1

Since version 21, it stabilized 'magic trailing comma' and Black become more smart, and if list is defined with last element with comma also, it will treat it as multiline, for easier copy/paste/add/edit.

Also may be useful info for some of users, thus I share:

You can use a “global” configuration, stored in a specific location in your home directory. This will be used as a fallback configuration, that is, it will be used if and only if Black doesn’t find any configuration as mentioned above. Depending on your operating system, this configuration file should be stored as:

Windows: ~.black

Unix-like (Linux, MacOS, etc.): $XDG_CONFIG_HOME/black (~/.config/black if the XDG_CONFIG_HOME environment variable is not set)

Note that these are paths to the TOML file itself.

So either to black config file or to pyproject.toml add this (adjusted):

[tool.black]
line-length = 120
skip-string-normalization = true
Misnomer answered 11/5 at 17:8 Comment(0)
R
0

You can do this easily on a project by project basis using a pyproject.toml file which is mentioned in the black documentation.

The lines you need in your pyproject.toml file are:

[tool.black]
line-length = 79

You can do this in one command with:

cat >> pyproject.toml <<'EOF'
[tool.black]
line-length = 79
EOF

Black should now format your code with PEP8 compliant maximum line length of 79 characters.

Radionuclide answered 9/5 at 18:37 Comment(0)
K
0

If you're using Visual Studio Code with the Black Formatter extension from Microsoft, just add the code below to settings.json:

"black-formatter.args": [
  "--line-length", "120"
],
Kaliningrad answered 25/6 at 19:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.