VS Code autoformats Python code to use 2 tabs

Question:

For some reason Visual Studio Code looks like it’s foramtting my code to use 2 tabs. I’ve changed my settings.json to use 2 spaces for tabs, which I’ve verified by pushing the tab button and it uses 2 spaces, as expected. However, 4 spaces (or 2 tabs) are still being used for Python indentation, as you can see in this picture:

enter image description here

You can see that it’s using two (2 spaced) tabs. I’ve looked at every Stack Overflow post I can find on configuring VS Code Python formatting and nothing I do works. It still autoformats to look like this. This is my settings.json:

{
  "python.pythonPath": "venv/bin/python3",
  "python.linting.enabled": true,
  "editor.tabSize": 2,
  "editor.formatOnSave": true,
  "editor.detectIndentation": false
}

Does anyone know what’s going on? For non Python files it works fine, so I don’t know if this is something going on with pylint. This is driving me crazy.

Asked By: Brett Fisher

||

Answers:

I figured it out – I changed my formatter to autopep8 and told it to use 2 spaces. This is my updated settings.json file:

{
  "python.pythonPath": "venv/bin/python3",
  "editor.tabSize": 2,
  "editor.formatOnSave": true,
  "python.linting.pylintArgs": [
    "--indent-string='  '"
  ],
  "python.formatting.autopep8Args": [
    "--indent-size=2"
  ],
  "python.linting.pylintEnabled": true,
  "python.formatting.provider": "autopep8"
}

I’m a little new to the linting / formatting stuff going on here, but I learned that linting and formatting are different: https://code.visualstudio.com/docs/python/editing#_formatting. My linter could be telling me that I needed two spaces, but I needed to configure the formatter to format with 2 spaces when I saved a file.

Answered By: Brett Fisher

This can also be achieved by the following steps

View -> Command Pallete.. -> Preferences: Open user settings -> search python>Formatting:Provider -> select autopep8 -> search python>Formatting:Autopep8 Args > add "–indent-size=2"

Answered By: Sandeep Parmar
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.