Setup black, isort, flake8 in VSCode

Jack Pan
3 min readNov 13, 2021

--

After you completed this article, the Python code will be auto formatting and linting whenever you save the file in VSCode.

VSCode Python Extension

Please make sure you have installed the python extension in the VSCode. You can install it through the UI.

Or type the “Ctrl + p” or “Cmd + p” (Based on you are using the Windows or MacOS). Paste the below line and hit enter to install.

ext install ms-python.python

Black

First, install the black into your Python environment by pip.

pip install black

Type the “Ctrl + ,” or “Cmd + ,” to open the settings page in the VSCode. (You can also find it through UI “Preferences -> Settings”)

Search “format on save” and check the checkbox.

Search “python formatting provider” and select the “black”.

Now, if you open the python file and save, it will be auto formatted by the black!

For example, if your file is like this before:

After save, it will be like this:

isort

Type “Ctrl + Shift + P” or “Cmd + Shift + P”. Search the “Preferences: Configure Language Specific Settings” and press enter. And search the “Python” and press enter. It will open the “settings.json”.

Please add the following settings:

"editor.codeActionsOnSave": {
"source.organizeImports": true
}

Therefore, it may look like this:

{
"python.formatting.provider": "black",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}

(VSCode already has the built-in function to use isort so that we don’t need to install it by pip)

Then isort will reorder your import order when you save the file. For example, if the file you have is like this:

After save, it will be like this:

flake8

First, install the flake8 into your Python environment by pip.

pip install flake8

Type “Ctrl + Shift + P” or “Cmd + Shift + P”. Search the “Python: Select Linter” and press enter. Select the “flake8”

Linting runs automatically when you save a file.

Reference

--

--