Planet Python
Follow
The Python Coding Stack: When You No Longer Need That Object • Dealing With Garbage in Python
Python, as an object-oriented language, manages object memory automatically. The __del__ method acts as a finalizer, called just before an object is destroyed. Python objects track their references, and when this count reaches zero, the object is removed from memory. The del keyword removes a name (reference) to an object, not the object itself. Deleting the last reference to an object triggers its destruction. Cyclic references occur when objects hold references to each other, preventing their reference counts from reaching zero. This situation leads to memory leaks if not handled. Python's cyclic garbage collector periodically identifies and removes these unreachable, cyclically referenced objects. While programmers don't need to manually manage memory, understanding these mechanisms can help diagnose program behavior. Forcing garbage collection can be done using the gc module.