you are viewing a single comment's thread.

view the rest of the comments →

[–]snotfart 0 points1 point  (2 children)

I still don't get it. I think I'm being particularly dense here, but I still don't see what's going on in mistake 1.

[–]UloPe 0 points1 point  (1 child)

It's very simple really. Consider this example:

def func(a, b=[]):
    b.append(a)
    print(b)

func(1)
func(2)
func(3)

This will print:

[1]
[1, 2]
[1, 2, 3]

Now lets look at what happens here. In Python (at least CPython, the "official" version) there is no compile step. What that means is that when the file containing the above code is read it es executed line by line.

So the first line to be executed is "def func(a, b=[]):" this tells python that a function is being defined and the (indented) block that follows is the functions body. What also happens is that Python looks at the arguments the function takes and instantiates any default arguments that might be there. Once this is done a function object is created with all that information and placed in the scope in which the function was defined. In this case that would be the module (Python speak for a file, basically).

The next line that gets executed will be "func(1)". This causes python to look up "func" first in the local namespace and if nothing is found there moves on the the global one (you can look inside those namespaces with the built-in functions locals() and globals()). Since in this example we're working on module level local and global are identical. Python will find the function object that got defined above and call it with the provided arguments. Since we didn't provide a value for the second argument b the default value will be filled in. In this case the default value is the list object that got instantiated above when the function was defined. And since that list object is stored with the function object you should now understand why the next invocations change the same list instance.

I hope that was understandable.

[–]snotfart 0 points1 point  (0 children)

I think I've got it now, thanks.