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 response to “Trying To Write More Pythonic With PEP-8 (Python)”

  1. UK Covid-19 / Coronavirus Data (Python) – Geek Tech Stuff Avatar

    […] note, as I am trying to improve how I write Python starting with trying to meet PEP-8 standards. Hopefully this will make my code easier to read and to […]

    Like

Welcome to GeekTechStuff

my home away from home and where I will be sharing my adventures in the world of technology and all things geek.

The technology subjects have varied over the years from Python code to handle ciphers and Pig Latin, to IoT sensors in Azure and Python handling Bluetooth, to Ansible and Terraform and material around DevOps.

Let’s connect