Enhance your Python code’s readability with pycodestyle
Automatically review the readability and quality of your Python scripts based on PEP-8 style conventions
Programming is an indispensable skill of a data practitioner’s toolkit, and while it is easy to create a script to execute basic functions, writing good readable code at scale requires more work and thought.
Given Python’s popularity in data science, I will be delving into the use of pycodestyle for style guide checking to improve the quality and readability of Python code.
Contents
(1) About PEP-8 (2) Motivation (3) Installation (4) Basic Usage (5) Advanced Usage
About PEP-8
The pycodestyle checker provides code recommendations based on the PEP-8 style conventions. So what exactly is PEP-8?
PEP stands for Python Enhancement Proposal, and PEP-8 is a guide that outlines the best practices of writing Python code. Authored in 2001, its main objective is to improve overall code consistency and readability by standardizing code styles.
One thing to note is that PEP-8 is meant to serve as a guide, and not intended to be interpreted as biblical instructions to always strictly adhere to.
Motivation
A quick look at the PEP-8 documentation will immediately make it evident that there are way too many best practices to remember.
Furthermore, having already spent so much effort in writing the many lines of code, surely you do not wish to waste more time in inspecting the scripts manually for gaps in readability.
This is where pycodestyle comes in to automatically analyze your Python scripts and pinpoint the specific areas where the code can be improved.
Installation
The package was called pep8, but was renamed as pycodestyle in a bid to reduce confusion. This is after Python’s creator (Guido van Rossum) highlighted that tools should not be named after style guides, as people may ‘pick a fight’ with PEP-8 (styling guide) based on the behavior of pep8 (tool).
pip is the preferred installer program to use, and you can install or upgrade pycodestyle by running the following commands in your terminal:
# Install pycodestyle
pip install pycodestyle
# Upgrade pycodestyle
pip install --upgrade pycodestyle
Basic Usage
The most straightforward use is to run pycodestyle on a Python script (.py file) as a command in the terminal. Let’s use the following sample script (named _pycodestyle_samplescript.py) for demonstration:
We put pycodestyle to work by running this simple command:
pycodestyle pycodestyle_sample_script.py
The output specifies the code locations where PEP-8 style convention is violated:
The pair of digits separated by the colon (e.g. 3:19) in each line refers to the line number and character number respectively.
For example, the output of 6:64 E202 whitespace before ')' means that in line 6, there is an unexpected whitespace at 64th character mark.
You can review the frequency of error occurrences by parsing the statistics argument:
pycodestyle --statistics -qq pycodestyle_sample_script.py
In the output above, we see that there are 4 occurrences of unexpected whitespace before a closing bracket ‘)‘.
Advanced Usage
We can also import pycodestyle directly into our Python code to execute automated tests. This is useful for automated testing of coding style conformance of multiple scripts.
For example, the following class can be written to automatically check for conformance to PEP-8 convention:
import unittest
import pycodestyle
class TestCodeFormat(unittest.TestCase):
def test_conformance(self):
"""Test that the scripts conform to PEP-8."""
style = pycodestyle.StyleGuide(quiet=True)
result = style.check_files(['file1.py', 'file2.py'])
self.assertEqual(result.total_errors, 0, "Found style
errors")
The tool can also be configured such that tests are done based on the style rule preferences we define. For example, we can remove specific error(s) that we do not want to be detected in the checks:
style = pycodestyle.StyleGuide(ignore=['E201', 'E202', 'E501'])
Alternatively, we can direct pycodestyle to use a different configuration file (containing a specific set of style rules) altogether.
import pycodestyle
style = pycodestyle.StyleGuide(config_file='/path/to/tox.ini')
There are more functionalities available to suit your needs, so do visit the pycodestyle‘s documentation page for more details.
Conclusion
In this article, we looked at how to use the pycodestyle tool to check that our Python scripts comply with PEP-8 code styling conventions.
Code is read more often than it is written, so it is vital that our code is consistent, understandable, and neatly structured. Trust me, your collaborators and your future self will thank you for this.
I welcome you to join me on a data science learning journey! Give this Medium page a follow to stay in the loop of more data science content, or reach out to me on LinkedIn. Happy coding!
References
Feel free to check out Remote Python Jobs, a job board for remote Python-related opportunities.
Share This Article
Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
Write for TDS