Python FAQ: Top Questions
4. What is PEP 8?
PEP 8 , which stands for **Python Enhancement Proposal 8**, is the official style guide for Python code. It is one of the most foundational documents in the Python ecosystem and provides a set of recommendations to write highly readable, consistent, and maintainable Python code. Its primary goal is to improve the consistency of Python code across different projects and developers, making it easier for everyone to read and understand code written by others (and by their future selves).
Adhering to PEP 8 is not mandatory for code to run, but it is considered a **best practice** and is widely adopted within the Python community. Most professional Python projects and open-source libraries follow PEP 8 rigorously.
Here are some of the most important and frequently encountered conventions prescribed by PEP 8:
-
Indentation:
- Use **4 spaces per indentation level**. This is a strict rule and is fundamental to Python's syntax (significant indentation).
- Never mix spaces and tabs for indentation within the same file. The strong recommendation is to use spaces.
-
Line Length:
- Limit all lines to a maximum of **79 characters**. For docstrings and comments, the limit is 72 characters.
- This convention improves readability, especially when viewing code on smaller screens, in side-by-side diffs, or in code review tools. Python allows lines to be broken using parentheses, brackets, or curly braces, or explicitly with a backslash `\`.
-
Blank Lines:
- Use two blank lines to separate **top-level function and class definitions**.
- Use one blank line to separate methods within a class.
- Use blank lines sparingly within functions to indicate logical sections.
-
Naming Conventions:
- **Modules:** Short, all-lowercase names, e.g., `my_module.py`.
- **Packages:** Short, all-lowercase names, e.g., `my_package/`.
- **Classes:** `CamelCase` (CapWords) style, e.g., `MyClass`, `HttpRequest`.
- **Functions, Variables, Methods:** `snake_case` (lowercase with underscores), e.g., `my_function`, `total_count`, `calculate_sum`.
- **Constants:** `ALL_CAPS` with underscores, e.g., `MAX_SIZE`, `PI`.
- **Private/Internal members:** Start with a single leading underscore (e.g., `_internal_method`).
- **Magic Methods (Dunder Methods):** Use double leading and trailing underscores (e.g., `__init__`, `__str__`).
-
Imports:
- Put each import on its own line.
-
Imports should be grouped in the following order:
- Standard library imports.
- Third-party library imports.
- Local application/module-specific imports.
- Each group should be separated by a blank line.
- Keep comments up-to-date.
- Focus comments on explaining the "why" of the code (the rationale behind decisions), rather than merely restating the "what" (what the code explicitly does).
- Use docstrings (triple quotes `"""Docstring"""`) for modules, functions, classes, and methods to provide comprehensive explanations.
- Avoid extraneous whitespace in various situations (e.g., immediately inside parentheses, brackets, or curly braces, immediately before a comma, semicolon, or colon).
- Use spaces around operators (e.g., `x = y + z` not `x=y+z`).
Tools like `flake8`, `black`, `isort`, and `autopep8` can help automate the process of checking and formatting code according to PEP 8 guidelines.
# --- Example of Bad PEP 8 Practices ---
import os, sys # Multiple imports on one line
x=10+5 # No spaces around operator
def foo ( a , b ): # Extraneous whitespace
return a*b # Wrong indentation (2 spaces instead of 4), no blank lines
class MyClass: # No blank line before class
def __init__(self, data):
self.data=data # No space around =
# --- Example of Good PEP 8 Practices ---
import os # Standard library import
import sys # Standard library import
import requests # Third-party library import
from my_project.utils import helper_function # Local import (hypothetical)
MAX_RETRIES = 3 # Global constant naming
def calculate_total_sum(list_of_numbers):
"""
Calculates the sum of numbers in a list.
This function iterates through the provided list and aggregates
their values. It's designed for readability and efficiency.
"""
current_sum = 0
for number in list_of_numbers:
current_sum += number
return current_sum
class UserProfile: # Class naming
"""
Represents a user profile with basic information.
"""
def __init__(self, username, email): # Method naming, 4-space indent
self.user_name = username # Variable naming
self.user_email = email
def display_info(self):
"""
Prints the user's name and email.
"""
print(f"Username: {self.user_name}")
print(f"Email: {self.user_email}")
# Usage adhering to PEP 8
my_numbers = [10, 20, 30, 40]
result = calculate_total_sum(my_numbers)
print(f"The total sum is: {result}")
new_user = UserProfile("john_doe", "john.doe@example.com")
new_user.display_info()
Explanation of the Example Code:
- The first "Bad PEP 8" section demonstrates common violations: multiple imports on one line, lack of spacing around operators, extraneous whitespace in function definitions, incorrect indentation, and lack of blank lines.
-
The "Good PEP 8" section showcases proper conventions:
- **Imports:** Grouped and separated by blank lines (`os`, `sys` then `requests` then `helper_function`).
- **Constants:** `MAX_RETRIES` uses `ALL_CAPS`.
- **Function Definition:** `calculate_total_sum` follows `snake_case` naming, uses 4-space indentation, and includes a comprehensive docstring explaining its purpose.
- **Class Definition:** `UserProfile` uses `CamelCase` naming, is separated by two blank lines from preceding code, and has a docstring.
- **Method Definition:** `__init__` and `display_info` use `snake_case` and are separated by one blank line.
- **Whitespace:** Correct spacing around operators (`=`, `+`) and in expressions.
This example clearly illustrates how adhering to PEP 8 creates code that is significantly more consistent, readable, and maintainable, making it easier for any Python developer to understand and contribute to a project.