Kodewick
開始學 →
型別標註31 / 31

Python 型別標註

第 31 課,共 31 課 · 第 6 部分 · 進階 · 約 20 分鐘

型別標註寫明引數和回傳值的型別,比如 def add(a: int, b: int) -> int:;執行時 Python 不檢查它,但編輯器和 mypy 會幫你查錯。

Python 從來不問一個變數裡裝的是什麼型別。短程式因此寫得短,可程式一大,就容易忘了一個函式要的到底是什麼:一個數、一個字串,還是一個列表,列表裡又是什麼?型別標註把答案直接寫進程式碼。它是寫給人、編輯器和檢查工具看的說明。這是整套課的最後一課,講怎麼寫標註,以及它能做什麼、不做什麼。

第一個型別標註

引數的標註寫在引數名後面,用冒號隔開。回傳值的型別寫在 -> 後面,在 def 那一行末尾的冒號之前。有預設值的,預設值寫在標註後面。

main.py
1def greet(name: str) -> str:2    return f"晚上好,{name}!"3 4def lamps_needed(houses: int, per_house: int = 2) -> int:5    return houses * per_house6 7print(greet("Wick"))8print(lamps_needed(5))
輸出
晚上好,Wick!
10

把第二個念出來:「lamps_needed 接受 int 型別的 houses 和 int 型別的 per_house,不給 per_house 就是 2,回傳一個 int。」變數也能標註,同樣用冒號:

def lamps_needed(houses①: int, per_house: int = 2②) -> int③:
  1. ①引數名後面加冒號和型別
  2. ②有預設值的,預設值寫在標註後面
  3. ③回傳值的型別寫在 -> 後面
一行 def 裡的三種標註
main.py
1lamp_count: int = 122town: str = "畫素小鎮"3oil_left: float = 3.54is_night: bool = True5print(lamp_count, town, oil_left, is_night)
輸出
12 畫素小鎮 3.5 True

大多數變數用不著:lamp_count = 12 誰都看得出是 int。看不出來的地方才需要,比如一個空列表、空字典,後面才往裡放東西。

填空點一個填進空格,再點空格可以拿回來

補上兩處標註:引數 n 是 int,函式也返回 int。

1def double(n) :2    return n * 23 4print(double(4))

Python 不強制檢查

幾乎每個人都會吃一驚:Python 執行程式碼時根本不看標註。傳錯了型別,也沒有誰攔著:

main.py
1def lamps_needed(houses: int, per_house: int = 2) -> int:2    return houses * per_house3 4print(lamps_needed("ab"))5print(lamps_needed(2.5))6count: int = 57count = "五"8print(count)
輸出
abab
5.0
五

"ab" * 2 就是 "abab",所以呼叫照樣成功,只是結果誰都不想要。標註沒有引發報錯:它不是規定,而是承諾,這裡也沒有人去查承諾有沒有做到。查承諾是 mypy 這類工具的事(這一課最後一關會講)。

執行 Pythonlamps_needed("ab")abab不看標註,照樣執行
用 mypy 檢查mypy lamps.pyerror執行之前就指出型別不對
同一個錯誤:執行時 Python 不管,mypy 不用執行就能指出來
猜輸出猜錯也沒關係

這段會顯示什麼?

1def half(n: int) -> int:2    return n / 23 4print(half(5))

容器的標註

列表要說明裡面裝的是什麼:list[int] 是一個裝 int 的列表。字典要寫兩個型別,一個給鍵,一個給值。

標註意思例子
list[int]裝 int 的列表[3, 8, 2]
dict[str, int]鍵是字串、值是 int 的字典{"磨坊": 5}
tuple[str, int]先是一個 str、再是一個 int 的元組("阿達", 12)
set[str]裝字串的集合{"鐵", "金"}
main.py
1def total_ore(loads: list[int]) -> int:2    return sum(loads)3 4def count_words(words: list[str]) -> dict[str, int]:5    counts: dict[str, int] = {}6    for word in words:7        counts[word] = counts.get(word, 0) + 18    return counts9 10print(total_ore([3, 8, 2]))11print(count_words(["鐵", "金", "鐵"]))
輸出
13
{'鐵': 2, '金': 1}

這裡變數的標註就有用了:光寫 counts = {},看不出以後要往裡放什麼。老程式碼裡會看到 List[int]、Dict[str, int],是從 typing 模組匯入的;Python 3.9 以前只能這麼寫,意思一樣。

單選

{"a": [3, 8], "b": [2]} 應該怎麼標註?

可能為空的值

很多函式回傳一個值或者 None,比如一次可能什麼都找不到的查詢。這寫成 int | None:「一個 int,或者 None」。

main.py
1def find_lamp(oil: dict[str, int], name: str) -> int | None:2    if name in oil:3        return oil[name]4    return None5 6oil = {"磨坊": 5, "橋頭": 0}7print(find_lamp(oil, "磨坊"))8print(find_lamp(oil, "城門"))
輸出
5
None

typing 模組裡有同一個意思的老寫法 Optional[int],很多程式碼裡都會見到。預設值是 None 的引數也這樣標:

main.py
1from typing import Optional2 3def light(name: str, hour: Optional[int] = None) -> str:4    if hour is None:5        return f"{name}:現在就點"6    return f"{name}:{hour} 點再點"7 8print(light("磨坊"))9print(light("橋頭", 21))
輸出
磨坊:現在就點
橋頭:21 點再點
單選猜錯也沒關係

會怎麼樣?

