anything like C++ references?

Noah noah at noah.org
Sun Jul 13 19:21:56 CEST 2003


Tom Plunket <tomas at fancy.org> wrote in message news:<13t0hvsb7idh0g6ac3upe5k0qd6flc17ah at 4ax.com>...
> I want to do something along the lines of the following C++ code:
> 
> void change(int& i)
> {
>    i++;
> }
> 
> 
> Is there any way to do references like this in Python?  It'd be
> like this, though clearly this doesn't change the thing I want it
> to change:
> 
> def change(val):
>    val += 1
> 
> v = 0
> change(v)
> 
> # v == 1 now.
> 
> thanks.
> 
> I can see that maybe if I passed in a list of one integer I could
> change that, but that seems circuitous to me.
> 
> 
> -tom!

As others have explained, you just return the value.
It's just a different point of view. Instead of
    change (v)
you have:
    v = change (v)

I was a C++ programmer in a former life and I remember being
annoyed at the lack of references in Python -- I mean, why would
something so obvious and cool as a reference variable be excluded, right?
Where people usually find themselves wanting references is 
when they need to modify more than one value at once.
For example, consider a function to rotate a 3D point through 
two angles, where x,y,z get modified by the rotate function:
    rotate (x,y,z, theta, phi)
Here you just have to remember that Python can return more than one
value at once as a tuple. So you should expect the code to look like this:
    x,y,z = rotate (x,y,z, theta, phi)
Your rotate() function would return a simple tuple as:
    return (x,y,z)

After I unlearned the C++ idiom I decided I liked the Python idiom better.
It's a teensy bit more verbose, but it is far more clear as to what
is going on. Your inputs and output are clearly defined. With C++ references
you have to look up the function definition to know which variables in modified.

Yours,
Noah




More information about the Python-list mailing list