marco
marco

Reputation: 899

Assignment of a variable

I am puzzled with an issue of a variable assignment in python. I tried looking for pages on internet about this issue, but I still do not understand it.

Let's say I assign a certain value to the variable:

v = 2

Python reserved a place in some memory location with a value 2. We now know how to access that particular memory location by assigning to it a variable name: v

If then, we do this:

v = v + 4

A new memory location will be filed with the value 6 (2+4), so now to access this value, we are binding the variable v to it.

Is this correct, or completely incorrect?

And what happens with the initial value 2 in the memory location? It is no longer bound to any variable, so this value can not be accessed any more? Does this mean that in the next couple of minutes, this memory location will be freed by the garbage collector?

Thank you for the reply.

EDIT:

The v = 2 and v = v + 2 are just simple examples. In my case instead of 2 and v+2 I have a non-python native objects which can weight from tens of megabytes, up to 400 megabytes. I apologize for not clearing this on the very start. I did not know there is a difference between integers and objects of other types.

Upvotes: 3

Views: 150

Answers (2)

Prune
Prune

Reputation: 77900

You're correct, as far as this goes. Actually, what happens is that Python constructs integer objects 2 and 4. In the first assignment, the interpreter makes v point to the 2 object.

In the second assignment, we construct an object 6 and make v point to that, as you suspected.

What happens next is dependent on the implementation. Most interpreters and compilers that use objects for even atomic values, will recognize the 2 object as a small integer, likely to be used again, and very cheap to maintain -- so it won't get collected. In general, a literal appearing in the code will not be turned over for garbage collection.


Thanks for updating the question. Yes, your large object, with no references to it, is now available for GC.

Upvotes: 3

aldanor
aldanor

Reputation: 3481

The example with small integers (-5 to 256) is not the best one because these are represented in a special way (see this for example).

You are generally correct about the flow of things, so if you had something like

v = f(v)

the following things happen:

  • a new object gets created as a result of evaluating f(v) (modulo the small integer or literal optimization)
  • this new object is bound to variable v
  • whatever was previously in v is now inaccessible and, generally, may get garbage collected soon

Upvotes: 3

Related Questions