I'm wrong or Will we fix the ducks limp?
BartC
bc at freeuk.com
Wed Jun 8 08:34:54 EDT 2016
On 08/06/2016 12:01, Antoon Pardon wrote:
> Op 08-06-16 om 12:33 schreef BartC:
>> But a 'proper' reference allows a complete replacement of what it
>> refers to. That would mean being able to do:
>>
>> B = "Cat"
>> print A # "Cat"
>>
>> No tricks involving in-place updates such as assigning to list
>> elements are needed.
>
> No it doesn't mean that. It means that if you mutate the object through one variable,
> you can see the result of that mutation through the other variable. But if the
> assignment doesn't mutate, you can't have such effect through assignment.
>
> In python, you can sometimes simulate a mutating assignment and then we get this.
>
> >>> A = [8, 5, 3, 2]
> >>> B = A
> >>> B[:] = [3, 5, 8, 13]
> >>> A
> [3, 5, 8, 13]
Well, it then becomes necessary to separate a mutating assignment
(a[i]=b) where the left-hand-size modifies part of a larger object, from
a full assignment (a=b) which replaces a whole object (the value of a)
with another.
So you have partial updates and full updates. A proper reference will be
able to do both via the reference. Python can only do a partial update
and the reason is that the reference points to the object, not the
variable; there is no way to change the variable to link it with
another, distinct object.
If the object is a list, then that can be modified to any extent, even
replacing the contents completely, but it will still be a list. In the
case of an int or string, then it's impossible to change. So there are
limitations to what can be done.
Getting back to Pascal (as I /can/ remember how reference parameters
work for integers), assigning to a reference integer parameter in a
function will change the caller's version. Python can only emulate that
by passing a one-element list or using some such trick. Affecting
readability and, likely, performance.
--
Bartc
More information about the Python-list
mailing list