Issue 23478: A list arg with default value inside function got appended each time the function is called (original) (raw)

I have a function (test) with a list variable APP and declared its default as an empty list [], while APP is not a global variable, if I execute the same function multiple times, each time the APP will get appended. To workaround this problem, I need to do APP.pop() inside the function or explicitly called the function with an argument (test([])). del APP or reassign APP=[] inside the function does not resolve the problem

same thing happens if the function is defined as an method inside a class.

Here is a little test program for testing:

def test(APP=[]): if len(APP) == 0: APP.append('1abc') print "APP=", APP APP.append('2def')

class test1 (object): def t1(self, abc=[]): abc.append('abc') print abc

if name == 'main':

print "class test"
t = test1()
i = 0
while i < 3:
    t.t1()
    i += 1

print "Test function::"
i = 0
while i < 3:
    test()
    i += 1

Here are the output:

class test ['abc'] ['abc', 'abc'] ['abc', 'abc', 'abc']

Test function:: APP= ['1abc'] APP= ['1abc', '2def'] APP= ['1abc', '2def', '2def']