473,414 Members | 1,711 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

function-arguments by reference

EsC
Hy!

is it possible to pass function-arguments by reference?
(for example in PHP you can use the "&" operator ... )

thx
iolo
Jul 18 '05 #1
7 1812
"EsC" <ch****************@liwest.at> writes:
is it possible to pass function-arguments by reference?
(for example in PHP you can use the "&" operator ... )


No. If there's a specific situation you want to handle, say what it
is and someone will say how to deal with it in Python. For example if
you want a function that returns multiple values, just return a list:

def get_three_nums ():
return (2, 3, 5)

a, b, c = get_three_nums ()

sets a=2, b=3, and c=5. You don't have to do anything kludgy like
"get_three_nums (&a, &b, &c)" or whatever. If you want to swap two
variables, you can just use a list assignment like in perl:

(x, y) = (y, x)
Jul 18 '05 #2
EsC:
is it possible to pass function-arguments by reference?


This is a FAQ.
http://www.python.org/doc/faq/progra...l-by-reference

--
René Pijlman
Jul 18 '05 #3
On Tue, 30 Dec 2003 14:21:46 +0100, rumours say that "EsC"
<ch****************@liwest.at> might have written:
Hy!

is it possible to pass function-arguments by reference?
(for example in PHP you can use the "&" operator ... )

thx
iolo


There is no such concept as "pass by value" in python. Only references
are passed around, and therefore there is no special syntax for that.

What you need to understand is that objects can be mutable (changeable)
or immutable. Search for these terms in the python documentation.

In other languages, variables are a container: they contain a "value".
In python, "variables" are only "names" referring to "objects" and they
have no "value". If you assign anything to a name, you just change the
object it is pointing to.

Presumably you ask this question because you want your function to pass
back some more data than its return value. Python handles fine multiple
values, check for "tuple" in the docs.

An example: (I am not familiar with php, therefore I will write program
A in pseudocode, but you will get the point I hope)

function f(&a):
if (a > 10) then a = 10
return (a*2)

var = 20
result = f(var)

This function makes sure that the "var" variable stays less than or
equal to 10, and then returns the double of the corrected argument.

In python you would do this:

def f(a):
if a > 10:
a = 10
return a, a*2

var = 20
var, result = f(var)

If not covered, please write back.

PS reading this could be helpful too:
http://www.effbot.org/zone/python-objects.htm

--
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix
Jul 18 '05 #4
EsC
hy!

thanks for your explanations!

i want to avoid performance-problems by repeated (very often)
function-calls with very long strings.
in some languages (C, PHP, Powerbuilder, ...) i have the opportunity,
to pass "by value" or "by reference/pointer)".

"by value": the CPU must perform a complete copy of the string
"by reference/pointer": only a long value (address) is passed ...
the performance difference is in most cases unimportant, but sometimes ...

Unfortunately i made an error by testing the behavior of Phyton, and
so i thougt, LISTs are also passed "by value".
But this isn't true, and so i can solve my problem by putting the string-
argument in the first place of a list.

greetings
iolo
"Christos TZOTZIOY Georgiou" <tz**@sil-tec.gr> schrieb im Newsbeitrag
news:79********************************@4ax.com...
On Tue, 30 Dec 2003 14:21:46 +0100, rumours say that "EsC"
<ch****************@liwest.at> might have written:
Hy!

is it possible to pass function-arguments by reference?
(for example in PHP you can use the "&" operator ... )

thx
iolo


There is no such concept as "pass by value" in python. Only references
are passed around, and therefore there is no special syntax for that.

What you need to understand is that objects can be mutable (changeable)
or immutable. Search for these terms in the python documentation.

In other languages, variables are a container: they contain a "value".
In python, "variables" are only "names" referring to "objects" and they
have no "value". If you assign anything to a name, you just change the
object it is pointing to.

Presumably you ask this question because you want your function to pass
back some more data than its return value. Python handles fine multiple
values, check for "tuple" in the docs.

An example: (I am not familiar with php, therefore I will write program
A in pseudocode, but you will get the point I hope)

function f(&a):
if (a > 10) then a = 10
return (a*2)

var = 20
result = f(var)

This function makes sure that the "var" variable stays less than or
equal to 10, and then returns the double of the corrected argument.

In python you would do this:

def f(a):
if a > 10:
a = 10
return a, a*2

var = 20
var, result = f(var)

If not covered, please write back.

PS reading this could be helpful too:
http://www.effbot.org/zone/python-objects.htm

--
TZOTZIOY, I speak England very best,
Ils sont fous ces Redmontains! --Harddix

