Tag: contextlib
9 รายการ
Blog
Python ExitStack.pop_all: โอนสิทธิ์ cleanup เมื่อทุกขั้นเตรียมสำเร็จ
ใช้ ExitStack.pop_all ทำ all-or-nothing resource setup พร้อม unittest ที่ตรวจ cleanup ก่อนและหลังโอน ownership
Python AsyncContextDecorator: ใช้ lifecycle เดียวกันทั้ง async with และ decorator
สร้างขอบเขต async ที่นำกลับใช้ได้สองรูปแบบ พร้อม unittest พิสูจน์ลำดับ enter/work/exit
Python AsyncExitStack: รวม cleanup แบบ sync และ async ไว้ในจุดเดียว
จัดการ resource ที่เปิดตามเงื่อนไขด้วย contextlib.AsyncExitStack และยืนยันลำดับปิดย้อนกลับด้วย unittest
Python redirect_stdout: จับ output ของโค้ดเก่าไว้ทดสอบ
ใช้ contextlib.redirect_stdout ครอบฟังก์ชันที่ print โดยไม่แก้ global state นานเกิน scope
Python nullcontext: ทำให้เส้นทางมีและไม่มี context manager ใช้โครงเดียวกัน
ใช้ contextlib.nullcontext ลด if ซ้ำรอบ with สำหรับ resource ที่ผู้เรียกอาจส่งมาให้แล้ว พร้อม unittest
Python contextlib.suppress: กลืนเฉพาะ error ที่ขั้นตอนนั้นยอมรับได้
ใช้ contextlib.suppress กับ cleanup แบบ best effort โดยจำกัด exception ให้แคบและทดสอบว่า error อื่นยังหลุดออกมา
Python contextlib.aclosing: ปิด Async Generator แม้ Loop หยุดก่อนจบ
ใช้ aclosing จัด lifecycle ของ async generator ให้ cleanup รันใน context เดิม พร้อม unittest ที่พิสูจน์กรณี break กลาง stream

contextlib.chdir: เปลี่ยนโฟลเดอร์ชั่วคราวแบบปลอดภัยใน with
สอนใช้ contextlib.chdir ตั้งแต่ Python 3.11 เทียบกับ os.chdir เปล่าๆ พร้อมตัวอย่างที่รันตรวจได้
Python ExitStack: จัดการ resource จำนวนไม่แน่นอนให้ปิดย้อนลำดับ
รวม context manager และ callback แบบ dynamic ด้วย ExitStack พร้อม unittest ที่พิสูจน์ลำดับ cleanup