How do I auto-indent Python code in Visual Studio Code?
Asked Answered
E

3

20

I'm using Visual Studio Code (not Visual Studio) on Linux and I can't seem to find out how to turn on auto-indentation for Python. I've looked all over preferences, spent some time on Google, and can't find anything.

Does anyone know how to do this?

Engineman answered 21/2, 2016 at 1:8 Comment(0)
F
30

In VS Code you can set the indentation in several places :

  • General/Workspace settings (bottom bar),
  • User settings,
  • language formatter settings.

When using Python, no matter what settings you set, all of them are overridden by the autopep8Args value of the autopep8 language formatter setting, which has an indent size of 4.

By default, autopep8 is used as VS Code Python formatter, but there are others, like yapf.

To update the indent size of this formatter, search in your user settings the "python.formatting.autopep8Args" and set it to : ["--indent-size=2"],

"python.formatting.autopep8Args": ["--indent-size=2"],
Fivefinger answered 8/9, 2017 at 14:24 Comment(3)
I added this line to my VS code user setting but it did not work, autopep8 still turn all indentation to 4 spaces.Subito
I'm using the Python extension in VS Code, autopep8 came with it. Not sure why this setting doesn't work in this case, any suggestion is appreciatedSubito
@LoganYang - I am not sure if you are seeing the conversion of indentation to spaces as the issue. If so, you should never use tabs for indentation in Python. Always use spaces. It is in PEP8 and it will save you so much trouble. The formatter no doubt does conversion of tabs for this reason.Opposite
F
0

Visual Studio Code doesn't have much support for Python (yet), aside from syntax-highlighting, and per-file intellisense (meaning it'll provide suggestions for symbols that have been found within the current file).

I'm willing to bet that the Visual Studio Code team will, eventually, increase their support for Python within Visual Studio Code, and with this, they'll likely add support for auto-indentation.

In the meantime, it might be worth trying this Visual Studio Code extension, which aims to add better support for Python, into Visual Studio Code.

The extension does add auto-indentation for Python, to Visual Studio Code, along with many other features.

Happy scripting!

Fanatical answered 23/5, 2016 at 19:53 Comment(0)
S
0

I auto-format python with autopep8, vscode can use it. It can be easily configured for tab-size and other stuff creating the config file: $HOME/.config/pep8

Here an example of that file:

[pep8]
indent-size = 2
max-line-length = 100
Samirasamisen answered 25/6, 2021 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.