PEP 8 is the official Python style guide that promotes readable and consistent coding practices. Following it ensures that your code is easy to understand and maintain.
This guide summarizes the key points of PEP 8 with examples.
1. Indentation
Indentation in Python organizes code into blocks and defines the program’s structure. PEP 8 recommends using 4 spaces per level to maintain readability and consistency.
if True:
print("This line is indented")
Note: 4 spaces is standard, but continuation lines may have more indentation if needed.
2. Docstrings
Use docstrings to describe functions or modules. Single-line descriptions use """Description""", while multi-line explanations use triple quotes spanning several lines.
def exam():
"""This function demonstrates a multi-line docstring.
It spans multiple lines for explanation.
"""
3. Line Length
Keep lines within 79 characters to enhance readability. Use parentheses, brackets, or braces to wrap long lines instead of backslashes.
with open('/path/to/read/file') as file_one, \
open('/path/to/write/file', 'w') as file_two:
file_two.write(file_one.read())
4. Comments
Use comments to explain code for better readability. Inline comments follow the code after '#', while block comments are placed above the code they describe.
geek = geek + 1 # Increment
5. Trailing Commas
Use trailing commas in data structures like tuples, lists, or dictionaries to improve readability and simplify adding new elements.
tup = ("geek",)
6. Encodings
Use standard encodings like UTF-8 or ASCII for your Python files to ensure compatibility and avoid issues with international text.
text = "Hello"
encoded = text.encode() # Default UTF-8 encoding
print(encoded)
Output
b'Hello'
7. Spaces Around Operators
Use spaces around operators and after commas for readability, but avoid spaces immediately inside parentheses, brackets, or braces.
a = f(1, 2) + g(3, 4)
8. Naming Conventions
Follow consistent naming conventions: use CamelCase for classes, lower_case_with_underscores for functions and variables, and all uppercase with underscores for constants.
# Variable
name = "Harry"
# Constant
MAX_AGE = 100
# Class
class Person:
pass
9. Class and Function Arguments
Always use self as the first argument in instance methods and cls as the first argument in class methods.
class Person:
def __init__(self, name):
self.name = name
p = Person("Harry")
print(p.name)
Output
Harry
Example: Factorial Program
A clean and PEP 8-compliant Python program:
num = 7
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial *= i
print("The factorial of", num, "is", factorial)