MakeUseOf logo

How to Lint Python Code Using Flake8

Binary values projected onto somebody’s back
Photo by Nina Hill from Pexels: https://www.pexels.com/photo/numbers-projection-on-woman-9121365/ . No attribution needed
Mary writes for the programming section and has been doing so for the past two years. Her educational background is in Computer Science and Physics.
Sign in to your MakeUseOf account

A linting tool is a valuable resource that can help you catch errors and inconsistencies in your code.

Flake8 is one of the most popular linting tools for Python. It identifies syntax and formatting errors in your code, along with other issues like unused imports. It's very flexible because, even though it has default rules, you can change them or add to them to fit your requirements.

You can also configure Flake8 to run when you save updates to your code using VS Code. All these features make it a valuable tool to have when writing Python programs.

Installing Flake8

Follow the steps below to install Flake8 on your development environment. You may need to install Pip on your machine first.

  1. Run the command below in your terminal to install Flake8:
    pip install flake8
    
  2. Verify that Flake8 is installed by running the following command:
    flake8 --version
    
  3. If Flake8 is installed correctly, you should see output similar to the following:
    4.0.1 (mccabe: 0.6.1, pycodestyle: 2.8.0, pyflakes: 2.4.0) CPython 3.9.13 on
    Linux
    

Once you’ve successfully installed Flake8, you can start using it.

Using Flake8 to Analyze Python Code

To understand how to use Flake8, start with the following code. It has a couple of intentional errors. Copy it into a file called greeting.py.

def greeting(name):
 print("Hello, " + name)
greeting("Alice")
 greeting("Bob")

Running Flake8 on a Single File

The syntax for running Flake8 on a single file is as follows.

flake8 path/to/file.py

In this example, navigate to the directory containing the greting.py file and run the following command.

flake8 greeting.py

Flake8 should return the following message showing there was an indentation error.

greeting.py:5:1: E999 IndentationError: unexpected indent

This output indicates that line 5 is unnecessarily indented. To fix this indentation error, you need to remove the space from the beginning of this line.

def greeting(name):
 print("Hello, " + name)
greeting("Alice")
greeting("Bob")

Now when you run Flake8, you’ll get the following warnings.

greeting.py:4:1: E305 expected 2 blank lines after class or function definition, found 1
greeting.py:5:16: W292 no newline at end of file

This output indicates the following issues:

  • On line 4, there should be two blank lines after the greeting function definition, but there is only one.
  • On line 5, there should be a new line at the end of the file.

Once you fix these issues, flake8 should not return any messages.

So far, we’ve analyzed only one file but in most cases, you’ll want to analyze multiple files.

Running Flake8 on Multiple Files

Say you have another called test_greeting.py that contains the following code:

from greeting import greeting
def test_greet():
 assert greeting("Alice") == "Hello, Alice!" 

To analyze these two files, run the following command.

flake8 greeting.py test_greeting.py

This method works but if you have more than two files, typing the file names out might be tiring and error-prone.

It's more efficient to use the following command to analyze all the files in the current directory:

flake8 .

Understanding Flake8 Errors and Warnings

Flake8 reports two types of issues:

  • Errors: An error indicates a syntax or structural issue that prevents your code from running like the indentation error from the greeting.py example.
  • Warnings: A warning indicates a potential issue or a violation of PEP 8 style guidelines like the “no newline at end of file” warning from the greeting.py example.

Some of the common errors and warnings are:

  • E101: indentation contains mixed spaces and tabs.
  • E302: expected 2 blank lines, found 0.
  • E999 IndentationError: unexpected indent.
  • W291: trailing white space.
  • E501: line too long (maximum 79 characters).
  • F401: module imported but unused.

When you run Flake8 it will output a message such as the one shown above and the line number, and code location the message references. This helps you know where exactly your code has issues which save you debugging time.

Configuring Flake8

For some projects, Flake8’s rules might be too rigid. In these cases, Flake8 allows you to configure it and tailor its behavior to fit your requirements.

You can provide configuration options such as:

  • Ignoring specific errors or warnings.
  • Setting the maximum line length.
  • Specifying additional rules.

To demonstrate, create a configuration file named setup.cfg. You can also add the configuration options to a file named tox.ini, or .flake8.

In this file, begin by creating a flake8 section as follows:

[flake8]

Then add the options you want to configure:

[flake8]
max-line-length = 100
ignore = F401

In this example, max-line-length = 100 tells Flake8 to issue warnings for any line in your source code files that exceed 100 characters in length. ignore = F401 tells Flake8 to ignore errors related to unused imports.

You don’t need to add these options to a configuration file as you can call specify them on the command line like this:

flake8 --ignore E203 --max-line-length 100

Using a configuration file is the best approach since you don’t need to specify the same options every time you use flake8.

Using Flake8 in VS Code

If you’re using VS Code to write your Python application, you can use the flake8 extension to lint your Python files as you type.

First, you need to install the flake8 extension from the VS Code marketplace. Next, to configure it open the VS Code settings, then search for "python.linting.flake8Enabled" and enable linting with flake8.

You should now see errors and warnings highlighted in your code with a squiggly line as you write it. Hovering over the highlighted text will display a message that explains the issue and suggests possible fixes.

Other Python IDEs such as Pycharm also have Flake8 extensions you can configure to simplify the linting process.

Why Should You Use a Linter?

As you write code, you might introduce errors and inconsistencies that cause your application to fail or have performance issues. A linter like Flake8 allows you to catch some of these issues in advance, helping you write cleaner code. Integrating it into your development workflow is very important.

You can do this by using it within your text editor or IDE and integrating it into your continuous integration pipeline to automatically check your code for errors and warnings before you merge it to your main branch.

AltStyle によって変換されたページ (->オリジナル) /