black formatter: How can I place one newline before and after function instead of two

Question:

I am using black formatter. I have two newlines before and two newlines after function definition. I want one newline before and one newline after function definition.

Can i do it using black config file black --config FILE. If so,how.

Asked By: Ahmad Ismail

||

Answers:

Using black formatter this is NOT possible. From it’s documentation:

By using it, you agree to cede control over minutiae of hand-formatting._

Current style:

It uses 2 lines to visually distinguish methods from empty lines in code structure. From the docs: Black will allow single empty lines inside functions, […] It will also insert proper spacing before and after function definitions. It’s one line before and after inner functions and two lines before and after module-level functions and classes.

From: the docs of black.readthedocs.io

Customization:

Command line options
Black has quite a few knobs these days, although Black is opinionated so style configuration options are deliberately limited and rarely added. You can list them by running black –help.

You need to change the formatter you use to something different to get your effect.

Answered By: Patrick Artner

OP here, I ended up using yapf.

The command looks like:

yapf --style={blank_lines_around_top_level_definition=1} file_name.py

for multiple arguments:

yapf --style={based_on_style=pep8} --style={blank_lines_around_top_level_definition=1} file_name.py

In vscode you can use the yapf styles like:

"python.formatting.yapfArgs": [
    "--style",
    "{based_on_style: pep8, blank_lines_around_top_level_definition: 1}"
],
Answered By: Ahmad Ismail
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.