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

Valentino Volonghi aka Dialtone dialtone at divmod.com
Thu Feb 9 19:47:51 CET 2006


On Thu, 09 Feb 2006 17:39:31 +0100, "\"Martin v. Löwis\"" <martin at v.loewis.de> wrote:
>It's not a specific example though: what precise library provides
>the visit method?

I'll provide my own usecase right now which is event driven programming of
any kind (from GUI toolkits, to network frameworks/libraries).

>From my experience these are the kind of usecases that suffer most from
having to define functions everytime and, worse, to define functions before
their actual usage (which is responsible for part of the bad reputation that,
for example, deferreds have).

Let's consider this piece of code (actual code that works today and uses
twisted for convenience):

def do_stuff(result):
    if result == 'Initial Value':
        d2 = work_on_result_and_return_a_deferred(result)
        d2.addCallback(println)
        return d2
    return 'No work on result'

def println(something):
    print something

d1 = some_operation_that_results_in_a_deferred()
d1.addCallback(do_stuff)
d1.addCallback(lambda _: reactor.stop())

reactor.run()

As evident the execution order is almost upside-down and this is because I
have to define a function before using it (instead of defining and using a
function inline). However python cannot have a statement inside an expression
as has already been said, thus I think some new syntax to support this could
be helpful, for example:

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()

reactor.run()

In this case the execution order is correct and indentation helps in
identifying which pieces of the execution will be run at a later time
(depending on the when block).

This way of coding could be useful for many kind of event driven frameworks
like GUI toolkits that could do the following:

when button.clicked() -> event, other_args:
    when some_dialog() -> result:
        if result is not None:
            window.set_title(result)

IMHO similar considerations are valid for other libraries/frameworks like
asyncore. What would this require? Python should basically support a protocol
for a deferred like object that could be used by a framework to support that
syntax. Something like:

callback(initial_value)
add_callback(callback, *a, **kw)
add_errback(callback, *a, **kw)
(extra methods if needed)

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