Search code examples
pythonvisual-studio-codepep8autopep8

Python Auto-Formatting Adds Extra Spaces


The problem I have been facing related to auto formatting in Visual Studio Code for my Python Files.

I like using tabs in Python, since it makes it easier to be consistent and type code quicker; however, when I save on Visual Studio Code the auto-format on save adds an extra space to each line. This means that the python script works, yet the structure looks off.

I have tried disabling prettify, and it still happens. I do not think prettier auto format formats python anyways. I tried checking the settings JSON file, but I do not think there is nothing there either.

Settings.json:

{
    "color-highlight.markerType": "dot-before",
    "editor.detectIndentation": false,
    "editor.formatOnSave": true,
    "editor.tabSize": 3,
    "liveServer.settings.donotShowInfoMsg": true,
    "prettier.tabWidth": 3,
    "python.pythonPath": "C:\\Users\\mtapi\\Anaconda3\\python.exe",
    "window.zoomLevel": 1,
    "python.condaPath": "C:\\Users\\mtapi\\Anaconda3\\Scripts\\conda.exe",
    "terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\cmd.exe",
    "editor.insertSpaces": false,
    "prettier.useTabs": true,
    "python.linting.pylintEnabled": true,
    "python.linting.enabled": true,
    "python.linting.pep8Enabled": true,
    "editor.mouseWheelZoom": true,
    "editor.fontSize": 15,
    "workbench.iconTheme": "vscode-icons",
    "workbench.colorTheme": "Default High Contrast"
}

Here is an example script before save on format:

enter image description here

Here is what happens after save:

enter image description here

This did not happen before. Let me know if anything is confusing or more information is needed


Solution

  • It looks like something in your editor is configured to have 4 spaces instead of 3 for the indentation.

    However, if you want to follow PEP8, I'd advise for you to use 4 spaces for indentation size, as suggested by the proposal itself (and not tabs): https://www.python.org/dev/peps/pep-0008/#indentation

    With that said, I'd guess it has something to do with these lines, since they tell the editor to use PEP8 and PEP8 asks for 4 spaces:

        "python.linting.pylintEnabled": true,
        "python.linting.enabled": true,
        "python.linting.pep8Enabled": true,
    

    Finally, one last thing I've noticed: your 'before' script has inconsistent indentation sizes, the line print(f'{A} {B} {C} {D}') has a different indentation size from the rest of the code.