複合文 (compound statement)
***************************

複合文には、他の文 (のグループ) が入ります; 複合文は、中に入っている他
の文の実行の制御に何らかのやり方で影響を及ぼします。一般的には、複合文
は複数行にまたがって書かれますが、全部の文を一行に連ねた単純な書き方も
あります。

The "if", "while" and "for" statements implement traditional control
flow constructs.  "try" specifies exception handlers and/or cleanup
code for a group of statements.  Function and class definitions are
also syntactically compound statements.

Compound statements consist of one or more 『clauses.』  A clause
consists of a header and a 『suite.』  The clause headers of a
particular compound statement are all at the same indentation level.
Each clause header begins with a uniquely identifying keyword and ends
with a colon.  A suite is a group of statements controlled by a
clause.  A suite can be one or more semicolon-separated simple
statements on the same line as the header, following the header’s
colon, or it can be one or more indented statements on subsequent
lines.  Only the latter form of suite can contain nested compound
statements; the following is illegal, mostly because it wouldn’t be
clear to which "if" clause a following "else" clause would belong:

   if test1: if test2: print x

Also note that the semicolon binds tighter than the colon in this
context, so that in the following example, either all or none of the
"print" statements are executed:

   if x < y < z: print x; print y; print z

まとめると、以下のようになります:

   compound_stmt ::= if_stmt
                     | while_stmt
                     | for_stmt
                     | try_stmt
                     | with_stmt
                     | funcdef
                     | classdef
                     | decorated
   suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
   statement     ::= stmt_list NEWLINE | compound_stmt
   stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]

Note that statements always end in a "NEWLINE" possibly followed by a
"DEDENT". Also note that optional continuation clauses always begin
with a keyword that cannot start a statement, thus there are no
ambiguities (the 『dangling "else"』 problem is solved in Python by
requiring nested "if" statements to be indented).

以下の節における文法規則の記述方式は、明確さのために、各節を別々の行に
書くようにしています。


"if" 文
=======

"if" 文は、条件分岐を実行するために使われます:

   if_stmt ::= "if" expression ":" suite
               ( "elif" expression ":" suite )*
               ["else" ":" suite]

"if" 文は、式を一つ一つ評価してゆき、真になるまで続けて、真になった節
のスイートだけを選択します (真: true と偽: false の定義については、 ブ
ール演算 (boolean operation) 節を参照してください); 次に、選択したスイ
ートを実行します (そして、 "if" 文の他の部分は、実行や評価をされません
)。全ての式が偽になった場合、 "else" 節があれば、そのスイートが実行さ
れます。


"while" 文
==========

"while" 文は、式の値が真である間、実行を繰り返すために使われます:

   while_stmt ::= "while" expression ":" suite
                  ["else" ":" suite]

"while" 文は式を繰り返し真偽評価し、真であれば最初のスイートを実行しま
す。式が偽であれば (最初から偽になっていることもありえます)、 "else"
節がある場合にはそれを実行し、ループを終了します。

最初のスイート内で "break" 文が実行されると、 "else" 節のスイートを実
行することなくループを終了します。 "continue" 文が最初のスイート内で実
行されると、スイート内にある残りの文の実行をスキップして、式の真偽評価
に戻ります。


"for" 文
========

"for" 文は、シーケンス (文字列、タプルまたはリスト) や、その他の反復可
能なオブジェクト (iterable object) 内の要素に渡って反復処理を行うため
に使われます:

   for_stmt ::= "for" target_list "in" expression_list ":" suite
                ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable
object.  An iterator is created for the result of the
"expression_list".  The suite is then executed once for each item
provided by the iterator, in the order of ascending indices.  Each
item in turn is assigned to the target list using the standard rules
for assignments, and then the suite is executed.  When the items are
exhausted (which is immediately when the sequence is empty), the suite
in the "else" clause, if present, is executed, and the loop
terminates.

A "break" statement executed in the first suite terminates the loop
without executing the "else" clause’s suite.  A "continue" statement
executed in the first suite skips the rest of the suite and continues
with the next item, or with the "else" clause if there was no next
item.

The suite may assign to the variable(s) in the target list; this does
not affect the next item assigned to it.

The target list is not deleted when the loop is finished, but if the
sequence is empty, it will not have been assigned to at all by the
loop.  Hint: the built-in function "range()" returns a sequence of
integers suitable to emulate the effect of Pascal’s "for i := a to b
do"; e.g., "range(3)" returns the list "[0, 1, 2]".

