364,111 Members | 2056 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

By value or by reference?

Riccardo Rossi
P: n/a
Riccardo Rossi
Hi all!

How does Python pass arguments to a function? By value or by reference?

Thanks,
Riccardo Rossi.


Jul 18 '05
Share this Question
Share on Google+
36 Replies


Roger Irwin
P: n/a
Roger Irwin
Riccardo Rossi wrote:
[color=blue]
> Hi all!
>
> How does Python pass arguments to a function? By value or by reference?
>
> Thanks,
> Riccardo Rossi.
>
>[/color]
By reference to an object....See the python tutorial.
Jul 18 '05

Jorge Godoy
P: n/a
Jorge Godoy
"Riccardo Rossi" <riccardo.rorssi76@email.it> writes:
[color=blue]
> Hi all!
>
> How does Python pass arguments to a function? By value or by reference?[/color]

IIRC, by reference. It uses a copy on write algorithm.

--
Godoy. <godoy@ieee.org>
Jul 18 '05

Jonathan  Ellis
P: n/a
Jonathan Ellis
Roger Irwin wrote:[color=blue]
> Riccardo Rossi wrote:
>[color=green]
> > Hi all!
> >
> > How does Python pass arguments to a function? By value or by[/color][/color]
reference?[color=blue][color=green]
> >
> > Thanks,
> > Riccardo Rossi.
> >
> >[/color]
> By reference to an object....See the python tutorial.[/color]

Wrong. Here is the difference between pass by reference and pass by
value to CS types:
[color=blue][color=green][color=darkred]
>>> def foo(a): a = 1[/color][/color][/color]
....[color=blue][color=green][color=darkred]
>>> i = 10
>>> foo(i)
>>> print i[/color][/color][/color]

With pass-by-reference, i would now be 1. However, since python is
pass-by-value, it remains 10.

-Jonathan

Jul 18 '05

Alex Martelli
P: n/a
Alex Martelli
Jonathan Ellis <jbellis@gmail.com> wrote:
...[color=blue][color=green]
> > By reference to an object....See the python tutorial.[/color]
>
> Wrong. Here is the difference between pass by reference and pass by
> value to CS types:
>[color=green][color=darkred]
> >>> def foo(a): a = 1[/color][/color]
> ...[color=green][color=darkred]
> >>> i = 10
> >>> foo(i)
> >>> print i[/color][/color]
>
> With pass-by-reference, i would now be 1. However, since python is
> pass-by-value, it remains 10.[/color]

....so you tell "CS types" it's pass-by-value, and they come right back
with

def bar(b): b.append(2)

z = []
bar(z)
print z

With pass-by-value, they'll say, z would still be []. However, since
what is passed is not just (a copy of) the value, but (a reference to)
the object itself, z is [2] instead.

The terminology problem may be due to the fact that, in python, the
value of a name is a reference to an object. So, you always pass the
value (no implicity copying), and that value is always a reference.

I find it simpler to explain as: the semantics of argument passing are
_exactly_ identical to that of assignment (binding) to a barename; you
can fruitfully see argument passing as local (bare) names of the called
function being assigned initial values by the caller (that's exactly
what happens, in practice). Now if you want to coin a name for that,
such as "by object reference", "by uncopied value", or whatever, be my
guest. Trying to reuse terminology that is more generally applied to
languages where "variables are boxes" to a language where "variables are
post-it tags" is, IMHO, more likely to confuse than to help.


Alex
Jul 18 '05

Oliver Fromme
P: n/a
Oliver Fromme
Jonathan Ellis wrote:[color=blue]
> Roger Irwin wrote:[color=green]
> > Riccardo Rossi wrote:[color=darkred]
> > > How does Python pass arguments to a function? By value or by reference?[/color]
> >
> > By reference to an object....See the python tutorial.[/color]
>
> Wrong. Here is the difference between pass by reference and pass by
> value to CS types:
>[color=green][color=darkred]
> > > > def foo(a): a = 1[/color][/color]
> ...[color=green][color=darkred]
> > > > i = 10
> > > > foo(i)
> > > > print i[/color][/color]
>
> With pass-by-reference, i would now be 1. However, since python is
> pass-by-value, it remains 10.[/color]

