[Tutor] beginning to code

Ned Batchelder ned at nedbatchelder.com
Mon Sep 25 15:44:23 EDT 2017


On 9/25/17 5:32 AM, Antoon Pardon wrote:
> Can you explain, what you mean by "Pass-By-Reference" as far a I understand,
> pass by reference means that the parameter of the function becomes an alias
> of the argument, so that if the entity is mutated through one name that
> mutation is visible through the other name.
>
>> function(x, y)  # allowed
>> function(namespace.x, module.y)  # allowed
>> function(x + 1, 2)  # FORBIDDEN: can't pass expressions or constants
> Pass by reference, doesn't imply the above is forbidden. A language can
> define, that the "x + 1" will produce an new entity and that a reference
> to that entity will be passed.
>

Wikipedia has the right definition of call by reference 
(https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference):

    /Call by reference/ (also referred to as /pass by reference/) is an
    evaluation strategy where a function receives an implicit reference
    <https://en.wikipedia.org/wiki/Reference_%28computer_science%29> to
    a variable used as argument, rather than a copy of its value. This
    typically means that the function can modify (i.e. assign to
    <https://en.wikipedia.org/wiki/Assignment_%28computer_science%29>)
    the variable used as argument—something that will be seen by its caller.

The key idea here is that it is a reference to a *variable* that is 
passed, not a reference to a value.  Python has no references to 
variables, so it cannot support call by reference.   Because Python 
passes references to values, it is easy to call it "call by reference," 
but that is not what the term means.

The Wikipedia definition unfortunately includes "rather than a copy of 
its value," as if those are the only two options (a common 
misunderstanding).

Elsewhere in this thread, someone asserted that to be call by reference, 
you have to be able to write a swap(x,y) function.  True 
call-by-reference would make this possible.  Python cannot do it.

--Ned.



More information about the Python-list mailing list