Using the Python Interpreter as a Reference

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Nov 28 17:24:46 EST 2011


On Mon, 28 Nov 2011 12:32:59 -0700, Ian Kelly wrote:

> On Sun, Nov 27, 2011 at 4:55 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
[...]
>>> Lambdas and functions are the same thing in my language, so no need
>>> for a special keyword.
>>
>> That does not follow. Lambdas and def functions are the same thing in
>> Python, but Python requires a special keyword.
> 
> I think the implication is that Unit has only one syntax for creating
> functions, which is lambda-style.  In any case, why does Python require
> a special keyword?  def is only used in a statement context, and lambda
> is only used in an expression context.  Why not use the same keyword for
> both?

Because the syntax is completely different. One is a statement, and 
stands alone, the other is an expression. Even putting aside the fact 
that lambda's body is an expression, and a def's body is a block, def 
also requires a name. Using the same keyword for both would require 
special case reasoning: sometimes def is followed by a name, sometimes 
without a name. That's ugly.

def name(args): block  # okay

funcs = [def args: expr,  # okay so far
         def name(args): expr,  # not okay
         def: expr,  # okay
         ]

def: expr  # also okay

def: expr
    expr  # but not okay

x = def x: expr  # okay
x = def x(x): expr  # not okay

Using the same keyword for named and unnamed functions is, in my opinion, 
one of those foolish consistencies we are warned about. When deciding on 
syntax, the difference between anonymous and named functions are more 
significant than their similarities.


> I think the answer is historical:  def came first, and when
> anonymous functions were added it didn't make sense to use the keyword
> "def" for them, because "def" implies a name being defined.

That reasoning still applies even if they were added simultaneously.

Lambda is pretty old: it certainly exists in Python 1.5 and almost 
certainly in 1.4. While it doesn't exist as a keyword in Python 0.9.1, 
there is a module called "lambda" with a function "lambda" that uses more 
or less the same syntax. Instead of lambda x: x+1, you would instead 
write lambda("x", "x+1"). So the idea of including anonymous functions 
was around in Python circles before the syntax was locked in.


-- 
Steven



More information about the Python-list mailing list