Python Linter—Write Clean Python Code (Examples)

A linter is an automated tool that enforces common style guidelines and best practices. It is every developer’s best friend. If you are not using one, you are missing out.

Linters are not a Python-only thing. They are commonly used in any software development project regardless of the language.

This is all it takes to fix a piece of Python code with autopep8 linter:

autopep8 --in-place --aggressive --aggressive Desktop/example.py

Commonly used linters in Python are flake8 and autopep8.

In this guide, you are going to learn how to help write cleaner and more readable code.

The Problem

Writing code is a brain-heavy task. There are many things you need to focus on at the same time.

One aspect that gets overlooked constantly is the readability of the code. When your code finally works it is tempting to ditch it as if you never had to come back at it again. But this is never the case. You or one of your teammates will most definitely have to look at that piece of code in the future. As a developer, it is thus your responsibility to write as readable code as possible.

The Solution

One of the easiest ways to write cleaner code is by using a linter as a code quality assistant.

A linter is a code analyzer that helps you write correctly formatted code that follows best practices. A linter inspects each line of code and points out any styling issues it detects.

Commonly a linter finds:

  • Syntax errors, such as incorrect indentations.
  • Structural issues, such as unused variables.
  • Best practice violations, such as too long lines.

Linters are flexible tools. Some linters even make it possible to auto-fix the styling errors on the fly. This can save you a lot of time.

How to Use a Linter in Python

Linters can be installed as separate tools that you can interact with using the command line. Also, a common way to use one is to integrate it with your favorite code editor, such as VSCode. This way the linter shows warnings in the code editor in real-time.

Now that you understand what a linter is and what problem it solves, it is time to get our hands dirty.

  • First, you are going to learn how to use a Python linter called flake8 via command line.
  • Then you are going to see how to use a linter called autopep8 that also fixes the listing issues.
  • Finally, you are going integrate flake8 into Visual Studio Code to show styling issues in the code editor.

Flake8 Linter in Python

When speaking about Python linters, you commonly hear flake8 mentioned first. It is a really common Python linter that is easy to install and use.

Installation

If you are on Mac or Windows, open up a command line window and run the following command:

pip install flake8

Wait for a couple of seconds for the installation to complete.

When the installation is completed, you are all set. Next, let’s take a look at how you can use the tool to point out the styling issues in your code.

Usage

Flake8 works such that it analyzes your code and displays all the issues. Then it is up to you to actually fix the issues. When you have fixed an issue, re-analyzing the code file does not show that issue in the result again.

To make flake8 analyze your code, run the following command in a command-line window:

flake8 <path_to_file>

Where you replace <path_to_file> with the correct path to the code file you want to analyze.

For example:

flake8 /Desktop/script.py

Analyzes a file called script.py on the Desktop.

Example in Real Life

Feel free to follow this worked-out example where you use flake8 to fix styling issues in a code file.

  • Create and open a file called example.py on your desktop.
  • Open up a command line window and navigate to desktop.
  • Copy-paste following code into the example.py file:
