[Python-ideas] Syntax for passing lambdas to functions
Steven D'Aprano
steve at pearwood.info
Thu Feb 27 08:30:51 CET 2014
On Wed, Feb 26, 2014 at 10:16:13PM -0800, Andrew Barnert wrote:
> From: Steven D'Aprano <steve at pearwood.info>
> >It's really a bad idea to have syntax for a "shorter lambda"
> >that works here:
> >
> > f(arg=***whatever***)
> >
> >but not in these:
>
> I don't think that's _necessarily_ a problem. After all, it's not a
> problem that you can filter a for loop in a comprehension but not
> anywhere else, is it?
I'll note that the ability to write "for x in seq if condition(x)" is a
frequently requested enhancement to for-loops.
Special case syntax, as suggested here, means that the user has to learn
a whole lot of special cases. Instead of learning:
"you can create <this object> with <this syntax>"
you have to learn:
"you can create <this object> with <this syntax> but only under
<these circumstances>"
which increases the burden of learning the language. Python is
relatively easy to learn and remember because it is so consistent: if a
piece of syntax works here, it almost always works there as well:
Q: Can I create a function using lambda inside a list?
A: Yes, you can create a function using lambda anywhere an expression
is legal.
Q: Can I create a function using lambda inside a dict?
A: Yes, you can create a function using lambda in a dict.
Q: How about inside a function call parens?
A: Expressions are legal inside parens, so yes you can use lambda
when calling a function.
Q: How about inside a function call using a keyword parameter?
A: Yes, whether the parameter is given by keyword or not makes no
difference.
Q: What about inside a set? Bet it doesn't work inside sets.
A: Yes, it works inside sets.
Q: How about tuples?
A: Yes, it works inside tuples.
Q. What, even on Fridays?
There are very few exceptions to this consistency, and most of them can
be sorted out by using parens. You nearly always can copy a valid
expression from one part of a .py file, paste it into a similar but not
identical context, and be very confident that it will be syntactically
valid in the new context as well.
--
Steven
More information about the Python-ideas
mailing list