注釈: There is a subtlety when the sequence is being modified by the
  loop (this can only occur for mutable sequences, i.e. lists). An
  internal counter is used to keep track of which item is used next,
  and this is incremented on each iteration.  When this counter has
  reached the length of the sequence the loop terminates.  This means
  that if the suite deletes the current (or a previous) item from the
  sequence, the next item will be skipped (since it gets the index of
  the current item which has already been treated).  Likewise, if the
  suite inserts an item in the sequence before the current item, the
  current item will be treated again the next time through the loop.
  This can lead to nasty bugs that can be avoided by making a
  temporary copy using a slice of the whole sequence, e.g.,

     for x in a[:]:
         if x < 0: a.remove(x)


"try" 文
========

"try" 文は、ひとまとめの文に対して、例外処理および/またはクリーンアッ
プコードを指定します:

   try_stmt  ::= try1_stmt | try2_stmt
   try1_stmt ::= "try" ":" suite
                 ("except" [expression [("as" | ",") identifier]] ":" suite)+
                 ["else" ":" suite]
                 ["finally" ":" suite]
   try2_stmt ::= "try" ":" suite
                 "finally" ":" suite

バージョン 2.5 で変更: In previous versions of Python,
"try"…"except"…"finally" did not work. "try"…"except" had to be nested
in "try"…"finally".

The "except" clause(s) specify one or more exception handlers. When no
exception occurs in the "try" clause, no exception handler is
executed. When an exception occurs in the "try" suite, a search for an
exception handler is started.  This search inspects the except clauses
in turn until one is found that matches the exception.  An expression-
less except clause, if present, must be last; it matches any
exception.  For an except clause with an expression, that expression
is evaluated, and the clause matches the exception if the resulting
object is 「compatible」 with the exception.  An object is compatible
with an exception if it is the class or a base class of the exception
object, or a tuple containing an item compatible with the exception.

例外がどの "except" 節にも合致しなかった場合、現在のコードを囲うさらに
外側、そして呼び出しスタックへと検索を続けます。 [1]

"except" 節のヘッダにある式を値評価するときに例外が発生すると、元々の
ハンドラ検索はキャンセルされ、新たな例外に対する例外ハンドラの検索を現
在の "except" 節の外側のコードや呼び出しスタックに対して行います
("try" 文全体が例外を発行したかのように扱われます)。

When a matching except clause is found, the exception is assigned to
the target specified in that except clause, if present, and the except
clause’s suite is executed.  All except clauses must have an
executable block.  When the end of this block is reached, execution
continues normally after the entire try statement.  (This means that
if two nested handlers exist for the same exception, and the exception
occurs in the try clause of the inner handler, the outer handler will
not handle the exception.)

Before an except clause’s suite is executed, details about the
exception are assigned to three variables in the "sys" module:
"sys.exc_type" receives the object identifying the exception;
"sys.exc_value" receives the exception’s parameter;
"sys.exc_traceback" receives a traceback object (see section 標準型の
階層) identifying the point in the program where the exception
occurred. These details are also available through the
"sys.exc_info()" function, which returns a tuple "(exc_type,
exc_value, exc_traceback)".  Use of the corresponding variables is
deprecated in favor of this function, since their use is unsafe in a
threaded program.  As of Python 1.5, the variables are restored to
their previous values (before the call) when returning from a function
that handled an exception.

オプションの "else" 節は、実行の制御が "try" 節の末尾に到達した場合に
実行されます。 [2] "else" 節内で起きた例外は、 "else" 節に先行する
"except" 節で処理されることはありません。

If "finally" is present, it specifies a 『cleanup』 handler.  The
"try" clause is executed, including any "except" and "else" clauses.
If an exception occurs in any of the clauses and is not handled, the
exception is temporarily saved. The "finally" clause is executed.  If
there is a saved exception, it is re-raised at the end of the
"finally" clause. If the "finally" clause raises another exception or
executes a "return" or "break" statement, the saved exception is
discarded:

   >>> def f():
   ...     try:
   ...         1/0
   ...     finally:
   ...         return 42
   ...
   >>> f()
   42

"finally" 節を実行している間は、プログラムからは例外情報は利用できませ
ん。

"try"…"finally" 文の "try" スイート内で "return" 、 "break" 、または
"continue" 文が実行された場合、 "finally" 節も 『抜け出る途中に (on
the way out)』 実行されます。 "finally" 節での "continue" 文の使用は不
正です。 (理由は現在の実装上の問題です – この制限は将来解消されるかも
しれません)。

