Strictly python question. Variable names point to objects, they don't contain them - I get that. I am having trouble understanding what is going on with this: def test(a=[]): a.append(1) return a The variable 'a' gets assigned to the same list object each time the function is called, so each time the list object gets mutated. What I don't get is - where is this object? - why does it persist ? - how does python always assign a to the same object? tia
You've defined a function test that takes an argument a. If no argument is passed to the function when it is called it will use the default you've specified. In creating the function, you created a list object [ ] for the function to use as its default. The list is part of the function. It persists because there is some other object with a reference to it. In this case the object which is keeping a reference to this list is the function itself. The dir function may help give some insight. It takes an object and returns a list of strings where each string in that list is the name of an attribute of the object. class Foo: def __init__(self,a): self.bar = a f = Foo('stuff') print dir(f) print f.bar The above code shows how dir works. From that info you can take a look at this small example taken from your function test. http://dpaste.com/519173/
Thank you very much for that answer and the dir function. I never even considered that the function was keeping ahold of it and I was going crazy cause it didn't show up in globals() or locals() (from the shell).
Join our real-time social learning platform and learn together with your friends!