Newbie question about python garbage collection when keeping only a reference to an object's member
steve at holdenweb.com
Fri Nov 12 23:18:44 CET 2010
On 11/12/2010 2:03 PM, George Burdell wrote:
> My understanding is that any object which is not pointed to by any
> variable will be automatically deleted. What if I create a class
> object, but only keep a reference to one of its members, and not a
> reference to the object itself? What goes on internally in Python?
> Does Python retain the whole object, or does it just keep a copy of
> the referenced member?
> For example, if I have
> def myclass:
> def __init__(self):
> self.x = [1,2,3]
> self.y = [4,5,6]
> x = myclass().x
> This works, and I correctly get x = [1,2,3]. But what happened to the
> myclass() object initially created, and the member "y"?
The myclass() call created a myclass instance (which contains a
reference to a newly created list, which therefore has a refcount of 1).
Attribute access to that instance then returns a second reference to the
list, which is bound to the name x in the current local namespace (or
the module global namespace if this is top-level code). The binding
results in a reference count of two for the list.
The instance, having no outstanding references, is then
garbage-collected, which means that the objects referenced by its
namespace have their reference counts decremented for each reference. So
the destruction of the myclass instance reduces the reference count of
the list [1, 2, 3] to one, and that of the list [4, 5, 6] to zero (which
causes *it* to be garbage collected).
And you are left with a local variable x that references a list whose
current contents are [1, 2, 3].
Remember, the new values aren't created in local namespace. They are
created in a shared area of memory (often referred to as the "heap"), so
it's quite easy to "keep objects alive" that were created inside
functions - just make sure you hold on to references outside the
functions, and you are fine.
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon 2011 Atlanta March 9-17 http://us.pycon.org/
See Python Video! http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list