1def find_lamp(oil: dict[str, int], name: str) -> int | None:2    if name in oil:3        return oil[name]4    return None5 6print(find_lamp({"磨坊": 5}, "城門") + 1)
練習 1

礦石在哪一車

把 find_cart 寫完:返回 ore 在 carts 裡的位置,不在裡面就返回 None。

要顯示
1
None
exercise1.py
1def find_cart(carts: list[str], ore: str) -> int | None:2    pass3 4print(find_cart(["鐵", "金", "銅"], "金"))5print(find_cart(["鐵", "金", "銅"], "銀"))
輸出
點「執行」或按 Ctrl+Enter

檢視標註

Python 不檢查標註,但會把它們留著。每個函式都有一個字典 __annotations__,一條標註一項;回傳值的型別在 "return" 下面。

main.py
1def lamps_needed(houses: int, per_house: int = 2) -> int:2    return houses * per_house3 4print(lamps_needed.__annotations__)5print(lamps_needed.__annotations__["return"])
輸出
{'houses': <class 'int'>, 'per_house': <class 'int'>, 'return': <class 'int'>}
<class 'int'>

int 這樣的普通型別顯示成 <class 'int'>,也就是這個類本身。容器的標註照你寫的樣子儲存,list[str] 就是 list[str],str | None 也一樣。沒標註的引數沒有這一項,-> None 存的就是 None:

main.py
1def area(width, height):2    return width * height3 4def greet(names: list[str], title: str | None = None) -> None:5    print(f"你好,{names}")6 7print(area.__annotations__)8print(greet.__annotations__)
輸出
{}
{'names': list[str], 'title': str | None, 'return': None}

自己很少會去讀 __annotations__,但工具會讀:@dataclass 就是這樣找到類的欄位的,有些庫也靠它替你檢查資料。

練習 2

給面積加標註

給 area 加上型別標註:兩個引數都是 int,結果也是 int。最後一行就會顯示它的標註。

要顯示
{'width': <class 'int'>, 'height': <class 'int'>, 'return': <class 'int'>}
exercise2.py
1def area(width, height):2    return width * height3 4print(area.__annotations__)
輸出
點「執行」或按 Ctrl+Enter

類裡的標註

方法和普通函式一樣標註。self 不用標;__init__ 什麼都不返回,標 -> None。在 dataclass(第 28 課)裡,標註不是可有可無的:有標註的那一行才算一個欄位。

main.py
1from dataclasses import dataclass2 3class Lamp:4    def __init__(self, name: str, oil: int = 0) -> None:5        self.name = name6        self.oil = oil7 8    def refill(self, amount: int) -> None:9        self.oil += amount10 11@dataclass12class Cart:13    ore: str14    weight: int15 16lamp = Lamp("磨坊")17lamp.refill(4)18print(lamp.name, lamp.oil)19print(Cart("鐵", 12))20print(Lamp.refill.__annotations__)
輸出
磨坊 4
Cart(ore='鐵', weight=12)
{'amount': <class 'int'>, 'return': None}
練習 3

給方法加標註

給 refill 加上型別標註:amount 是 int,方法什麼都不返回。最後一行就會顯示它的標註。

要顯示
{'amount': <class 'int'>, 'return': None}
exercise3.py
1class Lamp:2    def __init__(self) -> None:3        self.oil = 04 5    def refill(self, amount):6        self.oil += amount7 8print(Lamp.refill.__annotations__)
輸出
點「執行」或按 Ctrl+Enter

檢查標註,什麼時候用

想讓標註真的被檢查,就在執行之前用型別檢查工具過一遍程式碼。最有名的是 mypy,在自己的電腦上用 pip 安裝(瀏覽器裡跑不了)。拿這個檔案來說:

lamps.py
1def lamps_needed(houses: int, per_house: int = 2) -> int:2    return houses * per_house3 4print(lamps_needed("五"))
Terminal
$ pip install mypy
$ mypy lamps.py
lamps.py:4: error: Argument 1 to "lamps_needed" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

mypy 什麼都沒執行就找到了錯誤:第 4 行的第 1 個引數是 str,可要的是 int。VS Code、PyCharm 這些編輯器也讀標註:邊寫邊在型別不對的地方畫線,打一個點就提示合適的方法。

什麼時候值得寫標註?

  • 別人要呼叫的函式,或者一個月後你自己還要回來看的函式:標註是一份過時了也會被發現的說明。
  • 大一點的程式,配上檢查工具:一整類錯誤,比如忘了處理 None,在發生之前就能找出來。
  • dataclass,它離不開標註。
  • 短指令碼和小試驗用不著,就像這套課裡的大多數例子。標註是可選的,有用的地方加上就好。
單選

mypy 在什麼時候找出型別不對?

這一課學會了

  • 名字: 型別 標註引數或變數;-> 型別 標註函式返回什麼。
  • Python 執行時不檢查標註:它是寫給人、編輯器和 mypy 這類檢查工具看的承諾。
  • 容器要說明裝的是什麼:list[int]、dict[str, int]、tuple[str, int]、set[str]。
  • int | None(或者 Optional[int])表示這個值可能沒有。
  • 函式.__annotations__ 裡存著標註;dataclass 靠它找到自己的欄位。

這是最後一課了。現在你已經能寫真正的程式:挑一個自己的想法,比如待辦清單、一個小測驗,或者幫 Wick 記錄每盞燈的油,到 Python 線上編程 裡一點一點做出來。卡住了就回來翻需要的那一課,這裡的每個例子都還能執行、能單步。

這一課學完了嗎?點一下標記。進度存在這個瀏覽器裡,隨時可以撤銷。