1.1 Python 哲學與設計理念
1.1 Python 哲學與設計理念
在學習任何程式語言之前,了解其設計理念能幫助你寫出更符合語言風格的程式碼。Python 有一套廣為人知的設計原則,被稱為「Python 之禪」。
Python 之禪
在 Python 直譯器中輸入 import this,你會看到 Python 的設計原則:
1>>> import this
2The Zen of Python, by Tim Peters
3
4Beautiful is better than ugly.
5Explicit is better than implicit.
6Simple is better than complex.
7Complex is better than complicated.
8Flat is better than nested.
9Sparse is better than dense.
10Readability counts.
11...實踐中的 Python 哲學
顯式優於隱式(Explicit is better than implicit)
在 Hook 系統中,我們明確導入需要的函式,而不是使用 import *:
1# 好的做法:明確導入
2from lib.hook_io import read_hook_input, write_hook_output
3from lib.git_utils import get_current_branch
4
5# 不好的做法:隱式導入所有
6from lib.hook_io import * # 不知道導入了什麼可讀性很重要(Readability counts)
函式和變數命名要清楚表達用途:
1# 好的命名:一看就懂
2def get_current_branch() -> Optional[str]:
3 """獲取當前分支名稱"""
4 success, output = run_git_command(["branch", "--show-current"])
5 return output if success and output else None
6
7# 不好的命名:需要猜測
8def gcb():
9 s, o = rgc(["branch", "--show-current"])
10 return o if s and o else None簡單優於複雜(Simple is better than complex)
Hook 系統使用簡單的 (bool, str) 返回值模式:
1def run_git_command(args: list[str]) -> tuple[bool, str]:
2 """
3 執行 git 命令並返回結果
4
5 Returns:
6 tuple[bool, str]: (是否成功, 輸出內容或錯誤訊息)
7 """
8 try:
9 result = subprocess.run(
10 ["git"] + args,
11 capture_output=True,
12 text=True,
13 )
14 if result.returncode == 0:
15 return True, result.stdout.strip()
16 else:
17 return False, result.stderr.strip()
18 except Exception as e:
19 return False, str(e)這個設計比拋出異常更直觀,呼叫者可以用簡單的 if 來處理:
1success, output = run_git_command(["status"])
2if success:
3 print(output)
4else:
5 print(f"Error: {output}")扁平優於巢狀(Flat is better than nested)
避免過深的巢狀結構:
1# 不好:過深的巢狀
2def check_file(path):
3 if path:
4 if path.exists():
5 if path.suffix == '.py':
6 if path.stat().st_size > 0:
7 return True
8 return False
9
10# 好:使用 early return
11def check_file(path):
12 if not path:
13 return False
14 if not path.exists():
15 return False
16 if path.suffix != '.py':
17 return False
18 if path.stat().st_size <= 0:
19 return False
20 return True「Pythonic」的含義
當我們說程式碼是「Pythonic」時,意思是它遵循 Python 的慣例和風格。以下是一些例子:
使用 List Comprehension
1# Pythonic
2squares = [x**2 for x in range(10)]
3
4# 非 Pythonic
5squares = []
6for x in range(10):
7 squares.append(x**2)使用上下文管理器
1# Pythonic
2with open(file_path, "r", encoding="utf-8") as f:
3 content = f.read()
4
5# 非 Pythonic
6f = open(file_path, "r", encoding="utf-8")
7content = f.read()
8f.close() # 容易忘記關閉使用 enumerate 而非 range(len())
1# Pythonic
2for i, item in enumerate(items):
3 print(f"{i}: {item}")
4
5# 非 Pythonic
6for i in range(len(items)):
7 print(f"{i}: {items[i]}")實際範例:Hook 系統的設計體現
來自 .claude/lib/hook_io.py 的設計展示了這些原則:
1def write_hook_output(
2 output: dict,
3 ensure_ascii: bool = False,
4 indent: int = 2
5) -> None:
6 """
7 輸出 Hook 結果到 stdout
8
9 Args:
10 output: 要輸出的字典
11 ensure_ascii: 是否確保 ASCII 編碼(預設 False 以支援中文)
12 indent: JSON 縮排空格數
13 """
14 print(json.dumps(output, ensure_ascii=ensure_ascii, indent=indent))這個函式體現了:
- 顯式參數:每個參數都有預設值和明確的型別提示
- 文件字串:清楚說明函式用途和參數意義
- 單一職責:函式只做一件事 - 輸出 JSON
思考題
- 為什麼
ensure_ascii=False是預設值? - Hook 系統為什麼選擇返回
tuple[bool, str]而不是拋出異常? - 閱讀
.claude/lib/git_utils.py,找出三個體現 Python 哲學的設計選擇。
延伸閱讀
下一章:模組與套件組織