i

Python Programming

Garbage Collection

Python deletes unneeded objects automatically free memory space,process by which Python periodically reclaims blocks of memory that no longer are used called Garbage-Collection.

Python garbage-collector runs during program execution and is triggered, when object's reference count reaches zero. An object's reference count changes as number of aliases that point to their changes.

An object's reference count increases when it assigns a new name or placed in container like list, tuple, or dictionary. The object reference count decreases when it deleted with del, its reference reassigned, or its reference goes out of scope. When object's reference count reaches zero python collects automatically.

x = 40      # Create object <40>

y = x       # Increase ref. count  of <40>

z = [y]     # Increase ref. count  of <40>

del x      # Decrease ref. count  of <40>

y = 100     # Decrease ref. count  of <40>

z[0] = -1   # Decrease ref. count  of <40>

You normally will not notice when garbage collector destroys orphaned instance and reclaims its space. But a class can implement special method __del__(), called a destructor, that is invoked when instance is about to be destroyed. This method might used to clean up any non-memory resources used by instance.

Example

This __del__() destructor prints class name of an instance that about to be destroyed −

Live Demo

Output:

3083401323 3083401323 3083401323

Point now destroyed