[Python-Dev] Let's just *keep* lambda

Valentino Volonghi aka Dialtone dialtone at divmod.com
Fri Feb 10 09:19:37 CET 2006


On Fri, 10 Feb 2006 16:49:13 +1300, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>Valentino Volonghi aka Dialtone wrote:
>
>> when some_operation_that_results_in_a_deferred() -> result:
>>     if result == 'Initial Value':
>>         when work_on_result_and_return_a_deferred(result) -> inner_res:
>>             print inner_res
>>     else:
>>         print "No work on result"
>>     reactor.stop()
>
>Hmmm. This looks remarkably similar to something I got half
>way through dreaming up a while back, that I was going to
>call "Simple Continuations" (by analogy with "Simple Generators").
>Maybe I should finish working out the details and write it up.
>
>On the other hand, it may turn out that it's subsumed by
>the new enhanced generators plus a trampoline.

This in only partially true. In fact, let's consider again twisted for the example, you can do something like this:

@defgen
def foo():
    for url in urls:
        page = yield client.getPage(url)
        print page

This has 2 disadvantages IMHO. First of all I have to use a function or a method decorated with @defgen to write that. But most important that code, although correct is serializing things that could be parallel. The solution is again simple but not really intuitive:

@defgen
def foo():
    for d in map(client.getPage, urls):
        page = yield d
        print page

Written in this way it will actually work in a parallel way but it is not really an intuitive solution.

Using when instead:

for url in urls:
    when client.getPage(url) -> page:
        print page

This wouldn't have any problem and is quite readable. A similar construct is used in the E language and here http://www.skyhunter.com/marcs/ewalnut.html#SEC20 is explained how when works for them and their promise object. You can also have multiple things to wait for:

when (client.getPage(url), cursor.execute(query)) -> (page, results):
    print page, results

or

l = [list, of, deferreds]

when l -> *results:
    print results

and we could catch errors in the following way:

when client.getPage(url) -> page:
    print page
except socket.error, e:
    print "something bad happened"

HTH

-- 
Valentino Volonghi aka Dialtone
Now Running MacOSX 10.4
Blog: http://vvolonghi.blogspot.com
New Pet: http://www.stiq.it


More information about the Python-Dev mailing list