Amen
Amen

Reputation: 1633

Python Assignment or Variable binding?

x = 3
x = 4

Is the second line an assignment statement or a new variable binding?

Upvotes: 0

Views: 391

Answers (2)

georg
georg

Reputation: 214959

In (very basic) C terms, when you assign a new value to a variable this is what happens:

x = malloc(some object struct)

If I'm interpreting your question correctly, you're asking what happens when you reassign x - this:

A. *x = some other value

or this:

B. x = malloc(something else)

The correct answer is B, because the object the variable points to can be also referred to somewhere else and changing it might affect other parts of the program in an unpredictable way. Therefore, Python unbinds the variable name from the old structure (decreasing its "reference counter"), allocates a new structure and binds the name to this new one. Once reference counter of a structure becomes zero, it becomes garbage and will be freed at some point.

Of course, this workflow is highly optimized internally, and details may vary depending on the object itself, specific interpreter (CPython, Jython etc) and from version to version. As userland python programmers, we only have a guarantee that

x = old_object

and then

x = new_object

doesn't affect "old_object" in any way.

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251368

There is no difference. Assigning to a name in Python is the same whether or not the name already existed.

Upvotes: 3

Related Questions