Skip to content

A Complete Guide to Code Review and Refactoring Exercises for Applying PEP 8 Principles in Python

Updated: at 05:23 AM

PEP 8 is Python’s official style guide that provides coding conventions and best practices for writing clear, readable Python code. Adhering to PEP 8 principles enables writing uniform, easy-to-understand Python code that follows industry standards. This improves code maintainability and readability.

This guide will provide a comprehensive overview of PEP 8 recommendations and demonstrate practical code review and refactoring exercises developers can perform to identify and correct areas of improvement for applying PEP 8 principles in existing Python code.

Following the principles and techniques outlined in this guide will assist Python developers in writing high-quality Python code that conforms to the PEP 8 style guide. The concepts discussed are applicable for beginners learning Python and experienced developers working on Python projects in data science, machine learning, and software engineering domains.

Table of Contents

Open Table of Contents

Overview of Key PEP 8 Recommendations

Let us first briefly summarize some key PEP 8 recommendations related to Python code formatting and style conventions:

These are some of the key recommendations from PEP 8 that directly impact code readability, maintainability and style. The complete PEP 8 style guide contains many more conventions. We will now see some practical exercises for reviewing code to identify deviations from PEP 8 and then refactor the code to align with PEP 8 principles.

Code Review Exercises

Let’s go through code review checklists and exercises to spot areas not conforming to PEP 8 recommendations:

Checklist for Module Level Code

Checklist for Functions and Methods

Checklist for Classes

Checklist for Code Readability

Let’s apply these checklists to review the following sample code:

# Sample code

import os

CONST_VALUE = 10

def foo(x,y):
  print(x+y)

class myClass:

  def __init__(self):
    self.x = 10

  def myMethod(self, x, y):
    return x + y

print(CONST_VALUE)

By going through the checklists, we can identify the following issues:

This review helped spot many areas where the code deviates from PEP 8 conventions and principles. Similar checklist-driven reviews of existing code can help uncover areas for improvement.

Refactoring Exercises

Let’s now go through some refactoring exercises to fix the issues identified during the review and make the code PEP 8 compliant:

1. Add docstrings:

"""This module provides utility functions for math operations."""

def foo(x, y):
  """Prints the sum of two numbers."""

  print(x + y)

class MyClass:

  """Represents a class to operate on some data."""

  def __init__(self):
    """Initialize the class with default values."""
    self.x = 10

  def my_method(self, x, y):
    """Adds two numbers and returns the sum."""
    return x + y

2. Fix imports, constant name and spacing:

"""This module provides utility functions for math operations."""

import os

CONST_VALUE = 10

def foo(x, y):
  """Prints the sum of two numbers."""

  print(x + y)

class MyClass:

  """Represents a class to operate on some data."""

  def __init__(self):
    """Initialize the class with default values."""
    self.x = 10

  def my_method(self, x, y):
    """Adds two numbers and returns the sum."""
    return x + y

print(CONST_VALUE)

3. Make function return value rather than print:

def foo(x, y):
  """Returns the sum of two numbers."""

  return x + y

4. Use descriptive names and remove hardcoded values:

MAX_RETRIES = 5

def calculate_sum(first_number, second_number):
  """Returns the sum of two numbers."""

  return first_number + second_number

class DataClass:

  """Represents a class to operate on some data."""

  def __init__(self):
    """Initialize the class with default values."""
    self.number = 10

  def add_numbers(self, first_num, second_num):
    """Adds two numbers and returns the sum."""

    return first_num + second_num

These examples demonstrate how we can refactor existing code to fix PEP 8 issues identified during code review. The refactored code has proper spacing, naming conventions, docstrings, comments and style as per PEP 8 principles.

Refactoring Strategies

Let’s discuss some effective strategies for refactoring code to comply with PEP 8:

These refactoring techniques can help transform unstructured spaghetti code to modular, readable, Pythonic code conforming to PEP 8.

Automated PEP 8 Analysis Tools

Manually reviewing code for PEP 8 conformance has limitations. Automated tools can analyze code at scale and catch issues that may be missed during manual review.

Some popular automated PEP 8 analysis tools for Python include:

These automated tools provide an objective PEP 8 conformance report for Python code. Developers should run these routinely during development to detect issues early. The tools also suggest fixes for certain categories of PEP 8 deviations.

However, automation cannot catch all readability, logic and organization issues. Manual code review is still needed along with running these tools.

Exercises for Readers

To master PEP 8 principles and improve your Python code quality, try these practice exercises:

Regular practice and application of these exercises will help ingrain good PEP 8 habits into your coding skills.

Conclusion

PEP 8 provides comprehensive style guidelines and best practices for writing high quality Python code that is readable, maintainable and consistent. Performing code reviews against PEP 8 checklists coupled with refactoring using recommended strategies enables bringing existing Python code up to standard. Automated analysis tools can catch additional issues at scale.

Adopting the code review, refactoring exercises and tools covered in this guide will help Python developers to consistently write code following PEP 8 principles. This will improve the professionalism, reliability and collaboration on Python codebases. The benefits of standards are multiplied on large projects with many developers.

As PEP 8 is considered the de facto coding standard for Python, practicing it regularly is an essential skill for any Python programmer. The techniques presented in this guide should provide a useful methodology to assess and improve PEP 8 conformance of Python code in any environment.