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

157 views Asked by At

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

2

There are 2 answers

1
Muhammad Ikhwan Perwira On BEST ANSWER

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"
  },
}
5
Tim240 On

If you want to change the number of spaces in a tabulation, go to the settings (with Ctrl + , or Preferences<Settings). In the "Commonly Used" category, you will see a "Tab Size" parameter. Change the value (which is 4 spaces by default).

settings

You can also, when you are on your file, change this parameter in the "Spaces" option at the bottom of the screen:

spaces option