PEP 8 in Python
PEP 8 is the official style guide for Python code. It stands for Python Enhancement Proposal 8 and suggests guidelines for clean, readable, and consistent writing of Python code. Following PEP 8 ensures that your code is readable and understandable, especially in team projects.
Now, let’s get into details about PEP 8.
What is the purpose of PEP 8 in python ?
PEP 8 is a set of guidelines for writing clean, readable, and consistent Python code. The purpose is to ensure that code written by different developers looks the same and adheres to a standard, making it easier to read, maintain, and collaborate on.
Major Aims of PEP 8
1. Enhance Code Readability
- Developers can get an overview of the structure and logic of the code without disturbance caused by inconsistent styles, where consistent formatting has been adopted.
2. Promote Standardization
- PEP 8 thus encourages one and only one uniform way of writing Python code. This makes it easier to work in projects with multiple contributors or third-party code.
3. Promote Collaboration
- A common style guide ensures that all team members write code in the same fashion and makes it easier to review and debug and extend.
4. Establish Community Standards
- It establishes a common standard for a programming style in the Python community, educating new users on optimal practices and helping bring them up to par with experienced programmers.
1. Code Layout
a. Indentation
- Use 4 spaces per indentation level.
- Never use tabs for indentation.
- Maintain consistent indentation to improve readability.
def example_function():
if True:
print("Follow PEP 8")
b. Line Length
- Limit all lines to 79 characters (72 characters for comments/docstrings).
- For long lines, you can use line continuation with a backslash or implicit continuation inside parentheses, brackets, or braces.
# Explicit continuation with backslash
total = first_variable + second_variable + third_variable + \
fourth_variable
# Implicit continuation inside parentheses
total = (
first_variable
+ second_variable
+ third_variable
+ fourth_variable
)
c. Blank Lines
- Use blank lines to improve readability:
- Top-level functions and class definitions: separate by two blank lines.
- Inside classes or functions: Separate logic blocks with one blank line.
class MyClass:
def method_one(self):
pass
def method_two(self):
pass
d. Imports
- Put all import statements at the top of the file.
- Order is:
- Standard library imports
- Related third-party library imports
- Local application imports
- Use one import per line.
# Correct
import os
import sys
# Correct
from math import ceil, sqrt
2. Naming Conventions
a. Variables and Functions
- Use lowercase_with_underscores for variables and function names.
def calculate_total():
pass
item_price = 10.5
b. Class Names
- Use CamelCase for class names.
class MyClass:
pass
c. Constants
- Use ALL_CAPS_WITH_UNDERSCORES for constants.
PI = 3.14159
MAX_CONNECTIONS = 100
d. Private Members
- Use a single leading underscore for private methods or variables.
- Use double leading underscores to avoid name clashes in subclasses.
class MyClass:
def _private_method(self):
pass
def __mangled_method(self):
pass
3. Whitespace
a. Avoid Extraneous Whitespace
- No spaces around parentheses, brackets, or braces.
- Use a single space around operators and after commas, colons, and semicolons.
# Correct
spam(ham[1], {eggs: 2})
# Incorrect
spam( ham[ 1 ], { eggs: 2 } )
b. Function and Keyword Arguments
- Do not use spaces around the
=sign in keyword arguments.
# Correct
def function(arg1=None, arg2=42):
pass
# Incorrect
def function(arg1 = None, arg2 = 42):
pass
4. Comments
a. Block Comments
- Use block comments to explain sections of code. Start each line with
#and ensure comments are relevant and up-to-date.
# This function calculates the total price, including tax
def calculate_total(price, tax):
return price + (price * tax)
b. Inline Comments
- Use inline comments sparingly, ensuring they are concise and follow at least two spaces after the code.
x = x + 1 # Increment the counter
c. Docstrings
- Use docstrings to describe modules, classes, and functions.
- Use triple quotes (
""") for multi-line docstrings.
def example_function():
"""This function demonstrates proper docstring usage."""
pass
5. String Quotes
- Use single (
') or double (") quotes consistently.
# Both are correct, but be consistent
message = "Hello, world!"
greeting = 'Hi!'
6. Comparisons
- Use
isandis notwhen comparing toNone. - Use
==and!=for value comparisons.
# Correct
if value is None:
pass
# Incorrect
if value == None:
pass
7. Avoid Trailing Characters
- Remove trailing whitespace and avoid leaving blank lines with spaces.
8. When to Break the Rules
PEP 8 is not a rule; it is more of a guideline. It is quite acceptable to ignore it when:
- Following the rule reduces code readability.
- The project has its own style guide.