473,766 Members | 2,060 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
36 28122
Jonathan Ellis 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:


Actually it is a reference to an object being passed.
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.

def foo(a): .... print id(a)
.... i = 10
id(i) 168377924 foo(i)

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 #11
JCM
Michael Hoffman <m.************ *************** ******@example. com> wrote:
....
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>
The memory location of the object is the same; the memory location of
the reference is different.
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.


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


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 #13
JCM
Josiah Carlson <jc******@uci.e du> wrote:
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.
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.
It's really not that different. It's very similar to the way Java
handles objects, and how scheme does argument-passing.
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.
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.
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 #14
Josiah Carlson <jc******@uci.e du> wrote:
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.


It is because Python does it differently from most other languages, and


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 #15

[snip section about Java]

Indeed, I meant in reference to C, but I should have been more precise.
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.


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.


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 #16
In article <uQ************ **@newsread3.ne ws.pas.earthlin k.net>,
Andrew Dalke <ad****@mindspr ing.com> wrote:
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.


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, do**@u.washingt on.edu
Jul 18 '05 #17
In article <41************ ***********@new s.free.fr>,
Bruno Desthuilliers <bd************ *****@free.quel quepart.fr> wrote:
....
*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.


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, do**@u.washingt on.edu
Jul 18 '05 #18
Josiah Carlson <jc******@uci.e du> wrote:
...
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.


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 #19
JCM
Alex Martelli <al*****@yahoo. com> wrote:
....
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...!-).


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 #20

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

Similar topics

1
5986
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
2947
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
10791
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
26596
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
2469
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
8087
by: howa | last post by:
Hi, Consider a simple example, e.g. var a = { 'a': 'b', 'c': 'd' }
1
1256
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
12379
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
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10168
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
10008
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
7381
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
6651
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3929
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
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.