PEP 8 Code Style in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will learn how to apply the PEP 8 style guide to your Python code. PEP 8 is the official style guide for Python, providing a set of recommendations for writing readable and consistent code. Following these guidelines makes your code easier to read for yourself and others.

You will practice implementing key PEP 8 rules for indentation, line length, spacing, and naming conventions. You will also learn how to use the autopep8 tool to automatically format your code, saving you time and ensuring compliance with community standards.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 96% completion rate. It has received a 100% positive review rate from learners.

Understand PEP 8 Indentation and Line Length

Proper indentation and line length are fundamental to readable Python code. In this step, you will learn and apply the PEP 8 guidelines for these two aspects.

Indentation: PEP 8 recommends using 4 spaces per indentation level. This is a strong convention in the Python community.

Line Length: PEP 8 suggests limiting all lines to a maximum of 79 characters. For docstrings and comments, the limit is 72 characters. This improves readability, especially on smaller screens or when comparing code side-by-side.

Let's put this into practice. In the file explorer on the left, find and open the file indentation_example.py. The code inside demonstrates correct indentation for function definitions and multi-line statements.

## Correct indentation using 4 spaces.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

## Define some variables for demonstration.
var_one = "first"
var_two = "second"
var_three = "third"
var_four = "fourth"

## Aligning with the opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

## Using a hanging indent. The first line has no arguments,
## and subsequent lines are indented to distinguish them.
bar = long_function_name(
    var_one, var_two,
    var_three, var_four)

## A multi-line list.
my_list = [
    1, 2, 3,
    4, 5, 6,
]

## Calling the functions to produce output.
long_function_name("first call", "second", "third", "fourth")
foo = long_function_name("second call", "second", "third", "fourth")
bar = long_function_name("third call", "second", "third", "fourth")

After reviewing the code, run the script to see its output. Open the terminal at the bottom of the WebIDE and execute the following command:

python ~/project/indentation_example.py

The script will run and print the first argument from each function call. The output will be:

first call
second call
third call

This exercise demonstrates how consistent indentation makes complex function calls and data structures much easier to read.

Practice Spacing and Naming Conventions

Consistent spacing and clear naming conventions are also crucial for code readability. This step covers the PEP 8 rules for both.

Spacing:

  • Use a single space around most operators (=, +=, ==, <, >).
  • Use a space after commas in lists, tuples, and function arguments.
  • Avoid extra spaces immediately inside parentheses, brackets, or braces.

Naming Conventions:

  • snake_case: Use for functions and variables (e.g., my_function, user_name).
  • PascalCase: Use for class names (e.g., MyClass).
  • UPPERCASE_SNAKE_CASE: Use for constants (e.g., MAX_CONNECTIONS).

Let's see these rules in action. In the file explorer, open the style_guide_example.py file. The code includes examples of correct spacing and naming, with commented-out incorrect versions for comparison.

## A constant
MAX_OVERFLOW = 100

## A class name in PascalCase
class MySampleClass:
    def __init__(self, name):
        ## A variable name in snake_case
        self.instance_name = name

    ## A function name in snake_case
    def sample_method(self, var_one, var_two):
        ## Correct spacing around operators and after comma
        result = var_one + var_two
        print(self.instance_name, result)

## --- Incorrect examples for comparison ---
## class mySampleClass:
##     def SampleMethod(self, varOne, varTwo):
##         result=varOne+varTwo
##         print(self.instance_name,result)

## Create an object and call the method
my_object = MySampleClass("TestObject")
my_object.sample_method(10, 5)

Save the file if you made any changes, and run it from the terminal:

python ~/project/style_guide_example.py

The output will show the name of the object and the result of the calculation:

TestObject 15

By following these spacing and naming rules, you make the structure and purpose of your code immediately clearer to any reader.

Use autopep8 for Automatic Formatting

Manually formatting code can be tedious. Fortunately, tools exist to automate this process. In this step, you will install and use autopep8, a popular tool that automatically reformats Python code to conform to the PEP 8 style guide.

First, you need to install the autopep8 package. Open the terminal and run the following command. sudo is used to install it system-wide.

sudo pip3 install autopep8

The installation process will begin, and you should see output confirming its successful installation:

Collecting autopep8
...
Successfully installed autopep8-X.Y.Z

Next, let's work with a Python file that has deliberately poor formatting. In the file explorer, open unformatted_code.py and examine its content:

a=1
b=2;
def  my_function ( arg1 , arg2 = 0 ):
    result = arg1+arg2
    print( result)

This code has several style issues: inconsistent spacing, a redundant semicolon, and extra spaces in the function definition.

Now, let's use autopep8 to fix it. The --in-place flag tells the tool to modify the file directly. Run this command in your terminal:

autopep8 --in-place ~/project/unformatted_code.py

After the command finishes, open unformatted_code.py again in the editor. You will see that the code has been automatically cleaned up:

a = 1
b = 2


def my_function(arg1, arg2=0):
    result = arg1 + arg2
    print(result)

Notice how autopep8 corrected the spacing, removed the semicolon, and added two blank lines before the function definition, as recommended by PEP 8. Using an auto-formatter like autopep8 is a highly efficient way to maintain a consistent code style across your projects.

Putting It All Together: Refactoring a Script

Now it's time to apply everything you've learned. In this step, you will manually refactor a script that violates several PEP 8 guidelines. This exercise will test your understanding of indentation, spacing, and naming conventions.

First, open refactor_challenge.py from the file explorer. It contains the following code, which calculates the area of a rectangle but is written with poor style.

## This script calculates the area of a rectangle and prints it.
def CalculateArea(width,height):
    Area = width*height ## calculate area
    return Area

w = 10
h = 5
rectangle_area=CalculateArea(w,h)
print("The area of the rectangle is:",rectangle_area)

Your task is to manually edit this code in the editor to make it PEP 8 compliant. Look for issues with:

  1. Function Naming: Function names should be snake_case.
  2. Variable Naming: Variable names should also be snake_case.
  3. Spacing: Check for proper spacing around operators and after commas.
  4. Comments: Inline comments should have a space after the #.

Take a moment to refactor the code yourself. Once you are done, your code should look similar to this:

## This script calculates the area of a rectangle and prints it.
def calculate_area(width, height):
    """Calculate and return the area of a rectangle."""
    area = width * height  ## calculate area
    return area


w = 10
h = 5
rectangle_area = calculate_area(w, h)
print("The area of the rectangle is:", rectangle_area)

Notice the changes: CalculateArea became calculate_area, Area became area, and spacing was corrected. We also added a docstring to the function, which is a best practice for explaining what a function does.

Save your changes and run the script to ensure it still works correctly:

python ~/project/refactor_challenge.py

The output should be:

The area of the rectangle is: 50

This exercise shows that refactoring for style doesn't change what the code does, but it dramatically improves its readability and maintainability.

Summary

In this lab, you have learned the fundamentals of the PEP 8 style guide for Python. You practiced applying rules for indentation, line length, spacing, and naming conventions. You also discovered the power of autopep8 for automatically formatting your code to meet these standards. By completing a final refactoring challenge, you put all these concepts together to transform a poorly styled script into clean, readable, and maintainable Python code. Adhering to PEP 8 is a key practice for any professional Python developer, as it fosters collaboration and improves code quality.