Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return by reference possible?

Tags:

python

This is a simple question, but I could not find a similar one in SO. Is return by reference available in Python in anyway? (Maybe with simple hacks.)

Return by reference explanation:

def func(lst):
    return reference of lst[2] somehow

func([7, 8, 9, 10])        # returns 9
func([7, 8, 9, 10]) = 11   # lst is changed to [7, 8, 11, 10]

Is this behavior achievable? Maybe with some operator overloading?

An example of this usage in C++: Returning values by reference in C++

like image 416
Rockybilly Avatar asked Apr 19 '17 00:04

Rockybilly


People also ask

What does it mean to return by reference?

It means you return by reference, which is, at least in this case, probably not desired. It basically means the returned value is an alias to whatever you returned from the function. Unless it's a persistent object it's illegal.

Can you return a reference?

A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.

When should I return by reference?

Objects returned by reference must live beyond the scope of the function returning the reference, or a dangling reference will result. Never return a local variable by reference.

Why should we return by reference?

Functions can be declared to return a reference type. There are two reasons to make such a declaration: The information being returned is a large enough object that returning a reference is more efficient than returning a copy. The type of the function must be an l-value.


1 Answers

What you should probably do is just return 2 and then use that as an index into the list you passed in:

lyst = [7, 8, 9, 10]
def func(lst):
     # ...
     return 2

lyst[func(lyst)] = 11

You can create an object that encapsulates a reference to the container plus the index (or key, in the case of a dictionary) of the particular element:

class ElementRef(object):

    def __init__(self, obj, key):
        self.obj = obj
        self.key = key

    @property
    def value(self): return self.obj[self.key]

    @value.setter
    def value(self, value): self.obj[self.key] = value

Then your function looks like this:

 def func(lyst):
     # ...
     return ElementRef(lyst, 2)

And you can modify the element by setting its value attribute like this:

 func(lyst).value = 11

But I don't see a lot of value in this over just returning the index. Especially because the object can become useless if items are added to or removed from the list before it's used. Explicitly returning an index makes this an obvious problem, but if you get back an ElementRef you may assume it contains some kind of magic that it doesn't.

like image 129
kindall Avatar answered Oct 11 '22 18:10

kindall