Python › Memory Management & Garbage Collection

How do context managers and the `del` statement relate to timely memory cleanup versus relying on garbage collection?

Intermediate

Answer

`del` removes a name binding, decrementing the referenced object's refcount immediately -- if it reaches zero, the object is freed right away via reference counting, not waiting for a GC cycle. Context managers (with __exit__) similarly guarantee deterministic, immediate cleanup of resources (file handles, locks, connections) at block exit, which is more reliable than depending on garbage collection timing for external resources.
class DatabaseConnection:
    def __enter__(self):
        self.conn = connect()
        return self.conn
    def __exit__(self, *args):
        self.conn.close()  # deterministic cleanup, not left to GC

with DatabaseConnection() as conn:
    conn.query('SELECT 1')
Real-world example A file-processing script explicitly deletes large intermediate data structures with `del` between processing stages to free memory immediately rather than waiting for them to fall out of scope naturally.

Common follow-ups: Why shouldn't you rely on __del__ for critical resource cleanup?;How does this differ across Python implementations like PyPy?