[Tutor] How to do call by reference (or equiv.) in Py?

Jeff Shannon jeff@ccvcorp.com
Fri Nov 22 16:29:02 2002


Aztech Guy wrote:

> Hi fellow Pythonistas,
>
> I have a C background - but am a Py newbie ...
>
> How does one do call by reference in Python ? I.e. pass a variable
> by reference ? Or is it not possible at all ? Does that mean that
> I'd have to simulate the effect by using "return" ?

In general, you don't use pass-by-reference semantics.

The Pythonic way of doing things is to leave parameters unchanged.
Any changes that you want to make should be done through return
values.  The advantage of Python over C in this regard, is that a
Python function can return multiple values (or, more specifically, it
returns a tuple which can be automatically unpacked into multiple
values).

So, if you wanted a function to translate a pair of (x, y)
coordinates, in C++ you'd probably pass your variables by reference
and modify the parameters.  In Python, it'd make more sense to do
something like this:

def translate(x, y):
    new_x = (x * 2)
    new_y = (y * 3) - 20
    return (new_x, new_y)

You then use this function like so:

xval, yval = translate(x, y)

Or, if you really want to modify the names that you started with,

x, y = translate (x, y)

C/C++ programmers are so accustomed to using pointers and references
that this approach seems odd to them, but it really is more intuitive
-- having the value of a variable change depending on whether it's
used as a function parameter or not, can be a bit confusing.  The
style I use makes all changes to variables happen through explicit
assignment, so it's much easier to follow.

(There *are* ways to force reference-like semantics in Python, and the
true nature of Python variables is actually more reference-like than
value-like, but these are advanced topics and I don't have the time to
go into that just now...)

Jeff Shannon
Technician/Programmer
Credit International