What is PEP 8?
PEP 8 is a style guide for writing Python code. It outlines conventions and best practices that ensure:
- Consistency: Code looks uniform, making it easier to read and understand.
- Readability: It emphasizes writing clean and readable code.
- Community Standards: Encourages practices accepted and expected by the Python community.
Purpose of PEP 8
- Help Python developers write more understandable code.
- Ensure consistent style across Python codebases.
- Make it easier for newcomers to read and contribute to existing Python projects.
Key PEP 8 Guidelines
-
Indentation:
- Use 4 spaces per indentation level.
- Never mix tabs and spaces.
def example_function(): for i in range(10): print(i) # 4 spaces used for indentation
-
Line Length:
- Limit lines to a maximum of 79 characters.
- For longer blocks of text (like comments), limit them to 72 characters.
# This is a very long comment. To improve readability, limit lines # to 72 characters when writing block comments like this.
-
Blank Lines:
- Use blank lines to separate functions, classes, and blocks of code.
class Example: def method_one(self): pass def method_two(self): pass
-
Imports:
- Place all imports at the top of the file.
- Group imports in the following order:
- Standard library imports.
- Third-party library imports.
- Local application/library-specific imports.
# Example: import os import sys import numpy as np from myproject import mymodule
-
Whitespace:
- Avoid extra spaces in expressions or statements.
# Correct: x = 1 + 2 y = (a, b) # Incorrect: x = 1 + 2 y = ( a, b ) # Also incorrect: x = 1 + 2
-
Naming Conventions:
- Variable and function names:
snake_case
- Class names:
PascalCase
- Constants:
UPPER_CASE
# Example: class MyClass: def my_method(self): my_variable = 42
- Variable and function names:
-
Comments:
- Comments should be concise and relevant.
- Use complete sentences when explaining complex code.
# Correct: # This function calculates the square of a number. def square(n): return n ** 2 # Incorrect: # function calc square def square(n): return n ** 2
-
Docstrings:
- Use triple quotes for docstrings, and include a description for classes, functions, and modules.
def add(a, b): """Return the sum of a and b.""" return a + b
👉 Next tutorial: The Zen of Python