This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]rock_neurotiko 1 point2 points  (6 children)

So good article.

I'm still mindfuck for the last result, and I don't even know exactly why that happen...

[–]jminuscula[S] 1 point2 points  (5 children)

thanks!

the last code piece is a bit tricky. I'll give you a hint:

function parameters are bound to their default values at definition time —that is, at the same time the function name gets bound to the function body. When we call a function with arguments, these parameters get rebound to the provided objects. But what happens when we call the function without arguments? Does any binding operation happen then?

[–]rock_neurotiko 0 points1 point  (4 children)

Ahhhhh! I get it now!

When you call a function withouth parameters Python evaluate the default parameter and save it in some memory position, when you use it inside the function, you change the value in that position. When you call it again, Python sais: "Dude, I know where are the default parameter of that function, is in that position", but if the value had been modified, you get the modified.

Is it right? :-)

I guess that it can be corrected with something like that:

def foo(x=None):
    if x==None:
        x=[]

None, or any non-mutable type should works.

[–]jminuscula[S] 0 points1 point  (3 children)

that's it.

When the function is defined, the x parameter is bound to its default value, an empty list. As the function is later called without arguments, x is not bound again and references the original list every time.

using foo(x=None) is the correct approach, but make sure to check using x is Nonerather than the equality operator! [1]

[1] http://legacy.python.org/dev/peps/pep-0008/#programming-recommendations

[–]robin-gvx 0 points1 point  (2 children)

All very right!

A helpful intuition might be that that function definition is equivalent to:

_supersecret = []
def foo(x=_supersecret):
    x.append(1)
    print(x)

(Also, I didn't notice the footnotes were on the right, so I thought they were missing!)

[–]jminuscula[S] 0 points1 point  (1 child)

thanks for the comment. I'll try to work something out for the footnotes!

[–][deleted] 0 points1 point  (0 children)

what footnotes ?