5

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
7
  • 6
    Different scope, different variable. Commented Oct 5, 2017 at 15:50
  • addresses is a local variable... Commented Oct 5, 2017 at 15:57
  • @erip scope is the magic word I was missing in my Google searches, thanks! Commented Oct 5, 2017 at 15:58
  • 1
    In general, the name addresses exists in each scope (or frame) of the recursion. However, if get_addresses() is defined so that it returns a single mutable object, then the name doesn't matter because all frames will be referencing the same object. We generally don't talk about variables in Python, but rather names and objects. Commented Oct 5, 2017 at 15:59
  • 1
    Try you cold here pythontutor.com, then you will see Commented Oct 10, 2017 at 8:47

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Given the simplicity of the question, would probably be good to mention that most modern programming languages use a heap and stack for storing the values of variables in memory (maybe link to something like this, for reference).
@Darthfett Yes, your right. I'll edit to clarify this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.