Typing & Errors
สองระบบ เป้าหมายเดียว: โค้ดที่เชื่อถือได้
หัวข้อที่มีชื่อว่า “สองระบบ เป้าหมายเดียว: โค้ดที่เชื่อถือได้”Python มีเครื่องมือสองตัวที่ทำงานเสริมกันเพื่อเขียนโค้ดที่ “พังดัง” แทนที่จะ “พังเงียบ”:
- Type hints — annotation ที่บอกว่าตัวแปร, พารามิเตอร์ หรือค่าที่คืนออกมาควรเป็นประเภทใด ตรวจสอบโดย tool อย่าง mypy หรือ pyright แบบ static ไม่ใช่ตอน runtime
- Exceptions — กลไกส่งสัญญาณที่หยุดการทำงานปกติเมื่อเกิดสิ่งที่ไม่คาดคิด ทำให้เราจับและจัดการข้อผิดพลาดได้ หรือส่งต่อขึ้นไปยัง call stack
เมื่อใช้ร่วมกัน type hints และ exceptions ช่วยให้สื่อสาร intent ได้ชัดเจนและรับมือกับความผิดพลาดได้อย่างสง่างาม
Type hints ในหนึ่งบรรทัด
หัวข้อที่มีชื่อว่า “Type hints ในหนึ่งบรรทัด”def greet(name: str, count: int = 1) -> str: return (name + "! ") * countname: str, count: int, และ -> str คือ type hints Python ไม่สนใจสิ่งเหล่านี้ตอน runtime — มีไว้เพื่อ static checker และผู้อ่านโค้ดเท่านั้น ไม่ทำให้ greet("Alice") ช้าหรือเร็วขึ้นแต่อย่างใด
โมเดล exception ในหนึ่งบรรทัด
หัวข้อที่มีชื่อว่า “โมเดล exception ในหนึ่งบรรทัด”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 Hints | Annotate ตัวแปร, พารามิเตอร์, ค่าที่คืน; Optional, Union, type alias |
| Exceptions | try/except/else/finally, raise, exception chaining |
| Context Managers | with, __enter__/__exit__, contextlib |
| Custom Errors | Subclass Exception, custom attributes, exception hierarchy |
Demo ภาพรวมแบบ runnable
หัวข้อที่มีชื่อว่า “Demo ภาพรวมแบบ runnable”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 enforcementindex = find_item(fruits, "banana")print(f"Found at index: {index}")
missing = find_item(fruits, "mango")print(f"Not found: {missing}")
# exceptions signal runtime failurestry: value = fruits[10]except IndexError as e: print(f"IndexError: {e}")
# the else clause runs only when no exception was raisedtry: value = fruits[1]except IndexError: print("Out of range")else: print(f"Got: {value}")Loading Python runtime (first run only)…