function-arguments by reference

Christos TZOTZIOY Georgiou tzot at sil-tec.gr
Tue Dec 30 08:39:20 EST 2003


On Tue, 30 Dec 2003 14:21:46 +0100, rumours say that "EsC"
<christian.eslbauer at 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




More information about the Python-list mailing list