[Tutor] Object references and garbage collection confusion

Alan Gauld alan.gauld at btinternet.com
Tue May 5 10:48:00 CEST 2015


On 05/05/15 05:29, Brandon D wrote:
> Hello tutors,
>
> I'm having trouble understanding, as well as visualizing, how object
> references work in the following situation.  For demonstration purposes I
> will keep it at the most rudimentary level:
>
> x = 10
> x = x ** x

Its good to use a simple example but in this case your
example bears no relation to your comments below!

>
> If my knowledge serves me correctly, Python destroys the value once
> reassigned.

Eventually.
Or more accurately Python marks the object for deletion
once all references to the object have been lost. Remember
variables in Python are not storage locations, they are
names attached to objects. When there are no more names
attached to an object it can be deleted. But that does
not necessarily happen immediately, Python gets around
to it when it has the time.

> So, how does x = x +  1 work if it's destroyed before it can
> be referenced?

Its not. This says assign x to the object on the right.
So it has to work out what "the object on the right" is
before it can stick the label x onto the result.

> The only solution I came up with is that the two operands
> are evaluated before storing it in the variable, consequently
 > replacing the original value of 0.

Remember, its the name that moves, not the objects. Python
doesn't store the objects in the variables, it assigns
the variable names to the objects. There is a big difference.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list