Type Hints
Type hints คืออะไร
หัวข้อที่มีชื่อว่า “Type hints คืออะไร”Type hint คือ annotation ที่แนบไปกับตัวแปร, พารามิเตอร์ หรือค่าที่คืนออกมา เพื่อประกาศว่าควรเป็นประเภทใด
Python เก็บ annotation เหล่านี้ไว้ใน __annotations__ แต่ไม่เคยนำไปใช้ตอน runtime — เป็นเพียง metadata สำหรับ static analysis tool และผู้อ่านโค้ด
x: int = 10name: str = "Alice": int และ : str ไม่มีผลต่อการรันโค้ดเลย มีไว้เพื่อสื่อสาร intent เท่านั้น
Annotate signature ของฟังก์ชัน
หัวข้อที่มีชื่อว่า “Annotate signature ของฟังก์ชัน”สถานที่ที่มีประโยชน์ที่สุดสำหรับ type hints คือ function signature — ช่วยบอก contract ของทุก callable
def add(a: int, b: int) -> int: return a + b
def repeat(text: str, times: int = 1) -> str: return text * times-> int annotate ประเภทที่คืน ส่วน default value อยู่หลัง type annotation: times: int = 1
Built-in generic types
หัวข้อที่มีชื่อว่า “Built-in generic types”Python 3.9+ ให้ใช้ collection type โดยตรงเป็น generic ได้เลย ไม่ต้อง import
scores: list[int] = [95, 87, 92]mapping: dict[str, int] = {"a": 1, "b": 2}pair: tuple[str, int] = ("Alice", 30)unique: set[str] = {"red", "green", "blue"}ก่อน Python 3.9 ต้องเขียน List[int], Dict[str, int] จาก typing แนะนำให้ใช้ lowercase built-in form ใน Python 3.9+
Optional — ค่าที่อาจเป็น None
หัวข้อที่มีชื่อว่า “Optional — ค่าที่อาจเป็น None”Optional[T] หมายความว่าค่าเป็น T หรือ None ก็ได้ ย่อมาจาก Union[T, None]
from typing import Optional
def find_user(user_id: int) -> Optional[str]: users = {1: "Alice", 2: "Bob"} return users.get(user_id) # คืน str หรือ Noneใน Python 3.10+ เขียนเป็น str | None ได้เลย:
def find_user(user_id: int) -> str | None: users = {1: "Alice", 2: "Bob"} return users.get(user_id)ทั้งสองรูปแบบเทียบเท่ากัน แนะนำ X | None ใน Python สมัยใหม่
Union — หนึ่งในหลายประเภท
หัวข้อที่มีชื่อว่า “Union — หนึ่งในหลายประเภท”Union[X, Y] หมายถึงค่าอาจเป็น X หรือ Y ก็ได้ ใน Python 3.10+ ใช้ operator | ได้โดยตรง
from typing import Union
def process(value: Union[int, str]) -> str: return str(value)
# Python 3.10+ shorthand:def process_modern(value: int | str) -> str: return str(value)Type aliases
หัวข้อที่มีชื่อว่า “Type aliases”Type alias ตั้งชื่อให้กับ annotation ที่ซับซ้อน ทำให้ signature อ่านง่ายขึ้น
Vector = list[float]UserId = intUserMap = dict[UserId, str]
def scale(v: Vector, factor: float) -> Vector: return [x * factor for x in v]Python 3.12+ มี type statement:
type Vector = list[float] # Python 3.12+Demo แบบ runnable เต็มรูปแบบ
หัวข้อที่มีชื่อว่า “Demo แบบ runnable เต็มรูปแบบ”from typing import Optional, Union
# --- variable annotations ---x: int = 10name: str = "Alice"scores: list[int] = [95, 87, 92]mapping: dict[str, int] = {"a": 1, "b": 2}
# --- function signatures ---def add(a: int, b: int) -> int: return a + b
def repeat(text: str, times: int = 1) -> str: return text * times
# --- Optional / X | None ---def find_user(user_id: int) -> Optional[str]: users = {1: "Alice", 2: "Bob"} return users.get(user_id)
# --- Union / | ---def process(value: Union[int, str]) -> str: return str(value)
# --- type alias ---Vector = list[float]
def scale(v: Vector, factor: float) -> Vector: return [x * factor for x in v]
# --- run it ---print(add(3, 4))print(repeat("Hi", 3))print(find_user(1))print(find_user(99))print(process(42))print(process("hello"))print(scale([1.0, 2.0, 3.0], 2.5))
# hints do NOT restrict runtime behaviourprint(add("oops", " still works")) # Python does not enforce at runtimeLoading Python runtime (first run only)…