Python 型別提示 (Type Hints):讓程式碼更健壯 (第 21 章)

站主自己的課程,請大家支持
揭秘站長的架站心法:如何利用 Hugo × AI 打造高質感個人品牌網站? 揭秘站長的架站心法:如何利用 Hugo × AI 打造高質感個人品牌網站?
  • Post by
  • Jan 04, 2024
post-thumb

Python 自 3.5 版本引入 Type Hints (型別提示) 後,徹底改變了現代 Python 開發的面貌。雖然 Python 依然是動態語言 (執行期不會強制檢查型別),但加上型別提示能帶來巨大的好處:

  1. IDE 支援:VS Code 或 PyCharm 能提供精準的自動補全。
  2. 減少 Bug:透過靜態檢查工具 (如 mypy),在程式執行前就能發現型別錯誤。
  3. 即時文件:看一眼函式簽章 (Signature) 就知道參數該傳什麼。

1. 基礎語法

使用冒號 : 標記變數型別,使用箭頭 -> 標記回傳值型別。

# 傳統寫法
def greet(name):
    return "Hello, " + name

# 加上型別提示
def greet(name: str) -> str:
    return "Hello, " + name

# 變數宣告
age: int = 25
is_student: bool = True

2. 容器型別 (List, Dict, Tuple)

在 Python 3.9+,可以直接使用內建容器型別。如果是舊版本,需從 typing 模組匯入。

# Python 3.9+ 寫法 (建議)
def process_scores(scores: list[int]) -> float:
    return sum(scores) / len(scores)

def get_user_info(user_id: int) -> dict[str, str]:
    return {"name": "Alice", "role": "admin"}

# Tuple 通常用來表示固定長度與型別的組合
coordinate: tuple[int, int] = (10, 20)

3. 處理「可能為空」或「多種型別」

Union| (Python 3.10+)

當一個參數可能是整數浮點數時:

# Python 3.10+
def multiply(x: int | float, y: int | float) -> int | float:
    return x * y

# 舊版寫法 (需匯入 Union)
from typing import Union
def multiply_old(x: Union[int, float], y: Union[int, float]) -> Union[int, float]:
    return x * y

Optional

當變數可能是某個型別,也可能是 None 時:

from typing import Optional

def find_user(user_id: int) -> Optional[str]:
    if user_id == 1:
        return "Alice"
    return None # 沒找到

Optional[str] 其實等同於 str | None

4. 自訂型別別名 (Type Alias)

當型別太複雜時,可以取個名字。

# 定義一個複雜的字典結構型別
UserDict = dict[str, str | int]

def register(users: list[UserDict]):
    for u in users:
        print(u['name'])

data = [
    {"name": "Bob", "age": 30},
    {"name": "Carol", "age": 25}
]
register(data)

5. 靜態檢查工具:Mypy

寫了 Type Hints 但 Python 解譯器不會理它,那我們寫辛酸的嗎?不!我們要搭配 mypy 來檢查。

安裝: pip install mypy

假設我們有錯誤的程式碼 test.py

def add(x: int, y: int) -> int:
    return x + y

print(add(10, "20")) # 這裡傳了字串,執行時會報錯,但 Type Hints 能提前抓出

在終端機執行檢查: mypy test.py

Mypy 會告訴你: error: Argument 2 to "add" has incompatible type "str"; expected "int"

這就是靜態檢查的威力!

6. 總結

Type Hints 讓 Python 兼具了動態語言的靈活與靜態語言的嚴謹。在大型專案中,強烈建議全面採用 Type Hints。

本章重點回顧:

  • 基本型別: int, str, bool, float.
  • 容器: list[int], dict[str, int].
  • 複合: str | int (Union), Optional[str].
  • Mypy: 必備的靜態檢查工具。

下一章,我們將進入 Python 進階開發的深水區——並發程式設計 (Concurrency),首先挑戰 執行緒 (Threading) 與 多進程 (Multiprocessing)


延伸閱讀

LATEST POST
TAG