Ensure consistency in your Python code with flake8

Learn more about solving common Python problems in our series covering seven PyPI libraries.
146 readers like this.
Team checklist

Python is one of the most popular programming languages in use today—and for good reasons: it's open source, it has a wide range of uses (such as web programming, business applications, games, scientific programming, and much more), and it has a vibrant and dedicated community supporting it. This community is the reason we have such a large, diverse range of software packages available in the Python Package Index (PyPI) to extend and improve Python and solve the inevitable glitches that crop up.

In this series, we'll look at seven PyPI libraries that can help you solve common Python problems. Today, we'll look at flake8, a linter and linting platform that ensures consistency in Python code.


Python code is meant to be easy to read. For this reason, consistency matters. Consistency inside a project matters most of all. How can we enforce such consistency?

Flake8 is really two things: it is both a linter, enforcing some basic rules. Even more important, it is a linting platform that allows plugins to add or change linting rules.

The best thing about flake8 plugins is that you don't need to do anything other than installing them in the virtual environment where you want to run flake8.

Consider the following code:

# spew.py
print("Hello world")
# print("Goodbye universe")

If we install flake8 in a clean virtual environment and run it, it will say nothing: this file looks fine.

If we install flake8-print and run flake8 spew.py, we get:

spew.py:2:1: T001 print found.

If we instead install flake8-eradicate, we get:

spew.py:1:1: E800: Found commented out code:

We can, of course, install both—and get both warnings.

You can also write local, custom plugins. If your team has local conventions that are constantly nit-picked in reviews, why not automate them with a custom flake8 plugin?

In the seventh and final article in this series on solving Python problems, we'll look at MyPy, a way to check type annotation errors without running your program.

Review the previous articles in this series:

What to read next
Moshe sitting down, head slightly to the side. His t-shirt has Guardians of the Galaxy silhoutes against a background of sound visualization bars.
Moshe has been involved in the Linux community since 1998, helping in Linux "installation parties". He has been programming Python since 1999, and has contributed to the core Python interpreter. Moshe has been a DevOps/SRE since before those terms existed, caring deeply about software reliability, build reproducibility and other such things.

Comments are closed.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.