It remains 10 because integers are immutable, so the function
code cannot modify the caller's variable anyway. However, if
you pass a mutable variable, things look a little different:
[color=blue][color=green][color=darkred]
>>> def foo(a): a[0] = 1[/color][/color][/color]
....[color=blue][color=green][color=darkred]
>>> i = [10]
>>> foo(i)
>>> print i[/color][/color][/color]
[1]

Best regards
Oliver

--
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)
Jul 18 '05

Bruno Desthuilliers
P: n/a
Bruno Desthuilliers
Riccardo Rossi wrote:[color=blue]
> Hi all!
>
> How does Python pass arguments to a function? By value or by reference?[/color]

Both...
Err, no, none.
Well...

*Short answer :*
args are passed by ref, but bindings are local.

*Long answer :*
You first need to understand what 'variables' in Python are. They are in
fact just a symbol referencing an object. Think of a Python 'variable'
as an entry in a dict, the name of the variable (the 'symbol') being the
key and the reference to the object being the value (AFAIK, this is
exactly what they are).

You also need to understand the difference between mutable and immutable
objects. Strings, numerics and tuples are immutables. Which means that
you can not change them. When doing :
s = "Hello "
s += "World"
.... you are not modifying the string object bound to s, but creating a
new string object and binding it to s.

Now for the "By Val/By Ref" stuff... well, try this :

def my_fun(my_arg):
print "in my_fun, before rebinding my_arg: my_arg = %s" % my_arg
my_arg = "42"
print "in my_fun, after rebinding my_arg: my_arg = %s" % my_arg

the_arg = "Life, the Universe, and Everything"

print "before call to my_fun: the_arg = %s" % the_arg
my_fun(the_arg)
print "after call to my_fun: the_arg = %s" % the_arg


You should have somthing like this :

before call to my_fun: the_arg = Life, the Universe, and Everything
in my_fun, before rebinding my_arg: my_arg = Life, the Universe, and
Everything
in my_fun, after rebinding my_arg: my_arg = 42
after call to my_fun: the_arg = Life, the Universe, and Everything

So what ? are we passing args by value ? Well, retry with :

def my_fun_2(my_arg_2):
print "in my_fun, before appending to my_arg_2: my_arg_2 = %s" %
my_arg_2
my_arg_2.append("42")
print "in my_fun, after appending to my_arg_2: my_arg_2 = %s" %
my_arg_2

the_arg_2 = ["Life, the Universe, and Everything"]

print "before call to my_fun_2: the_arg_2 = %s" % the_arg_2
my_fun_2(the_arg_2)
print "after call to my_fun_2: the_arg_2 = %s" % the_arg_2

and what do we get ?

