A question on modification of a list via a function invocation

Steve D'Aprano steve+python at pearwood.info
Wed Aug 16 20:41:13 EDT 2017


On Thu, 17 Aug 2017 08:29 am, Mok-Kong Shen wrote:

> I have earlier learned some other (older) programming languages. For
> these the formal parameters are either "by reference" or "by value".

By reference and by value are not the only two conventions.

Perhaps if you go back to the 1950s you might be able to argue that "reference"
and "value" are the only two conventions, but alternatives have existed for
many decades, since *at least* 1960 when Algol introduced "call by name".

Python's evaluation strategy has existed for at least 43 years since Barbara
Liskov named the calling convention used by CLU "call by sharing" in 1974.

(It actually is much older than CLU, it goes back all the way to Lisp.)

https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing


> In the first case, any modification of the formal parameter 

Technically, you cannot modify the formal parameter, because the formal
parameter is just a name unbound to any value. It's just the label in the
function definition. You need to have actually passed a value as argument to
the function before there is anything to modify.

> inside 
> a function affects the corresponding actual parameter of a function
> call, while in the second case a copy of the actual parameter is
> passed into the function so that any modification of the formal
> parameter inside the function has no effect at all outside. This is
> extremely clear-cut in comparison to Python, isn't it?

Python (and Ruby, Scheme, Ocaml, etc) are very clear-cut too. Just different.

This may help:

http://import-that.dreamwidth.org/1130.html


> Anyway, while 
> any new user of a programming language certainly can be expected to
> take good efforts to learn a lot of new stuffs, I suppose it's good
> for any practical programming language to minimize the cases of
> surprises for those that come from other programming languages.

Indeed. And call by value is surprising: why should passing a giant array of a
million values make a copy of the array just because I pass it to a function?

And call by reference is even more surprising: if I assign a value to a local
name inside a function, why should it modify names in the caller's namespace?

Python's evaluation strategy is the least surprising of all the calling
strategies I've used.




-- 
Steven D'Aprano
“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