Right now I think I have understood most of the problems related to default value in Python. The questions on Stackoverflow has been a great help, but there is one case/example that they do not address. That example is in this link: http://effbot.org/zone/default-values.htm Here is the part in question:
Finally, it should be noted that more advanced Python code often uses this mechanism to its advantage; for example, if you create a bunch of UI buttons in a loop, you might try something like:
for i in range(10): def callback(): print "clicked button", i UI.Button("button %s" % i, callback)
only to find that all callbacks print the same value (most likely 9, in this case). The reason for this is that Python’s nested scopes bind to variables, not object values, so all callback instances will see the current (=last) value of the “i” variable. To fix this, use explicit binding:
for i in range(10): def callback(i=i): print "clicked button", i UI.Button("button %s" % i, callback)
The i=i
part binds the parameter i
(a local variable) to the current value of the outer variable i
.
I can understand why the second example works the way it does: in the def
line, the i
in the function is explicitly bounded to the i
in the for (this is done during the "def" statement, namely definition-time). But what I don't get is how the first example works. It seems to me that the i
variable there is bounded during run-time but then shouldn't it also be the same as the second one? Thank you very much.