before call to my_fun_2: the_arg_2 = ['Life, the Universe, and Everything']
in my_fun, before appending to my_arg_2: my_arg_2 = ['Life, the
Universe, and Everything']
in my_fun, after appending to my_arg_2: my_arg_2 = ['Life, the Universe,
and Everything', '42']
after call to my_fun_2: the_arg_2 = ['Life, the Universe, and
Everything', '42']

Argh ! So what ? Is it by val or by ref ?
Ok, let's try a third test :

def my_fun_3(my_arg_3):
print "in my_fun, before rebinding my_arg_3: my_arg_3 = %s" % my_arg_3
my_arg_3 = ["42"]
print "in my_fun, after rebinding my_arg_3: my_arg_3 = %s" % my_arg_3

the_arg_3 = ["Life, the Universe, and Everything"]

print "before call to my_fun_3: the_arg_3 = %s" % the_arg_3
my_fun_3(the_arg_3)
print "after call to my_fun_3: the_arg_3 = %s" % the_arg_3

An you get :
before call to my_fun_3: the_arg_3 = ['Life, the Universe, and Everything']
in my_fun, before rebinding my_arg_3: my_arg_3 = ['Life, the Universe,
and Everything']
in my_fun, after rebinding my_arg_3: my_arg_3 = ['42']
after call to my_fun_3: the_arg_3 = ['Life, the Universe, and Everything']

err... Time for some explanation ?-)

When you call a function with an arg, a "local variable" is created,
which references the object passed as the argument. (well... an entry
with the formal parameter name as key and a reference to the object
passed in is created in the 'local' dict).

So, rebinding this local symbol does not impact the binding in the
caller's namespace - because the symbol lives in another namespace.

*But* - and if the object referenced is mutable of course - modifying
the object in the function... well, just modifies the object, because
it's the *same* object that is bound to ('referenced by', if you prefer)
both symbols (the one in the caller's namespace and the one in the
function's namespace). So yes, the object *is* modified when the
function returns.

(Of course, doing anything to an immutable object is just rebinding the
symbol, so it won't never have any impact outside the function. So don't
expect to have a function having side-effects on strings, numerics and
tuples args. The good news being that this is not necessary, since the
only reason to do so would be to return multiple values, and Python can
already return multiple values.)


Does it make sens to you ?-)
[color=blue]
> Thanks,
> Riccardo Rossi.
>[/color]

HTH
Bruno

(Ho, BTW, please read the fine manual - and this too :
http://starship.python.net/crew/mwh/...jectthink.html)

Jul 18 '05

JCM
P: n/a
JCM
Jorge Godoy <godoy@ieee.org> wrote:[color=blue]
> "Riccardo Rossi" <riccardo.rorssi76@email.it> writes:[/color]
[color=blue][color=green]
>> Hi all!
>>
>> How does Python pass arguments to a function? By value or by reference?[/color][/color]
[color=blue]
> IIRC, by reference. It uses a copy on write algorithm.[/color]

Copy-on-write is an optimization. It doesn't affect the semantics of
the laguage.
Jul 18 '05

JCM
P: n/a
JCM
Oliver Fromme <olli@haluter.fromme.com> wrote:
....[color=blue][color=green][color=darkred]
> > > > > def foo(a): a = 1[/color]
> > ...[color=darkred]
> > > > > i = 10
> > > > > foo(i)
> > > > > print i[/color]
> >
> > With pass-by-reference, i would now be 1. However, since python is
> > pass-by-value, it remains 10.[/color][/color]
[color=blue]
> It remains 10 because integers are immutable, so the function
> code cannot modify the caller's variable anyway. However, if
> you pass a mutable variable, things look a little different:[/color]

It doesn't matter that integers are immutable. Rebinding formal
parameters cannot change variables in the callers scope.
[color=blue][color=green][color=darkred]
>>>> def foo(a): a[0] = 1[/color][/color]
> ...[color=green][color=darkred]
>>>> i = [10]
>>>> foo(i)
>>>> print i[/color][/color]
> [1][/color]

In this case, you're dereferencing the list (I'm using pointer-
terminolgy, but I'm still talking about the behavior of the language,
not its implemenation). You're basically modifying the object passed
into the function, not rebinding a variable.
Jul 18 '05

Andrew Dalke
P: n/a
Andrew Dalke
Jorge Godoy wrote:[color=blue]
> IIRC, by reference. It uses a copy on write algorithm.[/color]

Really? Where? I've heard theoretical rumblings about
that but didn't realized it had been added anywhere.

Andrew
dalke@dalkescientific.com
Jul 18 '05

Michael Hoffman
P: n/a
Michael Hoffman
Jonathan Ellis wrote:
[color=blue][color=green]
>>By reference to an object....See the python tutorial.[/color]
>
> Wrong. Here is the difference between pass by reference and pass by
> value to CS types:[/color]

Actually it is a reference to an object being passed.
[color=blue][color=green][color=darkred]
>>>>def foo(a): a = 1[/color][/color]
>
> ...
>[color=green][color=darkred]
>>>>i = 10
>>>>foo(i)
>>>>print i[/color][/color]
>
> With pass-by-reference, i would now be 1. However, since python is
> pass-by-value, it remains 10.[/color]
[color=blue][color=green][color=darkred]
>>> def foo(a):[/color][/color][/color]
.... print id(a)
....[color=blue][color=green][color=darkred]
>>> i = 10
>>> id(i)[/color][/color][/color]
168377924[color=blue][color=green][color=darkred]
>>> foo(i)[/color][/color][/color]
168377924

With pass-by-value, the memory location of a would be different than the
memory location of i. However, since Python is pass-by-reference, it
remains the same. <wink>

Alex is right that trying to shoehorn Python into a "pass-by-reference"
or "pass-by-value" paradigm is misleading and probably not very helpful.
In Python every variable assignment (even an assignment of a small
integer) is an assignment of a reference. Every function call involves
passing the values of those references.
--
Michael Hoffman
Jul 18 '05

JCM
P: n/a
JCM
Michael Hoffman <m.h.3.9.1.without.dots.at.cam.ac.uk@example.com > wrote:
....[color=blue]
> With pass-by-value, the memory location of a would be different than the
> memory location of i. However, since Python is pass-by-reference, it
> remains the same. <wink>[/color]

The memory location of the object is the same; the memory location of
the reference is different.
[color=blue]
> Alex is right that trying to shoehorn Python into a "pass-by-reference"
> or "pass-by-value" paradigm is misleading and probably not very helpful.
> In Python every variable assignment (even an assignment of a small
> integer) is an assignment of a reference. Every function call involves
> passing the values of those references.[/color]

I've given up expressing my opinion on the matter. Everyone here
seems to have a different notion of what "pass-by-reference" and
"pass-by-value" mean. It's funny--I've never run into trouble with
these terms before seeing these discussions on C.L.Py.
Jul 18 '05

Josiah Carlson
P: n/a
Josiah Carlson
[color=blue]
> I've given up expressing my opinion on the matter. Everyone here
> seems to have a different notion of what "pass-by-reference" and
> "pass-by-value" mean. It's funny--I've never run into trouble with
> these terms before seeing these discussions on C.L.Py.[/color]

It is because Python does it differently from most other languages, and
it doesn't fit the paradigms of "pass by value" or "pass by reference"
as already explained by Alex Martelli.

Python does name binding with references. That is, each reference is
given a name, but you cannot change data by assigning to a name; you can
only change what data that name points to. There are certain operations
that can be done with mutable objects and immutable objects, but that is
another discussion entirely.


There is not so much an argument, but there is a semantic "what the hell
is it doing" that is not being communicated properly. I am sure there
is a FAQ about this, but I don't have the link handy, and I can't quite
find the right incantation for Google.

- Josiah

Jul 18 '05

JCM
P: n/a
JCM
Josiah Carlson <jcarlson@uci.edu> wrote:
[color=blue][color=green]
>> I've given up expressing my opinion on the matter. Everyone here
>> seems to have a different notion of what "pass-by-reference" and
>> "pass-by-value" mean. It's funny--I've never run into trouble with
>> these terms before seeing these discussions on C.L.Py.[/color][/color]
[color=blue]
> It is because Python does it differently from most other languages, and
> it doesn't fit the paradigms of "pass by value" or "pass by reference"
> as already explained by Alex Martelli.[/color]

It's really not that different. It's very similar to the way Java
handles objects, and how scheme does argument-passing.
[color=blue]
> Python does name binding with references. That is, each reference is
> given a name, but you cannot change data by assigning to a name; you can
> only change what data that name points to. There are certain operations
> that can be done with mutable objects and immutable objects, but that is
> another discussion entirely.[/color]

Yes. These two issues often get muddled together in discussions about
argument passing. Are you avoiding the term "variable"? Some don't
like to use it because they see Python as somehow fundamentally
different than other languages. I think the term fits nicely.
[color=blue]
> There is not so much an argument, but there is a semantic "what the hell
> is it doing" that is not being communicated properly. I am sure there
> is a FAQ about this, but I don't have the link handy, and I can't quite
> find the right incantation for Google.[/color]
[color=blue]
> - Josiah[/color]

Jul 18 '05

Alex Martelli
P: n/a
Alex Martelli
Josiah Carlson <jcarlson@uci.edu> wrote:
[color=blue][color=green]
> > I've given up expressing my opinion on the matter. Everyone here
> > seems to have a different notion of what "pass-by-reference" and
> > "pass-by-value" mean. It's funny--I've never run into trouble with
> > these terms before seeing these discussions on C.L.Py.[/color]
>
> It is because Python does it differently from most other languages, and[/color]

Actually, where "real objects" are concerned (there's a slew of
exceptions for primitive builtin types such as int) Java has quite
similar semantics for both assignment and parameter passing. Python's
simpler: no exceptions. C#'s more complicated: besides the types that
are built-in exceptions you can also make user-defined types that are
also exceptions. But exceptions apart, the 'fundamental' semantics of
assignments and assignment passing is similar in all three languages.


Alex
Jul 18 '05

Josiah Carlson
P: n/a
Josiah Carlson

[snip section about Java]

Indeed, I meant in reference to C, but I should have been more precise.
[color=blue][color=green]
> > Python does name binding with references. That is, each reference is
> > given a name, but you cannot change data by assigning to a name; you can
> > only change what data that name points to. There are certain operations
> > that can be done with mutable objects and immutable objects, but that is
> > another discussion entirely.[/color]
>
> Yes. These two issues often get muddled together in discussions about
> argument passing. Are you avoiding the term "variable"? Some don't
> like to use it because they see Python as somehow fundamentally
> different than other languages. I think the term fits nicely.[/color]

In my mind, "variable" implies that the data is implicitly "variable" by
assignment, which is not the case in Python.

Underlying name binding in Python is a Python dictionary; a mapping of
keys to values, where keys are names, and values are pointers to actual
data (there are optimizations for local scopes that replace the
dictionary with a static table, but one could use a dictionary and it
would work the same).

As a result, an assignment in a scope is no more than doing doing an
assignment to a key/value pair in dictionary, with similar "hey, we're
just swapping pointers on assignment, not changing the data itself" (at
least in terms of the 'value' part of the key,value pair).


In a C-semantic pass by reference, you get the pointer to the actual
data, and when you assign to that pointer, you change the data itself.
In a C-semantic pass by value, you get a value with copy on write
semantics.

If what Python does is like Java, perhaps C# or what have you, great. It
is, however, different from the C semantic description of "pass by value",
"pass by reference", and the standard CS education definition of either.

- Josiah

Jul 18 '05

Donn Cave
P: n/a
Donn Cave
In article <uQScd.273$%h1.11@newsread3.news.pas.earthlink.net >,
Andrew Dalke <adalke@mindspring.com> wrote:
[color=blue]
> Jorge Godoy wrote:[color=green]
> > IIRC, by reference. It uses a copy on write algorithm.[/color]
>
> Really? Where? I've heard theoretical rumblings about
> that but didn't realized it had been added anywhere.[/color]

I think this is a misimpression - the copy on write
part, I mean - that may go back to a discussion that
took place a year ago here, where someone energetically
but erroneously advocated that point of view.

Donn Cave, donn@u.washington.edu
Jul 18 '05

Donn Cave
P: n/a
Donn Cave
In article <4173eed0$0$29488$636a15ce@news.free.fr>,
Bruno Desthuilliers <bdesth.quelquechose@free.quelquepart.fr> wrote:
....[color=blue]
> *Short answer :*
> args are passed by ref, but bindings are local.
>
> *Long answer :*
> You first need to understand what 'variables' in Python are. They are in
> fact just a symbol referencing an object. Think of a Python 'variable'
> as an entry in a dict, the name of the variable (the 'symbol') being the
> key and the reference to the object being the value (AFAIK, this is
> exactly what they are).
>
> You also need to understand the difference between mutable and immutable
> objects. Strings, numerics and tuples are immutables. Which means that
> you can not change them. When doing :
> s = "Hello "
> s += "World"
> ... you are not modifying the string object bound to s, but creating a
> new string object and binding it to s.[/color]

Well, true enough for string, but not true for list for example.

Aside from this wretched wart on the language, as another followup
has already pointed out, you really don't need to distinguish
mutable vs. immutable to understand argument passing and variable
binding in Python.

If you write:
def f(a, b):
a = 5
b.flog(5)

.... it makes no difference whether either argument is mutable
or immutable. a becomes a different object notwithstanding,
and b.flog operates on the caller's original object whether flog
modifies anything or not. We tend to make this too complicated.

Donn Cave, donn@u.washington.edu
Jul 18 '05

Alex Martelli
P: n/a
Alex Martelli
Josiah Carlson <jcarlson@uci.edu> wrote:
...[color=blue]
> If what Python does is like Java, perhaps C# or what have you, great. It
> is, however, different from the C semantic description of "pass by value",
> "pass by reference", and the standard CS education definition of either.[/color]

C is also very simple, just like Python: C always does pass by value.
I.e., C always does implicit copy (on assignment or parameter passing),
just like Python never does.

So in C you ask explicitly when you want a reference (pointer) instead,
e.g. with &foo -- in Python you ask explicitly when you want a copy
instead, e.g. with copy.copy(foo). Two simple language, at opposite
ends of the semantics scale, but each consistent and clean. (Python
matches 4.5 of the 5 points which define "the spirit of C" according to
the latter's Standard's preface...!-).

[[ok, each has its warts -- e.g. C has arrays which mysteriously decay
into pointers instead of getting copied, Python has slices that make
copies instead of sharing part of the original sequence [or not; it
depends whether said sequence is a list or Numeric.array, sigh...] --
being human and being perfect are incompatible traits. But _mostly_
they have simplicity and consistency, everything explicit.]]

The key point is that, in both languages, a function's arguments are
just like local variables pre-initialized by the caller with assignment
statements. In both languages, if the function reassigns an argument
it's just playing with its own local variables, the caller is never in
any way affected by that. In both languages, there are other ways
except plain barename assignments to possibly "affect the caller" (in C
you basically need to have been passed a pointer, and dereference that
pointer or another pointer computed from the first by pointer
arithmetic; in Python you basically need to have been passed a mutable
object, and call mutating methods on that object). Again, in both cases
I see simplicity and consistency, everything pretty explicit...


Alex
Jul 18 '05

JCM
P: n/a
JCM
Alex Martelli <aleaxit@yahoo.com> wrote:
....[color=blue]
> C is also very simple, just like Python: C always does pass by value.
> I.e., C always does implicit copy (on assignment or parameter passing),
> just like Python never does.[/color]
[color=blue]
> So in C you ask explicitly when you want a reference (pointer) instead,
> e.g. with &foo -- in Python you ask explicitly when you want a copy
> instead, e.g. with copy.copy(foo). Two simple language, at opposite
> ends of the semantics scale, but each consistent and clean. (Python
> matches 4.5 of the 5 points which define "the spirit of C" according to
> the latter's Standard's preface...!-).[/color]

This is misleading. copy.copy does a smart, data-structure-aware copy
(not a deep copy, but exactly what copy.copy does differs among
datatypes). Parameter passing isn't about data structures; it's about
what an assignment statement means when you're assigning to a formal
parameter within a function (also possibly about some other things
like lazy evaluation), for example whether the argument list is a
declaration of new variables or just a set of aliases for other
pre-existing values (I don't say "variables" here because the value
passed in may be anonymous).
Jul 18 '05

Josiah Carlson
P: n/a
Josiah Carlson
> The key point is that, in both languages, a function's arguments are[color=blue]
> just like local variables pre-initialized by the caller with assignment
> statements. In both languages, if the function reassigns an argument
> it's just playing with its own local variables, the caller is never in
> any way affected by that. In both languages, there are other ways
> except plain barename assignments to possibly "affect the caller" (in C
> you basically need to have been passed a pointer, and dereference that
> pointer or another pointer computed from the first by pointer
> arithmetic; in Python you basically need to have been passed a mutable
> object, and call mutating methods on that object). Again, in both cases
> I see simplicity and consistency, everything pretty explicit...[/color]

I agree with most everything you have said, though consider the pointer
vs. value of C to define the semantics of the passing. That is, if you
get a pointer in C, it is by reference. If you don't get a pointer, it
is by value.

I also agree that everything is pure and explicit in both languages, it
took me a few minutes mucking around with the interpreter my first time
to understand how Python deals with the base types.

I'm trying to point out that if you toss the standard C semantic
definition of "pass by value" and "pass by reference", by merely
pretending that the definitions have not been given in the history of
computer science, and just look at how Python does actual name binding
in namespaces/scopes, you can understand what Python does much better
than to get into a "Python does pass by reference" vs. "Python does pass
by value" argument.


- Josiah

Jul 18 '05

Jeremy Bowers
P: n/a
Jeremy Bowers
On Mon, 18 Oct 2004 15:30:54 +0000, Riccardo Rossi wrote:
[color=blue]
> Hi all!
>
> How does Python pass arguments to a function? By value or by reference?[/color]

Summarizing all of the arguments, it is "Pass by reference, by value".

The functions receive copies of the references, but the function receives
a new reference by value, not "the same reference" as it is in C++.

def something(a):
a = 11

immediately discards the passed-in reference with no affect on the caller.

This is never correct in Python:

somefunction() = "some value"

This is sort of "because" of the way Python bind names, and in another
sense, is the *cause* of the Python name binding behavior :-)
Jul 18 '05

Bengt Richter
P: n/a
Bengt Richter
On Mon, 18 Oct 2004 18:04:58 +0200, aleaxit@yahoo.com (Alex Martelli) wrote:
[color=blue]
>Jonathan Ellis <jbellis@gmail.com> wrote:
> ...[color=green][color=darkred]
>> > By reference to an object....See the python tutorial.[/color]
>>
>> Wrong. Here is the difference between pass by reference and pass by
>> value to CS types:
>>[color=darkred]
>> >>> def foo(a): a = 1[/color]
>> ...[color=darkred]
>> >>> i = 10
>> >>> foo(i)
>> >>> print i[/color]
>>
>> With pass-by-reference, i would now be 1. However, since python is
>> pass-by-value, it remains 10.[/color]
>
>...so you tell "CS types" it's pass-by-value, and they come right back
>with
>
>def bar(b): b.append(2)
>
>z = []
>bar(z)
>print z
>
>With pass-by-value, they'll say, z would still be []. However, since
>what is passed is not just (a copy of) the value, but (a reference to)
>the object itself, z is [2] instead.
>
>The terminology problem may be due to the fact that, in python, the
>value of a name is a reference to an object. So, you always pass the
>value (no implicity copying), and that value is always a reference.
>
>I find it simpler to explain as: the semantics of argument passing are
>_exactly_ identical to that of assignment (binding) to a barename; you
>can fruitfully see argument passing as local (bare) names of the called
>function being assigned initial values by the caller (that's exactly
>what happens, in practice). Now if you want to coin a name for that,
>such as "by object reference", "by uncopied value", or whatever, be my
>guest. Trying to reuse terminology that is more generally applied to
>languages where "variables are boxes" to a language where "variables are
>post-it tags" is, IMHO, more likely to confuse than to help.
>
>[/color]
Maybe something like this can help elucidate the mechanism(s) of passing arguments?
(I.e., as a sort of automatic tuple formation from the arg list and unpacking it
into the locals indicated by the parameter name list)?
[color=blue][color=green][color=darkred]
>>> a = 1
>>> b = 'two'
>>> def foo(x,y):[/color][/color][/color]
... print 'x=%r, y=%r'%(x, y)
...[color=blue][color=green][color=darkred]
>>> def bar(*args):[/color][/color][/color]
... x, y = args
... print 'x=%r, y=%r'%(x, y)
...[color=blue][color=green][color=darkred]
>>> c = (a, b)
>>> foo(a,b)[/color][/color][/color]
x=1, y='two'[color=blue][color=green][color=darkred]
>>> foo(*c)[/color][/color][/color]
x=1, y='two'[color=blue][color=green][color=darkred]
>>> bar(a,b)[/color][/color][/color]
x=1, y='two'[color=blue][color=green][color=darkred]
>>> bar(*c)[/color][/color][/color]
x=1, y='two'

Regards,
Bengt Richter
Jul 18 '05

Dan Bishop
P: n/a
Dan Bishop
"Riccardo Rossi" <riccardo.rorssi76@email.it> wrote in message news:<OkRcd.157598$35.7725273@news4.tin.it>...[color=blue]
> Hi all!
>
> How does Python pass arguments to a function? By value or by reference?[/color]

If you're familiar with C, think of it this way

/* Python function

def foo(arg1, arg2):
localA = arg1
localB = bar(arg2)
# ...

*/
object *foo(object *arg1, object *arg2) {
object *localA = arg1;
object *localB = bar(arg2);
/* ... */
}
Jul 18 '05

Alex Martelli
P: n/a
Alex Martelli

On 2004 Oct 18, at 22:46, Josiah Carlson wrote:
...[color=blue]
>
> I agree with most everything you have said, though consider the pointer
> vs. value of C to define the semantics of the passing. That is, if you
> get a pointer in C, it is by reference. If you don't get a pointer, it
> is by value.[/color]

I disagree: you get the value of the pointer. If you assign to the
barename of the pointer, this has no effect on the caller.

void foo(int* x) {
x = 0;
}

the fact that x is a pointer makes no difference whatsoever: the x=0;
within function foo is just assigning to local variable 'x', without
any effect on the caller, just as if the signature was '(int x)'
instead.

"By reference" semantics, in e.g. Fortran, Visual Basic, Pascal, C++,
...., are normally taken to mean that the function can do:
x = 0;
i.e. assign to the barename of an argument, and thereby affect the
caller. In Fortran (traditionally) it's always that way (the language
definition supports both value/return and reference semantics, with
lots of strictures on what is semantically correct in order to ensure
both mechanisms work; in practice, implementations for the last 30+
years have used references, 99% of Fortran programmers are unaware of
the strictures, and get big surprises when an aggressive optimizer,
taking advantage of the constraints the programmers routinely violate,
turns their code into mush;-). In Pascal, defining an argument in the
signature as "x:integer" or "var x:integer" makes all the difference;
in Visual Basic, the adjectives Byval and Byref do; in C++, the
referencemarker ampersand ('int&x' in the signature); etc.