関数の返り値は最後に実行された "return" 文によって決まります。
"finally" 節は必ず実行されるため、"finally" 節で実行された "return" 文
は常に最後に実行されます:

   >>> def foo():
   ...     try:
   ...         return 'try'
   ...     finally:
   ...         return 'finally'
   ...
   >>> foo()
   'finally'

例外に関するその他の情報は 例外 節にあります。また、 "raise" 文の使用
による例外の生成に関する情報は、 raise 文 節にあります。


"with" 文
=========

バージョン 2.5 で追加.

"with" 文は、ブロックの実行を、コンテキストマネージャによって定義され
たメソッドでラップするために使われます (with文とコンテキストマネージャ
セクションを参照してください)。これにより、よくある
"try"…"except"…"finally" 利用パターンをカプセル化して便利に再利用する
ことができます。

   with_stmt ::= "with" with_item ("," with_item)* ":" suite
   with_item ::= expression ["as" target]

一つの 「要素」 を持つ "with" 文の実行は以下のように進行します:

1. コンテキスト式 ("with_item" で与えられた式) を評価することで、コ
   ン テキストマネージャを取得します。

2. コンテキストマネージャの "__exit__()" メソッドが、後で使うために
   ロ ードされます。

3. コンテキストマネージャの "__enter__()" メソッドが呼ばれます。

4. "with" 文にターゲットが含まれていたら、それに "__enter__()" から
   の 戻り値が代入されます。

   注釈: "with" 文は、 "__enter__()" メソッドがエラーなく終了した場
     合には "__exit__()" が常に呼ばれることを保証します。ですので、も
     しターゲ ットリストへの代入中にエラーが発生した場合には、これはそ
     のスイー トの中で発生したエラーと同じように扱われます。以下のステ
     ップ 6 を 参照してください。

5. スイートが実行されます。

6. The context manager’s "__exit__()" method is invoked. If an
   exception caused the suite to be exited, its type, value, and
   traceback are passed as arguments to "__exit__()". Otherwise, three
   "None" arguments are supplied.

   If the suite was exited due to an exception, and the return value
   from the "__exit__()" method was false, the exception is reraised.
   If the return value was true, the exception is suppressed, and
   execution continues with the statement following the "with"
   statement.

   もしそのスイートが例外でない何らかの理由で終了した場合、その
   "__exit__()" からの戻り値は無視されて、実行は発生した終了の種類に応
   じた通常の位置から継続します。

複数の要素があるとき、コンテキストマネージャは複数の "with" 文がネスト
されたかのように進行します:

   with A() as a, B() as b:
       suite

は、以下と同等です

   with A() as a:
       with B() as b:
           suite

注釈: In Python 2.5, the "with" statement is only allowed when the
  "with_statement" feature has been enabled.  It is always enabled in
  Python 2.6.

バージョン 2.7 で変更: 複数のコンテキスト式をサポートしました。

参考:

  **PEP 343** - 「with」 ステートメント
     Python の "with" 文の仕様、背景、および例が記載されています。


関数定義
========

関数定義は、ユーザ定義関数オブジェクトを定義します (標準型の階層 節参
照):

   decorated      ::= decorators (classdef | funcdef)
   decorators     ::= decorator+
   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
   funcdef        ::= "def" funcname "(" [parameter_list] ")" ":" suite
   dotted_name    ::= identifier ("." identifier)*
   parameter_list ::= (defparameter ",")*
                      (  "*" identifier ["," "**" identifier]
                      | "**" identifier
                      | defparameter [","] )
   defparameter   ::= parameter ["=" expression]
   sublist        ::= parameter ("," parameter)* [","]
   parameter      ::= identifier | "(" sublist ")"
   funcname       ::= identifier

関数定義は実行可能な文です。関数定義を実行すると、現在のローカルな名前
空間内で関数名を関数オブジェクト (関数の実行可能コードをくるむラッパ)
に束縛します。この関数オブジェクトには、関数が呼び出された際に使われる
グローバルな名前空間として、現在のグローバルな名前空間への参照が入って
います。

関数定義は関数本体を実行しません; 関数本体は関数が呼び出された時にのみ
実行されます。 [3]

A function definition may be wrapped by one or more *decorator*
expressions. Decorator expressions are evaluated when the function is
defined, in the scope that contains the function definition.  The
result must be a callable, which is invoked with the function object
as the only argument. The returned value is bound to the function name
instead of the function object.  Multiple decorators are applied in
nested fashion. For example, the following code:

   @f1(arg)
   @f2
   def func(): pass

