Definition
The official Style Guide for Python Code, providing a set of conventions for how to format and organize code to ensure maximum readability.
Why It Matters
Readability is the only thing that makes code maintainable over years. If every developer uses their own “creative” formatting, the codebase becomes a tower of Babel that no one can safely edit. PEP 8 is the “social contract” of the Python community; adhering to it minimizes the “Cognitive Friction” of reading logic, ensuring that the team’s mental energy is spent on solving problems rather than deciphering indentation.
Core Concepts
- Readability: “Code is read much more often than it is written.”
- Indentation: Use 4 spaces per indentation level (no tabs).
- Naming Conventions:
snake_casefor variables and functions.PascalCasefor classes.UPPER_CASEfor constants.
# PEP 8 Compliant Example
CONSTANT_VAL = 100
class UserProfile:
def __init__(self, user_name):
self.user_name = user_name
def calculate_total(price, tax_rate):
return price * (1 + tax_rate)
- Line Length: Limit all lines to a maximum of 79 characters.
- Whitespace: Avoiding extraneous whitespace inside parentheses or before commas.