C has nothing like that. You can explicitly take the address of
something, you can pass (by value!) an address ('pointer'), you can
dereference an address -- and these are the mechanisms you can use to
get PAST the lack of byref parameters. The workarounds in Fortran for
the lack of byval parameters are sometimes even funnier: you see X+0
passed as the actual argument, for example, or sometimes X*1, in the
hope that this will make a copy of X and thereby preserve X from
modification (the interested reader can study the Fortran 66 and 77
manuals to see how this tricks have fared, standardswise... compilers
often are more accomodating than the standards, though in the Fortran
world optimization is SO crucial that this need not be so...).
[[similar tricks in Python are using L[:], L+[], or L*1, to get a copy
of L -- less forgivable in Python where list(L) does that cleanly,
explicitly and legibly, of course;-)]]
[color=blue]
>
> I also agree that everything is pure and explicit in both languages, it
> took me a few minutes mucking around with the interpreter my first time
> to understand how Python deals with the base types.
>
> I'm trying to point out that if you toss the standard C semantic
> definition of "pass by value" and "pass by reference", by merely
> pretending that the definitions have not been given in the history of
> computer science, and just look at how Python does actual name binding
> in namespaces/scopes, you can understand what Python does much better
> than to get into a "Python does pass by reference" vs. "Python does
> pass
> by value" argument.[/color]

I agree. But in C you cannot possibly do better than "C does pass by
value, and assigns by value [with an unfortunate hack regarding arrays
decaying to pointers]". The concept of passing by reference is needed
in other languages, but not in C (nor Python). "Pass by value"
normally (for most languages) implies a copy: once you realize that
Python doesn't do implicit copies (the +[], *1 and [:] hacks
notwithstanding, those ARE computing expressions after all) then 'pass
by value' is in fact just as applicable to Python -- the difference is
not in how arguments are passed, but in the fact that in Python a
name's value is ALWAYS a reference to an object, so the value (that is
passed) IS the reference (to the object), while in C variables are
little boxes with their value inside, so the value that is passed is a
copy of the box's contents (some of those boxes, known as pointers,
hold addresses...).


Alex

Jul 18 '05

36 Replies

Post your reply

Help answer this question



Didn't find the answer to your Python question?

You can also browse similar questions: Python byref+python python byref