Sorry for the long email, and thanks in advance. In the below example, is the list foo supposed to retain the value after the function, Bar(), returns?
Is the list foo supposed to reinitialized on each call to Bar(), meaning len(foo) == 0, and when Bar() returns len(foo) (when Bar() is called w/out parameters)? In the example, Bar() is called multiple times, and for the first three times, I expect foo to initialized as an empty list. When I call Bar() and make the assignment however, it turns out that foo is not reinitialized and it acts like a statically type variable in C or Java (e.g. retaining its value from each call and subsequent execution). I would have expected only one instance of the string in f after it is assigned the name of foo, however there are four. My understanding of the code below is as follows: --If Bar is called without any parameters, then foo is initialized as an empty list, always. --If Bar is called with a list parameter, then the name foo is aliased to that object. --In the last two cases, if Bar() returns a value to an assignment, the list will be aliased to that variable name as well --When Bar() returns, if there is nothing aliased to the list foo, then the list is destroyed Is the my understanding correct? Thank you again for taking the time to review my question. --Adam def Bar(foo=[]): foo.append("newb got a keyboard\n") return foo if __name__ == "__main__": Bar() Bar() Bar() f = Bar() print f Results: C:\workspace\ProvingGrounds\src\Bill>python Bug.py ['newb got a keyboard\n', 'newb got a keyboard\n', 'newb got a keyboard\n', 'newb got a keyboard\n']
def Bar(foo=[]): foo.append("newb got a keyboard\n") return foo if __name__ == "__main__": Bar() Bar() Bar() f = Bar() print f
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor