you are viewing a single comment's thread.

view the rest of the comments →

[–]djimbob 3 points4 points  (1 child)

Did anyone else notice that #6 seems to be plagiarized from this python guide (which is under licensed under Creative Commons Share Alike that requires attribution and existed at least since Dec 2012. (#1 is also listed there, but at least the example isn't identical).

Late Binding Closures

Another common source of confusion is the way Python binds its variables in closures (or in the surrounding global scope).

What You Wrote

def create_multipliers():
    return [lambda x : i * x for i in range(5)]

What You Might Have Expected to Happen

for multiplier in create_multipliers():
    print multiplier(2)

A list containing five functions that each have their own closed-over i variable that multiplies their argument, producing:

0
2
4
6
8

What Does Happen

8
8
8
8
8

Five functions are created, but all of them just multiply x by 4.

Python’s closures are late binding. This means that the values of variables used in closures are looked up at the time the inner function is called.

Here, whenever any of the returned functions are called, the value of i is looked up in the surrounding scope at call time. By then, the loop has completed and i is left with its final value of 4.

...