Pass by reference?

Jacek Generowicz jmg at ecs.soton.ac.uk
Thu May 25 12:09:28 CEST 2000


Dale Strickland-Clark wrote:

> Also the following program proves to me that arguments are passed by value
> and not by reference:

No, it doesn't, but I agree that if you do not keep in mind exactly what `='
does in Python, then you are likely to think so.

> def wibble(var):
>     var = 1
>
> x = 0
> wibble(x)
> print x
>
> It prints 0 showing that the assignment in wibble is made to a copy of x
>
> So - how do I pass a variable to a function/subroutine/method by reference?
>
> Thanks for any insight into this.

The deal is approximately this: Each time you use `=', the variable on the left
becomes a reference to whatever appears on the right. Function argument passing
is done by the same mechanism.

So, in your example, when x is passed to wibble(), wibble's var becomes a
reference to x. Then, when you assign 1 to var, var becomes a reference to 1.

Remeber that Python objects can be classed as mutable or immutable. Try passing
a mutable object to wibble, and mutating it in place (as opposed to
re-assigning it) and you will find that the argument really is passed by
reference.

program:
===============
def wibble( mutable ):
    mutable[0] = 5

x = [1]
print x
wibble( x )
print x
================
output:

[1]
[5]
=================

Now, change the body of wibble() to  mutable = [5] and you will find that x
remains unchanged.

Make sense ?

Jacek





More information about the Python-list mailing list