Reference counting manages memory by tracking how many references identify each object. An object begins with a reference from its variable; additional references can come from dictionaries, lists, or other objects. When the count reaches zero, Python destructs the object and releases its memory. section 10.2.3 section 10.2.4
Follow an object’s references through a small Python example:
- Create task = Task("Laundry"); the variable provides an initial reference. section 10.2.3
- Store task in a dictionary and list; each additional container reference increases the count. section 10.2.3
- Delete the list or replace the dictionary value; removing those references decreases the count. section 10.2.3
- Delete the remaining variable; Python calls __del__ for the instance and removes the name from the namespace. section 10.2.4
Inspecting references
Use sys.getrefcount(task) to observe changes while task is held by different names or containers. For example, the tracked count rises from 2 to 3 when task is placed in a dictionary, then to 4 when it is also placed in a list. Removing those references lowers the count again. section 10.2.3
Figure 10.3 The relationship between objects and variables. In the assignment statement, an instance object of the Task class is created in memory, and this object is associated with the task variable. Later, we assign a str object to the task variable. This reassignment disrupts the previous association between task and the actual Task("Laundry") object and creates a new association between task and the str object.
Trace how assigning a new object to task breaks its association with the original Task instance. section 10.2.3
Figure 10.4 The key events in an object’s lifecycle. An object starts with the construction and becomes active in an applicable namespace. During its usage, Python tracks its reference count. When there are no references to the object, Python destructs it to make its occupied memory available again.
Follow the lifecycle from construction and namespace activity through reference tracking to destruction. section 10.2.5



