[Python-ideas] Ruby-style Blocks in Python Idea (alternative)
Jan Kanis
jan.kanis at phil.uu.nl
Tue Mar 10 01:13:42 CET 2009
This being python-ideas, I'll also have a go at it.
Being someone who does like functional programing when used in limited
quantities, I also think multi line lambdas (or blocks, whatever you
call them) are a good thing if a good way could be found to embed them
into Python. But I don't like the part of tavs proposal of handling
them with a magic __do__ function. So what about this slightly
modified syntax and semantics:
def NAME(ARGS) [as OTHERNAME] with EXPRESSION_CONTAINING_NAME:
BODY
eg:
def callback(param) as result with do_something(with_our(callback),
other, args):
print("called back with "+param)
return foobar(param)
this would be equivalent to
def callback(param):
print("called back with "+param)
return foobar(param)
result = do_something(with_our(callback), other_args)
This example tav gave
for url in urls:
using pool.execute do:
print "%s fetching %s" % (time.asctime(), url)
httpc.get(url)
print "%s fetched %s" % (time.asctime(), url)
would be written as
for url in urls:
def fetch(url) with pool.execute(fetch):
print "%s fetching %s" % (time.asctime(), url)
httpc.get(url)
print "%s fetched %s" % (time.asctime(), url)
Compared to tavs proposal this would:
- allow for use in expressions where the block is not the only
argument, the block could even be passed in multiple parameter
positions
- make it clear that a function is being defined, and this syntax even
allows for re-using the function later on, including testing etc.
- not use any new keywords, as it is both syntactically and
semantically an extension of the 'def' keyword.
I think it also caters to those circumstances where you'd want to use
a multiline lambda, without having the awkward reordering of first
having to define the function and then passing it by name where the
emphasis has to be on what you do with the function (analogous to
decorators). It also does everything (I think) that Rubys blocks do.
It does not solve the case where you'd want to pass multiple
blocks/multiline lambdas to a function, but hey, you can't solve
everything.
There are several variations of this syntax that could also be
considered, eg having the 'with' clause before the 'as' clause, or
making the 'with' clause optional as well. Or doing 'using
foo(callback, other, args) as answer with callback(param):', that
would require a new keyword, but would allow the expression using the
new function to be first, as it is presumably the most important part.
my €0,02,
- Jan
More information about the Python-ideas
mailing list