473,585 Members | 2,596 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 28082
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
5973
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
2939
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...
35
10757
by: hasho | last post by:
Why is "call by address" faster than "call by value"?
4
1752
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...
13
26582
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
2454
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...
7
2128
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...
5
8074
by: howa | last post by:
Hi, Consider a simple example, e.g. var a = { 'a': 'b', 'c': 'd' }
1
1248
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
12169
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
7832
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...
0
8192
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. ...
0
6592
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5705
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...
0
5382
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3828
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2338
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
1
1442
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1167
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.