is equivalent to:

   def func(): pass
   func = f1(arg)(f2(func))

When one or more top-level *parameters* have the form *parameter* "="
*expression*, the function is said to have 「default parameter values.
」  For a parameter with a default value, the corresponding *argument*
may be omitted from a call, in which case the parameter’s default
value is substituted.  If a parameter has a default value, all
following parameters must also have a default value — this is a
syntactic restriction that is not expressed by the grammar.

**Default parameter values are evaluated when the function definition
is executed.**  This means that the expression is evaluated once, when
the function is defined, and that the same 「pre-computed」 value is
used for each call.  This is especially important to understand when a
default parameter is a mutable object, such as a list or a dictionary:
if the function modifies the object (e.g. by appending an item to a
list), the default value is in effect modified. This is generally not
what was intended.  A way around this  is to use "None" as the
default, and explicitly test for it in the body of the function, e.g.:

   def whats_on_the_telly(penguin=None):
       if penguin is None:
           penguin = []
       penguin.append("property of the zoo")
       return penguin

Function call semantics are described in more detail in section 呼び出
し (call). A function call always assigns values to all parameters
mentioned in the parameter list, either from position arguments, from
keyword arguments, or from default values.  If the form 「
"*identifier"」 is present, it is initialized to a tuple receiving any
excess positional parameters, defaulting to the empty tuple.  If the
form 「"**identifier"」 is present, it is initialized to a new
dictionary receiving any excess keyword arguments, defaulting to a new
empty dictionary.

It is also possible to create anonymous functions (functions not bound
to a name), for immediate use in expressions.  This uses lambda
expressions, described in section ラムダ (lambda).  Note that the
lambda expression is merely a shorthand for a simplified function
definition; a function defined in a 「"def"」 statement can be passed
around or assigned to another name just like a function defined by a
lambda expression.  The 「"def"」 form is actually more powerful since
it allows the execution of multiple statements.

**Programmer’s note:** Functions are first-class objects.  A 「"def"」
form executed inside a function definition defines a local function
that can be returned or passed around.  Free variables used in the
nested function can access the local variables of the function
containing the def.  See section 名前づけと束縛 (naming and binding)
for details.


クラス定義
==========

クラス定義は、クラスオブジェクトを定義します (標準型の階層 節参照):

   classdef    ::= "class" classname [inheritance] ":" suite
   inheritance ::= "(" [expression_list] ")"
   classname   ::= identifier

A class definition is an executable statement.  It first evaluates the
inheritance list, if present.  Each item in the inheritance list
should evaluate to a class object or class type which allows
subclassing.  The class’s suite is then executed in a new execution
frame (see section 名前づけと束縛 (naming and binding)), using a newly
created local namespace and the original global namespace. (Usually,
the suite contains only function definitions.)  When the class’s suite
finishes execution, its execution frame is discarded but its local
namespace is saved. [4] A class object is then created using the
inheritance list for the base classes and the saved local namespace
for the attribute dictionary.  The class name is bound to this class
object in the original local namespace.

**Programmer’s note:** Variables defined in the class definition are
class variables; they are shared by all instances.  To create instance
variables, they can be set in a method with "self.name = value".  Both
class and instance variables are accessible through the notation 「
"self.name"」, and an instance variable hides a class variable with
the same name when accessed in this way. Class variables can be used
as defaults for instance variables, but using mutable values there can
lead to unexpected results.  For *new-style class*es, descriptors can
be used to create instance variables with different implementation
details.

Class definitions, like function definitions, may be wrapped by one or
more *decorator* expressions.  The evaluation rules for the decorator
expressions are the same as for functions.  The result must be a class
object, which is then bound to the class name.

-[ 脚注 ]-

[1] 例外は、別の例外を送出するような "finally" 節が無い場合にのみ
    呼び 出しスタックへ伝わります。新しい例外によって、古い例外は失わ
    れます 。

[2] 現在、制御が 「末尾に到達する」 のは、例外が発生したり、
    "return", "continue", または "break" 文が実行される場合を除きます
    。

[3] 関数の本体の最初の文として現われる文字列リテラルは、その関数の
    "__doc__" 属性に変換され、その関数のドキュメンテーション文字列
    (*docstring*) になります。

[4] クラスの本体の最初の文として現われる文字列リテラルは、その名前
    空間 の "__doc__" 要素となり、そのクラスのドキュメンテーション文字
    列 (*docstring*)になります。
