How to Test Python Codes with Pycodestyle

How to Test Python Codes with Pycodestyle

Learn how to check your python programs against the pep8 style conventions accepted by the Python developer community.

Introduction

Your friend, Edmund, who just started to learn python, has finished his first project. He built a text-based adventure game to test his abilities. Edmund wishes to impress his assessors. So, he wants you to take a look at his code, make comments, and give him feedback on how to improve his code.

In reviewing python codes, several things beg your attention. Adherence to python style conventions is one of them. Always test your python code against python style conventions and best practices. That is part of the process of coding quality programs.

For instance, as a multiple award-winning writer, I always scan my works with a Grammer checker to ensure that everything I have written is in line with writing conventions, proper styles, and appropriate use of words. I also scan my articles with a plagiarism checker to keep my writings free of intellectual property violations. I am not the only one who does this. Most experienced writers do, and that is part of the process to produce quality written content.

There is good news anyway. Unlike your friends in the traditional writing world who are likely to export their articles to different platforms other than their text editors, python provides developers with a tool to check codes right from the command prompt. This tool is called pycodestyle.

This guide explains how to test python codes with pycodestyle. The guide discusses some of the common style conventions detected by pycodestyle and does not exhaust all the style guides covered by the Python Enhancement Proposal (PEP-8).

The guide is intended for beginners in python programming who wish to learn how to write quality, easy-to-read programs with python. Python programmers who want to improve the readability, organization, and functionality of their codes may find this guide helpful as well. This guide assumes that the reader has basic knowledge of python and can work comfortably with a command line interface using shell in windows or terminal in Mac.

After reading this guide, you will learn the following:

  • meaning of PEP-8

  • meaning of pycodestyle

  • how to install pycodestyle

  • how to upgrade pycodestyle

  • how to uninstall pycodestyle

  • how to scan your codes with pycodestyle

  • common errors detected by pycodestyle

  • how to fix style errors detected by pycodestyle

  • how to show the source code of errors with pycodestyle

  • how to display the frequency of error occurrences using pycodestyle

What is PEP-8?

PEP-8 (Python Enhancement Proposal 008) is a document that specifies coding conventions for python codes.

What is Pycodestyle?

Pycodestyle is a style guide checker or tool used to check python codes against most style conventions in python. As a creative writer scans their works with Grammarly for correctness, python programmers scan their codes with pycodestyle for adherence to style conventions. However, pycodestyle does not check for all python style conventions.

Install Pycodestyle

To install pycodestyle, type the following command in your shell/terminal:

$ pip install pycodestyle

Upgrade Pycodestyle

You can upgrade your pycodestyle with the following command:

$ pip install --upgrade pycodestyle

Uninstall Pycodestyle

To uninstall pycodestyle from your device, type in the following command:

$ pip uninstall pycodestyle

Scan your Codes with Pycodestyle

To check your friend, Edmund’s codes with pycodestyle, follow these steps:

  1. Open your command line interface (shell/termina)

  2. Navigate to the folder where you saved Edmund’s python code using the cd command (In this example, Edmund’s adventure game is saved in the python sub-folder, located within the programming folder on the desktop).

image.png

  1. Run the program on your command line using pycodestyle

image.png

Where:

  • ~/desktop/programming/python is the file path

  • $ is the command prompt

  • pycodestyle is the style checker

  • adventure.py is the file name of the program you wish to check

10 Common Errors Detected by PycodeStyle

This section discusses 10 of the common errors detected by pycodestyle under the PEP-8 style conventions.

Multiple Imports on one line:

image.png

This means that at the 12th character (column) on line 1, Edmund imported more than one module on the same line of code.

image.png

To fix this, bring the second import statement to another line.

Expected 2 Blank Lines, found one

image.png

It is a convention to leave two blank lines after each function or class definition. But between line 14 and 16 in Edmund’s code (between the print_pause() and intro() functions), pycodestyle found only one blank line.

image.png

To fix this issue, add another blank line before the intro() function.

Too Many Blank Lines

image.png

On line 5, character 1, pycodestyle found 3 blank lines which is higher than the conventional number of blank lines required in python.

image.png

After the import statements, the next block of code should begin from the 4th line (after two blank lines). But your friend added three instead.

To fix this issue, delete any of the blank lines to reduce the number of blank lines to two.

