Aliasing [was Re: [Tutor] beginning to code]

ROGER GRAYDON CHRISTMAN dvl at psu.edu
Tue Sep 26 17:30:14 EDT 2017


On Tue, Sep 26, 2017 12:00 PM, Steve D'Aprano <steve+python at pear wood.info>
wrote:
>
> a = 1
>> b = a
>> b = 2
>> 
>> a is not 2.
>
< snip >
int main () {
>   int a;
>   int& b = a;  // reference variable or alias
>
>   a = 1;
>   printf("a: %d, alias b: %d\n", a, b);
>   b = 2;
>   printf("a: %d, alias b: %d\n", a, b);
>   return 0;
>}
>
>
>And here is the output:
>
>
>a: 1, alias b: 1
>a: 2, alias b: 2
>
>
>So I stand by what I said: assignment in Python is NOT an alias operation. If
it
>were an alias operation, as you claim, then we could write this:
>
>a = 1
>b = a  # alias to a
>b = 2  # assigning to be is like assigning to a (as in the C++
>example)
>assert a == 2
>
>But Python is not like that, assignment is not an alias operation, and the
>assert will fail.
>

I think you are being a bit choosy in your analysis of the examples.
You essentially claim that "assignment is not an alias operation" by
assuming that some assignments are not an alias operations,
and then conclude that it is inconsistent for the rest to be.

Here is a discussion of the code in light of the claim that assignment
is an alias operation, meaning _all_ assignments are aliases,
and not just the ones you choose to prove your point.

a = 1     # 'a' is an alias to the value 1
b = a     # 'b' is an alias to the value named by a, which is also an alias to 1
b = 2     # 'b' is now an alias to the value of 2, and no longer an alias to
'a' or 1

Your C++ counterexample is invalid, because, indeed, only the second
of the three assignments is an alias operation, and only because you
specifically declare variable b to be a reference variable.  You are not
really 'assigning' to b -- you are initializing the reference variable named
b..  

If we were to add an additional statement into both examples.

b = c

In Python, this would be another aliasing operation, causing b to
refer to the same thing as c refers to (assuming c has been assigned).

But in C++, that statement would be completely invalid -- once you
associate a reference to a reference variable, you cannot change
the binding.    This further emphasizes that the statement "int &b = a"
is not an assignment statement, which means it is rather irrelevant
to the semantics of assignment statements.

Roger Christman
Pennsylvania State University




More information about the Python-list mailing list