call by reference howto????

Antoon Pardon apardon at forel.vub.ac.be
Fri Mar 14 06:33:39 EDT 2008


On 2008-03-13, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
> On Thu, 13 Mar 2008 08:54:43 +0000, Paul Rudin wrote:
>
>>> Whatever python has for a calling convention, it is close enough that
>>> naming it "call by reference" gives people a reasonable idea of what is
>>> going on.
>> 
>> Quite. The thing is not to get hung up with the label - but to
>> understand what actually happens.
>
> Agreed. And I think the best way to do that is to use the same terms that 
> other languages use to get very different behaviour indeed.
>
> "Python is call by reference, but this doesn't work like call by 
> reference in all the other languages I've used:
>
> def negate(n):
>     n = -n
>
> x = 2
> negate(x)
> assert x == -2
>
> Is this a bug, or is Python actually call by value?"

> And now comes the explanations that Python is actually call by value, but 
> the values being copied are *pointers* (ignoring Jython, IronPython and 
> PyPy); or that Python is really call by reference, but different 
> "things" (it's never quite clear what exactly) happen depending on 
> whether the arguments are mutable or immutable;

Which is wrong. The same thing happens with mutable and immutable
objects. What one needs to understand is:

Right after the call, x and n are the same object.
After the assigment x and n no longer are the same object.
The assignment doesn't negate the original object. It creates a
new object with the negative value of the original while the latter
remains bound to x.

As long as the person who has trouble with this behaviour doesn't
understand that the assignment is not a mutating operator. Your
explanation will get you nowhere. The trouble is mosly caused
because people see a line like n = -n and interpret this more
or less as the object bound to n has the negated value after
the assignment. That is why they think x should be -2 in your
example.

> or that if you define 
> reference broadly enough, everything is a reference; or that if you 
> define value broadly enough, everything is a value; or if schools would 
> just stop teaching kiddies C and start teaching them Lisp, call by 
> reference semantics would be understood in a different way, or or or or...


> And thus, by insisting that there are two and only two calling 
> conventions, no matter how many different kinds of calling behaviour 
> actually exist, we ensure that we'll be having this same *&$%^*# argument 
> when Python 4000 comes out.

But you seem to make the same kind of mistake, but with regard to
assignments. You seem to implicitly assume there is only one kind
of assignment and by trying to start from there and trying to
explain what goes on in terms of different calling conventions
you will ensure the same argument just as well.

-- 
Antoon Pardon



More information about the Python-list mailing list