pythonvisual-studio-codeindentationauto-indent

vscode python autoformat indentation to 2 spaces instead of 4 spaces when saving the file


How do I make my source code of python to forced using 2 spaces indentation when clicking save file. ChatGPT code generated always produce 4 spaces that's why I asked this. I don't feel comfortable for 4 spaces indentation in python. I tried autopep8 formatter extension but it didn't help me.

Here is my current .vscode/settings.json

{
  "editor.tabSize": 2,
  "editor.defaultFormatter": "ms-python.autopep8",
  "editor.autoIndent": "brackets",
  "editor.indentSize": "tabSize",
  "editor.detectIndentation": true,
  "editor.insertSpaces": true,
  "autopep8.args": [
    "--indent-size=2"
  ]
}

I expect from here:

if __name__ == '__main__':
    asyncio.run(main())

To the here after save the file:

if __name__ == '__main__':
  asyncio.run(main())

Replying @Tim240 answer: Here are I attached the screenshots, it seems same: enter image description here enter image description here enter image description here


Solution

  • Using editor.formatOnSave: true and then Ctrl+Shift+P type Format Document and then select autopep8, it worked!

    Here is my current settings.json:

    {
      "editor.tabSize": 2,
      "editor.autoIndent": "brackets",
      "editor.indentSize": "tabSize",
      "editor.detectIndentation": true,
      "editor.insertSpaces": true,
      "editor.formatOnSave": true,
      "pylint.args": [
        "--indent-string='  '"
      ],
      "autopep8.args": [
        "--indent-size=2"
      ],
      "docwriter.progress.trackMethods": false,
      "docwriter.style": "Auto-detect",
      "python.analysis.typeCheckingMode": "basic",
      "python.analysis.autoImportCompletions": true,
      "[python]": {
        "editor.defaultFormatter": "ms-python.autopep8"
      },
    }