1. What Is PEP 8
PEP stands for Python Enhancement Proposal; in Chinese, it is usually called “Python Enhancement Proposal.” It is a proposal mechanism used by the Python community to discuss, document, and standardize the development of the Python language and its ecosystem.
The full name of PEP 8 is:
PEP 8 — Style Guide for Python Code
It was developed with input from Guido van Rossum, Barry Warsaw, Nick Coghlan, and others, and is a code style guide widely adopted by the Python community.
The core goal of PEP 8 is not to change the execution logic of programs, but to make code written by different developers follow a similar organizational style, making the code easier to read, understand, review, and maintain.
For example, the following two code snippets implement exactly the same functionality:
def calculate_total(price,quantity):
return price*quantity
def calculate_total(price, quantity):
return price * quantity
The second style is more compliant with PEP 8:
- Spaces are used between function parameters.
- Spaces are used on both sides of operators.
- The code layout is clearer.
- It is easier for different developers to form consistent reading habits.
PEP 8 is not a syntax rule enforced by the Python interpreter, but a set of recommended coding conventions.
2. Core Design Principles of PEP 8
PEP 8 does not require all code to follow a rigid format; instead, it emphasizes consistency and readability in code style.
2.1 Readability First
Python's design philosophy emphasizes that code should be easy to read.
For example:
# Not recommended
x=price*quantity+tax
# Recommended
total_price = price * quantity + tax
The second style makes the business meaning conveyed by the code clearer through reasonable variable naming and spacing.
2.2 Consistency First
Within the same project, try to use consistent naming conventions, indentation rules, import order, and code formatting.
For example, a project should not contain all of the following at the same time:
def get_user_info():
pass
def GetUserInfo():
pass
def getUserInfo():
pass
It is recommended to consistently name functions using lowercase letters and underscores:
def get_user_info():
pass
def get_order_info():
pass
2.3 Do Not Sacrifice Readability Just to Follow the Rules
PEP 8 also emphasizes that the style guide is not an absolute set of rules.
When following a certain rule makes the code harder to read, you can make reasonable adjustments based on the actual situation.
For example:
result = (
first_value
+ second_value
+ third_value
)
Although this style adds line breaks, it is easier to understand than writing the entire complex expression on one line.
3. Indentation Guidelines
Python uses indentation to denote code blocks, so indentation not only affects code style but also directly affects program syntax.
3.1 Use Four Spaces for Indentation
PEP 8 recommends using four spaces for each indentation level.
def calculate_discount(price):
if price >= 100:
discount = 0.9
return price * discount
return price
Mixing tabs and spaces for indentation is not recommended:
def calculate_discount(price):
if price >= 100:
discount = 0.9
return price * discount
The code above may look similar visually, but if indentation characters are mixed, it may cause TabError or other indentation problems.
It is recommended to enable the following in your editor:
- Pressing Tab inserts four spaces.
- Show invisible characters.
- Automatically detect mixed indentation.
- Automatically format indentation.
3.2 Indentation of Multiline Expressions
When function parameters, lists, or expressions need to be wrapped across lines, keep the structure clear.
It is recommended to use parentheses for implicit line continuation:
result = calculate_total(
price,
quantity,
discount,
)
For multiline function calls, hanging indentation may be used:
def create_user(
username,
email,
password,
):
return {
"username": username,
"email": email,
}
You can also align arguments with the opening parenthesis:
result = calculate_total(
price,
quantity,
discount,
)
The key is to make the hierarchical relationship between parameters and expressions clear.
3.3 Indentation in Control Structures
The code blocks of statements such as if, for, while, and try should consistently use four-space indentation.
for user in users:
if user.is_active:
send_notification(user)
else:
log_inactive_user(user)
Packing multiple statements onto a single line is not recommended:
if user.is_active: send_notification(user)
Although some simple statements are syntactically allowed to be written this way, it reduces readability and makes later extension harder.
4. Line Length Conventions
4.1 Maximum Line Length
The traditional PEP 8 recommendation is:
- Regular code lines: no more than 79 characters.
- Docstrings and comments: no more than 72 characters.
This is a recommended convention, not a Python syntax restriction.
Modern projects also often use 88, 100, or 120 characters according to team agreement.
For example:
# Line too long
result = calculate_discounted_price(original_price, discount_rate, tax_rate, shipping_fee)
# Recommended split
result = calculate_discounted_price(
original_price,
discount_rate,
tax_rate,
shipping_fee,
)
4.2 Using Parentheses to Split Long Expressions
For complex expressions, prefer parentheses to lay out multiple lines:
total = (
product_price
+ shipping_fee
+ service_fee
- discount
)
For long conditional expressions:
if (
user.is_active
and user.has_permission
and user.account_balance > 0
):
process_order(user)
4.3 Do Not Use Backslashes for Unnecessary Line Continuation
Not recommended:
total = price + \
shipping_fee + \
tax
Recommended:
total = (
price
+ shipping_fee
+ tax
)
Parenthesized continuation is more intuitive and easier to maintain.
5. Spacing Conventions
Spacing is an important part of Python code layout.
5.1 Spaces on Both Sides of Operators
It is recommended to add spaces on both sides of assignment, comparison, arithmetic, and logical operators.
# Recommended
total = price + tax
is_valid = age >= 18
result = (a + b) * c
Not recommended:
total=price+tax
is_valid=age>=18
result=(a+b)*c
5.2 The Equals Sign in Function Arguments
Ordinary function calls and default parameters follow different layout rules.
Recommended:
def create_user(username, age=18):
pass
create_user("Alice", age=20)
Not recommended:
def create_user(username, age = 18):
pass
create_user("Alice", age = 20)
For default parameter assignment, no spaces are added on either side of the equals sign.
However, when a type annotation is present, the normal assignment spacing rules still apply:
def create_user(
username: str,
age: int = 18,
):
pass
5.3 Commas, Colons, and Semicolons
A space is usually added after a comma; colons in dictionaries and slices follow their respective rules.
# List
users = ["Alice", "Bob", "Charlie"]
# Dictionary
user = {
"name": "Alice",
"age": 20,
}
# Slicing
numbers = [1, 2, 3, 4, 5]
result = numbers[1:4]
Not recommended:
users = ["Alice","Bob","Charlie"]
user = {"name":"Alice","age":20}
5.4 Avoid Unnecessary Spaces
Not recommended:
user [ "name" ] = "Alice"
function_call ( value )
Recommended:
user["name"] = "Alice"
function_call(value)
5.5 Do not add trailing whitespace
Trailing whitespace usually has no real meaning and can create noise in code reviews.
Use an editor or formatting tool to clean it up automatically.
6. Naming Conventions
PEP 8 recommends different naming styles for different types of program elements.
6.1 Variable names: snake_case
Variables use all lowercase letters, with words joined by underscores.
user_name = "Alice"
total_price = 199.9
order_count = 10
Not recommended:
userName = "Alice"
TotalPrice = 199.9
orderCount = 10
6.2 Function names: snake_case
Function names likewise use lowercase letters and underscores.
def calculate_total():
pass
def get_user_info():
pass
def send_email():
pass
A function name should reflect its behavior or return value as much as possible.
6.3 Class names: PascalCase
Class names use PascalCase, meaning the first letter of each word is capitalized.
class UserAccount:
pass
class PaymentService:
pass
class OrderManager:
pass
Not recommended:
class user_account:
pass
class payment_service:
pass
6.4 Constant names: UPPER_SNAKE_CASE
Constants typically use all uppercase letters, with words joined by underscores.
MAX_RETRY_COUNT = 3
DEFAULT_TIMEOUT = 30
DATABASE_URL = "sqlite:///app.db"
Note that Python does not automatically prevent reassignment just because a name is all uppercase.
MAX_RETRY_COUNT = 3
MAX_RETRY_COUNT = 5
The second assignment is still syntactically valid. The constant convention mainly serves to express the developer's intent.
6.5 Internal variables and methods: single underscore
A name starting with a single underscore usually indicates that the member is an internal implementation detail.
class UserService:
def __init__(self):
self._cache = {}
def _load_user(self, user_id):
return self._cache.get(user_id)
A single underscore is not a strict access control mechanism; it is a convention.
6.6 Name mangling: double underscore
A double-underscore prefix in a class triggers name mangling.
class User:
def __init__(self):
self.__password = "secret"
The attribute name is rewritten to something like:
_User__password
This mechanism mainly avoids attribute name conflicts in subclasses; it is not true private access control.
6.7 Special methods: surrounded by double underscores
Python special methods generally use a naming form with double underscores at both ends, also known as dunder methods.
class User:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return f"User(name={self.name!r})"
Common special methods include:
| Method | Purpose |
|---|---|
__init__ |
Initialize an instance |
__str__ |
Provide a user-facing string representation |
__repr__ |
Provide a developer-facing object representation |
__len__ |
Define length behavior |
__iter__ |
Define iteration behavior |
__getitem__ |
Define index access behavior |
__enter__ |
Define context manager entry behavior |
__exit__ |
Define context manager exit behavior |
Do not casually invent special method names that conflict with Python language protocols.
6.8 Summary of naming conventions
| Object | Recommended style | Example |
|---|---|---|
| Variable | snake_case | user_name |
| Function | snake_case | get_user() |
| Method | snake_case | save_data() |
| Class | PascalCase | UserAccount |
| Constant | UPPER_SNAKE_CASE | MAX_SIZE |
| Module | snake_case | user_service.py |
| Package | short lowercase name | utils |
| Internal member | _name |
_cache |
| Name-mangled member | __name |
__password |
| Special method | __name__ |
__init__ |
7. Module and Import Conventions
7.1 Place import statements at the top of the file
Module imports are usually placed at the very top of the file, after the module docstring and before global variables and other code.
Recommended:
"""User management module."""
import os
import json
from pathlib import Path
def load_config():
pass
7.2 Import grouping
PEP 8 recommends organizing imports in the following order:
- Standard library.
- Third-party libraries.
- Internal modules of the current project.
Leave one blank line between different groups.
import json
import os
from pathlib import Path
import requests
from flask import Flask
from app.models import User
from app.services import UserService
7.3 Avoid wildcard imports
Not recommended:
from math import *
Recommended:
from math import ceil, floor, sqrt
You can also import the module directly:
import math
result = math.sqrt(16)
Wildcard imports can make it unclear where names come from and may also overwrite other names in the current namespace.
7.4 Prefer absolute imports
Recommended:
from app.services.user_service import UserService
For modules with a clear internal package structure, explicit relative imports can also be used appropriately:
from .user_service import UserService
Relying excessively on complex multi-level relative imports is not recommended:
from ....services.user_service import UserService
7.5 Do not compress imports just to reduce line count
Recommended:
import os
import sys
import json
Rather than:
import os, sys, json
Writing each import statement separately makes code review and later modifications easier.
8. Blank Lines and Code Organization
8.1 Use two blank lines between top-level functions and classes
import os
def load_config():
pass
def save_config():
pass
class UserService:
pass
8.2 Use one blank line between methods within a class
class UserService:
def create_user(self):
pass
def delete_user(self):
pass
def update_user(self):
pass
8.3 Leave reasonable blank lines between logical sections
def process_order(order):
validate_order(order)
calculate_total(order)
save_order(order)
return order
Blank lines help developers recognize logical groupings in code, but you should not insert a large number of meaningless blank lines just for layout.
IX. String and Quote Conventions
9.1 Both single and double quotes are acceptable
PEP 8 does not require strings to use single or double quotes.
Both of the following are valid:
name = "Alice"
city = 'Tokyo'
More importantly, be consistent within the same project.
9.2 Choose quotes based on string content
If a string contains a single quote, you can use double quotes to reduce escaping.
message = "It's a beautiful day."
If a string contains double quotes, you can use single quotes:
message = 'He said "Hello".'
9.3 Docstrings usually use triple double quotes
Recommended:
def calculate_total(price, quantity):
"""Calculate the total price of the products."""
return price * quantity
Multi-line docstring:
def create_user(username, email):
"""
Create a user.
Args:
username: Username.
email: User email address.
Returns:
The newly created user object.
"""
pass
9.4 Use f-strings to format strings
Where applicable, use f-strings to improve readability.
username = "Alice"
age = 20
message = f"{username} is {age} years old."
Complex string concatenation is not recommended:
message = username + " is " + str(age) + " years old."
X. Comment and Docstring Conventions
10.1 Comments should explain why, not repeat the code
Not recommended:
# Set age to 18
age = 18
Recommended:
# When no age is provided, use the default adult age according to business rules.
age = 18
Comments should explain business context, design rationale, constraints, and non-obvious logic.
10.2 Use complete, clear wording in comments
# Retry the request when the remote service is temporarily unavailable.
For Chinese-language projects, Chinese comments can also be used consistently:
# When the remote service is temporarily unavailable, retry at most three times.
Within a project, keep the comment language and style consistent.
10.3 Use inline comments sparingly
Recommended:
timeout = 30 # Request timeout in seconds
Not recommended:
timeout = 30 # timeout
Inline comments should be separated from the code by at least two spaces.
10.4 Write docstrings for public APIs
def calculate_discount(price, discount_rate):
"""
Calculate the discounted price.
Args:
price: Original price of the item.
discount_rate: Discount rate, ranging from 0 to 1.
Returns:
The discounted price.
"""
return price * (1 - discount_rate)
Docstrings can describe:
- The purpose of the function or class.
- The meaning and types of parameters.
- The meaning of the return value.
- Exceptions that may be raised.
- Usage restrictions and side effects.
PEP 257 is a proposal dedicated to Python docstring conventions and complements PEP 8.
XI. Comparison and Conditional Expression Conventions
11.1 Use is when comparing with None
Recommended:
if user is None:
print("用户不存在")
Not recommended:
if user == None:
print("用户不存在")
None is a singleton object, so to check whether something is None, you should use the identity comparison operator is.
11.2 When Comparing with Booleans, Prefer Direct Truth Checks
Recommended:
if is_active:
activate_user()
Not recommended:
if is_active == True:
activate_user()
If you need to explicitly check whether an object is the boolean value True, you can write:
if is_active is True:
activate_user()
But most business logic checks do not need to be written this way.
11.3 Use Collections to Test Multiple Candidate Values
Not recommended:
if status == "pending" or status == "processing" or status == "completed":
pass
Recommended:
if status in {"pending", "processing", "completed"}:
pass
Collection-based checks reduce repeated expressions and make conditions more concise.
11.4 Avoid Unnecessary Boolean Conversions
Not recommended:
if len(users) > 0:
process_users(users)
Recommended:
if users:
process_users(users)
Python containers have inherent truth-value testing: empty lists, empty dictionaries, and empty sets are all treated as false values.
Note, however, that you should not casually omit explicit checks in every scenario. For example, the number 0, an empty string, and None may carry different business meanings.
12. Exception Handling and Code Style
PEP 8 also addresses the readability of exception handling.
12.1 Catch Specific Exceptions
Not recommended:
try:
result = 10 / value
except:
result = 0
Recommended:
try:
result = 10 / value
except ZeroDivisionError:
result = 0
Catching specific exceptions helps avoid accidentally hiding other errors in the program.
12.2 Do Not Catch Exceptions Pointlessly
Not recommended:
try:
save_data()
except Exception:
pass
This style swallows errors and makes problems hard to troubleshoot when they occur.
If you truly need to catch an exception, you should log it, convert it, or handle it appropriately:
try:
save_data()
except OSError as exc:
logger.error("保存数据失败:%s", exc)
raise
12.3 Use finally to Manage Cleanup Logic
file = None
try:
file = open("data.txt", encoding="utf-8")
content = file.read()
finally:
if file is not None:
file.close()
For resources such as files, context managers are preferred:
with open("data.txt", encoding="utf-8") as file:
content = file.read()
This makes resource-release logic more concise.
13. Type Annotations and PEP 8
PEP 8 itself is not a type system specification, but type annotations also need to follow consistent formatting conventions.
13.1 Type Annotations for Function Parameters
def calculate_total(
price: float,
quantity: int,
) -> float:
return price * quantity
Do not put a space between the parameter name and the colon; add one space between the colon and the type.
13.2 Variable Type Annotations
username: str = "Alice"
age: int = 20
is_active: bool = True
13.3 Return Type Annotations
def get_user_name(user_id: int) -> str:
return "Alice"
Return value annotations use ->, with one space on each side of the arrow.
13.4 Complex Type Annotations
def get_user_roles(
user_id: int,
) -> list[str]:
return ["admin", "editor"]
For more complex types, you can use type aliases to improve readability:
UserRecord = dict[str, str | int]
def get_user(user_id: int) -> UserRecord:
return {
"name": "Alice",
"age": 20,
}
Type annotations are mainly intended to improve code comprehensibility and support static analysis; they do not mean that the Python runtime will automatically enforce all types.
14. The Relationship Between PEP 8 and Other PEPs
The Python ecosystem contains a large number of PEPs, with different proposals governing different areas of the specification.
| PEP | Name | Main Purpose |
|---|---|---|
| PEP 8 | Style Guide for Python Code | Code style guidelines |
| PEP 20 | The Zen of Python | Python design philosophy |
| PEP 257 | Docstring Conventions | Docstring conventions |
| PEP 484 | Type Hints | Type annotation system |
| PEP 526 | Syntax for Variable Annotations | Variable annotation syntax |
| PEP 585 | Type Hinting Generics In Standard Collections | Generic annotations in standard collection types |
| PEP 604 | Allow writing union types as X | Y | Union type syntax |
| PEP 695 | Type Parameter Syntax | Type parameter syntax |