Victor Victor - 6 months ago 9
Python Question

What is the best way to return a stack variable from a recursive function?

I have a situation where I need to return the first item found in a list, How do I return it when I use recursion ?:

def get_hostname (ifname):
try :
# Do something to get hostname
return hostname
except IOError:
return -1


def get_hostname_r(lst):
if not lst:
return False
if get_hostname(lst[0]) != -1 :
print 'Found ', get_hostname(lst[0])
return get_hostname(lst[0]) # DOESNT WORK
else :
print 'Not found ', get_hostname(lst[0])
get_hostname_r(lst[1:])

print 'return = ', get_hostname_r(['eth1','eth2','eth3','eth4','eth5' ])


I understand that the return goes back to the calling stack but Iam looking here for the best practices without using a global variable to get the value?

Answer

You can simply return the value, the returned value is handed over the whole recursion stack:

def get_hostname_r(lst):
    if not lst:
        return False
    if get_hostname(lst[0]) != -1 :
        print 'Found ', get_hostname(lst[0])
        return get_hostname(lst[0])
    else:
        print 'Not found ', get_hostname(lst[0])
        return get_hostname_r(lst[1:])

But easier to read is a for-loop:

def get_hostname_r(interfaces):
    for interface in interfaces:
        result = get_hostname(interface)
        if result != -1:
            return result
    return False