Brett Fisher
Brett Fisher

Reputation: 612

VS Code autoformats Python code to use 2 tabs

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.

Upvotes: 5

Views: 4035

Answers (2)

Brett Fisher
Brett Fisher

Reputation: 612

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.

Update 4/24:

Install: ms-python.autopep8

{
  "[python]": {
    "editor.tabSize": 2,
    "editor.detectIndentation": false,
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "ms-python.autopep8",
    
  },
  "autopep8.args": [
    # https://pypi.org/project/autopep8/#usage
    "--indent-size=2",
    "--max-line-length=140",
    "--ignore=E121"
  ],
}

Upvotes: 14

Sandeep Parmar
Sandeep Parmar

Reputation: 105

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"

Upvotes: 0

Related Questions