Search code examples
pythonvisual-studio-codeformatformatter

VSCode Python Formatting


I use VSCode and when I format the Python code with Black formatter (installed an extension) list's elements are printed one on each line. What's the problem?

From this:

a = [17, 24, 91, 96, 67, -27, 79, -71, -71, 58, 48, 88, 88, -16]

To this:

a = [
    17,
    24,
    91,
    96,
    67,
    -27,
    79,
    -71,
    -71,
    58,
    48,
    88,
    88,
    -16,
]

Here's settings.json file:

{
  "editor.formatOnSave": false,
  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter"
  }
}

I tried to use another formatters, but didn't like them


Solution

  • From the Black documentation:

    Black tries to render one full expression or simple statement per line. If this fits the allotted line length, great.

    [...]

    If not, Black will look at the contents of the first outer matching brackets and put that in a separate indented line.

    [...]

    If that still doesn’t fit the bill, it will decompose the internal expression further using the same rule, indenting matching brackets every time. If the contents of the matching brackets pair are comma-separated (like an argument list, or a dict literal, and so on) then Black will first try to keep them on the same line with the matching brackets. If that doesn’t work, it will put all of them in separate lines.

    So this is how Black formats code. If it splits your list into separate lines, the expression doesn't fit into one line.

    Black defaults to 88 characters per line

    If you want to change the line-length in order to have this particular statement on a single line, use Black's --line-length argument in your VS Code configuration:

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