What's going on with Python closures?


#1

I started playing CodeCombat yesterday and noticed some bizarre behavior when attempting to use closures in Python. For example, consider the following code:

def makeAdder(n):
    def adder(m):
        return m + n
    return adder

f = makeAdder(4)
self.say(f(3))

I would expect f to be a function which adds 4 to its argument, but self.saying f(3) produces [object Object] instead of 7. You can check with self.say(f) that f does get assigned some kind of function, and the object produced by f(3) appears to have .next and .throw methods. What’s going on here?


Strange behavior for Python code that uses first-class functions