一、命名清晰:見名知意
✅ 變量/函數/類名要有意義
# ❌ 差
d = {'a': 1, 'b': 2}
def calc(x, y):
return x * y
# ✅ 好
user_scores = {'Alice': 95, 'Bob': 88}
def calculate_area(length, width):
return length * width
✅ 遵循命名約定
- 變量/函數:
snake_case(小寫+下劃線) - 類名:
PascalCase - 常量:
UPPER_SNAKE_CASE - 私有成員:
_leading_underscore
二、善用空行與空格:視覺分隔
✅ 函數/類之間用兩個空行
✅ 邏輯塊之間用一個空行
✅ 操作符兩側加空格
def process_data(items):
cleaned_items = []
for item in items:
if item.is_valid():
cleaned_items.append(item.normalize())
return sorted(cleaned_items, key=lambda x: x.timestamp)
class UserManager:
MAX_RETRY_COUNT = 3
def __init__(self):
self.users = []
三、避免過長的行和複雜表達式
✅ 每行不超過 79~88 個字符(PEP 8 推薦 79)
✅ 拆分複雜邏輯
# ❌ 難讀
if user.age >= 18 and user.has_verified_email() and not user.is_banned and user.country in ALLOWED_COUNTRIES:
# ✅ 清晰
is_adult = user.age >= 18
has_valid_email = user.has_verified_email()
not_banned = not user.is_banned
from_allowed_country = user.country in ALLOWED_COUNTRIES
if is_adult and has_valid_email and not_banned and from_allowed_country:
grant_access(user)
四、使用列表推導式(但別過度)
✅ 簡潔場景用推導式
# ✅ 好
squares = [x**2 for x in range(10) if x % 2 == 0]
❌ 嵌套太深或邏輯複雜時,改用普通循環
# ❌ 難維護
result = [
transform(x)
for sublist in data
for x in sublist
if x > 0 and check(x) and another_check(x)
]
# ✅ 改為循環更清晰
result = []
for sublist in data:
for x in sublist:
if x > 0 and check(x) and another_check(x):
result.append(transform(x))
五、函數要“單一職責”
✅ 一個函數只做一件事
✅ 函數長度儘量短(< 20 行)
# ❌ 太多職責
def process_order(order):
validate(order)
charge_payment(order)
send_email(order)
update_inventory(order)
log_activity(order)
# ✅ 拆分後主流程清晰
def process_order(order):
validate_order(order)
charge_customer(order)
notify_customer(order)
update_stock(order)
log_order_event(order)
六、合理添加註釋和文檔字符串
✅ 註釋解釋“為什麼”,而不是“做什麼”(代碼應自解釋)
✅ 函數使用 docstring
def binary_search(arr, target):
"""
在已排序數組中查找目標值的索引。
Args:
arr (list): 升序排列的整數列表
target (int): 要查找的值
Returns:
int or None: 找到返回索引,否則返回 None
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return None
💡 小技巧:用
"""寫多行字符串作為函數説明,IDE 和help()都能識別。
七、利用類型提示(Type Hints,Python 3.5+)
✅ 提高可讀性和 IDE 支持
from typing import List, Optional
def find_user_by_id(user_id: int, users: List[dict]) -> Optional[dict]:
for user in users:
if user.get('id') == user_id:
return user
return None
即使不運行類型檢查,類型提示也能讓代碼意圖一目瞭然。
八、遵循 PEP 8 規範
PEP 8 是 Python 官方代碼風格指南。關鍵點包括:
- 縮進用 4 個空格(不是 tab)
- 模塊名小寫(
my_module.py) - 避免一行多個語句(用分號隔開)
- 導入分組並按標準庫、第三方、本地順序排列
工具推薦:
black:自動格式化代碼(強烈推薦!)flake8或pylint:檢查風格和潛在錯誤
pip install black
black your_script.py # 自動美化代碼
九、用好內置函數和標準庫
✅ 避免重複造輪子
# ✅ 好
total = sum(numbers)
max_val = max(data)
unique_items = set(items)
# ❌ 不必要地手寫
total = 0
for n in numbers:
total += n
十、寫可讀的條件和布爾表達式
✅ 正向邏輯優先
# ✅ 清晰
if user.is_active:
send_notification(user)
# ❌ 雙重否定難理解
if not user.is_inactive:
...
✅ 提前返回(early return)減少嵌套
def process_request(req):
if not req.is_valid():
return error_response("Invalid request")
if not user_exists(req.user_id):
return error_response("User not found")
# 主邏輯在這裏,無深層縮進
return handle_valid_request(req)