Checking Python style with pep8

A solid foundation in Python Style



If you've been coding with the Python language for a while, you have probably heard of PEP 8, the authoritative Python coding style guide authored by Guido van Rossum. While PEP 8 makes for a thrilling and inspiring read, something like a cross between Uncle John's Bathroom Reader and the US Constitution, it never occurred to me that there was a living application of the principles embodied in its chapters.

Today I learned that 'pep8' is a Python app! If you have pip installed, you can just 'pip install pep8'. If you don't have pip installed, install pip first with 'sudo apt-get install python-pip'. Pip is like apt-get, but for Python.

Pay attention, because this is the cool part. Now that you have pep8 you can use it to check your actual code against the actual PEP 8! It's like Guido himself was standing next to your desk, calmly eating canteloupe and critiquing your code for Pythonicity.

Here is the actual output I got from pep8 when I ran it for the first time on my Django project's settings.py:

$ pep8 cpi/settings.py
myproject/settings.py:6:80: E501 line too long (82 > 79 characters)
myproject/settings.py:110:1: E122 continuation line missing indentation or outdented
myproject/settings.py:133:1: W293 blank line contains whitespace
myproject/settings.py:138:1: W293 blank line contains whitespace
myproject/settings.py:143:13: W291 trailing whitespace
myproject/settings.py:156:80: E501 line too long (90 > 79 characters)
myproject/settings.py:130:1: E122 continuation line missing indentation or outdented
myproject/settings.py:151:14: E261 at least two spaces before inline comment
myproject/settings.py:152:22: E261 at least two spaces before inline comment
myproject/settings.py:153:16: E261 at least two spaces before inline comment
myproject/settings.py:231:1: E303 too many blank lines (3)
Ouch, that's a lot of errors! These are all the blunders in Python style which don't actually prevent execution of the code when it's run through the interpreter.

I was able to clear up all the errors, after which pep8 will run with no output:

$ pep8 cpi/settings.py

Joy!

No comments:

Post a Comment

Comments welcome!