Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python recursive variables referenced or copied?

I have the following recursive function, and I'm having trouble figuring out how python handles variables in recursive functions. Will it create a copy of the addresses variable for every recursion, or will it overwrite the variable and create a horrible mess?

def get_matches():
    addresses = get_addresses()

    #do stuff

    for addr in addresses:
        #do stuff
        if some_condition:
            get_matches()
        else:
            return
like image 662
jamzsabb Avatar asked Oct 05 '17 15:10

jamzsabb


People also ask

Is recursion more efficient than iteration?

Iteration is faster and more efficient than recursion. It's easier to optimize iterative codes, and they generally have polynomial time complexity.

How are recursive functions evaluated in memory?

When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to the calling function and a different copy of local variables is created for each function call.

How is recursion different from iteration?

A program is called recursive when an entity calls itself. A program is call iterative when there is a loop (or repetition).


1 Answers

The underlining concept your looking for is called a frame.

Inside of the Python interpreter is a stack commonly referred to as the call stack. Each time Python encounters a function call during execution, a new frame object is created and pushed on the stack. The frame represents the function call. Each one has it's own scope, and the current value of any arguments passed into the function.

This means that even for each recursive call of a function, a new frame is created for that specific function call and pushed on the stack. As I already said above, each frame has it's own scope. So each frames' scope has an address variable defined in it, separate from any other.

Note however that frame object's themselves do not store the values of the variables. You see, the Python interpreter only operates on the top-most frame of the stack. Python uses another stack, separate from the call stack, to store the values of the local variables of the frame it's currently executing.

like image 79
Christian Dean Avatar answered Sep 24 '22 00:09

Christian Dean