Reference Counting

suggest change

The vast majority of Python memory management is handled with reference counting.

Every time an object is referenced (e.g. assigned to a variable), its reference count is automatically increased. When it is dereferenced (e.g. variable goes out of scope), its reference count is automatically decreased.

When the reference count reaches zero, the object is immediately destroyed and the memory is immediately freed. Thus for the majority of cases, the garbage collector is not even needed.

>>> import gc; gc.disable()  # disable garbage collector
>>> class Track:

def init(self): print(“Initialized”) def del(self): print(“Destructed”)

>>> def foo():

Track()

destructed immediately since no longer has any references

print(”—”) t = Track()

variable is referenced, so it’s not destructed yet

print(”—”)

variable is destructed when function exits

>>> foo()
Initialized
Destructed
---
Initialized
---
Destructed

To demonstrate further the concept of references:

>>> def bar():
        return Track()
>>> t = bar()
Initialized
>>> another_t = t  # assign another reference
>>> print("...")
...
>>> t = None          # not destructed yet - another_t still refers to it
>>> another_t = None  # final reference gone, object is destructed
Destructed

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Garbage Collection:
* Reference Counting

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
85 Garbage Collection
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve