Search code examples
pythonname-binding

Python; name bindings are not object references?


I am trying to understand what exactly a Python name binding is, and when this binding is interpreted.

In c,

include <stdio.h>
int main()
{
int X = 42;
int* Y[1];
Y[0] = &X;
X = 666;
printf("%d", *Y[0]);
return 0;
}

prints 666. I was expecting the block of Python code:

X = 42
L = []
L.append(X) #3
X = 666
print(L) #5

to do the same, but it does not. What exactly happens between the lines labeled 3 and 5? Does #3 make another reference to the object known as "42", like X, lets call it X', and store X' in the object pointed to by L, which is []?


Solution

  • What you state is almost what happens:

    X = 42               # Create new object 42, bind name X to it.
    L = []
    L.append(X)          # Bind L[0] to the 42 object.
    X = 666              # Create new object 666, bind name X to it.
    print(L)             # Will not see the 666.
    

    The append is not binding the array element to the X, it's binding it to the object behind X, which is the 42.

    When I first realised this is the way Python worked, things (specifically, things like this which had previously confused me and caused much angst and gnashing of teeth) became so much clearer.