I have read a number of posts over the years that explained Python variables by "Python has names, other languages have variables" or by "objects and tags and boxes"
I have always disliked these kind of explanations, since they required new mental images and, in my opinion, try to redefine common terminology. (Arguably Python has variables too, and other languages have names too.)
Since I only ever did proper programming with Python, its behavior was the only one I knew, so these discussions didn't really affect me much.
Nonetheless, I would like to know whether my following understanding of this topic is correct, before I defend it in discussions with others:
All Python variables are pointers
While writing this question, I noticed that a similar question has been asked before, and everybody in that thread, including the OP, concluded that Python variables are not pointers (and instead, the answers used the explanations above instead), since
i = 5
j = i
j = 3
print(i)
results in 5
. However, to me this result makes perfect sense. In my understanding it is translated to
void *i;
void *j;
int temp1 = 5; %RHS of line 1 above
i = &temp1; %LHS of line 1 above
j = &i; %Line 2 above
int temp2 = 3; %RHS of line 3 above
j = &temp2; %LHS of line 3 above
(To be precise, there is one answer to the previously cited question that does provide more or less this explanation, but has a negative score and no comments as to what is wrong with it.)
As far as I understand, this model also perfectly explains parameters in Python, e.g, it explains why
def foo(b):
b=2
a=1
foo(a)
print(a)
results in 1
. Within foo
, the local pointer variable b
gets redirected to the address of a new integer object. The outer pointer variable a
still points to the integer object with value 1
.
To get a complete picture, and make sense of property access and why it can be used to change a variable that is passed to a function after all, I would then add the claim:
Property access with .
in Python translates to ->
in C++
Since indexing is just syntactic sugar, it is also covered by this rule.
In summary, I believe two simple rules explain everything about variables in Python. This is a bold statement, and I am happy to learn if and how it is wrong.
EDIT: Another very popular question whose answers argues against the pointer analogy