Linux/Unix > Python Essential Reference, Second Edition > 3. Types and Objects > Reference Counting and Garbage Collection | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104028131050041033147213

### Reference Counting and Garbage Collection

All objects are reference-counted. An object’s reference count is increased whenever it’s assigned to a new name or placed in a container such as a list, tuple, or dictionary, as shown here:

    a = 3.4      # Creates an object '3.4'
    b = a        # Increases reference count on '3.4'
    c = []
    c.append(b)  # Increases reference count on '3.4'

This example creates a single object containing the value `3.4`. The variable `a` is merely a name that refers to the newly created object. When `b` is assigned `a`, `b` becomes a new name for the same object, and the object’s reference count increases. Likewise, when you place `b` into a list, the object’s reference count increases again. In the example, only one object contains `3.4`. All other operations are simply creating new references to the object.

An object’s reference count is decreased by the `del` statement or whenever a reference goes out of scope (or is reassigned). For example:

    del a      # Decrease reference count of 3.4
    b = 7.8    # Decrease reference count of 3.4
    c[0]=2.0   # Decrease reference count of 3.4

When an object’s reference count reaches zero, it is garbage collected. However, in some cases a circular dependency may exist among a collection of objects that are no longer in use. For example:

    a = { }
    b = { }
    a['b'] = b      # a contains reference to b
    b['a'] = a      # b contains reference to a
    del a
    del b

In this example, the `del` statements decrease the reference count of `a` and `b` and destroy the names used to refer to the underlying objects. However, because each object contains a reference to the other, the reference count doesn’t drop to zero and the objects remain allocated. To address this problem, the interpreter periodically executes a cycle-detector that searches for cycles of inaccessible objects and deletes them. The cycle-detection algorithm can be fine-tuned and controlled using functions in the `gc` module described in Appendix A, “The Python Library.”

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.