This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: A list arg with default value inside function got appended each time the function is called
Type: behavior Stage:
Components: Interpreter Core Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: benjamin.peterson, yappyta
Priority: normal Keywords:

Created on 2015-02-18 17:50 by yappyta, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg236185 - (view) Author: P Yap (yappyta) Date: 2015-02-18 17:50
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']
msg236186 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2015-02-18 17:54
http://effbot.org/zone/default-values.htm
History
Date User Action Args
2022-04-11 14:58:12adminsetgithub: 67666
2015-02-18 17:54:27benjamin.petersonsetstatus: open -> closed

nosy: + benjamin.peterson
messages: + msg236186

resolution: not a bug
2015-02-18 17:50:09yappytacreate