@@ -11,8 +11,8 @@ \chapter{Compound statements}
1111handlers and/or cleanup code for a group of statements. Function and
1212class definitions are also syntactically compound statements.
1313
14- Compound statements consist of one or more `clauses'. A clause
15- consists of a header and a `suite'. The clause headers of a
14+ Compound statements consist of one or more `clauses.' A clause
15+ consists of a header and a `suite.' The clause headers of a
1616particular compound statement are all at the same indentation level.
1717Each clause header begins with a uniquely identifying keyword and ends
1818with a colon. A suite is a group of statements controlled by a
@@ -48,15 +48,13 @@ \chapter{Compound statements}
4848stmt_list: simple_stmt (";" simple_stmt)* [";"]
4949\end {verbatim }
5050
51- Note that statements always end in a \code {NEWLINE} possibly followed
52- by a \code {DEDENT}.
53- \index {NEWLINE token}
54- \index {DEDENT token}
55-
56- Also note that optional continuation clauses always begin with a
57- keyword that cannot start a statement, thus there are no ambiguities
58- (the `dangling \keyword {else}' problem is solved in Python by requiring
59- nested \keyword {if} statements to be indented).
51+ Note that statements always end in a
52+ \code {NEWLINE}\index {NEWLINE token} possibly followed by a
53+ \code {DEDENT}.\index {DEDENT token} Also note that optional
54+ continuation clauses always begin with a keyword that cannot start a
55+ statement, thus there are no ambiguities (the `dangling
56+ \keyword {else}' problem is solved in Python by requiring nested
57+ \keyword {if} statements to be indented).
6058\indexii {dangling}{else}
6159
6260The formatting of the grammar rules in the following sections places
@@ -68,16 +66,16 @@ \section{The \keyword{if} statement}
6866The \keyword {if} statement is used for conditional execution:
6967
7068\begin {verbatim }
71- if_stmt: "if" condition ":" suite
72- ("elif" condition ":" suite)*
69+ if_stmt: "if" expression ":" suite
70+ ("elif" expression ":" suite)*
7371 ["else" ":" suite]
7472\end {verbatim }
7573
76- It selects exactly one of the suites by evaluating the conditions one
74+ It selects exactly one of the suites by evaluating the expressions one
7775by one until one is found to be true (see section \ref {Booleans } for
7876the definition of true and false); then that suite is executed (and no
7977other part of the \keyword {if} statement is executed or evaluated). If
80- all conditions are false, the suite of the \keyword {else} clause, if
78+ all expressions are false, the suite of the \keyword {else} clause, if
8179present, is executed.
8280\kwindex {elif}
8381\kwindex {else}
@@ -86,24 +84,24 @@ \section{The \keyword{while} statement}
8684\stindex {while}
8785\indexii {loop}{statement}
8886
89- The \keyword {while} statement is used for repeated execution as long as a
90- condition is true:
87+ The \keyword {while} statement is used for repeated execution as long
88+ as an expression is true:
9189
9290\begin {verbatim }
93- while_stmt: "while" condition ":" suite
91+ while_stmt: "while" expression ":" suite
9492 ["else" ":" suite]
9593\end {verbatim }
9694
97- This repeatedly tests the condition and, if it is true, executes the
98- first suite; if the condition is false (which may be the first time it
95+ This repeatedly tests the expression and, if it is true, executes the
96+ first suite; if the expression is false (which may be the first time it
9997is tested) the suite of the \keyword {else} clause, if present, is
10098executed and the loop terminates.
10199\kwindex {else}
102100
103101A \keyword {break} statement executed in the first suite terminates the
104102loop without executing the \keyword {else} clause's suite. A
105103\keyword {continue} statement executed in the first suite skips the rest
106- of the suite and goes back to testing the condition .
104+ of the suite and goes back to testing the expression .
107105\stindex {break}
108106\stindex {continue}
109107
@@ -116,11 +114,11 @@ \section{The \keyword{for} statement}
116114\obindex {sequence}
117115
118116\begin {verbatim }
119- for_stmt: "for" target_list "in" condition_list ":" suite
117+ for_stmt: "for" target_list "in" expression_list ":" suite
120118 ["else" ":" suite]
121119\end {verbatim }
122120
123- The condition list is evaluated once; it should yield a sequence. The
121+ The expression list is evaluated once; it should yield a sequence. The
124122suite is then executed once for each item in the sequence, in the
125123order of ascending indices. Each item in turn is assigned to the
126124target list using the standard rules for assignments, and then the
@@ -144,12 +142,10 @@ \section{The \keyword{for} statement}
144142
145143The target list is not deleted when the loop is finished, but if the
146144sequence is empty, it will not have been assigned to at all by the
147- loop.
148-
149- Hint: the built-in function \function {range()} returns a sequence of
150- integers suitable to emulate the effect of Pascal's
145+ loop. Hint: the built-in function \function {range()} returns a
146+ sequence of integers suitable to emulate the effect of Pascal's
151147\code {for i := a to b do};
152- e.g. \code {range(3)} returns the list \code {[0, 1, 2]}.
148+ e.g., \code {range(3)} returns the list \code {[0, 1, 2]}.
153149\bifuncindex {range}
154150\indexii {Pascal}{language}
155151
@@ -164,7 +160,7 @@ \section{The \keyword{for} statement}
164160suite inserts an item in the sequence before the current item, the
165161current item will be treated again the next time through the loop.
166162This can lead to nasty bugs that can be avoided by making a temporary
167- copy using a slice of the whole sequence, e.g.
163+ copy using a slice of the whole sequence, e.g.,
168164\index {loop!over mutable sequence}
169165\index {mutable sequence!loop over}
170166
@@ -182,25 +178,26 @@ \section{The \keyword{try} statement} \label{try}
182178\begin {verbatim }
183179try_stmt: try_exc_stmt | try_fin_stmt
184180try_exc_stmt: "try" ":" suite
185- ("except" [condition ["," target]] ":" suite)+
181+ ("except" [expression ["," target]] ":" suite)+
186182 ["else" ":" suite]
187183try_fin_stmt: "try" ":" suite
188184 "finally" ":" suite
189185\end {verbatim }
190186
191187There are two forms of \keyword {try} statement:
192188\keyword {try}...\keyword {except} and
193- \keyword {try}...\keyword {finally}. These forms cannot be mixed.
189+ \keyword {try}...\keyword {finally}. These forms cannot be mixed (but
190+ they can be nested in each other).
194191
195192The \keyword {try}...\keyword {except} form specifies one or more
196193exception handlers
197194(the \keyword {except} clauses). When no exception occurs in the
198195\keyword {try} clause, no exception handler is executed. When an
199196exception occurs in the \keyword {try} suite, a search for an exception
200- handler is started. This inspects the except clauses in turn until
201- one is found that matches the exception. A condition -less except
197+ handler is started. This search inspects the except clauses in turn until
198+ one is found that matches the exception. An expression -less except
202199clause, if present, must be last; it matches any exception. For an
203- except clause with a condition , that condition is evaluated, and the
200+ except clause with an expression , that expression is evaluated, and the
204201clause matches the exception if the resulting object is `` compatible''
205202with the exception. An object is compatible with an exception if it
206203is either the object that identifies the exception, or (for exceptions
@@ -213,7 +210,7 @@ \section{The \keyword{try} statement} \label{try}
213210If no except clause matches the exception, the search for an exception
214211handler continues in the surrounding code and on the invocation stack.
215212
216- If the evaluation of a condition in the header of an except clause
213+ If the evaluation of an expression in the header of an except clause
217214raises an exception, the original search for a handler is cancelled
218215and a search starts for the new exception in the surrounding code and
219216on the call stack (it is treated as if the entire \keyword {try} statement
@@ -234,6 +231,13 @@ \section{The \keyword{try} statement} \label{try}
234231\code {sys.exc_traceback} receives a traceback object (see section
235232\ref {traceback }) identifying the point in the program where the
236233exception occurred.
234+ These details are also available through the \function {sys.exc_info()}
235+ function, which returns a tuple \code {(exc_type,} \code {exc_value,}
236+ \code {exc_traceback)}. Use of the corresponding variables is
237+ deprecated in favor of this function, since their use is unsafe in a
238+ threaded program. As of Python 1.5, the variables are restored to
239+ their previous values (before the call) when returning from a function
240+ that handled an exception.
237241\refbimodindex {sys}
238242\ttindex {exc_type}
239243\ttindex {exc_value}
@@ -252,12 +256,14 @@ \section{The \keyword{try} statement} \label{try}
252256\keyword {finally} clause is executed, and then the saved exception is
253257re-raised. If the \keyword {finally} clause raises another exception or
254258executes a \keyword {return}, \keyword {break} or \keyword {continue} statement,
255- the saved exception is lost.
259+ the saved exception is lost. The exception information is not
260+ available to the program during execution of the \keyword {finally}
261+ clause.
256262\kwindex {finally}
257263
258264When a \keyword {return} or \keyword {break} statement is executed in the
259265\keyword {try} suite of a \keyword {try}...\keyword {finally} statement, the
260- \keyword {finally} clause is also executed `on the way out'. A
266+ \keyword {finally} clause is also executed `on the way out.' A
261267\keyword {continue} statement is illegal in the \keyword {try} clause. (The
262268reason is a problem with the current implementation --- this
263269restriction may be lifted in the future).
@@ -269,9 +275,7 @@ \section{Function definitions} \label{function}
269275\indexii {function}{definition}
270276
271277A function definition defines a user-defined function object (see
272- section \ref {types }):\footnote {The new syntax to receive arbitrary
273- keyword arguments is not yet documented in this manual. See chapter
274- 12 of the Tutorial.}
278+ section \ref {types }):
275279\obindex {user-defined function}
276280\obindex {function}
277281
@@ -280,90 +284,81 @@ \section{Function definitions} \label{function}
280284parameter_list: (defparameter ",")* ("*" identifier [, "**" identifier]
281285 | "**" identifier
282286 | defparameter [","])
283- defparameter: parameter ["=" condition ]
287+ defparameter: parameter ["=" expression ]
284288sublist: parameter ("," parameter)* [","]
285289parameter: identifier | "(" sublist ")"
286290funcname: identifier
287291\end {verbatim }
288292
289293A function definition is an executable statement. Its execution binds
290- the function name in the current local name space to a function object
294+ the function name in the current local namespace to a function object
291295(a wrapper around the executable code for the function). This
292- function object contains a reference to the current global name space
293- as the global name space to be used when the function is called.
296+ function object contains a reference to the current global namespace
297+ as the global namespace to be used when the function is called.
294298\indexii {function}{name}
295299\indexii {name}{binding}
296300
297301The function definition does not execute the function body; this gets
298302executed only when the function is called.
299303
300- When one or more top-level parameters have the form \var {parameter \code {=}
301- condition}, the function is said to have `` default parameter values'' .
302- Default parameter values are evaluated when the function definition is
303- executed. For a parameter with a default value, the correponding
304- argument may be omitted from a call, in which case the parameter's
305- default value is substituted. If a parameter has a default value, all
306- following parameters must also have a default value --- this is a
307- syntactic restriction that is not expressed by the grammar.%
304+ When one or more top-level parameters have the form \var {parameter}
305+ \code {=} \var {expression}, the function is said to have `` default
306+ parameter values.'' \strong {Default parameter values are evaluated
307+ when the function definition is executed.} For a parameter with a
308+ default value, the corresponding argument may be omitted from a call,
309+ in which case the parameter's default value is substituted. If a
310+ parameter has a default value, all following parameters must also have
311+ a default value --- this is a syntactic restriction that is not
312+ expressed by the grammar.%
308313\footnote {Currently this is not checked; instead,
309314\code {def f(a=1, b)} is interpreted as \code {def f(a=1, b=None)}.}
310315\indexiii {default}{parameter}{value}
311316
312- Function call semantics are described in section \ref {calls }. When a
313- user-defined function is called, first missing arguments for which a
314- default value exists are supplied; then the arguments (a.k.a. actual
315- parameters) are bound to the (formal) parameters, as follows:
316- \indexii {function}{call}
317- \indexiii {user-defined}{function}{call}
318- \index {parameter}
319- \index {argument}
320- \indexii {parameter}{formal}
321- \indexii {parameter}{actual}
322-
323- \begin {itemize }
324-
325- \item
326- If there are no formal parameters, there must be no arguments.
327-
328- \item
329- If the formal parameter list does not end in a star followed by an
330- identifier, there must be exactly as many arguments as there are
331- parameters in the formal parameter list (at the top level); the
332- arguments are assigned to the formal parameters one by one. Note that
333- the presence or absence of a trailing comma at the top level in either
334- the formal or the actual parameter list makes no difference. The
335- assignment to a formal parameter is performed as if the parameter
336- occurs on the left hand side of an assignment statement whose right
337- hand side's value is that of the argument.
338-
339- \item
340- If the formal parameter list ends in a star followed by an identifier,
341- preceded by zero or more comma-followed parameters, there must be at
342- least as many arguments as there are parameters preceding the star.
343- Call this number \var {N}. The first \var {N} arguments are assigned to
344- the corresponding formal parameters in the way descibed above. A
345- tuple containing the remaining arguments, if any, is then assigned to
346- the identifier following the star. This variable will always be a
347- tuple: if there are no extra arguments, its value is \code {()}, if
348- there is just one extra argument, it is a singleton tuple.
349- \indexii {variable length}{parameter list}
350-
351- \end {itemize }
352-
353- Note that the `variable length parameter list' feature only works at
354- the top level of the parameter list; individual parameters use a model
355- corresponding more closely to that of ordinary assignment. While the
356- latter model is generally preferable, because of the greater type
357- safety it offers (wrong-sized tuples aren't silently mistreated),
358- variable length parameter lists are a sufficiently accepted practice
359- in most programming languages that a compromise has been worked out.
360- (And anyway, assignment has no equivalent for empty argument lists.)
317+ Function call semantics are described in more detail in section
318+ \ref {calls }.
319+ A function call always assigns values to all parameters mentioned in
320+ the parameter list, either from position arguments, from keyword
321+ arguments, or from default values. If the form `` \code {*identifier}''
322+ is present, it is initialized to a tuple receiving any excess
323+ positional parameters, defaulting to the empty tuple. If the form
324+ `` \code {**identifier}'' is present, it is initialized to a new
325+ dictionary receiving any excess keyword arguments, defaulting to a
326+ new empty dictionary.
327+
328+
329+
330+
361331
362332It is also possible to create anonymous functions (functions not bound
363333to a name), for immediate use in expressions. This uses lambda forms,
364- described in section \ref {lambda }.
334+ described in section \ref {lambda }. Note that the lambda form is
335+ merely a shorthand for a simplified function definition; a function
336+ defined in a `` \keyword {def}'' statement can be passed around or
337+ assigned to another name just like a function defined by a lambda
338+ form. The `` \keyword {def}'' form is actually more powerful since it
339+ allows the execution of multiple statements.
365340\indexii {lambda}{form}
366341
342+ \strong {Programmer's note:} a `` \code {def}'' form executed inside a
343+ function definition defines a local function that can be returned or
344+ passed around. Because of Python's two-scope philosophy, a local
345+ function defined in this way does not have access to the local
346+ variables of the function that contains its definition; the same rule
347+ applies to functions defined by a lambda form. A standard trick to
348+ pass selected local variables into a locally defined function is to
349+ use default argument values, like this:
350+
351+ \begin {verbatim }
352+ # Return a function that returns its argument incremented by 'n'
353+ def make_incrementer(n):
354+ def increment(x, n=n):
355+ return x+n
356+ return increment
357+
358+ add1 = make_incrementer(1)
359+ print add1(3) # This prints '4'
360+ \end {verbatim }
361+
367362\section {Class definitions } \label {class }
368363\indexii {class}{definition}
369364
@@ -372,22 +367,31 @@ \section{Class definitions} \label{class}
372367
373368\begin {verbatim }
374369classdef: "class" classname [inheritance] ":" suite
375- inheritance: "(" [condition_list ] ")"
370+ inheritance: "(" [expression_list ] ")"
376371classname: identifier
377372\end {verbatim }
378373
379374A class definition is an executable statement. It first evaluates the
380375inheritance list, if present. Each item in the inheritance list
381376should evaluate to a class object. The class's suite is then executed
382377in a new execution frame (see section \ref {execframes }), using a newly
383- created local name space and the original global name space .
378+ created local namespace and the original global namespace .
384379(Usually, the suite contains only function definitions.) When the
385380class's suite finishes execution, its execution frame is discarded but
386- its local name space is saved. A class object is then created using
387- the inheritance list for the base classes and the saved local name
388- space for the attribute dictionary. The class name is bound to this
389- class object in the original local name space .
381+ its local namespace is saved. A class object is then created using
382+ the inheritance list for the base classes and the saved local
383+ namespace for the attribute dictionary. The class name is bound to this
384+ class object in the original local namespace .
390385\index {inheritance}
391386\indexii {class}{name}
392387\indexii {name}{binding}
393388\indexii {execution}{frame}
389+
390+ \strong {Programmer's note:} variables defined in the class definition
391+ are class variables; they are shared by all instances. To define
392+ instance variables, they must be given a value in the the
393+ \method {__init__()} method or in another method. Both class and
394+ instance variables are accessible through the notation
395+ `` `code{self.name}'' , and an instance variable hides a class variable
396+ with the same name when accessed in this way. Class variables with
397+ immutable values can be used as defaults for instance variables.
0 commit comments