Python Coding in Style: PEP 8

Lukas Schaub
5 min readJun 16, 2023

--

Python is a popular programming language that is widely used in various fields such as data science, web development, and artificial intelligence. As the language has evolved over the years, it has become essential to establish a set of guidelines for writing Python code that is easy to read, maintain, and understand. That is where PEP 8 comes in.

PEP 8 is the official style guide for Python code. PEP stands for Python Enhancement Proposal, and it is a document that proposes new features or changes to the Python language. PEP 8 was created to provide a set of conventions for writing Python code that is consistent and easy to read. Let me try to convince you, that following a guide like this can help you make your code more industry ready. In this article, we will explore the key principles of PEP 8 and why it is essential to follow them.

PEP 8 The Style Guide for production-ready code

Code Layout

PEP 8 recommends that you use four spaces for indentation and avoid using tabs. This helps to ensure that your code looks consistent across different text editors and environments. It is also recommended that lines should not exceed 79 characters and that you use blank lines to separate functions, classes, and other logical blocks.

Here is a BAD example:

def calculate_average(numberssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss):
total = 0
count = 0
for number in numberssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss:
total += number
count += 1
average = total / count
return average

You should immediately realize the rediculous long variable name: “numberssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss”. However this is not the only bad part about this function. Did you realize how the variable: average and the return statement are not intended as the rest of the code? This makes it harder to read and less understandable.
Here is the same code but in a GOOD way:

def calculate_average(numbers):
total = 0
count = 0
for number in numbers:
total += number
count += 1
average = total / count
return average

Naming Conventions

Naming conventions are essential for making your code readable and understandable. PEP 8 recommends using lowercase letters for variable and function names, with words separated by underscores. For class names, use the CamelCase convention, starting with an uppercase letter. It is also recommended to avoid using single-character names unless they are for temporary or looping variables.

A BAD example:

def calculateavg(numbers):
total = 0
count = 0
for num in numbers:
total += num
count += 1
avg = total / count
return avg

Try to avoid combined words. Also abbreviations like “avg” and “num” might not make sense to all people avoid potential issues by calling the variables “average” and “number”. See the GOOD approach to this code snippet:

def calculate_average(numbers):
total = 0
count = 0
for number in numbers:
total += number
count += 1
average = total / count
return average

Function and Method Arguments

When defining function and method arguments, PEP 8 recommends that you use descriptive names that make it clear what each argument represents. Additionally, you should avoid using mutable objects such as lists or dictionaries as default argument values.

BAD example

def calculate_area(length, Width):
area = length * Width
return area

Here the code shows the variable “Width” which is written with w capitalized “W”. Do it like shown below:

def calculate_area(length, width):
area = length * width
return area

Comments

Comments are an essential part of any codebase, and PEP 8 provides guidelines on how to write clear and useful comments. Comments should be used to explain what the code does, not how it does it. It is also recommended to use complete sentences and proper grammar when writing comments.

BAD examples

# This function calculates the area of a rectangle
def area(length, width):
return length * width


# Function to calculate average
def calc_avg(nums):
# Initializing variables
total = 0
count = 0

# Loop to sum numbers
for num in nums:
total += num
count += 1

# Calculating average
avg = total / count
return avg

The first function should rather use a docstring. The second function comments are not very informative! Time for some GOOD code to see how it is properly done:

def area(length, width):
"""Calculate the area of a rectangle."""
return length * width

def calculate_average(numbers):
total = 0
count = 0

# Summing up the numbers
for number in numbers:
total += number
count += 1

# Calculating the average
average = total / count
return average

Import Statements

PEP 8 recommends that import statements should be placed at the top of the file, immediately after any module comments or docstrings. Additionally, you should group your import statements in the following order: standard library imports, third-party library imports, and local imports.

BAD examples

import math, os, sys
from datetime import datetime, timedelta
from pandas import *
from urllib.request import urlopen, Request

Use one import statement per module! Avoid the “*” import it is not specific enough and will most likely lead to naming conflicts. Standard libraries like “urllib.request” should be imported seperatly.

How to do it correctly:

import math
import os
import sys

from datetime import datetime, timedelta

import pandas as pd

from urllib.request import Request
from urllib.request import urlopen

Why is it important to follow PEP 8?

Following PEP 8 guidelines make your code more readable and easier to understand for yourself and others. When working on a project with other developers, using a consistent style guide ensures that everyone is on the same page and reduces the time spent on code reviews. Additionally, following PEP 8 can improve the performance of your code by making it more efficient and easier to debug.

In conclusion, PEP 8 is an essential document for Python developers who want to write high-quality and maintainable code. Following its guidelines ensures that your code is consistent and easy to read, making it easier for you and other developers to work on it in the future. By following PEP 8, you will not only improve the quality of your code, but you will also become a better Python developer.

If you want to have a more detailed look at the quite funny written PEP 8 follow this Link.

Have you tried to clear your code with PEP8 Style Guide? Did you like this article? Let me know by commenting, clapping, and following me for more content like this.

--

--

Lukas Schaub

Programming and Data addict. With many other interests including languages and cooking.