In Python 3.2, according to this: http://docs.python.org/py3k/reference/expressions.html#summary
lambda is the operator with the lowest precedence in Python.
And according to this: http://docs.python.org/py3k/reference/lexical_analysis.html#keywords
lambda is a Python language keyword.
HOWEVER, according to this: http://docs.python.org/py3k/reference/lexical_analysis.html#other-tokens
Operators and keywords are distinct entities.
I’m trying to systematically explain Python 3.2 to someone and I don’t want to confuse them. I, myself, am confused, though, on the exact definitions of operators and keywords.
My best guess is that the term “operator” means something slightly different when used in the context of the Python parser versus the Python lexer.
lambda clearly is a keyword; it’s a special word recognised by the parser, which would otherwise fall within the definition of an
lambda is not semantically an operator. An operator is just a function, but invoked with a different syntax. We can imagine replacing the
+ operator with an
add function; all our programs with addition would get more verbose and harder to read, but we could still write them. The
lambda language construct on the other hand could not be replaced with a function;
lambda x: x+1 is not just calculating a result from the values
x+1, because in this context they are not values at all (
x is the name of the parameter to the function being defined, and
x+1 is the code of the lambda body).
In the same page you linked to we have: http://docs.python.org/py3k/reference/lexical_analysis.html#operators
The following tokens are operators:
+ - * ** / // % << >> & | ^ ~ < > <= >= == !=
That’s the entire contents of the subsection on operators. From this I take it to mean that in the context of defining the tokens of the language “operators” are symbolic operators, whereas the section on keywords is explicitly spelling out that “these things which would otherwise be identifiers are keywords”. That’s why I think the keyword operators like
in, etc are not listed. But there certainly are things that are semantically operators that are keywords, whether or not the parser considers them separate classes.
I’m not sure why http://docs.python.org/py3k/reference/expressions.html#summary describes
lambda as an operator; I certainly wouldn’t. Strictly speaking it doesn’t explicitly say “
lambda is the operator with the lowest precedence”, it just lists
lambda in a table whose column heading is “Operator”. Perhaps it was just a convenience; describing
lambda as a thing with low precedence is a good way of clarifying how Python will parse
lambda x: x + 1 (it could theoretically be either
(lambda x: x) + 1 or
lambda x: (x + 1)).