Call by binding [was Re: [Tutor] beginning to code]
bartc
bc at freeuk.com
Sun Sep 24 11:56:06 EDT 2017
On 24/09/2017 15:49, Steve D'Aprano wrote:
> On Mon, 25 Sep 2017 12:35 am, Stefan Ram wrote:
>
>> WRT to assertions about Python, I try to base them on the
>> "The Python Language Reference, Release 3.6.0" (PRL).
>>
>> So, WRT to parameter passing, I would use this part of the PRL:
>>
>> »The following constructs bind names: formal parameters
>> to functions,« PRL 4.2.1
>>
>> . Therefore, what Python does, I'd call »call by binding«.
>
> I am not aware of "call by binding" being a well-known or recognised term. Did
> you make it up?
>
> Also, the problem is that *any* form of function call binds *something* to the
> function parameters. If we consider the Pascal declaration:
>
> procedure proc(x: integer; var y: integer);
>
>
> and then we call it:
>
> var
> a, b: integer;
> begin
> a := 1;
> b := 2;
> proc(a, b);
> end.
>
>
> then 1 is bound to x and 2 is bound to y. They happen to exist in different
> scopes (x is local to proc, the *name* y is local to proc, but the variable is
> bound to y is global) but that's not important.
>
> The point I am making is that we could describe just about any and all languages
> with functions "call by binding", whether they are call by value like C, call
> by reference like Fortran, call by need like Haskell, or call by sharing like
> Python.
Then 'binding' is either ill-defined or used wrongly.
Imagine that each name (a,b,x,y) is a little box.
In Pascal, the boxes for a and b contain 1 and 2 respectively. For x and
y, they contain pointers (dereferenced behind the scenes). Fortran is
similar (or Fortran IV was; I don't know modern ones). C works the same
way: every variable has a box, and that box directly contains a value.
In Python, those boxes don't contain anything, except one end of a piece
of string. The other end is attached to an object.
When you pass a variable to a function like this:
def fn(X):
A=1
fn(A)
Then X gets set up with a string which has the same object at the other
end as A. (And the object might have a reference count to reflect that
extra string.)
This is why you can't change A in the caller as there is no way to get
from X's box to A's box. And the strings to the object are one-way.
In the case of fn(A+2), a new object is created (with value '3', or an
existing '3' might be used), a new string is attached to it, and the
other is attached to X.
--
bartc
More information about the Python-list
mailing list