Quick guide to Python formatting in VS Code

Posted: October 22, 2020

You've followed Microsoft's tutorial on setting up Python in VS Code but formatting is just not working? It might be that other extensions are interfering with your Python formatter.

If you use VS Code mostly for web development, you most likely also use Prettier for formatting. I'm talking about Prettier as an extension, not as a package. Check if you have the following configuration in your settings:

(Open VS Code, hit Ctrl + Shift + P on Windows / Cmd + Shift + P on MacOS to open the Command Palette and search for "Settings", check both "Workspace" and "User" settings).

Prettier does not work with Python

1"editor.defaultFormatter": "esbenp.prettier-vscode"

If you find this config in your settings, you've found the reason why autopep8, black or yapf are not working - The above configuration will choose Prettier to format Python, which is not supported. In your settings, make sure you override the default formatter for python like so:

1  "[python]": {
2    "editor.defaultFormatter": null
3  }

And don't forget to install and select the actual formatter that you want (just like in the official docs).

1  "python.formatting.provider": "black",
2  "python.formatting.blackArgs": ["--line-length", "120"]

Override default formatter

You can either overwrite editor.defaultFormatter just for your workspace or globally for your user. Also, it doesn't matter whether you're using a global Python installation or a virtual environment.

I prefer applying this configuration to my user settings - this way, I can easily start a Python project and will get formatting out of the box based on my user settings. No need to create dedicated workspace settings for every single project and override the formatter over and over. Here's the relevant config from my settings:

1{
2  "editor.defaultFormatter": "esbenp.prettier-vscode",
3  "[python]": {
4    "editor.defaultFormatter": null
5  },
6  "python.formatting.blackArgs": ["--line-length", "120"],
7  "python.formatting.provider": "black",
8}

Preview picture by @fidpad on unsplash.