N. Cross
N. Cross

Reputation: 227

Object Creation in Python - What happenes to the modified variable?

After getting in touch with the more deeper workings of Python, I've come to the understanding that assigning a variable equals to the creation of a new object which has their own specific address regardless of the variable-name that was assigned to the object.

In that case though, it makes me wonder what happens to an object that was created and modified later on. Does it sit there and consumes memory?

The scenarion in mind looks something like this:

# Creates object with id 10101001 (random numbers)
x = 5

# Creates object with id 10010010 using the value from object 10101001.
x += 10

What happens to object with the id 10101001? Out of curiosity too, why do objects need an ID AND a refrence that is the variable name, wouldn't it be better to just assign the address with the variable name?

I apologize in advance for the gringe this question might invoke in someone.

Upvotes: 2

Views: 73

Answers (2)

tynn
tynn

Reputation: 39853

First of all Augmented assignment statements states:

An augmented assignment expression like x += 1 can be rewritten x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

So depending on the type of x this might not create a new object.

Python is reference counted. So the reference count of the object with id 10101001 decremented. If this count hits zero, the is freed almost immediately. But most low range integers are cached anyways. Refer to Objects, Types and Reference Counts for all the details.

Regarding the id of an object:

CPython implementation detail: This is the address of the object in memory.

So basically id and reference are the same. The variable name is just a binding to the object itself.

Upvotes: 2

William Clemens
William Clemens

Reputation: 174

Here is a great talk that was given at PyCon by Ned Batchelder this year about how Python manages variables.

https://www.youtube.com/watch?v=_AEJHKGk9ns

I think it will help clear up some of your confusion.

Upvotes: 2

Related Questions