Replacement for lambda - 'def' as an expression?
Tom Anderson
twic at urchin.earth.li
Wed Sep 7 06:09:18 EDT 2005
On Tue, 6 Sep 2005, talin at acm dot org wrote:
> add = def( a, b ):
> return a + b
+1
This is so obviously the right syntax for closures in python that i really
can't believe we're still arguing about it.
> What about passing an anonymous function as an argument, which is the
> most common case? This gets tricky, because you can't embed a suite
> inside of an expression. Or can you?
>
> The most powerful option would be to leverage the fact that you can
> already do line breaks inside of parentheses. So the "def" keyword
> would tell the parser to restart the normal indentation calculations,
> which would terminate whenever an unmatched brace or paren was
> encountered:
>
> a = map(
> (def( item ):
> item = do_some_calculation( item )
> return item
> ), list )
Can't we just rely on indentation here:
a = map(
def(item):
item = do_some_calculation(item)
return item
, list)
?
A consequence of that is that you *must* end the suite on a line of its
own; with your scheme, you can in fact write:
a = map((def(item):
item = do_some_calculation(item)
return item), list)
Although i'm not convinced that this is something i want to be possible!
> The one-liner version looks a lot prettier of course:
>
> a = map( (def( item ): return item * item), list )
To do one-liners, which is absolutely essential, we can't rely on line
ends, of course, so we'd need your scheme to be in operation here. For
consistency, it should also apply to multi-line suites; it should be
possible to have both the bracket-based and line-based rules in effect at
the same time - changes in indent level are essentially treated as a kind
of bracket.
> And it looks even nicer if we switch the order of the arguments around,
> since you can now use the final paren of the enclosing function call to
> terminate the def suite.
>
> a = map( list, def( item ): return item * item )
>
> Unfortunately, there's no other good way I can think of to signal the
> end of the block of statements without introducing some radical new
> language construct.
If there were no statements which ended with an expression list, it would
be possible to detect the end by the presence of a comma. The python
grammar would only need a few changes to meet that requirement, none of
them that disruptive (mostly, you replace the expression list with a tuple
- in many cases, making explicit what was previously implicit).
> (Besides, if being an expression is good enough for 'yield', why
> shouldn't def get the same privilege? :)
A fine point!
tom
--
And the future is certain, give us time to work it out
More information about the Python-list
mailing list