ข้ามไปยังเนื้อหา

Type Hints

Type hint คือ annotation ที่แนบไปกับตัวแปร, พารามิเตอร์ หรือค่าที่คืนออกมา เพื่อประกาศว่าควรเป็นประเภทใด Python เก็บ annotation เหล่านี้ไว้ใน __annotations__ แต่ไม่เคยนำไปใช้ตอน runtime — เป็นเพียง metadata สำหรับ static analysis tool และผู้อ่านโค้ด

x: int = 10
name: str = "Alice"

: int และ : str ไม่มีผลต่อการรันโค้ดเลย มีไว้เพื่อสื่อสาร intent เท่านั้น

สถานที่ที่มีประโยชน์ที่สุดสำหรับ 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

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[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[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 alias ตั้งชื่อให้กับ annotation ที่ซับซ้อน ทำให้ signature อ่านง่ายขึ้น

Vector = list[float]
UserId = int
UserMap = 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+
from typing import Optional, Union
# --- variable annotations ---
x: int = 10
name: 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 behaviour
print(add("oops", " still works")) # Python does not enforce at runtime
Syntax ของ Python 3.10+ สำหรับ 'str หรือ None' คืออะไร?
Python ทำอะไรถ้าส่ง string ไปยังพารามิเตอร์ที่ annotate เป็น `int`?
การ annotate list ของ integer ที่ถูกต้องใน Python 3.9+ คืออะไร?
Type alias คืออะไร?