Aliasing [was Re: [Tutor] beginning to code]
Steve D'Aprano
steve+python at pearwood.info
Tue Sep 26 08:28:41 EDT 2017
On Tue, 26 Sep 2017 03:26 am, Antoon Pardon wrote:
>>> I'm not sure that Steve knows how it works. When he denies that the
>>> assignment is an alias operation in Python that casts an important doubt.
>>
>> I can assure you that Steve knows how it works. Again, the disagreement is
>> almost certainly over the semantics of the word "alias."
>
> Sorry, what he wrote contradicts that. Maybe he was just really confused
> at that moment, but it still needed correction. If the assignment is
> an alias operator then after the statements
>
> a = 1
> b = a
> b = 2
>
> a is not 2.
How do you get that conclusion? I think you are mistaken.
If assignment were an alias operation, then a would be 2, because b is an alias
to a. That's how var parameters in Pascal work, and out parameters in Ada, and
both are described as aliasing.
Its also how reference variables ("aliases") in C++ work.
https://www.tutorialspoint.com/cplusplus/cpp_references.htm
https://stackoverflow.com/a/17025902
Here's some C++ code that demonstrates it. Apologies in advance if it isn't the
most idiomatic C++ code.
#include <iostream>
#include<stdio.h>
using namespace std;
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.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list