Jul 18 '05 #5
JCM
EsC <ch****************@liwest.at> wrote:
hy! thanks for your explanations! i want to avoid performance-problems by repeated (very often)
function-calls with very long strings.
in some languages (C, PHP, Powerbuilder, ...) i have the opportunity,
to pass "by value" or "by reference/pointer)".


The text of the string is not copied; a reference to the string/object
is passed into the function. You can modify objects passed into
functions (but only if they're mutable--strings and integers are
examples of immutable objects), but you cannot rebind the variable
holding the value in the caller's scope.

There have been some discussions in this newsgroup about whether
Python is call-by-value or not. I'm not sure if I want to recommend
looking for them; there was no good consensus about the terminology.
Jul 18 '05 #6
EsC
hy JCM!

damned - you are right!
i didn't know the way Python is handling arguments
up to now! It's a little bit different to other languages
i know - and somtimes even a little bit easier.

i made some (useless) performance-tests to proof your exclamations ...
if somebody is interested: i enclosed the code and results ...

- String 1 & String2: only read-access within the called function
the runtime is almost identical; therefore the text of the string can't
be copied
- String 3: the argument string is modified but NOT passed back to
the caller;
- String 4: the argument string is passed "by reference" within a
list object and modified.

i think this informations are very interesting
thanks!

greetings
iolo
------------ CODE -------------
import sys
from string import *
from time import *

def ls(str):
return len(str)

def ll(str):
return len(str[0])

def as(str):
str += "x"
return len( str )

def al(str):
str[0] += "x"
return len( str[0] )

loop = 2000
strlen = 30000
strl = []
strl.append("")
strs = ""

for a in range(strlen):
strs += 'x'
strl[0] += 'y'

print "Loop: ", loop
print "Stringlength: " , strlen

print
print 'String 1'
l = 0
start = time()
for x in range(loop):
l += ls(strs)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if strlen == l / loop:
print 'OK'
else:
print 'ERROR'

print
print 'String 2'
l = 0
start = time()
for x in range(loop):
l += ll(strl)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if strlen == l / loop:
print 'OK'
else:
print 'ERROR'

print
print 'String 3'
l = 0
start = time()
for x in range(loop):
l += as(strs)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if l == loop * strlen + loop:
print 'OK'
else:
print 'ERROR'

print
print 'String 4'
l = 0
start = time()
for x in range(loop):
l += al(strl)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if l == (loop / 2 ) * ((strlen + 1) + (strlen + loop)):
print 'OK'
else:
print 'ERROR'

---------------- RESULT ----------------
Loop: 50000
Stringlength: 200000

String 1
duration in seconds: 0.0620000362396
result: 10000000000
OK

String 2
duration in seconds: 0.0779999494553
result: 10000000000
OK

String 3
duration in seconds: 3.2349998951
result: 10000050000
OK

String 4
duration in seconds: 5.93700003624
result: 11250025000
OK
--------------------------------------------------

"JCM" <jo******************@myway.com> schrieb im Newsbeitrag
news:bs**********@fred.mathworks.com...
EsC <ch****************@liwest.at> wrote:
hy!

thanks for your explanations!

i want to avoid performance-problems by repeated (very often)
function-calls with very long strings.
in some languages (C, PHP, Powerbuilder, ...) i have the opportunity,
to pass "by value" or "by reference/pointer)".


The text of the string is not copied; a reference to the string/object
is passed into the function. You can modify objects passed into
functions (but only if they're mutable--strings and integers are
examples of immutable objects), but you cannot rebind the variable
holding the value in the caller's scope.

There have been some discussions in this newsgroup about whether
Python is call-by-value or not. I'm not sure if I want to recommend
looking for them; there was no good consensus about the terminology.

Jul 18 '05 #7
EsC wrote:
hy JCM!

damned - you are right!
i didn't know the way Python is handling arguments
up to now! It's a little bit different to other languages
i know - and somtimes even a little bit easier.

i made some (useless) performance-tests to proof your exclamations ...
if somebody is interested: i enclosed the code and results ...

- String 1 & String2: only read-access within the called function
the runtime is almost identical; therefore the text of the string can't
be copied

I don't think your test code proves that the string is not copied, only
that passing a reference to a string takes approximately the same amount
of time as passing a reference to a list and accessing the 1st item.

A better "proof" that the string is not copied is:
s1 = 'this is a string'
def f(s2): ... print s1 is s2
... f(s1) True


The "True" result indicates that both s1 and s2 are bound to the same
string object.
- String 3: the argument string is modified but NOT passed back to
the caller;
- String 4: the argument string is passed "by reference" within a
list object and modified.

i think this informations are very interesting
thanks!

greetings
iolo
------------ CODE -------------
import sys
from string import *
from time import *

def ls(str):
return len(str)

def ll(str):
return len(str[0])

def as(str):
str += "x"
return len( str )

def al(str):
str[0] += "x"
return len( str[0] )

loop = 2000
strlen = 30000
strl = []
strl.append("")
strs = ""

for a in range(strlen):
strs += 'x'
strl[0] += 'y'

print "Loop: ", loop
print "Stringlength: " , strlen

print
print 'String 1'
l = 0
start = time()
for x in range(loop):
l += ls(strs)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if strlen == l / loop:
print 'OK'
else:
print 'ERROR'

print
print 'String 2'
l = 0
start = time()
for x in range(loop):
l += ll(strl)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if strlen == l / loop:
print 'OK'
else:
print 'ERROR'

print
print 'String 3'
l = 0
start = time()
for x in range(loop):
l += as(strs)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if l == loop * strlen + loop:
print 'OK'
else:
print 'ERROR'

print
print 'String 4'
l = 0
start = time()
for x in range(loop):
l += al(strl)
end = time()
print "duration in seconds: ", end - start
print "result: ", l
if l == (loop / 2 ) * ((strlen + 1) + (strlen + loop)):
print 'OK'
else:
print 'ERROR'

---------------- RESULT ----------------
Loop: 50000
Stringlength: 200000

String 1
duration in seconds: 0.0620000362396
result: 10000000000
OK

String 2
duration in seconds: 0.0779999494553
result: 10000000000
OK

String 3
duration in seconds: 3.2349998951
result: 10000050000
OK

String 4
duration in seconds: 5.93700003624
result: 11250025000
OK
--------------------------------------------------

"JCM" <jo******************@myway.com> schrieb im Newsbeitrag
news:bs**********@fred.mathworks.com...

EsC <ch****************@liwest.at> wrote:

hy!
thanks for your explanations!
i want to avoid performance-problems by repeated (very often)
function-calls with very long strings.
in some languages (C, PHP, Powerbuilder, ...) i have the opportunity,
to pass "by value" or "by reference/pointer)".

The text of the string is not copied; a reference to the string/object
is passed into the function. You can modify objects passed into
functions (but only if they're mutable--strings and integers are
examples of immutable objects), but you cannot rebind the variable
holding the value in the caller's scope.

There have been some discussions in this newsgroup about whether
Python is call-by-value or not. I'm not sure if I want to recommend
looking for them; there was no good consensus about the terminology.


--
Matt Goodall, Pollenation Internet Ltd
w: http://www.pollenation.net
e: ma**@pollenation.net

Jul 18 '05 #8

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

Similar topics

2
by: | last post by:
OK: Purpose: Using user's input and 3 recursive functions, construct an hour glass figure. Main can only have user input, loops and function calls. Recursive function 1 takes input and displays...
2
by: joe | last post by:
hi, after reading some articles and faq, i want to clarify myself what's correct(conform to standard) and what's not? or what should be correct but it isn't simply because compilers don't...
5
by: amit kumar | last post by:
I am calling a function which returns pointer to a map. The declaration of the map is map<int,vectxyz*>. vectxyz is a vector containing pointer to a class xyz. For map<int,vectxyz*>* p1 In the...
16
by: WittyGuy | last post by:
Hi, What is the major difference between function overloading and function templates? Thanks! http://www.gotw.ca/resources/clcm.htm for info about ]
1
by: John | last post by:
// Between these two ways of creating a JS function, do they represent the exact same thing?: function myFn(a) {return 1;} // SAMPLE A myFn = function(a) {return 1;} // SAMPLE B // ... and...
5
by: phil_gg04 | last post by:
Dear Javascript Experts, Opera seems to have different ideas about the visibility of Javascript functions than other browsers. For example, if I have this code: if (1==2) { function...
2
by: sushil | last post by:
+1 #include<stdio.h> +2 #include <stdlib.h> +3 typedef struct +4 { +5 unsigned int PID; +6 unsigned int CID; +7 } T_ID; +8 +9 typedef unsigned int (*T_HANDLER)(void); +10
8
by: Olov Johansson | last post by:
I just found out that JavaScript 1.5 (I tested this with Firefox 1.0.7 and Konqueror 3.5) has support not only for standard function definitions, function expressions (lambdas) and Function...
2
by: f rom | last post by:
----- Forwarded Message ---- From: Josiah Carlson <jcarlson@uci.edu> To: f rom <etaoinbe@yahoo.com>; wxpython-users@lists.wxwidgets.org Sent: Monday, December 4, 2006 10:03:28 PM Subject: Re: ...
6
by: RandomElle | last post by:
Hi there I'm hoping someone can help me out with the use of the Eval function. I am using Access2003 under WinXP Pro. I can successfully use the Eval function and get it to call any function with...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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...
0
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...
0
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...
0
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...

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.