rest25/reference/compound_stmts.rst => rest262/reference/compound_stmts.rst
39statements are executed::
40
41   if x < y < z: print x; print y; print z
42
43Summarizing:
44
45.. productionlist::
46   compound_stmt: `if_stmt`
n47-                : \| `while_stmt`
n47+                : | `while_stmt`
48-                : \| `for_stmt`
48+                : | `for_stmt`
49-                : \| `try_stmt`
49+                : | `try_stmt`
50-                : \| `with_stmt`
50+                : | `with_stmt`
51-                : \| `funcdef`
51+                : | `funcdef`
52-                : \| `classdef`
52+                : | `classdef`
53+                : | `decorated`
53-   suite: `stmt_list` NEWLINE \| NEWLINE INDENT `statement`+ DEDENT
54+   suite: `stmt_list` NEWLINE | NEWLINE INDENT `statement`+ DEDENT
54-   statement: `stmt_list` NEWLINE \| `compound_stmt`
55+   statement: `stmt_list` NEWLINE | `compound_stmt`
55-   stmt_list: `simple_stmt` (";" `simple_stmt`)\* [";"]
56+   stmt_list: `simple_stmt` (";" `simple_stmt`)* [";"]
56
57.. index::
58   single: NEWLINE token
59   single: DEDENT token
60   pair: dangling; else
61
62Note that statements always end in a ``NEWLINE`` possibly followed by a
63``DEDENT``. Also note that optional continuation clauses always begin with a
65'dangling :keyword:`else`' problem is solved in Python by requiring nested
66:keyword:`if` statements to be indented).
67
68The formatting of the grammar rules in the following sections places each clause
69on a separate line for clarity.
70
71
72.. _if:
n74+.. _elif:
75+.. _else:
73
74The :keyword:`if` statement
75===========================
76
n77-.. index:: statement: if
78- 
79-The :keyword:`if` statement is used for conditional execution:
80- 
81-.. productionlist::
82-   if_stmt: "if" `expression` ":" `suite`
83-          : ( "elif" `expression` ":" `suite` )\*
84-          : ["else" ":" `suite`]
85- 
86.. index::
n81+   statement: if
87   keyword: elif
88   keyword: else
n84+ 
85+The :keyword:`if` statement is used for conditional execution:
86+ 
87+.. productionlist::
88+   if_stmt: "if" `expression` ":" `suite`
89+          : ( "elif" `expression` ":" `suite` )*
90+          : ["else" ":" `suite`]
89
90It selects exactly one of the suites by evaluating the expressions one by one
91until one is found to be true (see section :ref:`booleans` for the definition of
92true and false); then that suite is executed (and no other part of the
93:keyword:`if` statement is executed or evaluated).  If all expressions are
94false, the suite of the :keyword:`else` clause, if present, is executed.
95
96
97.. _while:
98
99The :keyword:`while` statement
100==============================
101
102.. index::
103   statement: while
104   pair: loop; statement
n107+   keyword: else
105
106The :keyword:`while` statement is used for repeated execution as long as an
107expression is true:
108
109.. productionlist::
110   while_stmt: "while" `expression` ":" `suite`
111             : ["else" ":" `suite`]
n112- 
113-.. index:: keyword: else
114
115This repeatedly tests the expression and, if it is true, executes the first
116suite; if the expression is false (which may be the first time it is tested) the
117suite of the :keyword:`else` clause, if present, is executed and the loop
118terminates.
119
120.. index::
121   statement: break
130.. _for:
131
132The :keyword:`for` statement
133============================
134
135.. index::
136   statement: for
137   pair: loop; statement
n138- 
139-.. index:: object: sequence
140- 
141-The :keyword:`for` statement is used to iterate over the elements of a sequence
142-(such as a string, tuple or list) or other iterable object:
143- 
144-.. productionlist::
145-   for_stmt: "for" `target_list` "in" `expression_list` ":" `suite`
146-           : ["else" ":" `suite`]
147- 
148-.. index::
149   keyword: in
150   keyword: else
151   pair: target; list
n142+   object: sequence
143+ 
144+The :keyword:`for` statement is used to iterate over the elements of a sequence
145+(such as a string, tuple or list) or other iterable object:
146+ 
147+.. productionlist::
148+   for_stmt: "for" `target_list` "in" `expression_list` ":" `suite`
149+           : ["else" ":" `suite`]
152
153The expression list is evaluated once; it should yield an iterable object.  An
154iterator is created for the result of the ``expression_list``.  The suite is
155then executed once for each item provided by the iterator, in the order of
156ascending indices.  Each item in turn is assigned to the target list using the
157standard rules for assignments, and then the suite is executed.  When the items
158are exhausted (which is immediately when the sequence is empty), the suite in
159the :keyword:`else` clause, if present, is executed, and the loop terminates.
201
202::
203
204   for x in a[:]:
205       if x < 0: a.remove(x)
206
207
208.. _try:
n207+.. _except:
208+.. _finally:
209
210The :keyword:`try` statement
211============================
212
n213-.. index:: statement: try
n213+.. index::
214+   statement: try
215+   keyword: except
216+   keyword: finally
214
215The :keyword:`try` statement specifies exception handlers and/or cleanup code
216for a group of statements:
217
218.. productionlist::
n219-   try_stmt: try1_stmt \| try2_stmt
n222+   try_stmt: try1_stmt | try2_stmt
220   try1_stmt: "try" ":" `suite`
n221-            : ("except" [`expression` ["," `target`]] ":" `suite`)+
n224+            : ("except" [`expression` [("as" | ",") `target`]] ":" `suite`)+
222            : ["else" ":" `suite`]
223            : ["finally" ":" `suite`]
224   try2_stmt: "try" ":" `suite`
225            : "finally" ":" `suite`
226
227.. versionchanged:: 2.5
228   In previous versions of Python, :keyword:`try`...\ :keyword:`except`...\
229   :keyword:`finally` did not work. :keyword:`try`...\ :keyword:`except` had to be
230   nested in :keyword:`try`...\ :keyword:`finally`.
n231- 
232-.. index:: keyword: except
233
234The :keyword:`except` clause(s) specify one or more exception handlers. When no
235exception occurs in the :keyword:`try` clause, no exception handler is executed.
236When an exception occurs in the :keyword:`try` suite, a search for an exception
237handler is started.  This search inspects the except clauses in turn until one
238is found that matches the exception.  An expression-less except clause, if
239present, must be last; it matches any exception.  For an except clause with an
240expression, that expression is evaluated, and the clause matches the exception
267   single: exc_type (in module sys)
268   single: exc_value (in module sys)
269   single: exc_traceback (in module sys)
270
271Before an except clause's suite is executed, details about the exception are
272assigned to three variables in the :mod:`sys` module: ``sys.exc_type`` receives
273the object identifying the exception; ``sys.exc_value`` receives the exception's
274parameter; ``sys.exc_traceback`` receives a traceback object (see section
n275-:ref:`traceback`) identifying the point in the program where the exception
n276+:ref:`types`) identifying the point in the program where the exception
276occurred. These details are also available through the :func:`sys.exc_info`
277function, which returns a tuple ``(exc_type, exc_value, exc_traceback)``.  Use
278of the corresponding variables is deprecated in favor of this function, since
279their use is unsafe in a threaded program.  As of Python 1.5, the variables are
280restored to their previous values (before the call) when returning from a
281function that handled an exception.
282
283.. index::
315lifted in the future).
316
317Additional information on exceptions can be found in section :ref:`exceptions`,
318and information on using the :keyword:`raise` statement to generate exceptions
319may be found in section :ref:`raise`.
320
321
322.. _with:
n324+.. _as:
323
324The :keyword:`with` statement
325=============================
326
327.. index:: statement: with
328
329.. versionadded:: 2.5
330
331The :keyword:`with` statement is used to wrap the execution of a block with
332methods defined by a context manager (see section :ref:`context-managers`). This
333allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` usage
334patterns to be encapsulated for convenient reuse.
335
336.. productionlist::
n337-   with_stmt: "with" `expression` ["as" target] ":" `suite`
n339+   with_stmt: "with" `expression` ["as" `target`] ":" `suite`
338
339The execution of the :keyword:`with` statement proceeds as follows:
340
341#. The context expression is evaluated to obtain a context manager.
342
343#. The context manager's :meth:`__enter__` method is invoked.
344
345#. If a target was included in the :keyword:`with` statement, the return value
366
367   If the suite was exited for any reason other than an exception, the return value
368   from :meth:`__exit__` is ignored, and execution proceeds at the normal location
369   for the kind of exit that was taken.
370
371.. note::
372
373   In Python 2.5, the :keyword:`with` statement is only allowed when the
n374-   ``with_statement`` feature has been enabled.  It will always be enabled in
n376+   ``with_statement`` feature has been enabled.  It is always enabled in
375-   Python 2.6.  This ``__future__`` import statement can be used to enable the
377+   Python 2.6.
376-   feature::
377- 
378-      from __future__ import with_statement
379- 
380
381.. seealso::
382
383   :pep:`0343` - The "with" statement
384      The specification, background, and examples for the Python :keyword:`with`
385      statement.
386
387
388.. _function:
n387+.. _def:
389
390Function definitions
391====================
392
393.. index::
n393+   statement: def
394   pair: function; definition
n395-   statement: def
n395+   pair: function; name
396- 
396+   pair: name; binding
397-.. index::
398   object: user-defined function
399   object: function
400
401A function definition defines a user-defined function object (see section
402:ref:`types`):
403
404.. productionlist::
n405-   funcdef: [`decorators`] "def" `funcname` "(" [`parameter_list`] ")" ":" `suite`
n404+   decorated: decorators (classdef | funcdef)
406-   decorators: `decorator`+
405+   decorators: `decorator`+
407   decorator: "@" `dotted_name` ["(" [`argument_list` [","]] ")"] NEWLINE
n407+   funcdef: "def" `funcname` "(" [`parameter_list`] ")" ":" `suite`
408-   dotted_name: `identifier` ("." `identifier`)\*
408+   dotted_name: `identifier` ("." `identifier`)*
409-   parameter_list: (`defparameter` ",")\*
409+   parameter_list: (`defparameter` ",")*
410-                 : (  "\*" `identifier` [, "\*\*" `identifier`]
410+                 : (  "*" `identifier` [, "**" `identifier`]
411-                 : \| "\*\*" `identifier`
411+                 : | "**" `identifier`
412-                 : \| `defparameter` [","] )
412+                 : | `defparameter` [","] )
413   defparameter: `parameter` ["=" `expression`]
n414-   sublist: `parameter` ("," `parameter`)\* [","]
n414+   sublist: `parameter` ("," `parameter`)* [","]
415-   parameter: `identifier` \| "(" `sublist` ")"
415+   parameter: `identifier` | "(" `sublist` ")"
416   funcname: `identifier`
n417- 
418-.. index::
419-   pair: function; name
420-   pair: name; binding
421
422A function definition is an executable statement.  Its execution binds the
423function name in the current local namespace to a function object (a wrapper
424around the executable code for the function).  This function object contains a
425reference to the current global namespace as the global namespace to be used
426when the function is called.
427
428The function definition does not execute the function body; this gets executed
n429-only when the function is called.
n425+only when the function is called. [#]_
430
n427+.. index::
428+  statement: @
429+ 
431-A function definition may be wrapped by one or more decorator expressions.
430+A function definition may be wrapped by one or more :term:`decorator` expressions.
432Decorator expressions are evaluated when the function is defined, in the scope
433that contains the function definition.  The result must be a callable, which is
434invoked with the function object as the only argument. The returned value is
435bound to the function name instead of the function object.  Multiple decorators
436are applied in nested fashion. For example, the following code::
437
438   @f1(arg)
439   @f2
463as the default, and explicitly test for it in the body of the function, e.g.::
464
465   def whats_on_the_telly(penguin=None):
466       if penguin is None:
467           penguin = []
468       penguin.append("property of the zoo")
469       return penguin
470
n470+.. index::
471+  statement: *
472+  statement: **
473+ 
471Function call semantics are described in more detail in section :ref:`calls`. A
472function call always assigns values to all parameters mentioned in the parameter
473list, either from position arguments, from keyword arguments, or from default
474values.  If the form "``*identifier``" is present, it is initialized to a tuple
475receiving any excess positional parameters, defaulting to the empty tuple.  If
476the form "``**identifier``" is present, it is initialized to a new dictionary
477receiving any excess keyword arguments, defaulting to a new empty dictionary.
478
494
495
496.. _class:
497
498Class definitions
499=================
500
501.. index::
n505+   object: class
506+   statement: class
502   pair: class; definition
n503-   statement: class
n508+   pair: class; name
504- 
509+   pair: name; binding
505-.. index:: object: class
510+   pair: execution; frame
511+   single: inheritance
512+   single: docstring
506
507A class definition defines a class object (see section :ref:`types`):
508
509.. productionlist::
510   classdef: "class" `classname` [`inheritance`] ":" `suite`
511   inheritance: "(" [`expression_list`] ")"
512   classname: `identifier`
n513- 
514-.. index::
515-   single: inheritance
516-   pair: class; name
517-   pair: name; binding
518-   pair: execution; frame
519
520A class definition is an executable statement.  It first evaluates the
521inheritance list, if present.  Each item in the inheritance list should evaluate
522to a class object or class type which allows subclassing.  The class's suite is
523then executed in a new execution frame (see section :ref:`naming`), using a
524newly created local namespace and the original global namespace. (Usually, the
525suite contains only function definitions.)  When the class's suite finishes
n526-execution, its execution frame is discarded but its local namespace is saved.  A
n527+execution, its execution frame is discarded but its local namespace is
527-class object is then created using the inheritance list for the base classes and
528+saved. [#]_ A class object is then created using the inheritance list for the
528-the saved local namespace for the attribute dictionary.  The class name is bound
529+base classes and the saved local namespace for the attribute dictionary.  The
529-to this class object in the original local namespace.
530+class name is bound to this class object in the original local namespace.
530
531**Programmer's note:** Variables defined in the class definition are class
n532-variables; they are shared by all instances.  To define instance variables, they
n533+variables; they are shared by all instances.  To create instance variables, they
533-must be given a value in the :meth:`__init__` method or in another method.  Both
534+can be set in a method with ``self.name = value``.  Both class and instance
534-class and instance variables are accessible through the notation
535+variables are accessible through the notation "``self.name``", and an instance
535-"``self.name``", and an instance variable hides a class variable with the same
536+variable hides a class variable with the same name when accessed in this way.
536-name when accessed in this way.  Class variables with immutable values can be
537+Class variables can be used as defaults for instance variables, but using
537-used as defaults for instance variables. For new-style classes, descriptors can
538+mutable values there can lead to unexpected results.  For :term:`new-style
538-be used to create instance variables with different implementation details.
539+class`\es, descriptors can be used to create instance variables with different
540+implementation details.
541+ 
542+Class definitions, like function definitions, may be wrapped by one or more
543+:term:`decorator` expressions.  The evaluation rules for the decorator
544+expressions are the same as for functions.  The result must be a class object,
545+which is then bound to the class name.
539
540.. rubric:: Footnotes
541
n542-.. [#] The exception is propogated to the invocation stack only if there is no
n549+.. [#] The exception is propagated to the invocation stack only if there is no
543   :keyword:`finally` clause that negates the exception.
544
545.. [#] Currently, control "flows off the end" except in the case of an exception or the
546   execution of a :keyword:`return`, :keyword:`continue`, or :keyword:`break`
547   statement.
548
t556+.. [#] A string literal appearing as the first statement in the function body is
557+   transformed into the function's ``__doc__`` attribute and therefore the
558+   function's :term:`docstring`.
559+ 
560+.. [#] A string literal appearing as the first statement in the class body is
561+   transformed into the namespace's ``__doc__`` item and therefore the class's
562+   :term:`docstring`.
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op