Search code examples
pythonpython-3.xfunctionscoping

Variable defined inside of function carries over when function is called multiple times


This is in python.

So, I have defined a function of the sort:

def function(var1, var2 = [[], 0]):
    # some code that changes both var1 and var2
    return (var2, var1)

Then, I made a for loop:

for x in range(10):
    print(function(x))

I make a couple changes to var2 inside of the function. The issue that I am having is that the changes happened inside of var2 carry over for each next iteration in the for loop involving x. I don't understand why it does so. The way I've fixed it is calling this instead:

for x in range(10):
    print(function(x, [[], 0]))

However, I don't want to have to do this (to specify each time that var2 is [[], 0]).

Also, if that may help, the function is recursive. It runs fine, just that var2 carries over.

How can I prevent this for happening?


Solution

  • Python creates a function's default parameters once when the code is first compiled and uses that object whenever a default is needed. One consequence is that if the parameter is mutable, like a list, any changes to it are seen in all future calls. One solution is to use a different value as a default and use it to create the default dynamically

    def function(var1, var2=None):
        if var2 is None:
            var2 = [[], 0]
        # some code that changes both var1 and var2
        return (var2, var1)
    

    Another option is to stop mutating the list in place, but return a copy instead.

    from copy import deepcopy
    
    def function(var1, var2=[[], 0]):
        var1 = deepcopy(var1)
        var2 = deepcopy(var2)
        # some code that changes both var1 and var2
        return (var2, var1)