Improving Code Quality with Flake8 and Black: A Guide for Python Developers

Huzaifa Zahoor
5 min readMar 21, 2023

--

As a Python developer, maintaining a clean and consistent codebase is crucial for ensuring that your code is readable, maintainable, and efficient. Flake8 and Black are two tools that can help you achieve this goal.

Flake8 is a popular linter tool that checks your code for style and syntax errors, while Black is a code formatter that automatically formats your code according to a set of predefined rules. In this article, we will go through how to use Flake8 and Black in Python to ensure that your code is of high quality.

Installing Flake8 and Black

Before we can use Flake8 and Black, we need to install them. To install Flake8 and Black, we will use the pip package manager. Open your terminal and run the following commands:

pip install flake8
pip install black

Once Flake8 and Black are installed, we can start using them to improve the quality of our Python code.

Using Flake8

Flake8 is a command-line tool that checks your code for style and syntax errors. To use Flake8, open your terminal and navigate to the directory containing your Python code. Then, run the following command:

flake8 .

This command will check all the Python files in the current directory for style and syntax errors. If Flake8 finds any errors, it will display them in the terminal output.

Flake8 also supports a number of configuration options that you can use to customize its behavior. For example, you can specify a maximum line length or ignore certain types of errors. To learn more about Flake8’s configuration options, check out the official documentation.

Flake8 Example

Here is an example of code with a style and syntax error:

def sum(numbers):
total = 0
for number in numbers:
total += number
return total

The error in this code is that the return statement is inside the for loop. To fix this error, we need to move the return statement outside the loop. Here is the corrected code:

def sum(numbers):
total = 0
for number in numbers:
total += number
return total

When we run Flake8 on this code, we will see the following output:

./example.py:3:9: E702 indentation contains mixed spaces and tabs
./example.py:5:9: E701 multiple statements on one line (colon)
./example.py:5:9: E703 statement ends with a semicolon

These errors indicate that the code contains mixed spaces and tabs for indentation, has multiple statements on one line and ends a statement with a semicolon. By fixing these errors, we can improve the style and readability of the code.

Another Flake8 Example

One of the most common errors that Flake8 checks for are the line length error. By default, Flake8 enforces a maximum line length of 79 characters. This means that if a line of code exceeds 79 characters, Flake8 will raise a line length error.

However, in some cases, it may be necessary to exceed this limit, such as when writing long strings or comments. In such cases, you can add an exception to ignore the line length error for that specific line of code.

To ignore the line length error for a specific line of code, you can add the # noqa: E501 comment at the end of the line. Here, E501 is the error code for the line length error in Flake8.

For example, consider the following code:

def my_function():
# This is a really long comment that exceeds the 79-character limit and
# causes a line length error in Flake8.
return 42

To ignore the line length error for the long comment, you can modify the code as follows:

def my_function():
# This is a really long comment that exceeds the 79-character limit and
# causes a line length error in Flake8. # noqa: E501
return 42

By adding the # noqa: E501 comment, Flake8 will ignore the line length error for that specific line of code.

In addition to the # noqa: E501 comment, Flake8 also supports other types of comments to ignore errors, such as # noqa, which ignores all errors on the line. However, it's generally recommended to use these exceptions sparingly and only when necessary to maintain code readability and clarity.

Using Black

Black is a code formatter that automatically formats your code according to a set of predefined rules. To use Black, open your terminal and navigate to the directory containing your Python code. Then, run the following command:

black .

This command will format all the Python files in the current directory according to Black’s formatting rules. If you have any code that does not conform to Black’s formatting rules, Black will automatically reformat it.

Black is highly configurable and allows you to customize its formatting rules to suit your needs. To learn more about Black’s configuration options, check out the official documentation.

Black Example

Here is an example of code before and after using Black:

Before:

def compute_total(a, b, c):
total = a + b + c
if total > 100:
print(f"Total exceeds 100: {total}")
return total

After:

def compute_total(a, b, c):
total = a + b + c
if total > 100:
print(f"Total exceeds 100: {total}")
return total

In this example, we have a function that computes the total of three variables a, b, and c. Before applying Black, the code had inconsistent indentation and lacked whitespace around the addition operator.

After running Black on the code, the indentation is corrected and whitespace is added, resulting in more consistent and readable code.

Integrating Flake8 and Black into Your Workflow

Using Flake8 and Black can greatly improve the quality of your Python code, but it can also be time-consuming to run these tools manually every time you make a change to your code. Fortunately, there are a number of ways to integrate Flake8 and Black into your workflow to automate this process.

One option is to use an integrated development environment (IDE) that supports Flake8 and Black, such as PyCharm or Visual Studio Code. These IDEs will automatically run Flake8 and Black on your code as you type, highlighting any errors and formatting your code as you go.

Another option is to use a pre-commit hook that automatically runs Flake8 and Black before you commit your changes to your code repository. This ensures that your code always meets the highest quality standards before it is merged into your codebase. To set up a pre-commit hook, you can use a tool like pre-commit, which allows you to define a set of Git hooks that run Flake8 and Black automatically.

Conclusion

In this article, we have discussed how to use Flake8 and Black in Python to ensure that your code is of high quality. Flake8 is a linter tool that checks your code for style and syntax errors, while Black is a code formatter that automatically formats your code according to a set of predefined rules. By using Flake8 and Black, you can ensure the good quality of your Python code.

--

--

Huzaifa Zahoor

Huzaifa Zahoor is a Python developer and data engineer with over 4 years of experience in building web applications for the stock market.