In David Beazley's talk on generators, he shows how to create a generator function from any single-argument function thus:
def generate(func):
def gen_func(s):
for item in s:
yield func(item)
return gen_func
and illustrates it with math.sqrt
:
gen_sqrt = generate(math.sqrt)
for x in gen_sqrt(xrange(100)):
print x
So why does:
gen_sum = generate(sum)
for x in gen_sum([1,2,3,4,5]):
print x
produce:
TypeError Traceback (most recent call last)
<ipython-input-73-ef521f2bbfc8> in <module>()
1 gen_sum = generate(sum)
----> 2 for x in gen_sum(1):
3 print x
<ipython-input-50-3c0ba12c2429> in gen_func(s)
1 def generate(func):
2 def gen_func(s): # closure
----> 3 for item in s:
4 yield func(item)
5 return gen_func
TypeError: 'int' object is not iterable
Is it more accurate to say that the function being a single-argument function is a necessary but insufficient condition for this approach to work? And that the other necessary condition is that the single argument must be a single item (and not a sequence)?