A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python

Kay Schluehr kay.schluehr at gmx.net
Sat Oct 14 08:42:04 CEST 2006

brenocon at gmail.com wrote:

> But [embedding a definition, ks] is awkward since the lambda is constrained to be one
> line; you
> can't come back later and add much to the callback's code.
> Furthermore, this example isn't even legal, because 'print' isn't a
> function, but a statement -- lambda is further constrained to only
> contain an expression.
> Many have complained about this crippled-ness of lambda, but it
> actually makes some sense.  Since Python uses colons and indentation to
> define blocks of code, it would be awkward to close a multiline lambda.
>  The best I could think of would look like
>     deferred.addCallback(lambda r:
>         print("fancy formatting %s" % r.text)
>     )
>     ^
>     |
> That trailing paranthesis is WAY un-Pythonic.

Maybe it is not common place because some users are underinformed and
hypnotized by whitespace semantics but you can add a trailing backslash
to achieve line coninuation within a single expression:

>>> deferred.addCallback(lambda r:  puts("fancy formatting %s" \
... 	))

This works syntactically.


> There might be some sort of overlap with PEP 343 and the 'with'
> statement, but I'm not sure exactly.  Sorry I'm late to the game and
> commenting on last year's PEP's, but I've only started reading them.
> Note that PEP's 343 and 340 are very focused on resource management --
> but I think that letting one define code blocks as closures could make
> resource handling routines be easily written in Python.

The with statement is already implemented in Python 2.5.


The main difference between the with statement and Ruby blocks is that
the with-statement does not support loops. Yielding a value of a
function decorated with a contextmanager and passing it to the BLOCK of
the with statement is essentially a one-shot. Therefore you can't use
the with statement to define iterators. It is not a lightweight visitor
pattern replacement as it is in Ruby. Hence the with- and the
for-statement are orthogonal to each other in Python.

More information about the Python-list mailing list