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

Typing & Errors

Python มีเครื่องมือสองตัวที่ทำงานเสริมกันเพื่อเขียนโค้ดที่ “พังดัง” แทนที่จะ “พังเงียบ”:

  1. Type hints — annotation ที่บอกว่าตัวแปร, พารามิเตอร์ หรือค่าที่คืนออกมาควรเป็นประเภทใด ตรวจสอบโดย tool อย่าง mypy หรือ pyright แบบ static ไม่ใช่ตอน runtime
  2. Exceptions — กลไกส่งสัญญาณที่หยุดการทำงานปกติเมื่อเกิดสิ่งที่ไม่คาดคิด ทำให้เราจับและจัดการข้อผิดพลาดได้ หรือส่งต่อขึ้นไปยัง call stack

เมื่อใช้ร่วมกัน type hints และ exceptions ช่วยให้สื่อสาร intent ได้ชัดเจนและรับมือกับความผิดพลาดได้อย่างสง่างาม

def greet(name: str, count: int = 1) -> str:
return (name + "! ") * count

name: str, count: int, และ -> str คือ type hints Python ไม่สนใจสิ่งเหล่านี้ตอน runtime — มีไว้เพื่อ static checker และผู้อ่านโค้ดเท่านั้น ไม่ทำให้ greet("Alice") ช้าหรือเร็วขึ้นแต่อย่างใด

try:
result = int("abc")
except ValueError as e:
print(f"Caught: {e}")
finally:
print("Always runs")

try ครอบโค้ดที่อาจล้มเหลว except จับ exception ตามประเภทที่ระบุ finally ทำงานเสมอไม่ว่าจะเกิด exception หรือไม่

Type hints และ exceptions ไม่ได้ขัดแย้งกัน — ต่างทำงานต่างช่วง:

ช่วงเครื่องมือ
Static analysis (ก่อนรัน)Type hints + mypy/pyright
ความผิดพลาดตอน runtime (ระหว่างรัน)Exceptions

Signature ของฟังก์ชันบอก caller ว่าต้องการประเภทใด ส่วน exception บอกว่ารันไปแล้วอาจเจออะไรได้บ้าง

บทเรียนสิ่งที่จะได้เรียนรู้
Type HintsAnnotate ตัวแปร, พารามิเตอร์, ค่าที่คืน; Optional, Union, type alias
Exceptionstry/except/else/finally, raise, exception chaining
Context Managerswith, __enter__/__exit__, contextlib
Custom ErrorsSubclass Exception, custom attributes, exception hierarchy
from typing import Optional
def find_item(items: list[str], target: str) -> Optional[int]:
"""Return the index of target in items, or None if not found."""
for i, item in enumerate(items):
if item == target:
return i
return None
fruits = ["apple", "banana", "cherry"]
# type hints describe intent — no runtime enforcement
index = find_item(fruits, "banana")
print(f"Found at index: {index}")
missing = find_item(fruits, "mango")
print(f"Not found: {missing}")
# exceptions signal runtime failures
try:
value = fruits[10]
except IndexError as e:
print(f"IndexError: {e}")
# the else clause runs only when no exception was raised
try:
value = fruits[1]
except IndexError:
print("Out of range")
else:
print(f"Got: {value}")
Python ทำอะไรกับ type hints ตอน runtime?
Block ใดใน try statement ที่ทำงานเสมอไม่ว่าจะเกิด exception หรือไม่?
Block `else` ใน try statement ทำงานเมื่อใด?
Tool ใดตรวจสอบ Python type hints แบบ static?