Ideas for Python 3
Peter Otten
__peter__ at web.de
Thu May 6 03:44:45 EDT 2004
Josiah Carlson wrote:
> How about this for a manual page for lambda...
>
> In other languages, Python's lambda would be considered an 'anonymous
> function', that is, a function that does not require a name.:
>
> >>> (lambda arg: arg*arg)(9)
> 81
>
> Certainly you can give lambdas names with standard assignments.:
>
> >>> square = lambda arg: arg*arg
> >>> square(9)
> 81
>
> The equivalent function definition is below.:
>
> >>> def square(arg):
> ... return arg*arg
> ...
> >>> square(9)
> 81
>
> Generally, lambdas are functions with a single expression in its body
> whose value is returned. Just like normal function definitions, lambdas
> can take multiple arguments, contain keyword arguments, return any
> Python type, etc., as long as the function body is a single expression,
> and whose parameters match standard function definition syntax, the
> lambda is valid. (leave annotation and/or link to what an expression is)
I suggest that you submit the above as a patch for the tutorial
http://www.python.org/doc/current/tut/node6.html. Currently there is an
example with a nice trick which has nothing to do with lambda. Your more
straightforward example demonstrates how simple lambda really is.
> An ugly example of this is as follows.:
>
> >>> f = lambda a, b=1, *args, **kwargs: (a, b, args, kwargs)
> >>> f(1,2,3,c=4)
> (1, 2, (3,), {'c': 4})
>
> Which is equivalent to:
>
> >>> def f(a, b=1, *args, **kwargs):
> ... return (a, b, args, kwargs)
> ...
> >>> f(1,2,3,c=4)
> (1, 2, (3,), {'c': 4})
At this point of learning the language a newbie may or may not be
comfortable with the *args, **kw special arguments. As their usage is
completely orthogonal to functions/lambdas I wouldn't mention them here.
Peter
More information about the Python-list
mailing list