Question

Is it possible in python to pass a reference by reference? In C++, the python model of passing data can be mimicked by passing a pointer to the data: the pointer is passed by value, and the function can change whatever it points to, but the function cannot change the value of the pointer. However, in C++ you can also pass a reference to the pointer, in which case you can modify the pointer value as well as the thing it points to.

What I have in mind is an analogue of the following C++ snippet,

#include <iostream>

int k=5;

void fun(int * &p)
    {
    p=&k;
    }

int main()
    {
    int i=3;
    int *p = &i;

    std::cout << *p << std::endl;
    fun(p);
    std::cout << *p << std::endl;
    }

The function changes the value of the pointer p which was passed in; the output is '3' and '5'.

If I drop the '&' in the function declaration above I get something like what the following python snippet does:

def fun(p):
    p=5

p=3
print p
fun(p)
print p

Which prints 3 twice because fun cannot change the value of the 'reference' p in the main body. Any way to get the behaviour as in the C++ bit above?

(For completeness: I know python's data passing model is not the same as passing a pointer by value, because you do not need to dereference it explicitly inside the function. It is more like passing a reference by value. However, I cannot write the C++ example above by passing a reference by reference, because C++ does not allow me to change references. So please ignore that difference).

Was it helpful?

Solution 2

While the other answers are correct in the sense that Python does not really have a simple way to do what I asked, there is a backdoor way of doing things: modify the 'locals' dict. A kind soul on SO pointed this out to me when I was trying to do something similar as I asked in the question here, but via the C API. See https://stackoverflow.com/a/21976146/120751 for details.

OTHER TIPS

No you cannot. Python is pass by assignment

Alternative solutions is to provide an instance of a class, or mutable container but these are both bad ideas in the long run, its just better to return the value out again and modify the global variable by assigning the return value to it.

You can pass your variable inside a mutable object like this:

def fun(p):
    p[0]=5
p=[3]
print p
fun(p)
print p

But this will compromise the readability of the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top