Python รองรับ runtime context ผ่านคำสั่ง with โดย context manager จะกำหนดบริบทรันไทม์ มีเมธอดหลัก 2 ตัว:
__enter__()
เข้าสู่บริบทรันไทม์ คืนค่าออบเจ็กต์ปัจจุบันหรือออบเจ็กต์ที่เกี่ยวข้อง ค่าที่คืนจะถูกผูกกับตัวแปรใน as clause
__exit__(exc_type, exc_val, exc_tb)
ออกจากบริบท คืนค่า Boolean บ่งบอกว่ามีข้อยกเว้นเกิดขึ้นหรือไม่ หากมีข้อยกเว้น จะไปยังบล็อกสิ้นสุด
ตัวอย่าง: จัดการไฟล์ด้วย Context Manager
class MyFileManager:
def __init__(self, fname):
self.file_name = fname
def __enter__(self):
self.myFile = open(self.file_name, 'r')
return self.myFile
def __exit__(self, exc_type, exc_val, exc_tb):
if self.myFile:
self.myFile.close()
with MyFileManager('sampleTextFile.txt') as myFile:
x = myFile.read()
print(x)
ผลลัพธ์
Test File. We can store different contents in this file ~!@#$%^&*()_+/*-+\][{}|:;"'<.>/,'"]