473,749 Members | 2,451 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

By value or by reference?

Hi all!

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

Thanks,
Riccardo Rossi.
Jul 18 '05 #1
36 28121
Riccardo Rossi wrote:
Hi all!

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

Thanks,
Riccardo Rossi.

By reference to an object....See the python tutorial.
Jul 18 '05 #2
"Riccardo Rossi" <ri************ ***@email.it> writes:
Hi all!

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


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

--
Godoy. <go***@ieee.org >
Jul 18 '05 #3
Roger Irwin wrote:
Riccardo Rossi wrote:
Hi all!

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

Thanks,
Riccardo Rossi.

By reference to an object....See the python tutorial.


Wrong. Here is the difference between pass by reference and pass by
value to CS types:
def foo(a): a = 1 .... i = 10
foo(i)
print i


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

-Jonathan

Jul 18 '05 #4
Jonathan Ellis <jb*****@gmail. com> wrote:
...
By reference to an object....See the python tutorial.


Wrong. Here is the difference between pass by reference and pass by
value to CS types:
def foo(a): a = 1 ... i = 10
foo(i)
print i


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


....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 #5
Jonathan Ellis wrote:
Roger Irwin wrote:
Riccardo Rossi wrote:
How does Python pass arguments to a function? By value or by reference?


By reference to an object....See the python tutorial.


Wrong. Here is the difference between pass by reference and pass by
value to CS types:
> def foo(a): a = 1 ... > i = 10
> foo(i)
> print i
With pass-by-reference, i would now be 1. However, since python is
pass-by-value, it remains 10.


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:
def foo(a): a[0] = 1 .... i = [10]
foo(i)
print i

[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 #6
Riccardo Rossi wrote:
Hi all!

How does Python pass arguments to a function? By value or by reference?
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_ar g_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_ar g_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 ?-)
Thanks,
Riccardo Rossi.


HTH
Bruno

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

Jul 18 '05 #7
JCM
Jorge Godoy <go***@ieee.org > wrote:
"Riccardo Rossi" <ri************ ***@email.it> writes:
Hi all!

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

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


Copy-on-write is an optimization. It doesn't affect the semantics of
the laguage.
Jul 18 '05 #8
JCM
Oliver Fromme <ol**@haluter.f romme.com> wrote:
....
> > > > def foo(a): a = 1 > ...
> > > > i = 10
> > > > foo(i)
> > > > print i

>
> With pass-by-reference, i would now be 1. However, since python is
> pass-by-value, it remains 10. 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:


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

[1]


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 #9
Jorge Godoy wrote:
IIRC, by reference. It uses a copy on write algorithm.


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

Andrew
da***@dalkescie ntific.com
Jul 18 '05 #10

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

Similar topics

1
5985
by: Christopher | last post by:
Hi all, I am trying to store a reference to a variable in my data providerr class but cannot save a reference to it. Can anyone help me? I would like this code to allow me to store any field by referenece so that it's contents can be written to using the Value property.
5
2946
by: Jerry Morton | last post by:
Hi, I'm new to C# and have run into a problem of my own making! I originally took from the documentation that as long as I didn't use the "ref" keyword in method declarations, that everything would be passed "by value". I now believe I was incorrect and that it's only types like int, bool, etc. that behave like that? i.e. things like XmlDocument are always passed by reference in method calls? I was writing a "wrapper" class around a...
35
10786
by: hasho | last post by:
Why is "call by address" faster than "call by value"?
4
1757
by: mflanagan | last post by:
I think I've figured out my interop problems, but I'd like some confirmation that I'm not going down the wrong path. I'm connecting to a web service over which I have no control, and it's written in Java. My client is written in C#. Several of the WSDLs use nil char, nil dateTime, nil decimal (that is, they all use 'nillable', they do not use occurs=0) for many of the response variables. Therefore, I have to do something in my proxy...
13
26595
by: mitchellpal | last post by:
i am really having a hard time trying to differentiate the two..........i mean.....anyone got a better idea how each occurs?
14
2468
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 is happening? also a copy is passed ? in C++ there is a pass-by-reference too... and in that case the paramter can be considered as an alias of the argument...
7
2139
by: Nikola Skoric | last post by:
I noticed that System.Windows.Forms.Form constructor treats his parameters as though they are passed by reference even if I omit the "ref" keyword. Why's (and how does he do) that? Shouldn't objects be passed by value if I don't explicitly put "ref" in parameter list? -- "Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms...
5
8085
by: howa | last post by:
Hi, Consider a simple example, e.g. var a = { 'a': 'b', 'c': 'd' }
1
1255
by: puzzlecracker | last post by:
I am sort of confused about the differences among them as I am coming from C++ Can anyone explain how they are allocated, where are they stored, etc? I am also shocked that struct is value type? Can struct have member methods? Thanks
275
12346
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
8833
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9568
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9389
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6801
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3320
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2794
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.