Blank Line Contains Whitespace

image.png

This means that the blank line on line 16 contains a whitespace - probably given with a space bar - on the first character. This whitespace is invisible as no character appears on that spot. Remove the whitespace with the delete or backspace key to fix the issue.

Line Too Long

image.png

On line 69 of the code, pycodestyle discovered 128 characters which are greater than the maximum 79 characters per line recommended by python. Python style conventions recommend no more than 79 characters for each line of code.

image.png

To fix this issue, break the sentence into two different lines using multi-line syntax. A good way to convert long sentences to multi-line statements is by enclosing the texts in a single bracket. Each line of the same sentence must be covered by quotation marks. Be sure to account for any spaces between words and lines as python will not fix that for you.

def intro():
    print_pause("You are a celebrity who finds himself in a cold world "
                "where the act of giving is under serious threat\n")
    print_pause("It has been observed that so many people walking the "
                "Earth has jettisoned alms giving due to previous ugly\n")

The code above shows two multi-line statements in python.

Trailing Whitespace

image.png

At the 21st character of line 38, pycodestyle detected whitespace (probably given by a space bar). You may not see this whitespace. To fix this issue, place your cursor just after the last visible character on that line and press the delete key on your keyboard.

Missing Whitespace around Operator

image.png

Python style conventions recommend spaces around the mathematical operators (=, +, -, *, /) used in python. However, on line 79 of Edmund’s program, pycodestyle found no spaces around the operator (=) used in that line.

image.png

To fix this, add spaces before and after operators.

Expected an Indented Block

image.png

On line 79, pycodestyle expected to see an indented block. But that was not the case.

image.png

The input statement assigned to the request variable on line 79 is written inside the request_help() function. Therefore, you should indent the ‘request’ block to show that it is under the request_help() function. Keeping the input method on the same indentation with the request_help() function signifies that both of them are separate code blocks on the same level. This is not what the developer intended.

To fix this error, place your cursor behind the request variable and strike the space bar four times to correct the indentation.

Unexpected Indentation

image.png

At the 6th character of line 41, the developer indented a block of code wrongly.

image.png

Looking at the piece of code above, you understand that all the print_pause() methods are the same level of codes declared inside the go_to_stadium() function. Hence, all the print_pause() methods should take the same length of indentation.

To fix this issue, use the backspace or delete key to correct the indentation.

Indentation is not a Multiple of 4

image.png

The correct indentation pattern in python is carried out by striking the space bar four times. Striking the tab key once may also achieve the same effect. But Python does not allow mixing spaces and tabs for indentation. However, on line 41 in the piece of code below, the developer only gave two spaces.

image.png

To fix this issue, add two more spaces at the start of line 41 to complete the 4 space-indentation that python style conventions recommend.

Display the Source Code of Each Error using the Show-Source Argument

You can get pycodestyle to display the source code of each error it identifies on the command line interface. To display the source codes of the errors in a python program, run the program with pycodestyle in this format:

$ pycodestyle --show-source adventure.py

Where:

  • $ is the command prompt

  • Pycodestyle is the style checker

  • --show-source is the command used to display the source codes of each error

  • adventure.py is the name of the python program under review

You must ensure that you are still within the folder where your python program is stored. If not, navigate to the correct folder using the cd command.

The image below is a sample outcome of the --show-source argument.

image.png

Display the Frequency of Error Occurrences Using the Statistics Argument

You can also display how often each error was found using the statistics argument. To achieve this, run the program with the following command:

$ pycodestyle --statistics -qq adventure.py

Where:

  • $ is the command prompt

  • Pycodestyle is the style checker

  • --statistics -qq is the argument to display the frequency of errors

  • Adventure.py is the filename of the python program.

You must ensure that you are still within the folder where your python program is stored. If not, navigate to the correct folder using the cd command.

The --statistics argument displays the following:

  • frequency of errors

  • the error codes

  • the error messages

The image below is a sample outcome of the --statistics argument.

image.png

Closing Thoughts

Pycodestyle is an invaluable tool that python provides developers to enhance the organization, readability, and functionality of python programs. Do employ the tool always to ensure adherence to style conventions and best practices accepted by the Python developer community.

I hope you got value from this article. Your feedback is invaluable to me.