Question

There are two examples.

# 1st example
>>> def accum(sum, a):
        return sum + a
>>> sum = 0
>>> for sum in iter(lambda:accum(sum, 2), 40):
        print sum,

2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32...

# 2nd example
>>> def accum(sum, a):
        return sum + a
>>> sum = 0
>>> for sum in iter(accum(sum, 2), 40):
        print sum,
TypeError: iter(v, w) : v must be callable

Why lambda function doesn't make error but accum function makes error?

Thanks in advance :)

Was it helpful?

Solution

In neither case you are passing a function that takes arguments. In second case the value of v is bound to the integer 2, whereas in the first case v refers to a callable anonymous lambda function () -> sum + a.

The following 2 are almost equivalent:

def x():
    return sum + a

x = lambda: sum + a

except lambda does not provide nice debugging traceback, since lambda functions are unnamed.

Also, the names of the variables are a bit misleading, took me a some moments to figure out what is happening. There are exactly 2 variables called sum - the one within accum function, and the other in the global scope. There is also the 3rd, masked one that contains the global built-in function sum...

OTHER TIPS

The lambda is an anonymous function and is callable. If the notation is confusing, you can replace it with a named function:

def wrapper():
    return accum(sum, 2)

for sum in iter(wrapper, 40):

The v argument must be callable. The result of accum(sum, 2) is an integer, which isn't callable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top