[Tutor] Memory and functions
Peter Otten
__peter__ at web.de
Sun Dec 18 13:07:35 CET 2011
Charles Becker wrote:
> For functions that return values (ie the list method pop): If you don't
> assign the returned value to anything does it still end up residing in
> memory? Just seems like this could be a potential problem to watch out
> for when memory usage is an issue (probably not most of the time).
Every object in CPython has a counter to keep track how many times it is
referenced. When this counter drops to zero the object is destroyed and the
memory is available for reuse. This is simple and works most of the time
except when there are reference cycles. Consider:
class A:
pass
a = A()
b = A()
a.other = b
b.other = a
del a
del b
There is now no way for your program to reach a or b, but the reference
counter of a is still one because it is referenced by b as b.other, and the
reference counter of b is still one because it's referenced by a.
Therefore CPython has another mechanism called garbage collection as a
backup that periodically searches for reference cycles.
While the specific mechanism described above is only implemented in CPython
all variants (pypy, jython, ironpython) guarantee that you don't have to
bother about object lifetime.
More information about the Tutor
mailing list