call-by-reference (was Re: Any other Python flaws?)

Donn Cave donn at u.washington.edu
Fri Jun 15 19:55:05 EDT 2001


Quoth jcm <grumble at usa.net>:
| Martijn Faassen <m.faassen at vet.uu.nl> wrote:
|> jcm <grumble at usa.net> wrote:
|>> In my experience, there's good agreement about what call-by-reference
|>> means just about everywhere but in newsgroups.  Python supports only
|>> call-by-value -- you can't change the value of a variable in your
|>> caller's scope (globals aside).
|
|> Um, I wouldn't say it that way. Python supports changing the value a
|> name references just fine:
|
|> def foo(a):
|>    a.append(42)
|
|> l = [1, 2, 3]
|> foo(l)
|
| Note I said you can't change the value of a _variable_ in your
| caller's scope.  Changing the state of an object isn't the same.

Aside from the semantics of whether the state of an object has
anything to do with its value, etc., it's questionable whether
"you can't change the value of a variable" is the way to identify
"call by value".  It may be, but then it just illustrates why
"call by value" isn't relevant to Python.

Call by value in a language like C is a copy operation.  Your
function receives a copy of the variable.  So of course it can
change the value of the copy, but the original is unaffected.
If you say Python calls by value, then Martijn's example shows
that it doesn't make this copy, so there's some confusion.  You
can say Python calls by value but not the same way that C does,
but that begs the question, what good does it do to say call by
value, if it doesn't mean something reasonably consistent?

If we give up on call by value and decide Python must therefore
call by reference, then you can drag out your examples and show
how it can't be doing that.

Python has "call by the one right way".

	Donn Cave, donn at u.washington.edu

-- call by value C example.

struct Z {
    int a, b;
};
int
bfol(struct Z z)
{
    z.a = 0;
}

-- Python (un)equivalent
def bfol(z):
    z.a = 0



More information about the Python-list mailing list