contextlib Module
contextlib มี utilities ที่ช่วยให้การสร้างและใช้งาน Context Managers (with statement) ง่ายขึ้น โดยไม่ต้องเขียน class แบบเต็มๆ
ทำไมต้องใช้ contextlib
Section titled “ทำไมต้องใช้ contextlib”ลองนึกภาพว่าเราต้อง cleanup resources หลังใช้งาน เช่น ปิดไฟล์ ปิด database connection หรือ release locks การใช้ context managers ช่วยให้จัดการได้สะอาดและปลอดภัย
Use Cases หลัก
Section titled “Use Cases หลัก”| Use Case | Description | Example |
|---|---|---|
| Resource cleanup | ปิด resources อัตโนมัติ | Files, connections |
| Temporary state | เปลี่ยนสถานะชั่วคราว | Settings, environment |
| Exception handling | จัดการ errors | Suppress, retry |
| Timing | วัดเวลา | Profiling, benchmarks |
| Locking | Thread safety | Mutex, semaphores |
ปัญหาของการสร้าง Context Manager แบบ Class
Section titled “ปัญหาของการสร้าง Context Manager แบบ Class”# แบบเดิม - ต้องเขียน class ยาวclass TimerContext: """ Context manager สำหรับจับเวลา (แบบ class) ต้อง implement __enter__ และ __exit__ """ def __init__(self, label): # เก็บ label สำหรับแสดงผล self.label = label self.start = None
def __enter__(self): # เรียกเมื่อเข้า with block import time self.start = time.perf_counter() print(f"[{self.label}] Starting...") return self # ค่าที่ส่งให้ as variable
def __exit__(self, exc_type, exc_val, exc_tb): # เรียกเมื่อออกจาก with block import time elapsed = time.perf_counter() - self.start print(f"[{self.label}] Finished in {elapsed:.4f}s") return False # False = re-raise exceptions
# ใช้งานwith TimerContext("Demo") as timer: total = sum(range(100000)) print(f" Sum: {total}")
print("Class-based CM ใช้งานได้ แต่ยาวมาก!")เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google