Draft Pep (was: Re: Let's Talk About Lambda Functions!)
jonathan at onegoodidea.com
Mon Aug 5 18:39:01 CEST 2002
On 5/8/2002 17:18, in article 3D4EA5B0.6060501 at nowhere.org, "Bryan Olson"
<fakeaddress at nowhere.org> wrote:
> John Roth wrote:
>>> Contrary to popular belief, lambda did not add anoymous functions to
>>> Python. Python had them even without lambda.
>>> def define_twice():
>>> def _twice(x):
>>> return x + x
>>> return _twice
>>> print define_twice()(17)
>>> The above code passes 17 to a function which is not bound to any name.
>> It is bound to a name. Specifically, it's bound to _twice. The
>> fact that the name is part of the function's scope, and not the
>> enclosing class or module scope doesn't make it not a name!
> Check the rules on local variables. The function was, at one
> time, bound to the name _twice. Nevertheless, the above code
> passes 17 to a function that is not bound to any name.
This is all getting a bit silly, but having no name does not necessarily
make something anonymous. First-class functions and anonymous functions are
not the same thing.
Python has first-class functions, meaning they can be slung around like all
other values in Python - assigned to names, returned from functions, put in
The function above returns a function as a value, but the function it
returns is not an "anonymous function" using the generally accepted meaning
of the term.
An anonymous function is one which is defined in an expression context
without modifying the namespace. It must be defined in an expression context
as, since the creation doesn't insert anything into the namespace, it can
only be used as an immediate value.
A normal 'def' can only be used in a statement context and it inserts a new
name for the function into the namespace. If we later remove that name (or
remove the entire namespace) while retaining a reference to the function, we
have not magically gone back in time and defined the function as an
>>> twice = lambda x: x + x
does not stop the lambda being an anonymous function just because we have
assigned the value to a name.
More information about the Python-list