PEP 8
PEP 8 is the de facto code style guide for Python. A high quality,easy-to-read version of PEP 8 is also available at pep8.org.
This is highly recommended reading. The entire Python community does theirbest to adhere to the guidelines laid out within this document. Some projectmay sway from it from time to time, while others mayamend its recommendations.
That being said, conforming your Python code to PEP 8 is generally a good ideaand helps make code more consistent when working on projects with otherdevelopers. There is a command-line program, pycodestyle(previously known as pep8
), that can check your code for conformance.Install it by running the following command in your terminal:
- $ pip install pycodestyle
Then run it on a file or series of files to get a report of any violations.
- $ pycodestyle optparse.py
- optparse.py:69:11: E401 multiple imports on one line
- optparse.py:77:1: E302 expected 2 blank lines, found 1
- optparse.py:88:5: E301 expected 1 blank line, found 0
- optparse.py:222:34: W602 deprecated form of raising exception
- optparse.py:347:31: E211 whitespace before '('
- optparse.py:357:17: E201 whitespace after '{'
- optparse.py:472:29: E221 multiple spaces before operator
- optparse.py:544:21: W601 .has_key() is deprecated, use 'in'
The program autopep8 can be used toautomatically reformat code in the PEP 8 style. Install the program with:
- $ pip install autopep8
Use it to format a file in-place with:
- $ autopep8 --in-place optparse.py
Excluding the —in-place
flag will cause the program to output the modifiedcode directly to the console for review. The —aggressive
flag will performmore substantial changes and can be applied multiple times for greater effect.