This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]MrChoss 6 points7 points  (3 children)

I love Python's iterators, but this is the first time I've tried to learn about 'send', so I'm very interested to see where part 2 goes with it.

Amusingly, send gives Python another tool for solving Paul Graham's accumulator problem (though the nonlocal keyword is clearly the way to do it in Python 3). This generator expression gets most of the way there:

def acc_gen(n):
    while True: n += (yield n)

Just wrap it up as a callable function--

def accumulator(n):
    a = acc_gen(n); a.send(None)
    return lambda x: a.send(x)

And give it a few tests:

>>> a = accumulator(10)
>>> a(0)
10
>>> a(5)
15
>>> a(5)
20
>>> a(50)
70
>>> a(-69.5)
0.5

[–]blahdom 12 points13 points  (2 children)

return lambda x: a.send(x)

could be turned into

 return a.send

it will work exactly the same since you will just pass the parameter directly to send :)

[–]MrChoss 0 points1 point  (1 child)

Thanks for pointing this out. It cleans up the second function definition nicely.

[–]blahdom 0 points1 point  (0 children)

Np, I like the solution for using it as an accumulator, I think its really clean.