Commit cd65933a authored by Fred Drake's avatar Fred Drake

Update a "Programmer's note" about lambda forms and scoping to reflect

the availability of nested scoping in Python 2.1 and 2.2.
parent 32716140
...@@ -869,17 +869,31 @@ that functions created with lambda forms cannot contain statements. ...@@ -869,17 +869,31 @@ that functions created with lambda forms cannot contain statements.
\indexii{lambda}{form} \indexii{lambda}{form}
\indexii{anonmymous}{function} \indexii{anonmymous}{function}
\strong{Programmer's note:} a lambda form defined inside a function \strong{Programmer's note:} Prior to Python 2.1, a lambda form defined
has no access to names defined in the function's namespace. This is inside a function has no access to names defined in the function's
because Python has only two scopes: local and global. A common namespace. This is because Python had only two scopes: local and
work-around is to use default argument values to pass selected global. A common work-around was to use default argument values to
variables into the lambda's namespace, e.g.: pass selected variables into the lambda's namespace, e.g.:
\begin{verbatim} \begin{verbatim}
def make_incrementor(increment): def make_incrementor(increment):
return lambda x, n=increment: x+n return lambda x, n=increment: x+n
\end{verbatim} \end{verbatim}
As of Python 2.1, nested scopes were introduced, and this work-around
has not been necessary. Python 2.1 supports nested scopes in modules
which include the statement \samp{from __future__ import
nested_scopes}, and more recent versions of Python enable nested
scopes by default. This version works starting with Python 2.1:
\begin{verbatim}
from __future__ import nested_scopes
def make_incrementor(increment):
return lambda x: x+increment
\end{verbatim}
\section{Expression lists\label{exprlists}} \section{Expression lists\label{exprlists}}
\indexii{expression}{list} \indexii{expression}{list}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment