Function args

Fraser Hanson fraser at fake_email.cx
Fri Apr 9 13:48:58 EDT 2004


Jean-Michel Caricand wrote:
> Hi,
> 
> I'm new in Python. I have a problem with function args. I want to pass 
> args by reference because the function must modify this arg. How I do 
> that in Python.
> 
> I didn't found documentation !

The short answer is, you can modify mutable types(lists and 
dictionaries) by passing them to a function.  You cannot modify 
immutable types (strings, numbers, tuples) in this way.  If you want to 
modify a variable pointing to an immutable type, then you must have your 
function return the modified value or values, and assign your value to 
the result of your function.  Like this:

	def func(s):
		return s + " shop"

	a = "cheese"
	a = func(a)
	print a                         # prints "cheese shop"

Python allows you to return multiple variables from a function call, so 
you can modify any number of variables with this method.  (Technically, 
when you use a statement like "return a,b,c" you are not returning three 
variables, you are returning one tuple.  Still it looks and acts like 
three variables, it's just good to be aware of these things.)

	def func(x,y,z):
		x = x + 5
		y = y + 10
		z = z + 15
		return x, y, z

	a, b, c = 1, 2, 3
	a, b, c = func(a,b,c)
	print a, b, c               # prints "6, 12, 18"


The reason for this is as follows.

All variables in Python are just names that point to the "real" object, 
sort of like C pointers.  When you pass an immutable type argument to a 
function, the function receives a new variable that happens to be 
pointing to the same object.  When you assign to that variable, you are 
making it point to a different object.  Thus when your function exits, 
your old variable in the original scope still points to the same object 
it did before the function call.  By assigning the original variable to 
something returned by your function, your are achieving the intended 
effect in a more explicit way.

Some of this is discussed in the documentation here:

	Mutable and immutable types:
	http://www.python.org/doc/2.3.3/ref/objects.html

	What happens during assignment:
	http://www.python.org/doc/2.3.3/ref/assignment.html

--Fraser Hanson

ps. Are you aware that your message was posted 12 times in a row?



More information about the Python-list mailing list