Following Official PEP 8 Specification Philosophies
๐ท๏ธ Python Scripting Best Practices / Code Style and PEP 8
Python's design philosophy is captured in the Zen of Python (PEP 20), which emphasizes readability, simplicity, and explicitness. PEP 8 is the official style guide that translates these philosophies into practical coding conventions. Following PEP 8 ensures your code is consistent, maintainable, and easy for others (including your future self) to understand.
๐ง Core Philosophy: Readability Counts
Python code is read far more often than it is written. PEP 8 exists to make that reading experience smooth and predictable. The key philosophies include:
- Explicit is better than implicit โ Code should clearly state what it does without relying on hidden behavior.
- Simple is better than complex โ Prefer straightforward solutions over clever or overly abstract ones.
- Flat is better than nested โ Avoid deep indentation levels; restructure logic when possible.
- Sparse is better than dense โ Use whitespace to separate logical sections and improve visual clarity.
- Consistency is key โ Follow established patterns so readers can focus on logic, not formatting surprises.
โ๏ธ Indentation and Line Length
PEP 8 is strict about how code is structured visually:
- Use 4 spaces per indentation level โ never tabs. Most editors can be configured to convert tabs to spaces automatically.
- Limit all lines to a maximum of 79 characters for code and 72 for comments and docstrings.
- When a line exceeds the limit, break it using parentheses, brackets, or a backslash (though parentheses are preferred).
Example of proper line breaking:
- A function call with many arguments can be wrapped inside parentheses, with each argument on its own line indented once.
- A long conditional statement can be broken after logical operators (and, or) to improve readability.
๐ Naming Conventions
PEP 8 defines clear naming patterns so you can instantly recognize what a name represents:
| Element | Convention | Example |
|---|---|---|
| Variables and functions | lowercase_with_underscores | total_count, get_data() |
| Constants | UPPERCASE_WITH_UNDERSCORES | MAX_RETRIES, DEFAULT_TIMEOUT |
| Classes | CapitalizedWords (CamelCase) | ConfigParser, NetworkClient |
| Private attributes | single leading underscore | _internal_value |
| Strongly private attributes | double leading underscore | __private_method() |
| Avoid confusion | single trailing underscore | class_ (to avoid keyword clash) |
๐ ๏ธ Whitespace and Blank Lines
Whitespace is not decorative โ it signals structure:
- Use two blank lines before top-level function and class definitions.
- Use one blank line between methods inside a class.
- Use one blank line to separate logical sections within a function.
- Avoid extraneous whitespace immediately inside parentheses, brackets, or braces.
Examples of whitespace rules:
- Do not put a space before a comma, semicolon, or colon.
- Do put a space after a comma, semicolon, or colon (unless at the end of a line).
- Always surround binary operators (+, -, ==, =) with a single space on each side.
๐ต๏ธ Comments and Docstrings
Comments explain why, not what โ the code itself should show what it does. PEP 8 recommends:
- Comments should be complete sentences starting with a capital letter.
- Use inline comments sparingly โ only when the code is not self-explanatory.
- Every module, class, and public function should have a docstring (triple-quoted string) that describes its purpose.
- Keep comments up to date โ outdated comments are worse than no comments.
Docstring structure:
- First line: a brief summary ending with a period.
- If more detail is needed, add a blank line after the summary, then the full description.
- For functions, describe arguments, return values, and any exceptions raised.
๐ Imports Organization
Imports should be grouped and ordered to make dependencies clear:
- Standard library imports (os, sys, json, etc.)
- Third-party library imports (requests, pandas, flask, etc.)
- Local application imports (your own modules)
Separate each group with a blank line. Within each group, sort imports alphabetically. Avoid wildcard imports (from module import *) because they pollute the namespace and make it unclear where names come from.
โ Practical Checklist for PEP 8 Compliance
- [ ] Indentation uses 4 spaces (no tabs).
- [ ] Lines are under 79 characters for code, 72 for comments.
- [ ] Names follow the correct convention (snake_case, CamelCase, UPPER_CASE).
- [ ] Two blank lines before top-level definitions, one between methods.
- [ ] Operators and commas have proper spacing.
- [ ] Imports are grouped and alphabetically sorted.
- [ ] Comments explain why, not what.
- [ ] Docstrings exist for all public modules, classes, and functions.
๐ง Tools to Enforce PEP 8 Automatically
You don't have to memorize every rule. Use these tools to check and fix your code:
- pycodestyle (formerly pep8) โ checks your code against PEP 8 and reports violations.
- autopep8 โ automatically reformats your code to comply with PEP 8.
- flake8 โ combines pycodestyle with other linting tools for a comprehensive check.
- black โ an opinionated formatter that enforces a consistent style (slightly stricter than PEP 8 in some areas).
Running these tools regularly (or integrating them into your editor) ensures your code stays clean without manual effort.
๐ก Final Thought
PEP 8 is not a law โ it is a guideline designed to improve collaboration and reduce cognitive load. When a rule would make your code less readable (for example, breaking a long line in an awkward place), use your judgment. The ultimate goal is code that is clear, consistent, and easy to maintain for everyone who reads it.
PEP 8 is the official style guide for Python code that defines conventions for writing readable and consistent code.
๐งน Example 1: Using 4 spaces per indentation level (not tabs)
This example shows the standard indentation rule for blocks of code.
def calculate_area(radius):
pi = 3.14159
area = pi * radius ** 2
return area
result = calculate_area(5)
print(result)
๐ค Output: 78.53975
๐ Example 2: Limiting all lines to a maximum of 79 characters
This example demonstrates how to break a long line into multiple shorter lines.
# Long line broken with parentheses
total_cost = (item_price * quantity
+ shipping_fee
- discount_amount)
print(total_cost)
๐ค Output: depends on variable values
๐ค Example 3: Using lowercase with underscores for variable and function names
This example follows the snake_case naming convention for readability.
def calculate_engine_efficiency(fuel_used, distance_traveled):
efficiency = distance_traveled / fuel_used
return efficiency
result = calculate_engine_efficiency(10, 500)
print(result)
๐ค Output: 50.0
๐ฆ Example 4: Placing imports on separate lines at the top of the file
This example shows the correct way to organize import statements.
import os
import sys
import math
current_directory = os.getcwd()
pi_value = math.pi
print(current_directory)
print(pi_value)
๐ค Output: /home/user/project
๐ค Output: 3.141592653589793
๐งฉ Example 5: Adding two blank lines around top-level functions and one blank line around methods
This example demonstrates proper spacing between function definitions.
def read_sensor_data():
sensor_value = 42
return sensor_value
def process_data(value):
processed = value * 2
return processed
sensor = read_sensor_data()
result = process_data(sensor)
print(result)
๐ค Output: 84
๐ PEP 8 Quick Comparison
| Rule | Correct Example | Incorrect Example |
|---|---|---|
| Indentation | 4 spaces per level | Tab or mixed spaces |
| Line length | Max 79 characters | Lines longer than 79 |
| Naming | engine_speed |
engineSpeed or EngineSpeed |
| Imports | One per line, at top | Multiple imports on one line |
| Blank lines | Two around functions | No blank lines between functions |
Python's design philosophy is captured in the Zen of Python (PEP 20), which emphasizes readability, simplicity, and explicitness. PEP 8 is the official style guide that translates these philosophies into practical coding conventions. Following PEP 8 ensures your code is consistent, maintainable, and easy for others (including your future self) to understand.
๐ง Core Philosophy: Readability Counts
Python code is read far more often than it is written. PEP 8 exists to make that reading experience smooth and predictable. The key philosophies include:
- Explicit is better than implicit โ Code should clearly state what it does without relying on hidden behavior.
- Simple is better than complex โ Prefer straightforward solutions over clever or overly abstract ones.
- Flat is better than nested โ Avoid deep indentation levels; restructure logic when possible.
- Sparse is better than dense โ Use whitespace to separate logical sections and improve visual clarity.
- Consistency is key โ Follow established patterns so readers can focus on logic, not formatting surprises.
โ๏ธ Indentation and Line Length
PEP 8 is strict about how code is structured visually:
- Use 4 spaces per indentation level โ never tabs. Most editors can be configured to convert tabs to spaces automatically.
- Limit all lines to a maximum of 79 characters for code and 72 for comments and docstrings.
- When a line exceeds the limit, break it using parentheses, brackets, or a backslash (though parentheses are preferred).
Example of proper line breaking:
- A function call with many arguments can be wrapped inside parentheses, with each argument on its own line indented once.
- A long conditional statement can be broken after logical operators (and, or) to improve readability.
๐ Naming Conventions
PEP 8 defines clear naming patterns so you can instantly recognize what a name represents:
| Element | Convention | Example |
|---|---|---|
| Variables and functions | lowercase_with_underscores | total_count, get_data() |
| Constants | UPPERCASE_WITH_UNDERSCORES | MAX_RETRIES, DEFAULT_TIMEOUT |
| Classes | CapitalizedWords (CamelCase) | ConfigParser, NetworkClient |
| Private attributes | single leading underscore | _internal_value |
| Strongly private attributes | double leading underscore | __private_method() |
| Avoid confusion | single trailing underscore | class_ (to avoid keyword clash) |
๐ ๏ธ Whitespace and Blank Lines
Whitespace is not decorative โ it signals structure:
- Use two blank lines before top-level function and class definitions.
- Use one blank line between methods inside a class.
- Use one blank line to separate logical sections within a function.
- Avoid extraneous whitespace immediately inside parentheses, brackets, or braces.
Examples of whitespace rules:
- Do not put a space before a comma, semicolon, or colon.
- Do put a space after a comma, semicolon, or colon (unless at the end of a line).
- Always surround binary operators (+, -, ==, =) with a single space on each side.
๐ต๏ธ Comments and Docstrings
Comments explain why, not what โ the code itself should show what it does. PEP 8 recommends:
- Comments should be complete sentences starting with a capital letter.
- Use inline comments sparingly โ only when the code is not self-explanatory.
- Every module, class, and public function should have a docstring (triple-quoted string) that describes its purpose.
- Keep comments up to date โ outdated comments are worse than no comments.
Docstring structure:
- First line: a brief summary ending with a period.
- If more detail is needed, add a blank line after the summary, then the full description.
- For functions, describe arguments, return values, and any exceptions raised.
๐ Imports Organization
Imports should be grouped and ordered to make dependencies clear:
- Standard library imports (os, sys, json, etc.)
- Third-party library imports (requests, pandas, flask, etc.)
- Local application imports (your own modules)
Separate each group with a blank line. Within each group, sort imports alphabetically. Avoid wildcard imports (from module import *) because they pollute the namespace and make it unclear where names come from.
โ Practical Checklist for PEP 8 Compliance
- [ ] Indentation uses 4 spaces (no tabs).
- [ ] Lines are under 79 characters for code, 72 for comments.
- [ ] Names follow the correct convention (snake_case, CamelCase, UPPER_CASE).
- [ ] Two blank lines before top-level definitions, one between methods.
- [ ] Operators and commas have proper spacing.
- [ ] Imports are grouped and alphabetically sorted.
- [ ] Comments explain why, not what.
- [ ] Docstrings exist for all public modules, classes, and functions.
๐ง Tools to Enforce PEP 8 Automatically
You don't have to memorize every rule. Use these tools to check and fix your code:
- pycodestyle (formerly pep8) โ checks your code against PEP 8 and reports violations.
- autopep8 โ automatically reformats your code to comply with PEP 8.
- flake8 โ combines pycodestyle with other linting tools for a comprehensive check.
- black โ an opinionated formatter that enforces a consistent style (slightly stricter than PEP 8 in some areas).
Running these tools regularly (or integrating them into your editor) ensures your code stays clean without manual effort.
๐ก Final Thought
PEP 8 is not a law โ it is a guideline designed to improve collaboration and reduce cognitive load. When a rule would make your code less readable (for example, breaking a long line in an awkward place), use your judgment. The ultimate goal is code that is clear, consistent, and easy to maintain for everyone who reads it.
Interactive Views
You are currently in ๐ All-in-One mode. Use the tabs at the top to switch to ๐ Theory Only or ๐ป Code Only views.
PEP 8 is the official style guide for Python code that defines conventions for writing readable and consistent code.
๐งน Example 1: Using 4 spaces per indentation level (not tabs)
This example shows the standard indentation rule for blocks of code.
def calculate_area(radius):
pi = 3.14159
area = pi * radius ** 2
return area
result = calculate_area(5)
print(result)
๐ค Output: 78.53975
๐ Example 2: Limiting all lines to a maximum of 79 characters
This example demonstrates how to break a long line into multiple shorter lines.
# Long line broken with parentheses
total_cost = (item_price * quantity
+ shipping_fee
- discount_amount)
print(total_cost)
๐ค Output: depends on variable values
๐ค Example 3: Using lowercase with underscores for variable and function names
This example follows the snake_case naming convention for readability.
def calculate_engine_efficiency(fuel_used, distance_traveled):
efficiency = distance_traveled / fuel_used
return efficiency
result = calculate_engine_efficiency(10, 500)
print(result)
๐ค Output: 50.0
๐ฆ Example 4: Placing imports on separate lines at the top of the file
This example shows the correct way to organize import statements.
import os
import sys
import math
current_directory = os.getcwd()
pi_value = math.pi
print(current_directory)
print(pi_value)
๐ค Output: /home/user/project
๐ค Output: 3.141592653589793
๐งฉ Example 5: Adding two blank lines around top-level functions and one blank line around methods
This example demonstrates proper spacing between function definitions.
def read_sensor_data():
sensor_value = 42
return sensor_value
def process_data(value):
processed = value * 2
return processed
sensor = read_sensor_data()
result = process_data(sensor)
print(result)
๐ค Output: 84
๐ PEP 8 Quick Comparison
| Rule | Correct Example | Incorrect Example |
|---|---|---|
| Indentation | 4 spaces per level | Tab or mixed spaces |
| Line length | Max 79 characters | Lines longer than 79 |
| Naming | engine_speed |
engineSpeed or EngineSpeed |
| Imports | One per line, at top | Multiple imports on one line |
| Blank lines | Two around functions | No blank lines between functions |