How to Set Formatting and Linting on VSCode for Python using Black Formatter and Flake8 Extensions
Tags: beginners, python, tutorial, vscode
Published: 2023-10-12 23:47:38

In this tutorial, I will demonstrate how you might configure VSCode to use code formatter and linter for Python 3.

A **code formatter** is a tool or software that automatically and consistently formats source code in a programming language according to a predefined set of style rules or coding conventions.

A **code linter** (or simply "linter") is a tool that analyzes source code for potential errors, coding style violations, and other issues.

These two tools are optional, but can be an essential part of maintaining code quality and consistency in software development projects, especially in large or collaborative teams where adherence to a common coding style is crucial.

We will use [Black](https://pypi.org/project/black/) as a Python code formatter, and [Flake8](https://flake8.pycqa.org/en/latest/) as a Python linter.

## Install Extensions

Black and Flake8 can be installed using pip, and configured that way. But it seems the built-in support is going to be deprecated soon. They are now migrating to individual Python tool extension. (Check [here](https://github.com/microsoft/vscode-python/wiki/Migration-to-Python-Tools-Extensions) for more information.)

On Visual Studio Code, go to View > Extensions to see list of extensions. Type "Black Formatter" to download extension from Microsoft. Do the same with "Flake8", also from Microsoft.

(You might want to install "isort" as well - also from Microsoft - if you want your import statements to sort when you save file.)

(If you want to disable these extensions, you can [disable the extension](https://code.visualstudio.com/docs/editor/extension-marketplace#_disable-an-extension) per workspace in Visual Studio Code.)

Now we are ready to use these tools.

## Create Settings File

Create a new folder in the project root folder, and name it `.vscode`. Inside newly created folder, create a json file and name it `settings.json`.

![Project Folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3cns7dvkbnww9ua6kfql.png)

## Configure Black Formatter in Settings File

The settings file is in json format, so you need to enclose everything in a curly bracket (`{ }`). Let's first set the default formatter to use Black; you can do that by typing this into the `settings.json`:

```javascript
{
   "editor.defaultFormatter": "ms-python.black-formatter",
}
```

If you want VSCode to format on save, you need to write this:

```javascript
{
   "editor.defaultFormatter": "ms-python.black-formatter",
   "editor.formatOnSave": true, // new
}
```

You can enforce a line length by passing an argument to Black Formatter:

```javascript
{
   // ...
   "black-formatter.args": [
    "--line-length", "88",
   ],
}
```

(The line length is 88 by default, which seems to be the recommended length.)

If you want the settings to apply to specific language such as "Python", you can do that like this:

```javascript
{
   // ...
   "[python]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": true
    },
   },
}
```

The above code organize import statements when you save Python files. You can add previous settings here instead so it only applies to Python file (don't forget the commas):

```javascript
{
   // ...
   "[python]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": true
    },
    "editor.formatOnSave": true, // new
   },
}
```

## Configure Flake8

When you install Flake8 and enable the extension, it is automatically used without any additional settings applied. 

If you have a bug in the program or a typo, and you save a file, you can see that flake8 warns you with a message, such as:

![Flake8 Warning Message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h4a2wc3gmzdhd0z0s210.png)

Just like Black Formatter, you can pass Flake8 with an argument. For example:

```javascript
{
   // ...
   "flake8.args": [
    "--max-line-length", "88",
    "--extend-ignore", "E203"
   ],
}
```

You can set max length by using `--max-line-length`.

`--extend-ignore` can be used to ignore certain errors depending on their codes.

Check these links for more information on the various codes:
- [Flake8 Options](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#flake8)
- [Flake8 Error/Violation Codes](https://flake8.pycqa.org/en/6.1.0/user/error-codes.html)
- [pycodestyle’s list of error codes](https://pycodestyle.pycqa.org/en/latest/intro.html#error-codes)

And that is basically it! There are more to the settings, and read Black and Flake8 documentation to learn more, but I hope this tutorial gives you an idea how it can be done.

The finished settings might look like this:

![Final Settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ea5hdfbl3klrae42qtgk.png)

Hopefully this tutorial was helpful. Leave me comments if you have any questions :)