Trying To Write More Pythonic With PEP-8 (Python)

The Python language has a list of Python Enhancement Proposals (PEPs) that have been suggested as ways to improve Python. In this blog post I am going to look briefly at PEP-8.

The Index Of PEPs

Python.org keeps a list of all the PEPs at: https://www.python.org/dev/peps/ once a PEP has been assigned a PEP number, that number never changes.

PEP-8

  • Use 4 spaces for indentation
  • That’s spaces, not tabs
  • 79 characters per line
  • Line breaks should be before operators, not after
  • Top level functions and class definitions should be surrounded by 2 blank lines
  • Method definitions in a class should be surrounded by 1 blank line
  • Imports should be on separate lines
  • Imports should be in order of:
        • standard library imports
        • related 3rd party imports
        • local application imports
  • Each of the above import groups should have a blank line in between the groups

Kenneth Reitz created a cool site containing all the PEP-8 conventions, and it is broken down into sections making it really easy to read. Check it out at: https://pep8.org

Why Use PEP-8?

Having a standard look to code makes it easier for others (both programmers and non-programmers) to read. In turn this makes it easier for others to understand what the code is trying to achieve.

Testing For PEP-8

There is a PEP-8 tool available from https://pypi.org/project/pep8/ , however this was replaced by pycodestyle (https://pypi.org/project/pycodestyle/). pycodestyle can be installed via the command:

pip3 install pycodestyle

Code can then be tested via the command:

pycodestyle python_file_name.py

The pycodestyle output will then report back any Errors (E) that break PEP-8 or Warnings (W), a reference number and the line of the code where the issue is. A list of the error codes can be found at https://pep8.readthedocs.io/en/release-1.7.x/intro.html#error-codes

One thought on “Trying To Write More Pythonic With PEP-8 (Python)

Comments are closed.