Cleanup เกิดขึ้นกับ Globals โดยการตั้งค่าเป็น None Locals จะ Self-destruct ที่จบ Session ฟังก์ชัน __del__ ที่ Python เรียก ตั้งค่า Globals เป็น None
พิจารณาโค้ดต่อไปนี้ที่มี Cleanup ของ Objects ทั้งหมดใน Class ที่กำหนด -
ตัวอย่าง
class Counter:
Count = 0 # This is the count of objects of this class
def __init__(self, name):
self.name = name
print(name, 'created')
Counter.Count += 1
def __del__(self):
print(self.name, 'deleted')
Counter.Count -= 1
if Counter.Count == 0:
print('Last Counter object deleted')
else:
print(Counter.Count, 'Counter objects remaining')
x = Counter("First")
del x
โดยไม่มี del ตัวสุดท้าย คุณจะได้ Exception
จาก Python Docs เกี่ยวกับ __del__ -
Warning: เนื่องจากสภาพแวดล้อมที่อันตรายที่ __del__() Methods ถูก Invoke Exceptions ที่เกิดระหว่าง Execution ถูก Ignore และ Warning ถูกพิมพ์ไปที่ sys.stderr แทน นอกจากนี้ เมื่อ __del__() ถูก Invoke ตอบสนองต่อ Module ที่ถูกลบ (เช่น เมื่อ Execution ของ Program จบ) Globals อื่นๆ ที่ถูกอ้างอิงโดย __del__() Method อาจถูกลบไปแล้ว เพื่อเหตุผลนี้ __del__() Methods ควรทำแค่ Minimum ที่จำเป็นเพื่อ Maintain External Invariants
โดยไม่มี Explicit Call ถึง del __del__ จะถูกเรียกแค่ตอนจบ Program Counter และ/หรือ Count อาจถูก GC แล้วก่อนที่ __del__ จะถูกเรียก (ลำดับที่ Objects ถูก Collect ไม่ Deterministic) Exception หมายถึง Counter ถูก Collect แล้ว คุณไม่สามารถทำอะไรฟูซซี่กับ __del__ ได้
มีสอง Solutions ที่เป็นไปได้
- ใช้ Explicit Finalizer Method เช่น
close()สำหรับ File Objects - ใช้ Weak References