Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Pass by reference or by value?

3 views
Skip to first unread message

Robert Dailey

unread,
Jul 13, 2007, 3:10:32 PM7/13/07
to
Hi,

I noticed in Python all function parameters seem to be passed by
reference. This means that when I modify the value of a variable of a
function, the value of the variable externally from the function is
also modified.

Sometimes I wish to work with "copies", in that when I pass in an
integer variable into a function, I want the function to be modifying
a COPY, not the reference. Is this possible?

Thanks.

Robert Dailey

unread,
Jul 13, 2007, 3:22:43 PM7/13/07
to

Correction:

I ran a few more tests and python actually does a pass by value,
meaning that a "copy" is made and the external variable that was
passed in remains unchanged. I actually want to know how to "pass by
reference", in that any changes made to a parameter inside of a
function also changes the variable passed in.

Thanks.

James Stroud

unread,
Jul 13, 2007, 3:28:47 PM7/13/07
to

Not only is this possible, that is actually what happens with ints!

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/

James Stroud

unread,
Jul 13, 2007, 3:34:47 PM7/13/07
to
Robert Dailey wrote:
> I actually want to know how to "pass by
> reference", in that any changes made to a parameter inside of a
> function also changes the variable passed in.

Pass a mutable type.

py> class C(object):
... def __repr__(self):
... return str(self.value)
... def __init__(self, v):
... self.value = v
...
py> c = C(4)
py> c
4
py> def doit(v):
... v.value = v.value * 2
...
py> doit(c)
py> c
8

James

star....@gmail.com

unread,
Jul 13, 2007, 4:11:43 PM7/13/07
to
On Jul 13, 3:10 pm, Robert Dailey <rcdai...@gmail.com> wrote:
> Hi,
>
> I noticed in Python all function parameters seem to be passed by
> reference. ... [And later otherwise, etc, snip]

Heya. Go read through the thread from yesterday, title starts with
"Understanding Python Functions" -- they go through the whole pass by
object, mutable vs immutable stuff pretty well in there.

Short possibly bad version: Assigning (inclding to a function var)
makes a new name for an object, reassigning (x=...) only changes what
the indvidual name (x) means, but changing the object itself
(x[n]=..., x.n=..., etc) affects anything that has a name for that
object. Names are names, not variables.

--
Weaver[0]=Star

Carsten Haese

unread,
Jul 13, 2007, 4:42:47 PM7/13/07
to pytho...@python.org
On Fri, 2007-07-13 at 19:22 +0000, Robert Dailey wrote:
> Correction:
>
> I ran a few more tests and python actually does a pass by value,
> meaning that a "copy" is made

That is patently incorrect. A function call in Python *never* makes a
copy of any of its arguments.

> and the external variable that was
> passed in remains unchanged.

That depends entirely on what kind of object the "variable" is and how
you're trying to change the "variable."

> I actually want to know how to "pass by
> reference", in that any changes made to a parameter inside of a
> function also changes the variable passed in.

Python is Pass By Reference. Always. Period.

The root of your misunderstanding is that you don't understand how the
assignment statement works in Python. You come from the world of C where
a variable is a predefined memory location and "a=1;" means "Write the
value '1' into the memory location that is inhabited by 'a',
obliterating any contents that were previously in this memory location."

Python doesn't actually have variables. Python has objects and
namespaces, and assignment statements work very differently. This has
been widely discussed before. For more information, see
http://effbot.org/zone/python-objects.htm and the thread "Understanding
python functions" that started just yesterday on this very same list.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net


Bruno Desthuilliers

unread,
Jul 14, 2007, 12:46:06 AM7/14/07
to
Robert Dailey a écrit :

> On Jul 13, 2:10 pm, Robert Dailey <rcdai...@gmail.com> wrote:
>
>>Hi,
>>
>>I noticed in Python all function parameters seem to be passed by
>>reference.
(snip)

>
> Correction:
>
> I ran a few more tests and python actually does a pass by value,
(snip)

Still wrong !-)

Python passes references to objects, but the *names* are local. So while
*mutating* (ie: calling a method that changes the state of) an object in
a function will impact the object outside the function, *rebinding* a
name will not impact the name outside the function.

But anyway, as Star mentionned, Ben Finney gave a pretty good (IMHO)
explanation in the nearby thread named "understanding python functions".

Erik Max Francis

unread,
Jul 13, 2007, 6:26:13 PM7/13/07
to
James Stroud wrote:

> Robert Dailey wrote:
>> I noticed in Python all function parameters seem to be passed by
>> reference. This means that when I modify the value of a variable of a
>> function, the value of the variable externally from the function is
>> also modified.
>>
>> Sometimes I wish to work with "copies", in that when I pass in an
>> integer variable into a function, I want the function to be modifying
>> a COPY, not the reference. Is this possible?
>

> Not only is this possible, that is actually what happens with ints!

But that's because ints are immutable, not because there is an explicit
copy of anything being made.

--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
Ipsa scientia potestas est. "Knowledge itself is power."
-- a Latin proverb

James Stroud

unread,
Jul 13, 2007, 7:02:42 PM7/13/07
to
Erik Max Francis wrote:
> James Stroud wrote:
>
>> Robert Dailey wrote:
>>
>>> I noticed in Python all function parameters seem to be passed by
>>> reference. This means that when I modify the value of a variable of a
>>> function, the value of the variable externally from the function is
>>> also modified.
>>>
>>> Sometimes I wish to work with "copies", in that when I pass in an
>>> integer variable into a function, I want the function to be modifying
>>> a COPY, not the reference. Is this possible?
>>
>>
>> Not only is this possible, that is actually what happens with ints!
>
>
> But that's because ints are immutable, not because there is an explicit
> copy of anything being made.
>

Yes. I was taking his quotes around "copies" to mean a description of
behavior and not implementation.

James

Dan Bishop

unread,
Jul 13, 2007, 7:31:50 PM7/13/07
to
On Jul 13, 2:10 pm, Robert Dailey <rcdai...@gmail.com> wrote:
> Hi,
>
> I noticed in Python all function parameters seem to be passed by
> reference. This means that when I modify the value of a variable of a
> function, the value of the variable externally from the function is
> also modified.

Python is pass-by-value. It's just that all values are implicit
"pointers". Much like Java except without a distinction between
primitives and objects.

> Sometimes I wish to work with "copies", in that when I pass in an
> integer variable into a function, I want the function to be modifying
> a COPY, not the reference. Is this possible?

Typically, there's no reason to make a copy of an immutable object.
But if you want to copy things, take a look at the "copy" module.

sturlamolden

unread,
Jul 13, 2007, 11:58:55 PM7/13/07
to
On Jul 13, 9:10 pm, Robert Dailey <rcdai...@gmail.com> wrote:

> I noticed in Python all function parameters seem to be passed by
> reference. This means that when I modify the value of a variable of a
> function, the value of the variable externally from the function is
> also modified.


Pass-by-value and pass-by-reference usually refer to the semantics
used in C and Fortran, respectively.


Here is an example showing the distinction between the 'pass-by-value'
semantics of C and the 'pass-by-reference' semantics of Fortran:


In C you can pass pointers, but it is still a pure 'pass-by-value'
semantics. The pointer itself is passed by value (which is an
address). What that means, is that the function receives a copy of the
argument used in the call:

int a = 1;
foo(&a);
bar(&a);

void foo(int *a)
{
a = (int*) 0; /* no side effect */
}

void bar(int *a)
{
*a = 0; /* side effect, but a is still passed by value */
}

Now take a look at how the functions foo and bar are called. They both
have the same signature,
void ()(* int). Thus they must be called equivalently. But still one
produces a side-effect and the other does not. Often in C litterature
you can see what happens in the function bar called 'pass-by-
reference'. But that is very incorrect, C never passes anything by
reference.

'Pass-by-value' is thus equivalent to 'pass-a-copy'.


In Fortran you can only pass references.

integer(4) :: a
a = 1
call bar(a)

subroutine bar(a)
integer(4) :: a
a = 0 ! side-effect
end subroutine

That means, when a variable is used to call a function, the function
receives a pointer to the actual argument, not a local copy. That is
very different from C's copy-passing behaviour.

C++ can pass-by-value and pass-by-reference:

int a = 1;
foo(&a); // no side-effect
bar(&a); // side-effect
foo2(a); // no side-effect
bar2(a); // side-effect!!!

void foo(int *a) // pass-by-value
{
a = (int*) 0; // no side effect
}

void bar(int *a) // pass-by-value
{
*a = 0; // side effect, but a is still passed by value
}


void foo2(int a) // pass-by-value
{
a = 0; // no side effect !!!
}


void bar2(int &a) // pass-by-reference
{
a = 0; // side effect !!!
}

The C++ example clearly shows what we mean by pass-by-reference. It
seems when we call the function bar2 that we give it the value of a,
when we in fact give it a reference to a. That is the same thing that
happens in Fortran.

What it all boils down to is this:


Local copies are made in the 'pass-by-value' semantics.
Local copies are not made in the 'pass-by-reference' semantics.

Now that we have defined 'pass-by-value' and 'pass-by-reference'
precisely, it is time to examine what Python does.

It turns out that Python neither works like C nor like Fortran.
Rather, Python works like LISP. That is:


Python names are pointers bound to values.
Python always pass pointers to values.
Python never pass local copies.
Function arguments are referenced by names in the function's local
namespace.
Names referencing function arguments can be rebound in the local
scope.


>From this you might think that Python does pass-by-reference. Afterall
it does not create local copies. But as names can be rebound in the
local scope, function calls in Python and Fortran behave very
differently.

That is:

a = 1 # a points to an int(1)
foobar(a)
# a still points to an int(1)

def foobar(a):
a = 0 # rebinds a locally, produces no side-effect
# in Fortran this would have produced a side-effect


Now, examine this code sniplet:

a = 1 # a points to an int(1)
foobar(a)
# a still points to an int(1) as an int is immutable
a = [1, 2, 3] # rebinds a, a points to a mutable type
foobar(a)
# a points to [1,2,3,1,2,3]

def foobar(a):
a *= 2 # rebinds a only if a points to an immutable type,
# otherwise the value pointed to by a is changed


If you take a careful look at these examples, you should be able to
figure out what Python does.

Python does 'pass-by-reference' in the sense that it always pass
pointers.

Python does 'pass-by-value' in the sense that names has a local scope
and can be rebound in the local scope.

The correct statement would be to say that Python does neither pass-by-
reference nor pass-by-value in the conventional meaning of the terms.

Rather Python does 'pass-as-lisp'.

Sturla Molden

P.S. You could think of Python as a Java only having reference types.
What makes the semantics of Java and C# 'pass-by-value' like C, is the
fact that they make copies of value-types when passed to a function. A
reference type is also passed by value, in this case the value of the
reference is passed. Python does not have value types. But Python does
have immutable types. An int is an immutable type in Python and a
value type in Java. What happens when Python and Java calls a function
with an int as argument is very different. Java makes a copy of the
int and passes that. Python passes a pointer to the int. But as an int
is immutable in Python, it may look like Python passes ints 'by value'
when in fact it never creates a local copy.


Aahz

unread,
Jul 15, 2007, 7:07:43 PM7/15/07
to
[posted and e-mailed]

[top-posting because I want to make only a one-line response]

Please stick this on a web-page somewhere -- it makes an excellent
counterpoint to

http://starship.python.net/crew/mwh/hacks/objectthink.html
http://effbot.org/zone/python-objects.htm

In article <1184385535.5...@22g2000hsm.googlegroups.com>,


--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/

I support the RKAB

John DeRosa

unread,
Jul 16, 2007, 1:10:07 PM7/16/07
to
On 15 Jul 2007 16:07:43 -0700, aa...@pythoncraft.com (Aahz) wrote:

>[posted and e-mailed]
>
>[top-posting because I want to make only a one-line response]
>
>Please stick this on a web-page somewhere -- it makes an excellent
>counterpoint to
>
>http://starship.python.net/crew/mwh/hacks/objectthink.html
>http://effbot.org/zone/python-objects.htm

Eh... That's more than one line. :-)

Beliavsky

unread,
Jul 16, 2007, 1:40:06 PM7/16/07
to
On Jul 13, 11:58 pm, sturlamolden <sturlamol...@yahoo.no> wrote:

<snip>

> In Fortran you can only pass references.
>
> integer(4) :: a
> a = 1
> call bar(a)
>
> subroutine bar(a)
> integer(4) :: a
> a = 0 ! side-effect
> end subroutine
>
> That means, when a variable is used to call a function, the function
> receives a pointer to the actual argument, not a local copy. That is
> very different from C's copy-passing behaviour.

In Fortran, if a procedure argument is modified within the procedure,
that change is propagated to the value of the argument in the caller.
The standard does NOT mandate how this is accomplished, and one could
in theory write a compiler that makes a local copy of all procedure
arguments, as long as the variables passed as arguments were updated
in the caller. Early implementations of Fortran 90 often made copies
of array arguments, hurting performance. Current compilers do this
less often.

It is common to pass constants and expressions to Fortran procedures,
which does not fit the pass-by-reference paradigm.

Fortran 2003 has the VALUE attribute to give the C pass-by-value
behavior when desired.

Steve Holden

unread,
Jul 16, 2007, 1:55:26 PM7/16/07
to pytho...@python.org
You can pass a reference to a constant just as easily as you can pass a
reference to a variable. The only think you have to ensure is that when
you pass a reference to a constant something stops the procedure from
changing it.

Some early Fortran compilers omitted this small but important detail,
leading to programs with incomprehensible semantics, as the values of
numeric literals could no longer be relied upon.

> Fortran 2003 has the VALUE attribute to give the C pass-by-value
> behavior when desired.
>

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Message has been deleted
0 new messages