472,977 Members | 1,703 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,977 software developers and data experts.

Pass by reference or by value?

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.

Jul 13 '07 #1
10 13383
On Jul 13, 2:10 pm, Robert Dailey <rcdai...@gmail.comwrote:
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.
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.

Jul 13 '07 #2
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
Jul 13 '07 #3
Robert Dailey a écrit :
On Jul 13, 2:10 pm, Robert Dailey <rcdai...@gmail.comwrote:
>>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".
Jul 13 '07 #4
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 && ma*@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
Jul 13 '07 #5
On Jul 13, 2:10 pm, Robert Dailey <rcdai...@gmail.comwrote:
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.

Jul 13 '07 #6
On Jul 13, 9:10 pm, Robert Dailey <rcdai...@gmail.comwrote:
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.


Jul 14 '07 #7
[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/...jectthink.html
http://effbot.org/zone/python-objects.htm

In article <11**********************@22g2000hsm.googlegroups. com>,
sturlamolden <st**********@yahoo.nowrote:
>On Jul 13, 9:10 pm, Robert Dailey <rcdai...@gmail.comwrote:
>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 (aa**@pythoncraft.com) <* http://www.pythoncraft.com/

I support the RKAB
Jul 15 '07 #8
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/...jectthink.html
http://effbot.org/zone/python-objects.htm
Eh... That's more than one line. :-)
Jul 16 '07 #9
On Jul 13, 11:58 pm, sturlamolden <sturlamol...@yahoo.nowrote:

<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.

Jul 16 '07 #10
Beliavsky wrote:
On Jul 13, 11:58 pm, sturlamolden <sturlamol...@yahoo.nowrote:

<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.
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 -------------

Jul 16 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: dumboo | last post by:
hi there i m little bit confused over the following problem, i have understood wt the following code is doing...but not able to get the actual techinical stuff.....i have had a lot of hot debate...
9
by: Alvin Bruney | last post by:
The more knowledgable I get about this .net world, the more questions I have. ..NET uses pass by reference for all objects....uhhh I mean pass by value. (Couldn't resist this jab) Consider a...
4
by: z_learning_tester | last post by:
I'm reading the MS press C# book and there seems to be a contradiction. Please tell me which one is correct, 1 or 2. Thanks! Jeff 1. First it gives the code below saying that it prints 0 then...
13
by: pauldepstein | last post by:
My texts give plenty of examples where passing by reference is necessary. For instance, the famous swap example. However, I've never seen an example where passing a variable by value is...
14
by: xdevel | last post by:
Hi, I need your help because I don't understand very well this: in C arguments are passed by-value. The function parameters get a copy of the argument values. But if I pass a pointer what really...
4
by: kinaxx | last post by:
Hello, now I'm learning progamming language in university. but i have some question. in textbook. says there are four passing Mechanism 1) pass by value (inother words : call by value) 2)...
11
by: kinaxx | last post by:
Hello, now I'm learning progamming language in university. but i have some question. in textbook. says there are four passing Mechanism 1) pass by value (inother words : call by value) 2)...
13
by: Francois Appert | last post by:
This post was originally in the C# Corner site, but their server is down. I'd like to see if this group can answer. I program in C++ and am learning C#. The issue is: why should anybody...
11
by: venkatagmail | last post by:
I have problem understanding pass by value and pass by reference and want to how how they are or appear in the memory: I had to get my basics right again. I create an array and try all possible...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.