I'm trying to use black as a formatter for Python on VS Code on Ubuntu 20.04 but it's not working on auto save.
I've selected black
in Python>Formatting:Provider
. I'm using prettier as my default formatter for which I added a .prettierignore, disabled, and uninstalled to make sure it wasn't interfering with black. I also added a custom path to ./local/bin/black
. It works though when I run it through the terminal. How do I make it work?
{
editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"python.formatting.provider": "black",
"python.formatting.blackArgs": [
"-l 120"
],
"editor.formatOnType": true,
"python.formatting.blackPath": "./local/bin/black"
}
There are only a few settings you need to setup black
as a formatter on VS Code. It seems you got most of it right, but I am doubtful about using relative paths for blackPath
(but VS Code should show an error if the path is indeed incorrect). So I suggest switching to an absolute path.
Here are my settings:
// User Settings
"editor.defaultFormatter": null,
"editor.formatOnSave": false, // enable per language
"[python]": {
"editor.formatOnSave": true
},
"python.formatting.provider": "black",
"python.formatting.blackPath": "/usr/local/bin/black"
// Workspace Settings
"python.formatting.blackPath": "/absolute/path/to/venv/with/black",
"python.formatting.blackArgs": [
"-l 120"
],
First of all, I suggest getting rid of the editor.defaultFormatter
setting (or just set it back to the default null
). Instead of setting a default for everything, configure your formatter for each language and for each extension. Here, it's null and then I configure python
-specific settings (then I have separate ones for JS and C++ settings). You mentioned something about Prettier, and that could be interfering with VS Code using black.
Second, make sure you are modifying the correct settings. VS Code has 3 sets of settings: User, Workspace, and Folder. I normally have the formatOnSave
enabled for Python on the User settings, and provider
set to black
(using system-wide installed black
). On a specific workspace, I have a virtual environment and I override the blackPath
to the black
specifically installed on that virtual environment. You can also just put all the settings in the User settings or use the same system-wide-installed black
. But the main point here is to use absolute paths for both (basically copying the output of which black
from the console).
Note that, if you specified blackPath
to point to a particular virtual environment, make sure to select that same virtual environment on your workspace.
Lastly, you can check for any issues from the Output tab > Python: