What is PEP 8?

PEP stands for Python Enhancement Proposal. It’s a document that suggests changes and improvements to Python. PEP 8 is one of the most popular PEPs because it provides guidelines for writing clean and readable Python code. Created in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan, PEP 8 provides a detailed guide for writing clean and readable Python code.

This encapsulates the core philosophy of PEP 8: prioritizing clarity, which ultimately makes collaboration and maintenance easier.

Why do we need PEP 8?

The main goal of PEP 8 is to make Python code readable. Python code should be easy to understand. The easier it is to read, the easier it is to maintain, update, and share with others. Writing readable code also reduces bugs and errors.

Naming convention

Names in Python are important. PEP 8 recommends using meaningful and descriptive names for variables, functions, and classes.

  • Variables and functions: Use lowercase letters with words separated by underscores (my_variable, calculate_total()).

  • Classes: Use capitalized words without underscores (MyClass, CustomerOrder).

  • Constants: Use all uppercase letters, separating words with underscores (MAX_SPEED, PI_VALUE).

  • Functions: Use lowercase with underscores (my_function())

Example:

def calculate_sum(numbers_list):
total_sum = 0
for number in numbers_list:
total_sum += number
return total_sum

How to choose names

Names should be easy to understand. Avoid abbreviations. Use full words that describe what the variable or function does. For example, instead of calc(), use calculate().

Code layout

PEP 8 provides rules for organizing your code. Keep your lines short and use blank lines to separate sections of code.

  • Keep lines under 79 characters.

  • Use two blank lines before functions and classes.

Example:

class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def start_engine(self):
print("Engine started!")

Indentation

Indentation shows the structure of the code. PEP 8 recommends using 4 spaces per indentation level.

Example:

if x > 5:
print("x is greater than 5")

Tabs vs. spaces

PEP 8 says to use spaces, not tabs. Mixing tabs and spaces can cause errors.

Indentation following line breaks

If a line is too long, break it up. Indent the second line to line up with the first.

Example:

my_list = [1, 2, 3,
4, 5, 6]

Where to put the closing bracket

When a line breaks, the closing bracket should line up with the first line of code or the indentation level.

Example:

my_list = [
1, 2, 3,
4, 5, 6
]

Comments

Comments explain your code. Use them to make your code easier to understand.

Block comments

Block comments explain a section of code. They should be placed above the code.

Example:

# Calculate the total sum of the numbers in the list.
total_sum = sum(numbers_list)

Inline comments

Inline comments explain a single line of code. Keep them short and simple.

Example:

x = x + 1 # Increase x by 1

Documentation strings

Use docstrings to explain what your functions and classes do.

Example:

def add(a, b):
"""Return the sum of a and b."""
return a + b

Whitespace in expressions and statements

Use whitespace to make your code clearer.

Whitespace around binary operators

Add a single space around operators like +, -, and =.

Example:

total = price + tax

When to avoid adding whitespace

Do not add extra spaces inside parentheses, brackets, or braces.

Example:

# Correct
my_list = [1, 2, 3]
# Incorrect
my_list = [ 1, 2, 3 ]

Programming recommendations

PEP 8 also suggests some programming best practices:

  • Use is or is not to compare with None.

  • Don’t use == to compare Boolean values.

Example:

# Recommended
if my_var is None:
print("my_var is None")

Let's solve the quiz below:

1

Which PEP 8 recommendation does this code violate?

myVariable = 10

A)

This follows PEP 8.

B)

Variable names should be written in snake_case.

C)

The variable name should be more descriptive.

Question 1 of 30 attempted

Tips and tricks to follow PEP 8

There are tools that can help you follow PEP 8:

  • Linters: Tools like pylint and flake8 can check your code for PEP 8 violations.

  • Autoformatters: Tools like black and autopep8 can automatically format your code to follow PEP 8.

PEP 8, Python's style guide for code, remains a resource for maintaining consistency and readability in Python codebases. It's updated periodically to reflect changes in the language and its evolving best practices. As Python continues to expand and introduce new features, PEP 8 adapts to ensure that its guidelines remain aligned with the latest developments in the language. Keeping up with these updates ensures that your code stays current and follows community-driven standards.

Key takeaways:

  • PEP 8: A Python guideline for writing clean, readable, and maintainable code.

  • Naming conventions: Use lower_case_with_underscores for variables/functions, CamelCase for classes, and ALL_CAPS for constants.

  • Code layout: Keep lines under 79 characters, and use 2 blank lines before functions/classes.

  • Indentation: Use 4 spaces per level, no tabs.

  • Comments and docstrings: Use block comments for sections, inline comments for single lines, and docstrings to describe functions/classes.

  • Whitespace: Add spaces around operators; avoid spaces inside parentheses.

  • Best practices: Use is/is not for None comparisons, avoid == for booleans.

  • Tools: Use linters (e.g., pylint, flake8) and autoformatters (e.g., black, autopep8) to enforce PEP 8.

Ready to deepen your Python knowledge? Start our Become a Python Developer path, beginning with Python's basic concepts and advancing to more complex topics, preparing you for a career as a Python developer.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


When can we ignore PEP 8?

Sometimes, it’s okay to break PEP 8 rules if it makes the code easier to read. The goal is always readability.


How to get PEP 8 in Python?

Install the pep8 tool using pip by running pip install pep8. This tool checks your Python code for PEP 8 compliance.


How to check for PEP 8?

Use tools like flake8, pylint, or pep8 to check your Python code for PEP 8 compliance by running them in your terminal.


What is PEP 8 in Python interview questions?

In interviews, PEP 8 is discussed as the official style guide for Python code, focusing on naming conventions, indentation, and code layout to ensure readability and consistency.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved