以下是根据 PEP 8 编码规范 提供的详细说明,并附上代码示例,帮助你更好地理解如何在实际开发中应用这些规范。
🧱 一、代码布局(Code Layout)
1.1 缩进(Indentation)
- 使用 4个空格 进行缩进,不要使用 Tab 键。
- 同一逻辑层级的代码保持相同缩进。
def greet(name):
print("Hello, " + name) # 正确:4个空格缩进
❌ 错误示例(混合使用 Tab 和空格):
def greet(name):
print("Hello, " + name) # 错误:使用了 Tab 缩进
1.2 最大行长度(Maximum Line Length)
- 每行不超过 79个字符。
- 注释和文档字符串建议不超过 72个字符。
- 长行可通过括号进行隐式换行。
# 正确:使用括号自动换行
result = (long_function_name(arg1, arg2, arg3, arg4)
+ another_long_function_name())
# 正确:使用反斜杠显式换行(不推荐)
result = long_function_name(arg1, arg2, \
arg3, arg4)
1.3 空行(Blank Lines)
- 顶层函数和类之间用两个空行隔开。
- 类中的方法之间用一个空行隔开。
- 函数内部逻辑段落之间可用空行分隔。
def func1():
pass
def func2():
pass
class MyClass:
def method1(self):
pass
def method2(self):
pass
1.4 导入(Imports)
- 每个导入语句单独一行。
- 按顺序:标准库 → 第三方库 → 本地库。
- 不要使用
from module import *。
import os
import sys
from flask import Flask
from requests import get
from mymodule import my_function
📝 二、命名约定(Naming Conventions)
2.1 包和模块名(Packages and Modules)
- 全部小写,不使用下划线(除非必要)。
- 简短,有意义。
# 文件名:utils.py
2.2 类名(Class Names)
- 使用 CapWords(首字母大写)。
class Person:
pass
class Student(Person):
pass
2.3 函数、方法和变量名(Function, Method, Variable Names)
- 使用 小写字母 + 下划线 分隔。
def calculate_total_price():
total_price = 0
return total_price
2.4 常量(Constants)
- 全部大写,单词用下划线分隔。
MAX_CONNECTIONS = 100
DEFAULT_TIMEOUT = 30
2.5 私有属性和方法(Private Names)
- 使用 单下划线前缀 表示“内部使用”。
class MyClass:
def __init__(self):
self._internal_value = 42 # 私有属性
def _helper(self):
pass # 私有方法
🔢 三、表达式与语句(Expressions and Statements)
3.1 空格(Whitespace)
- 在运算符周围添加空格(
=、==、+等)。 - 不在括号、逗号后加空格。
# 正确
x = 5
y = x + 2
if x == 5:
pass
# 错误
x=5
y=x+2
if(x ==5):
pass
3.2 复杂表达式(Complex Expressions)
- 长表达式建议拆分,提高可读性。
# 拆分多个条件
if (some_long_condition and
another_long_condition and
yet_another_condition):
do_something()
3.3 列表推导式(List Comprehensions)
- 保持简洁,避免嵌套太深。
squares = [x**2 for x in range(10)] # 正确
❌ 不推荐:
results = [x for x in data if x % 2 == 0 if x > 10 if x < 100] # 太复杂
💬 四、注释(Comments)
4.1 块注释(Block Comments)
- 位于代码上方,与代码同缩进。
# Calculate total price with tax
total_price = price * (1 + tax_rate)
4.2 行内注释(Inline Comments)
- 与代码在同一行,至少两个空格分隔。
x = 0 # Initialize counter
4.3 文档字符串(Docstrings)
- 所有公共模块、函数、类、方法都应有文档字符串。
- 使用三引号
""",并以句号结尾。
def greet(name):
"""Greet the user with a personalized message."""
print(f"Hello, {name}")
🧠 五、编程建议(Programming Recommendations)
5.1 使用 is 或 is not 比较 None
- 不要用
== None。
# 正确
if value is None:
pass
# 错误
if value == None:
pass
5.2 不要在循环头中赋值
- 不要在
for或while的头部进行赋值操作。
# 正确
for i in range(10):
print(i)
# 错误(不推荐)
for line in (lines = get_lines()):
print(line)
5.3 尽量避免使用可变默认参数
- 默认参数应为不可变对象。
# 错误
def add_item(item, lst=[]):
lst.append(item)
return lst
# 正确
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
✅ 总结
| 类别 | 规范要点 | 示例代码 |
|---|---|---|
| 缩进 | 使用4个空格 | def f():<br> pass |
| 行长度 | 每行不超过79字符 | 使用括号或反斜杠 |
| 空行 | 顶层函数类之间2空行,类方法之间1空行 | 见示例 |
| 导入 | 每个import一行,按顺序导入 | import os |
| 命名 | 小写+下划线(变量/函数),CapWords(类) | my_function, MyClass |
| 注释 | 块注释在上,行内注释在后,两个空格分隔 | # 注释 |
| 文档字符串 | 三引号,一句话概括 | """说明""" |
| 空格 | 运算符前后空格,括号内无空格 | x = y + 1 |
| None比较 | 使用 is None | if x is None: |
| 可变默认参数 | 不要使用可变类型作为默认参数 | def f(x=None): |
如需自动化格式化代码,可使用:
autopep8(命令行)black(更严格)- IDE 插件(如 VS Code 的 Pylance、Flake8、Black)
如需进一步学习,可访问:
🔗 PEP 8 官方文档


5456

被折叠的 条评论
为什么被折叠?



