Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 277
Brett Fisher Avatar asked Mar 03 '23 11:03

Brett Fisher


1 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.

like image 83
Brett Fisher Avatar answered Mar 12 '23 14:03

Brett Fisher