import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,'a'  );
    some_variable={'long':'Long code lines should be wrapped within 79 characters.',
    'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
    'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)

This piece of code is valid in Python, but it has a lot of styling/best practice issues. To expose these issues, run the following command in the command line:

flake8 example.py

(Notice how the path of the file is the name of the file because you are working in the same directory as the file.)

As a result, you see a lengthy output in the command line window:

example.py:1:1: F401 'sys' imported but unused
example.py:1:12: E401 multiple imports on one line
example.py:1:17: E703 statement ends with a semicolon
example.py:3:1: E302 expected 2 blank lines, found 1
example.py:4:5: E265 block comment should start with '# '
example.py:4:80: E501 line too long (83 > 79 characters)
example.py:5:15: E225 missing whitespace around operator
example.py:5:17: E201 whitespace after '('
example.py:5:21: E231 missing whitespace after ','
example.py:5:26: E231 missing whitespace after ','
example.py:5:31: E202 whitespace before ')'
example.py:5:33: E703 statement ends with a semicolon
example.py:6:18: E225 missing whitespace around operator
example.py:6:26: E231 missing whitespace after ':'
example.py:6:80: E501 line too long (84 > 79 characters)
example.py:7:5: E128 continuation line under-indented for visual indent
example.py:7:12: E231 missing whitespace after ':'
example.py:7:26: E231 missing whitespace after ','
example.py:7:30: E231 missing whitespace after ','
example.py:7:34: E231 missing whitespace after ','
example.py:7:45: E231 missing whitespace after ','
example.py:7:80: E501 line too long (83 > 79 characters)
example.py:8:5: E122 continuation line missing indentation or outdented
example.py:8:11: E231 missing whitespace after ':'
example.py:8:20: E231 missing whitespace after ':'
example.py:8:65: E231 missing whitespace after ','
example.py:8:76: E231 missing whitespace after ':'
example.py:9:5: E128 continuation line under-indented for visual indent
example.py:9:7: E231 missing whitespace after ','
example.py:9:11: E231 missing whitespace after ','
example.py:9:17: E231 missing whitespace after ','
example.py:9:27: E231 missing whitespace after ','
example.py:10:39: W292 no newline at end of file

These are all the linting issues found in the code. To get rid of these issues, read what each line suggests and fix the issues. After addressing all these issues, your code should look like this:

import math


def example1():
    # This is a long comment. This should be wrapped to fit within 72
    # characters.
    some_tuple = (1, 2, 3, 'a')
    some_variable = {
        'long': 'Long code lines should be wrapped within 79 characters.',
        'other': [
            math.pi,
            100,
            200,
            300,
            9876543210,
            'This is a long string that goes on'],
        'more': {
            'inner': 'This whole logical line should be wrapped.',
            some_tuple: [
                1,
                20,
                300,
                40000,
                500000000,
                60000000000000000]}}
    return (some_tuple, some_variable)

To verify that you fixed all the issues, run flake8 example.py again. If the output is empty, you are all set.

Awesome! Now you understand how linting works and how to use one in your project.

As you probably noticed, fixing all the issues manually in this particular piece of code took a while. But there is a way to automate this whole process. You can use another type of linter that not only detects issues but also fixes them. In the next chapter, you are going to learn how to use a linter called autopep8 that fixes all the styling issues for you

Autopep8 – Auto-Fix Code Style Issues

Autopep8 is a Python linter that analyzes your code and fixes styling/formatting issues.

Installation

Installing autopep8 is simple. If you are on Mac or Windows, open up a command line window and run the following command:

pip install autopep8

After the installation completes, you are ready to use autopep8.

Usage

To make autopep8 fix your code styling issues, run the following command in the command line window:

autopep8 --in-place --aggressive --aggressive <path_to_file>

Where you replace the <path_to_file> with the actual path to the file you want to fix.

For example, if you have a file called script.py on the Desktop, you can fix the styling issues in it by:

autopep8 --in-place --aggressive --aggressive Desktop/script.py

Example

Feel free to follow this worked-out example where you use autopep8 to fix formatting issues in your code.

  • Create and open a file called example.py on your desktop.
  • Open up a command line window and navigate to desktop.
  • Copy-paste the same code as in the previous example into the example.py file:
import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,'a'  );
    some_variable={'long':'Long code lines should be wrapped within 79 characters.',
    'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
    'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)

This is all valid Python code. However, it has multiple style/best practice issues. To fix these issues, use autopep8 by running the following command in the command line:

autopep8 --in-place --aggressive --aggressive example.py

Now if you look at the example.py file, you can see it is formatted nicely:

import math
import sys


def example1():
    # This is a long comment. This should be wrapped to fit within 72
    # characters.
    some_tuple = (1, 2, 3, 'a')
    some_variable = {
        'long': 'Long code lines should be wrapped within 79 characters.',
        'other': [
            math.pi,
            100,
            200,
            300,
            9876543210,
            'This is a long string that goes on'],
        'more': {
            'inner': 'This whole logical line should be wrapped.',
            some_tuple: [
                1,
                20,
                300,
                40000,
                500000000,
                60000000000000000]}}
    return (some_tuple, some_variable)

This saves time as you do not have to go through the list of issues and fix them one by one. This is super handy if you want to make your code look nice and clean with ease.

So far you have learned how to use linters to both show and fix styling issues in your code with a single command.

Chances are that you are using a code editor when writing code. It is useful to know that most of the code editors allow integrating a linter to them to show the linting errors in the editor.

Let’s take a look at an example of how to integrate the flake8 linter in Visual Studio Code, a really common code editor.

Integrate a Python Linter in VSCode

Visual Studio Code, which is one of the most popular code editors to date, can be made support Python linters.

In this example, I show you how to integrate flake8 linter in Visual Studio Code to warn about code formatting issues in real-time.

  • Open up a new Visual Studio Code window.
  • Press Command + Shift + P (⇧⌘P). This opens a search bar.
  • Type Python: Select Linter into the search bar and hit enter.

This opens up a list of linters that Visual Studio Code currently supports.

Choose the flake8 option.

Now that the linter is defined you can open up any Python code file. However, if you have not installed flake8 yet, you see this error:

To proceed, just click “Install”. This installs flake8 on your system so that VSCode can use it.

Now the linter is activated and you should be able to see code issues directly in the VSCode editor.

For example, copy-paste the following code into a Python file and open the file with Visual Studio Code:

import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,'a'  );
    some_variable={'long':'Long code lines should be wrapped within 79 characters.',
    'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
    'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)

You are going to see a lot of red. These are the styling issues picked up by the flake8 linter.

If you hover over any red error, you see a modal that describes the styling issue.

This is useful as now you get real-time feedback about the code styling mistakes you make. Now it is up to you to fix these issues and make the code look readable.

Conclusion

Today you learned about linters in Python.

To recap, a linter is a code analyzer that helps you write clean code that follows style guides and best practices. Any software developer should use a linter in their projects. A linter is very easy to install and use. A popular choice as a Python linter is flake8.

You can use a linter that warns you about styling issues. Commonly you can couple one of these with your favorite code editor to see the issues in real-time.

Alternatively, you can use a linter that not only shows the issues but also fixes them by running a command from the command line. An example of this is the autopep8 linter.

Thanks for reading.

Happy coding!

Further Reading

50 Python Interview Questions