Python 的最佳實踐
本文章會說明在 Python 中的最佳實踐方法。
我們將透過實際代碼示例說明 Python 的最佳實踐,介紹如何撰寫可讀性與可維護性高的程式碼。
YouTube Video
Python 的最佳實踐
將可讀性放在第一優先
首先,來看看「把可讀性作為首要目標」。
Python 是一個十分重視「可讀性」的語言。首先,優先撰寫一眼就能明瞭意圖的代碼。
1# Bad example: unclear variable names
2a = 10
3b = 5
4c = a * b在這段程式碼中,變數名稱無法傳達其意義,導致之後他人閱讀時需要花時間才能理解。
1# Good example: descriptive variable names
2price = 10
3quantity = 5
4total_cost = price * quantity透過具體明確的變數名稱,你的程式碼本身就可以當作文件。
撰寫明確的程式碼
接下來,看一下「撰寫明確的程式碼」。
在 Python 中,「明確的意圖」優於「隱含的行為」。
1# Bad example: implicit truthy check
2if data:
3 process(data)在這段程式碼中,無法明確知道 data 應該是什麼,這很容易產生潛在的錯誤。
1# Good example: explicit condition
2if len(data) > 0:
3 process(data)透過明確的條件表達,程式碼的意圖就能與規格一致。
讓函式保持精簡並專注於單一職責
接下來,看一下「讓函式精簡並專注於單一職責」。
當一個函式做太多事情時,測試與維護都會變得困難。
1# Bad example: doing too many things
2def handle_user(user):
3 save_to_database(user)
4 send_email(user)
5 write_log(user)在這段程式碼中,各個處理步驟彼此緊密耦合,導致很難重複使用及修改。
1# Good example: single responsibility
2def save_user(user):
3 save_to_database(user)
4
5def notify_user(user):
6 send_email(user)
7
8def log_user(user):
9 write_log(user)透過拆分函式,每個角色變得明確,測試也更加容易。
積極使用型別提示(Type Hints)
接下來,看一下「主動使用型別提示」。
型別提示既是文件也是防止錯誤的有力工具。
1# Bad example: Without type hints
2def add(a, b):
3 return a + b在這段程式碼中,參數及回傳值的型別不明確,容易造成誤用。
1# Good example: With type hints
2def add(a: int, b: int) -> int:
3 return a + b使用型別提示後,IDE 補全、靜態分析與可讀性都會大幅提升。
明確標示可能回傳 None 的情況
接下來,看一下「明確告知可能回傳 None 的情況」。
那些可能回傳 None 的函式,常常被使用者忽略這點。
1# Bad example: Ambiguous return value
2def find_user(user_id):
3 if user_id == 1:
4 return {"id": 1, "name": "Alice"}
5 return None在這段程式碼中,是否有回傳值並不明確。
1# Good example: explicit return type
2from typing import Optional, Dict, Any
3
4def find_user(user_id: int) -> Optional[Dict[str, Any]]:
5 if user_id == 1:
6 return {"id": 1, "name": "Alice"}
7 return None透過使用 Optional,可以將回傳 None 的可能性做為型別表示出來。
請勿過度廣泛地捕捉例外狀況
接下來,看一下「避免過度捕捉例外」。
例外處理基本上應該只捕捉必要的情況。
1# Bad example: catching all exceptions
2try:
3 result = int(value)
4except Exception:
5 result = 0這段程式碼可能會隱藏本應被發現的錯誤。
1# Good example: catch specific exception
2try:
3 result = int(value)
4except ValueError:
5 result = 0限制例外捕捉的範圍,才能避免忽略掉未預期的問題。
使用 with 陳述式安全地管理資源
接下來,看一下「使用 with 陳述式安全管理資源」。
像是檔案、鎖等資源,一定要能夠確實釋放。
1# Bad example: manual close
2file = open("data.txt")
3content = file.read()
4file.close()在這段範例中,若發生例外,close() 可能不會被呼叫。
1# Good example: using context manager
2with open("data.txt") as file:
3 content = file.read()使用 with 陳述式,即使發生例外情況,也能安全完成收尾動作。
適當地使用列表生成式(List Comprehension)
接下來,看一下「適當使用列表生成式」。
簡單的轉換處理,可以用列表生成式簡潔地撰寫。
1# Bad example: Verbose loop
2squares = []
3for i in range(10):
4 squares.append(i * i)在這段程式碼中,核心處理不易看出。
1# Good example: Clear list comprehension
2squares = [i * i for i in range(10)]適當使用列表生成式可以提升程式碼的可讀性。
避免魔術數字(Magic Numbers)
接下來,看一下「避免使用魔術數字」。
直接寫數值或字串會讓其意義變得不明確。
1# Bad example: magic number
2if status == 404:
3 handle_not_found()在這段程式碼中,假設你已經知道 404 的意思。
1# Good example: named constant
2NOT_FOUND = 404
3
4if status == NOT_FOUND:
5 handle_not_found()為其命名能讓意圖變得明確。
撰寫可維護的程式碼,而不只是「能跑就好」的程式碼
最後來看看「撰寫可維護,而不只是可運作的程式碼」。
重點在於你未來的自己或其他人是否能夠懂得這段程式碼。
1# Bad example: Hard to maintain
2def f(x):
3 return x * 1.08 + 100在這段程式碼中,從程式碼看不出任何規格。
1# Good example: Easy to maintain
2TAX_RATE = 1.08
3BASE_FEE = 100
4
5def calculate_total(price: float) -> float:
6 return price * TAX_RATE + BASE_FEE透過名稱來表現其含意,使程式碼本身成為規格說明。
總結
Python 的最佳實踐就是「寫容易懂的程式碼,而不是炫技的程式碼」。養成這些小習慣能讓你的程式碼更少出錯也更長久可用。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。