式 (expression)
***************

この章では、Python の式における個々の要素の意味について解説します。

**表記法に関する注意:** この章と以降の章での拡張BNF (extended BNF) 表
記は、字句解析規則ではなく、構文規則を記述するために用いられています。
ある構文規則 (のある表現方法) が、以下の形式

   name ::= othername

で記述されていて、この構文特有の意味付け (semantics) が記述されていな
い場合、 "name" の形式をとる構文の意味付けは "othername" の意味付けと
同じになります。


算術変換 (arithmetic conversion)
================================

When a description of an arithmetic operator below uses the phrase 「
the numeric arguments are converted to a common type,」 the arguments
are coerced using the coercion rules listed at  Coercion rules.  If
both arguments are standard numeric types, the following coercions are
applied:

* 片方の引数が複素数型であれば、他方は複素数型に変換されます;

* それ以外の場合で、片方の引数が浮動小数点数であれば、他方は浮動小数
  点 型に変換されます;

* otherwise, if either argument is a long integer, the other is
  converted to long integer;

* otherwise, both must be plain integers and no conversion is
  necessary.

Some additional rules apply for certain operators (e.g., a string left
argument to the 『%』 operator). Extensions can define their own
coercions.


アトム、原子的要素 (atom)
=========================

Atoms are the most basic elements of expressions.  The simplest atoms
are identifiers or literals.  Forms enclosed in reverse quotes or in
parentheses, brackets or braces are also categorized syntactically as
atoms.  The syntax for atoms is:

   atom      ::= identifier | literal | enclosure
   enclosure ::= parenth_form | list_display
                 | generator_expression | dict_display | set_display
                 | string_conversion | yield_atom


識別子 (identifier、または名前 (name))
--------------------------------------

アトムの形になっている識別子 (identifier) は名前 (name) です。字句定義
については 識別子 (identifier) およびキーワード (keyword) 節を、名前付
けや束縛については 名前づけと束縛 (naming and binding) 節を参照してく
ださい。

名前があるオブジェクトに束縛されている場合、名前 atom を評価するとその
オブジェクトになります。名前が束縛されていない場合、 atom を評価しよう
とすると "NameError" 例外を送出します。

**プライベートな名前の名前修飾:** クラス定義内に書かれた識別子で、2つ
以上のアンダースコアから始まり、末尾が2つ以上のアンダースコアで終わっ
ていないものは、そのクラスの *プライベートな名前* とみなされます。プラ
イベートな名前は、コードが生成される前により長い形式に変換されます。こ
の変換によって、クラス名の先頭にアンダースコアがあれば除去し、先頭にア
ンダースコアを1つ付加し、名前の前に挿入されます。例えば、クラス名
"Ham" の中の識別子 "__spam" は、"_Ham__spam" に変換されます。変換は識
別子が使用されている構文のコンテキストからは独立しています。変換された
名前が非常に長い (255文字を超える) 場合、実装によっては名前の切り詰め
が行われるかもしれません。クラス名がアンダースコアのみから成る場合は変
換は行われません。


リテラル
--------

Python supports string literals and various numeric literals:

   literal ::= stringliteral | integer | longinteger
               | floatnumber | imagnumber

Evaluation of a literal yields an object of the given type (string,
integer, long integer, floating point number, complex number) with the
given value.  The value may be approximated in the case of floating
point and imaginary (complex) literals.  See section リテラル for
details.

リテラルは全て変更不能なデータ型に対応します。このため、オブジェクトの
アイデンティティはオブジェクトの値ほど重要ではありません。同じ値を持つ
複数のリテラルを評価した場合、(それらのリテラルがプログラムの同じ場所
由来のものであっても、そうでなくても) 同じオブジェクトを指しているか、
まったく同じ値を持つ別のオブジェクトになります。


丸括弧形式 (parenthesized form)
-------------------------------

丸括弧形式とは、式リストの一形態で、丸括弧で囲ったものです:

   parenth_form ::= "(" [expression_list] ")"

丸括弧で囲われた式のリストは、個々の式が表現するものになります: リスト
内に少なくとも一つのカンマが入っていた場合、タプルになります; そうでな
い場合、式のリストを構成している単一の式自体の値になります。

中身が空の丸括弧のペアは、空のタプルオブジェクトを表します。タプルは変
更不能なので、リテラルと同じ規則が適用されます (すなわち、空のタプルが
二箇所で使われると、それらは同じオブジェクトになることもあるし、ならな
いこともあります)。

タプルは丸括弧で作成されるのではなく、カンマによって作成されることに注
意してください。例外は空のタプルで、この場合には丸括弧が *必要です* —
丸括弧のつかない 「何も記述しない式 (nothing)」 を使えるようにしてしま
うと、文法があいまいなものになってしまい、よくあるタイプミスが検出され
なくなってしまいます。


リスト表現
----------

リスト表現は、角括弧で囲われた式の系列です。系列は空の系列であってもか
まいません:

   list_display        ::= "[" [expression_list | list_comprehension] "]"
   list_comprehension  ::= expression list_for
   list_for            ::= "for" target_list "in" old_expression_list [list_iter]
   old_expression_list ::= old_expression [("," old_expression)+ [","]]
   old_expression      ::= or_test | old_lambda_expr
   list_iter           ::= list_for | list_if
   list_if             ::= "if" old_expression [list_iter]

A list display yields a new list object.  Its contents are specified
by providing either a list of expressions or a list comprehension.
When a comma-separated list of expressions is supplied, its elements
are evaluated from left to right and placed into the list object in
that order.  When a list comprehension is supplied, it consists of a
single expression followed by at least one "for" clause and zero or
more "for" or "if" clauses.  In this case, the elements of the new
list are those that would be produced by considering each of the "for"
or "if" clauses a block, nesting from left to right, and evaluating
the expression to produce a list element each time the innermost block
is reached [1].


Displays for sets and dictionaries
----------------------------------

For constructing a set or a dictionary Python provides special syntax
called 「displays」, each of them in two flavors:

* 明示的に列挙される、または

* *内包表記 (comprehension)* と呼ばれる、ループ処理とフィルター処理
  の 命令の組み合わせを通じて計算されます。

内包表記の共通の構文要素はこの通りです:

   comprehension ::= expression comp_for
   comp_for      ::= "for" target_list "in" or_test [comp_iter]
   comp_iter     ::= comp_for | comp_if
   comp_if       ::= "if" expression_nocond [comp_iter]

内包表記はまず単一の式、続いて "for" 節、さらに続いて 0 個以上の "for"
節や "if" 節からなります。この場合、新たなコンテナの各要素は、各々の
"for" や "if" 節を、左から右にネストしたブロックとみなして実行し、ネス
トの最内のブロックに到達する度に式を評価することで作成されたものになり
ます。

Note that the comprehension is executed in a separate scope, so names
assigned to in the target list don’t 「leak」 in the enclosing scope.


ジェネレータ式
--------------

ジェネレータ式 (generator expression) とは、丸括弧を使ったコンパクトな
ジェネレータ表記法です:

   generator_expression ::= "(" expression comp_for ")"

ジェネレータ式は新たなジェネレータオブジェクトを与えます。この構文は内
包表記とほぼ同じですが、角括弧や波括弧ではなく、丸括弧で囲まれます。

Variables used in the generator expression are evaluated lazily when
the "__next__()" method is called for generator object (in the same
fashion as normal generators).  However, the leftmost "for" clause is
immediately evaluated, so that an error produced by it can be seen
before any other possible error in the code that handles the generator
expression.  Subsequent "for" clauses cannot be evaluated immediately
since they may depend on the previous "for" loop. For example: "(x*y
for x in range(10) for y in bar(x))".

The parentheses can be omitted on calls with only one argument.  See
section 呼び出し (call) for the detail.


辞書表現
--------

辞書表現は、波括弧で囲われた、キーと値のペアからなる系列です。系列は空
の系列であってもかまいません:

   dict_display       ::= "{" [key_datum_list | dict_comprehension] "}"
   key_datum_list     ::= key_datum ("," key_datum)* [","]
   key_datum          ::= expression ":" expression
   dict_comprehension ::= expression ":" expression comp_for

辞書表現は、新たな辞書オブジェクトを表します。

カンマ区切りの一連のキー/データの対が与えられたときは、その要素は左か
ら右へ評価され、辞書の項目を定義します。すなわち、それぞれのキーオブジ
ェクトが、辞書内で対応するデータを保存するキーとして使われます。これに
より、キー/データリストの中で同じキーを複数回指定することができ、その
キーに対する最終的な辞書の値は、最後に与えられたものになります。

辞書内包表記は、リストや集合の内包表記とは対照的に、通常の 「for」 や
「if」 節の前に、コロンで分けられた 2 つの式が必要です。内包表記が起動
すると、結果のキーと値の要素が、作られた順に新しい辞書に挿入されます。

キーの値として使える型に関する制限は 標準型の階層 節ですでに列挙してい
ます。(一言でいうと、キーは変更可能なオブジェクトを全て排除した
*hashable* でなければなりません。) 重複するキー間で衝突が起きても、衝
突が検出されることはありません; あるキーに対して、最後に渡されたデータ
(プログラムテキスト上では、辞書表記の最も右側値となるもの) が使われま
す。


集合表現
--------

集合表現は波括弧で表され、キーと値を分けるコロンがないことで辞書表現と
区別されます:

   set_display ::= "{" (expression_list | comprehension) "}"

集合表示は、一連の式または内包表記によって指定された内容の、ミュータブ
ルな集合オブジェクトを与えます。カンマ区切りの一連の式が与えられたとき
は、その要素は左から右へ順に評価され、集合オブジェクトに加えられます。
内包表記が与えられたときは、内包表記の結果となる要素で集合が構成されま
す。

空集合は "{}" で構成できません。このリテラルは空の辞書を構成します。


String conversions
------------------

A string conversion is an expression list enclosed in reverse (a.k.a.
backward) quotes:

   string_conversion ::= "`" expression_list "`"

A string conversion evaluates the contained expression list and
converts the resulting object into a string according to rules
specific to its type.

If the object is a string, a number, "None", or a tuple, list or
dictionary containing only objects whose type is one of these, the
resulting string is a valid Python expression which can be passed to
the built-in function "eval()" to yield an expression with the same
value (or an approximation, if floating point numbers are involved).

(In particular, converting a string adds quotes around it and converts
「funny」 characters to escape sequences that are safe to print.)

Recursive objects (for example, lists or dictionaries that contain a
reference to themselves, directly or indirectly) use "..." to indicate
a recursive reference, and the result cannot be passed to "eval()" to
get an equal value ("SyntaxError" will be raised instead).

The built-in function "repr()" performs exactly the same conversion in
its argument as enclosing it in parentheses and reverse quotes does.
The built-in function "str()" performs a similar but more user-
friendly conversion.


Yield 式
--------

   yield_atom       ::= "(" yield_expression ")"
   yield_expression ::= "yield" [expression_list]

バージョン 2.5 で追加.

The "yield" expression is only used when defining a generator
function, and can only be used in the body of a function definition.
Using a "yield" expression in a function definition is sufficient to
cause that definition to create a generator function instead of a
normal function.

When a generator function is called, it returns an iterator known as a
generator.  That generator then controls the execution of a generator
function. The execution starts when one of the generator’s methods is
called.  At that time, the execution proceeds to the first "yield"
expression, where it is suspended again, returning the value of
"expression_list" to generator’s caller.  By suspended we mean that
all local state is retained, including the current bindings of local
variables, the instruction pointer, and the internal evaluation stack.
When the execution is resumed by calling one of the generator’s
methods, the function can proceed exactly as if the "yield" expression
was just another external call. The value of the "yield" expression
after resuming depends on the method which resumed the execution.

All of this makes generator functions quite similar to coroutines;
they yield multiple times, they have more than one entry point and
their execution can be suspended.  The only difference is that a
generator function cannot control where should the execution continue
after it yields; the control is always transferred to the generator’s
caller.


ジェネレータ-イテレータメソッド
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

この説ではジェネレータイテレータのメソッドについて説明します。これらは
ジェネレータ関数の実行制御に使用できます。

以下のジェネレータメソッドの呼び出しは、ジェネレータが既に実行中の場合
"ValueError" 例外を送出する点に注意してください。

generator.next()

   Starts the execution of a generator function or resumes it at the
   last executed "yield" expression.  When a generator function is
   resumed with a "next()" method, the current "yield" expression
   always evaluates to "None".  The execution then continues to the
   next "yield" expression, where the generator is suspended again,
   and the value of the "expression_list" is returned to "next()"』s
   caller. If the generator exits without yielding another value, a
   "StopIteration" exception is raised.

generator.send(value)

   Resumes the execution and 「sends」 a value into the generator
   function.  The "value" argument becomes the result of the current
   "yield" expression.  The "send()" method returns the next value
   yielded by the generator, or raises "StopIteration" if the
   generator exits without yielding another value. When "send()" is
   called to start the generator, it must be called with "None" as the
   argument, because there is no "yield" expression that could receive
   the value.

generator.throw(type[, value[, traceback]])

   Raises an exception of type "type" at the point where generator was
   paused, and returns the next value yielded by the generator
   function.  If the generator exits without yielding another value, a
   "StopIteration" exception is raised.  If the generator function
   does not catch the passed-in exception, or raises a different
   exception, then that exception propagates to the caller.

generator.close()

   Raises a "GeneratorExit" at the point where the generator function
   was paused.  If the generator function then raises "StopIteration"
   (by exiting normally, or due to already being closed) or
   "GeneratorExit" (by not catching the exception), close returns to
   its caller.  If the generator yields a value, a "RuntimeError" is
   raised.  If the generator raises any other exception, it is
   propagated to the caller.  "close()" does nothing if the generator
   has already exited due to an exception or normal exit.

以下の簡単なサンプルはジェネレータとジェネレータ関数の振る舞いを実際に
紹介します:

   >>> def echo(value=None):
   ...     print "Execution starts when 'next()' is called for the first time."
   ...     try:
   ...         while True:
   ...             try:
   ...                 value = (yield value)
   ...             except Exception, e:
   ...                 value = e
   ...     finally:
   ...         print "Don't forget to clean up when 'close()' is called."
   ...
   >>> generator = echo(1)
   >>> print generator.next()
   Execution starts when 'next()' is called for the first time.
   1
   >>> print generator.next()
   None
   >>> print generator.send(2)
   2
   >>> generator.throw(TypeError, "spam")
   TypeError('spam',)
   >>> generator.close()
   Don't forget to clean up when 'close()' is called.

参考:

  **PEP 0342** - 拡張されたジェネレータを用いたコルーチン
     シンプルなコルーチンとして利用できるように、ジェネレータの構文と
     API を拡張する提案です。


プライマリ
==========

プライマリは、言語において最も結合の強い操作を表します。文法は以下のよ
うになります:

   primary ::= atom | attributeref | subscription | slicing | call


属性参照
--------

属性参照は、プライマリの後ろにピリオドと名前を連ねたものです:

   attributeref ::= primary "." identifier

The primary must evaluate to an object of a type that supports
attribute references, e.g., a module, list, or an instance.  This
object is then asked to produce the attribute whose name is the
identifier.  If this attribute is not available, the exception
"AttributeError" is raised. Otherwise, the type and value of the
object produced is determined by the object.  Multiple evaluations of
the same attribute reference may yield different objects.


添字表記 (subscription)
-----------------------

添字表記は、シーケンス (文字列、タプルまたはリスト) やマップ (辞書) オ
ブジェクトから、要素を一つ選択します:

   subscription ::= primary "[" expression_list "]"

The primary must evaluate to an object of a sequence or mapping type.

プライマリがマップであれば、式リストの値評価結果はマップ内のいずれかの
キー値に相当するオブジェクトにならなければなりません。添字表記は、その
キーに対応するマップ内の値 (value) を選択します。 (式リストの要素が単
独である場合を除き、式リストはタプルでなければなりません。)

If the primary is a sequence, the expression (list) must evaluate to a
plain integer.  If this value is negative, the length of the sequence
is added to it (so that, e.g., "x[-1]" selects the last item of "x".)
The resulting value must be a nonnegative integer less than the number
of items in the sequence, and the subscription selects the item whose
index is that value (counting from zero).

文字列型の要素は文字 (character) です。文字は個別の型ではなく、 1 文字
だけからなる文字列です。


スライス表記 (slicing)
----------------------

スライス表記はシーケンスオブジェクト (文字列、タプルまたはリスト) にお
けるある範囲の要素を選択します。スライス表記は式として用いたり、代入や
"del" 文の対象として用いたりできます。スライス表記の構文は以下のように
なります:

   slicing          ::= simple_slicing | extended_slicing
   simple_slicing   ::= primary "[" short_slice "]"
   extended_slicing ::= primary "[" slice_list "]"
   slice_list       ::= slice_item ("," slice_item)* [","]
   slice_item       ::= expression | proper_slice | ellipsis
   proper_slice     ::= short_slice | long_slice
   short_slice      ::= [lower_bound] ":" [upper_bound]
   long_slice       ::= short_slice ":" [stride]
   lower_bound      ::= expression
   upper_bound      ::= expression
   stride           ::= expression
   ellipsis         ::= "..."

There is ambiguity in the formal syntax here: anything that looks like
an expression list also looks like a slice list, so any subscription
can be interpreted as a slicing.  Rather than further complicating the
syntax, this is disambiguated by defining that in this case the
interpretation as a subscription takes priority over the
interpretation as a slicing (this is the case if the slice list
contains no proper slice nor ellipses).  Similarly, when the slice
list has exactly one short slice and no trailing comma, the
interpretation as a simple slicing takes priority over that as an
extended slicing.

The semantics for a simple slicing are as follows.  The primary must
evaluate to a sequence object.  The lower and upper bound expressions,
if present, must evaluate to plain integers; defaults are zero and the
"sys.maxint", respectively.  If either bound is negative, the
sequence’s length is added to it.  The slicing now selects all items
with index *k* such that "i <= k < j" where *i* and *j* are the
specified lower and upper bounds.  This may be an empty sequence.  It
is not an error if *i* or *j* lie outside the range of valid indexes
(such items don’t exist so they aren’t selected).

The semantics for an extended slicing are as follows.  The primary
must evaluate to a mapping object, and it is indexed with a key that
is constructed from the slice list, as follows.  If the slice list
contains at least one comma, the key is a tuple containing the
conversion of the slice items; otherwise, the conversion of the lone
slice item is the key.  The conversion of a slice item that is an
expression is that expression.  The conversion of an ellipsis slice
item is the built-in "Ellipsis" object.  The conversion of a proper
slice is a slice object (see section 標準型の階層) whose "start",
"stop" and "step" attributes are the values of the expressions given
as lower bound, upper bound and stride, respectively, substituting
"None" for missing expressions.


呼び出し (call)
---------------

呼び出しは、呼び出し可能オブジェクト (例えば *function*) を
*arguments* の系列とともに呼び出します。系列は空の系列であってもかまい
ません:

   call                 ::= primary "(" [argument_list [","]
            | expression genexpr_for] ")"
   argument_list        ::= positional_arguments ["," keyword_arguments]
                       ["," "*" expression] ["," keyword_arguments]
                       ["," "**" expression]
                     | keyword_arguments ["," "*" expression]
                       ["," "**" expression]
                     | "*" expression ["," keyword_arguments] ["," "**" expression]
                     | "**" expression
   positional_arguments ::= expression ("," expression)*
   keyword_arguments    ::= keyword_item ("," keyword_item)*
   keyword_item         ::= identifier "=" expression

A trailing comma may be present after the positional and keyword
arguments but does not affect the semantics.

The primary must evaluate to a callable object (user-defined
functions, built-in functions, methods of built-in objects, class
objects, methods of class instances, and certain class instances
themselves are callable; extensions may define additional callable
object types).  All argument expressions are evaluated before the call
is attempted.  Please refer to section 関数定義 for the syntax of
formal *parameter* lists.

キーワード引数が存在する場合、以下のようにして最初に位置引数
(positional argument) に変換されます。まず、値の入っていないスロットが
仮引数に対して生成されます。N 個の位置引数がある場合、位置引数は先頭の
N スロットに配置されます。次に、各キーワード引数について、識別子を使っ
て対応するスロットを決定します (識別子が最初の仮引数名と同じなら、最初
のスロットを使う、といった具合です)。スロットがすでにすべて埋まってい
たなら "TypeError" 例外が送出されます。それ以外の場合、引数値をスロッ
トに埋めていきます。 (式が "None" であっても、その式でスロットを埋めま
す)。全ての引数が処理されたら、まだ埋められていないスロットをそれぞれ
に対応する関数定義時のデフォルト値で埋めます。(デフォルト値は、関数が
定義されたときに一度だけ計算されます; 従って、リストや辞書のような変更
可能なオブジェクトがデフォルト値として使われると、対応するスロットに引
数を指定しない限り、このオブジェクトが全ての呼び出しから共有されます;
このような状況は通常避けるべきです。) デフォルト値が指定されていない、
値の埋められていないスロットが残っている場合 "TypeError" 例外が送出さ
れます。そうでない場合、値の埋められたスロットからなるリストが呼び出し
の引数として使われます。

実装では、名前を持たない位置引数を受け取る組み込み関数を提供されるかも
しれません。そういった引数がドキュメント化のために 『名付けられて』 い
たとしても、実際には名付けられていないのでキーワードでは提供されません
。 CPython では、C 言語で実装された関数の、名前を持たない位置引数をパ
ースするために "PyArg_ParseTuple()" を使用します。

仮引数スロットの数よりも多くの位置引数がある場合、構文 "*identifier"
を使って指定された仮引数がないかぎり、 "TypeError" 例外が送出されます;
仮引数 "*identifier" がある場合、この仮引数は余分な位置引数が入ったタ
プル (もしくは、余分な位置引数がない場合には空のタプル) を受け取ります
。

キーワード引数のいずれかが仮引数名に対応しない場合、構文
"**identifier" を使って指定された仮引数がない限り、 "TypeError" 例外が
送出されます; 仮引数 "**identifier" がある場合、この仮引数は余分なキー
ワード引数が入った (キーワードをキーとし、引数値をキーに対応する値とし
た) 辞書を受け取ります。余分なキーワード引数がない場合には、空の (新た
な) 辞書を受け取ります。

If the syntax "*expression" appears in the function call, "expression"
must evaluate to an iterable.  Elements from this iterable are treated
as if they were additional positional arguments; if there are
positional arguments *x1*, …, *xN*, and "expression" evaluates to a
sequence *y1*, …, *yM*, this is equivalent to a call with M+N
positional arguments *x1*, …, *xN*, *y1*, …, *yM*.

A consequence of this is that although the "*expression" syntax may
appear *after* some keyword arguments, it is processed *before* the
keyword arguments (and the "**expression" argument, if any – see
below).  So:

   >>> def f(a, b):
   ...     print a, b
   ...
   >>> f(b=1, *(2,))
   2 1
   >>> f(a=1, *(2,))
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: f() got multiple values for keyword argument 'a'
   >>> f(1, *(2,))
   1 2

キーワード引数と "*expression" 構文を同じ呼び出しで一緒に使うことはあ
まりないので、実際に上記のような混乱が生じることはありません。

If the syntax "**expression" appears in the function call,
"expression" must evaluate to a mapping, the contents of which are
treated as additional keyword arguments.  In the case of a keyword
appearing in both "expression" and as an explicit keyword argument, a
"TypeError" exception is raised.

Formal parameters using the syntax "*identifier" or "**identifier"
cannot be used as positional argument slots or as keyword argument
names.  Formal parameters using the syntax "(sublist)" cannot be used
as keyword argument names; the outermost sublist corresponds to a
single unnamed argument slot, and the argument value is assigned to
the sublist using the usual tuple assignment rules after all other
parameter processing is done.

呼び出しを行うと、例外を送出しない限り、常に何らかの値を返します。
"None" を返す場合もあります。戻り値がどのように算出されるかは、呼び出
し可能オブジェクトの形態によって異なります。

各形態では—

ユーザ定義関数:
   関数のコードブロックに引数リストが渡され、実行されます。コードブロ
   ックは、まず仮引数を実引数に結合 (bind) します; この動作については
   関数定義 で記述しています。コードブロックで "return" 文が実行される
   際に、関数呼び出しの戻り値 (return value) が決定されます。

組み込み関数またはメソッド:
   結果はインタプリタに依存します; 組み込み関数やメソッドの詳細は 組み
   込み関数 を参照してください。

クラスオブジェクト:
   そのクラスの新しいインスタンスが返されます。

クラスインスタンスメソッド:
   対応するユーザ定義の関数が呼び出されます。このとき、呼び出し時の引
   数リストより一つ長い引数リストで呼び出されます: インスタンスが引数
   リストの先頭に追加されます。

クラスインスタンス:
   クラスで "__call__()" メソッドが定義されていなければなりません;
   "__call__()" メソッドが呼び出された場合と同じ効果をもたらします。


べき乗演算 (power operator)
===========================

べき乗演算は、左側にある単項演算子よりも強い結合優先順位があります; 一
方、右側にある単項演算子よりは低い結合優先順位になっています。構文は以
下のようになります:

   power ::= primary ["**" u_expr]

従って、べき乗演算子と単項演算子からなる演算列が丸括弧で囲われていない
場合、演算子は右から左へと評価されます (この場合は演算子の評価順序を強
制しません。つまり "-1**2" は "-1" になります)。

The power operator has the same semantics as the built-in "pow()"
function, when called with two arguments: it yields its left argument
raised to the power of its right argument.  The numeric arguments are
first converted to a common type.  The result type is that of the
arguments after coercion.

With mixed operand types, the coercion rules for binary arithmetic
operators apply. For int and long int operands, the result has the
same type as the operands (after coercion) unless the second argument
is negative; in that case, all arguments are converted to float and a
float result is delivered. For example, "10**2" returns "100", but
"10**-2" returns "0.01". (This last feature was added in Python 2.2.
In Python 2.1 and before, if both arguments were of integer types and
the second argument was negative, an exception was raised).

Raising "0.0" to a negative power results in a "ZeroDivisionError".
Raising a negative number to a fractional power results in a
"ValueError".


単項算術演算とビット単位演算 (unary arithmetic and bitwise operation)
=====================================================================

全ての単項算術演算とビット単位演算は、同じ優先順位を持っています:

   u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr

単項演算子 "-" (マイナス) は、引数となる数値の符号を反転 (negation) し
ます。

単項演算子 "+" (プラス) は、数値引数を変更しません。

The unary "~" (invert) operator yields the bitwise inversion of its
plain or long integer argument.  The bitwise inversion of "x" is
defined as "-(x+1)".  It only applies to integral numbers.

上記の三つはいずれも、引数が正しい型でない場合には "TypeError" 例外が
送出されます。


二項算術演算 (binary arithmetic operation)
==========================================

二項算術演算は、慣習的な優先順位を踏襲しています。演算子のいずれかは、
特定の非数値型にも適用されるので注意してください。べき乗 (power) 演算
子を除き、演算子には二つのレベル、すなわち乗算的 (multiplicatie) 演算
子と加算的 (additie) 演算子しかありません:

   m_expr ::= u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr
              | m_expr "%" u_expr
   a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr

The "*" (multiplication) operator yields the product of its arguments.
The arguments must either both be numbers, or one argument must be an
integer (plain or long) and the other must be a sequence. In the
former case, the numbers are converted to a common type and then
multiplied together.  In the latter case, sequence repetition is
performed; a negative repetition factor yields an empty sequence.

The "/" (division) and "//" (floor division) operators yield the
quotient of their arguments.  The numeric arguments are first
converted to a common type. Plain or long integer division yields an
integer of the same type; the result is that of mathematical division
with the 『floor』 function applied to the result. Division by zero
raises the "ZeroDivisionError" exception.

"%" (剰余: modulo) 演算は、第一引数を第二引数で除算したときの剰余にな
ります。数値引数はまず共通の型に変換されます。右引数値がゼロの場合には
"ZeroDivisionError" 例外が送出されます。引数値は浮動小数点でもよく。例
えば "3.14%0.7" は "0.34" になります ("3.14" は "4*0.7 + 0.34" だから
です)。剰余演算子は常に第二引数と同じ符号 (またはゼロ) の結果になりま
す; 剰余演算の結果の絶対値は、常に第二引数の絶対値よりも小さくなります
。 [2]

The integer division and modulo operators are connected by the
following identity: "x == (x/y)*y + (x%y)".  Integer division and
modulo are also connected with the built-in function "divmod()":
"divmod(x, y) == (x/y, x%y)".  These identities don’t hold for
floating point numbers; there similar identities hold approximately
where "x/y" is replaced by "floor(x/y)" or "floor(x/y) - 1" [3].

In addition to performing the modulo operation on numbers, the "%"
operator is also overloaded by string and unicode objects to perform
string formatting (also known as interpolation). The syntax for string
formatting is described in the Python Library Reference, section
String Formatting Operations.

バージョン 2.3 で撤廃: The floor division operator, the modulo
operator, and the "divmod()" function are no longer defined for
complex numbers.  Instead, convert to a floating point number using
the "abs()" function if appropriate.

The "+" (addition) operator yields the sum of its arguments. The
arguments must either both be numbers or both sequences of the same
type.  In the former case, the numbers are converted to a common type
and then added together.  In the latter case, the sequences are
concatenated.

"-" (減算) 演算は、引数間で減算を行った値を返します。数値引数はまず共
通の型に変換されます。


シフト演算 (shifting operation)
===============================

シフト演算は、算術演算よりも低い優先順位を持っています:

   shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr

These operators accept plain or long integers as arguments.  The
arguments are converted to a common type.  They shift the first
argument to the left or right by the number of bits given by the
second argument.

A right shift by *n* bits is defined as division by "pow(2, n)".  A
left shift by *n* bits is defined as multiplication with "pow(2, n)".
Negative shift counts raise a "ValueError" exception.

注釈: 現在の実装では、右辺被演算子は最大でも "sys.maxsize" でなけれ
  ばなり ません。右辺被演算子が "sys.maxsize" よりも大きいと、
  "OverflowError" 例外が送出されます。


ビット単位演算の二項演算 (binary bitwise operation)
===================================================

以下の三つのビット単位演算には、それぞれ異なる優先順位レベルがあります
:

   and_expr ::= shift_expr | and_expr "&" shift_expr
   xor_expr ::= and_expr | xor_expr "^" and_expr
   or_expr  ::= xor_expr | or_expr "|" xor_expr

The "&" operator yields the bitwise AND of its arguments, which must
be plain or long integers.  The arguments are converted to a common
type.

The "^" operator yields the bitwise XOR (exclusive OR) of its
arguments, which must be plain or long integers.  The arguments are
converted to a common type.

The "|" operator yields the bitwise (inclusive) OR of its arguments,
which must be plain or long integers.  The arguments are converted to
a common type.


比較
====

C 言語と違って、Python における比較演算子は同じ優先順位をもっており、
全ての算術演算子、シフト演算子、ビット単位演算子よりも低くなっています
。また "a < b < c" が数学で伝統的に用いられているのと同じ解釈になる点
も C 言語と違います:

   comparison    ::= or_expr ( comp_operator or_expr )*
   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
                     | "is" ["not"] | ["not"] "in"

比較演算の結果はブール値: "True" または "False" になります。

比較はいくらでも連鎖することができます。例えば "x < y <= z" は "x < y
and y <= z" と等価になります。ただしこの場合、前者では "y" はただ一度
だけ評価される点が異なります (どちらの場合でも、 "x < y" が偽になると
"z" の値はまったく評価されません)。

形式的には、 *a*, *b*, *c*, …, *y*, *z* が式で *op1*, *op2*, …, *opN*
が比較演算子である場合、 "a op1 b op2 c ... y opN z" は "a op1 b and b
op2 c and ... y opN z" と等価になります。ただし、前者では各式は多くて
も一度しか評価されません。

"a op1 b op2 c" と書いた場合、 *a* から *c* までの範囲にあるかどうかの
テストを指すのではないことに注意してください。例えば "x < y > z" は (
きれいな書き方ではありませんが) 完全に正しい文法です。

The forms "<>" and "!=" are equivalent; for consistency with C, "!="
is preferred; where "!=" is mentioned below "<>" is also accepted.
The "<>" spelling is considered obsolescent.


値の比較
--------

演算子 "<", ">", "==", ">=", "<=", および "!=" は2つのオブジェクトの値
を比較します。 オブジェクトが同じ型を持つ必要はりません。

オブジェクト、値、および型 の章では、オブジェクトは (型や id のに加え
て) 値を持つことを述べています。 オブジェクトの値は Python ではやや抽
象的な概念です: 例えば、オブジェクトの値にアクセスする正統な方法はあり
ません。 また、その全てのデータ属性から構成されるなどの特定の方法で、
オブジェクトの値を構築する必要性もありません。 比較演算子は、オブジェ
クトの値とは何かについての特定の概念を実装しています。 この比較の実装
によって、間接的にオブジェクトの値を定義している考えることもできます。

Types can customize their comparison behavior by implementing a
"__cmp__()" method or *rich comparison methods* like "__lt__()",
described in 基本的なカスタマイズ.

等価性比較 ("==" および "!=") のデフォルトの振る舞いは、オブジェクトの
同一性に基づいています。 従って、同一のインスタンスの等価性比較の結果
は等しいとなり、同一でないインスタンスの等価性比較の結果は等しくないと
なります。 デフォルトの振る舞いをこのようにしたのは、全てのオブジェク
トを反射的 (reflexive つまり "x is y" ならば "x == y") なものにしたか
ったからです。

The default order comparison ("<", ">", "<=", and ">=") gives a
consistent but arbitrary order.

(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the "in" and "not in"
operators. In the future, the comparison rules for objects of
different types are likely to change.)

同一でないインスタンスは常に等価でないとする等価性比較のデフォルトの振
る舞いは、型が必要とするオブジェクトの値や値に基づいた等価性の実用的な
定義とは対照的に思えるでしょう。 そのような型では比較の振る舞いをカス
タマイズする必要が出てきて、実際にたくさんの組み込み型でそれが行われて
います。

次のリストでは、最重要の組み込み型の比較の振る舞いを解説しています。

* いくつかの組み込みの数値型 (Numeric Types — int, float, long,
  complex) と標準ライブラリの型 "fractions.Fraction" および
  "decimal.Decimal" は、同じ型や別の型どうしで比較できますが、複素数で
  は順序比較がサポートされていないという制限があります。 関わる型の制
  限の範囲内では、精度のロス無しに数学的に (アルゴリズム的に) 正しい比
  較が行われます。

* Strings (instances of "str" or "unicode") compare
  lexicographically using the numeric equivalents (the result of the
  built-in function "ord()") of their characters. [4] When comparing
  an 8-bit string and a Unicode string, the 8-bit string is converted
  to Unicode.  If the conversion fails, the strings are considered
  unequal.

* Instances of "tuple" or "list" can be compared only within each of
  their types.  Equality comparison across these types results in
  unequality, and ordering comparison across these types gives an
  arbitrary order.

  These sequences compare lexicographically using comparison of
  corresponding elements, whereby reflexivity of the elements is
  enforced.

  In enforcing reflexivity of elements, the comparison of collections
  assumes that for a collection element "x", "x == x" is always true.
  Based on that assumption, element identity is compared first, and
  element comparison is performed only for distinct elements.  This
  approach yields the same result as a strict element comparison
  would, if the compared elements are reflexive.  For non-reflexive
  elements, the result is different than for strict element
  comparison.

  組み込みのコレクションどうしの辞書式比較は次のように動作します:

  * 比較の結果が等価となる2つのコレクションは、同じ型、同じ長さ、対
    応 する要素どうしの比較の結果が等価でなければなりません (例えば、
    "[1,2] == (1,2)" は型が同じでないので偽です)。

  * Collections are ordered the same as their first unequal elements
    (for example, "cmp([1,2,x], [1,2,y])" returns the same as
    "cmp(x,y)").  If a corresponding element does not exist, the
    shorter collection is ordered first (for example, "[1,2] <
    [1,2,3]" is true).

* マッピング ("dict" のインスタンス) の比較の結果が等価となるのは、
  同 じ *(key, value)* を持っているときかつそのときに限ります。 キーと
  値 の等価性比較では反射性が強制されます。

  Outcomes other than equality are resolved consistently, but are not
  otherwise defined. [5]

* Most other objects of built-in types compare unequal unless they
  are the same object; the choice whether one object is considered
  smaller or larger than another one is made arbitrarily but
  consistently within one execution of a program.

比較の振る舞いをカスタマイズしたユーザ定義クラスは、可能なら次の一貫性
の規則に従う必要があります:

* 等価比較は反射的でなければなりません。 つまり、同一のオブジェクト
  は 等しくなければなりません:

     "x is y" は暗黙的に "x == y"

* 比較は対称でなければなりません。 つまり、以下の式の結果は同じでな
  け ればなりません:

     "x == y" と "y == x"

     "x != y" と "y != x"

     "x < y" と "y > x"

     "x <= y" と "y >= x"

* 比較は推移的でなければなりません。 以下の (包括的でない) 例がその
  説 明です:

     "x > y and y > z" は暗黙的に "x > z"

     "x < y and y <= z" は暗黙的に "x < z"

* 比較の逆はブールの否定でなければなりません。 つまり、以下の式の結
  果 は同じでなければなりません:

     "x == y" と "not x != y"

     "x < y" と "not x >= y" (全順序の場合)

     "x > y" と "not x <= y" (全順序の場合)

  最後の2式は全順序の集まりに適用されます (たとえばシーケンスには適用
  されますがセットやマッピングには適用されません)。 "total_ordering()"
  デコレータも参照してください。

* "hash()" の結果は等価性と一貫している必要があります。 等価なオブジ
  ェ クトどうしは同じハッシュ値を持つか、ハッシュ値が計算できないもの
  とさ れる必要があります。

Python does not enforce these consistency rules.


帰属検査演算
------------

演算子 "in" および "not in" は、帰属 (membership) を調べます。 "x in
s" の評価は、 *x* が *s* の要素であれば "True" となり、そうでなければ
"False" となります。 "x not in s" は "x in s" の否定 (negation) を返し
ます。すべての組み込みのシーケンスと集合型に加えて、辞書も、 "in" を辞
書が与えられたキーを持っているかを調べるものとしてサポートしています。
リスト、タプル、集合、凍結集合、辞書、あるいは collection.deque のよう
なコンテナ型について、式 "x in y" は "any(x is e or x == e for e in
y)" と等価です。

文字列やバイト列型については、 "x in y" は *x* が *y* の部分文字列であ
るとき、かつそのときに限り "True" になります。これは "y.find(x) != -1"
と等価です。空文字列は、他の任意の文字列の部分文字列とみなされます。従
って """ in "abc"" は "True" を返すことになります。

"__contains__()" メソッドを実装したユーザ定義クラスでは、
"y.__contains__(x)" の返り値が真となる場合に "x in y" の返り値は
"True" となり、そうでない場合は "False" となります。

"__contains__()" を定義していないが "__iter__()" は定義しているユーザ
定義クラスでは、 "x in y" は "x == z" となるようなある値 *z* が "y" 内
にわたる反復で生成された場合、 "True" となります。もし、反復の間に例外
が発生すれば、 "in" が例外を発生させたようにみえます。

Lastly, the old-style iteration protocol is tried: if a class defines
"__getitem__()", "x in y" is "True" if and only if there is a non-
negative integer index *i* such that "x == y[i]", and all lower
integer indices do not raise "IndexError" exception. (If any other
exception is raised, it is as if "in" raised that exception).

演算子 "not in" は "in" の真値を反転した値として定義されています。


同一性の比較
------------

The operators "is" and "is not" test for object identity: "x is y" is
true if and only if *x* and *y* are the same object.  "x is not y"
yields the inverse truth value. [6]


ブール演算 (boolean operation)
==============================

   or_test  ::= and_test | or_test "or" and_test
   and_test ::= not_test | and_test "and" not_test
   not_test ::= comparison | "not" not_test

In the context of Boolean operations, and also when expressions are
used by control flow statements, the following values are interpreted
as false: "False", "None", numeric zero of all types, and empty
strings and containers (including strings, tuples, lists,
dictionaries, sets and frozensets).  All other values are interpreted
as true.  (See the "__nonzero__()" special method for a way to change
this.)

演算子 "not" は、引数が偽である場合には "True" を、それ以外の場合には
"False" になります。

式 "x and y" は、まず *x* を評価します; *x* が偽なら *x* の値を返しま
す; それ以外の場合には、 *y* の値を評価し、その結果を返します。

式 "x or y" は、まず *x* を評価します; *x* が真なら *x* の値を返します
; それ以外の場合には、 *y* の値を評価し、その結果を返します。

(Note that neither "and" nor "or" restrict the value and type they
return to "False" and "True", but rather return the last evaluated
argument. This is sometimes useful, e.g., if "s" is a string that
should be replaced by a default value if it is empty, the expression
"s or 'foo'" yields the desired value.  Because "not" has to invent a
value anyway, it does not bother to return a value of the same type as
its argument, so e.g., "not 'foo'" yields "False", not "''".)


Conditional Expressions
=======================

バージョン 2.5 で追加.

   conditional_expression ::= or_test ["if" or_test "else" expression]
   expression             ::= conditional_expression | lambda_expr

条件式 (しばしば 「三項演算子」 と呼ばれます) は最も優先度が低いPython
の演算です。

The expression "x if C else y" first evaluates the condition, *C*
(*not* *x*); if *C* is true, *x* is evaluated and its value is
returned; otherwise, *y* is evaluated and its value is returned.

条件演算に関してより詳しくは **PEP 308** を参照してください。


ラムダ (lambda)
===============

   lambda_expr     ::= "lambda" [parameter_list]: expression
   old_lambda_expr ::= "lambda" [parameter_list]: old_expression

Lambda expressions (sometimes called lambda forms) have the same
syntactic position as expressions.  They are a shorthand to create
anonymous functions; the expression "lambda arguments: expression"
yields a function object.  The unnamed object behaves like a function
object defined with

   def name(arguments):
       return expression

See section 関数定義 for the syntax of parameter lists.  Note that
functions created with lambda expressions cannot contain statements.


式のリスト
==========

   expression_list ::= expression ( "," expression )* [","]

An expression list containing at least one comma yields a tuple.  The
length of the tuple is the number of expressions in the list.  The
expressions are evaluated from left to right.

単一要素のタプル (別名 *単集合 (singleton)* ) を作りたければ、末尾にカ
ンマが必要です。単一の式だけで、末尾にカンマをつけない場合には、タプル
ではなくその式の値になります (空のタプルを作りたいなら、中身が空の丸括
弧ペア: "()" を使います。)


評価順序
========

Python evaluates expressions from left to right. Notice that while
evaluating an assignment, the right-hand side is evaluated before the
left-hand side.

以下に示す実行文の各行での評価順序は、添え字の数字順序と同じになります
:

   expr1, expr2, expr3, expr4
   (expr1, expr2, expr3, expr4)
   {expr1: expr2, expr3: expr4}
   expr1 + expr2 * (expr3 - expr4)
   expr1(expr2, expr3, *expr4, **expr5)
   expr3, expr4 = expr1, expr2


演算子の優先順位
================

The following table summarizes the operator precedences in Python,
from lowest precedence (least binding) to highest precedence (most
binding). Operators in the same box have the same precedence.  Unless
the syntax is explicitly given, operators are binary.  Operators in
the same box group left to right (except for comparisons, including
tests, which all have the same precedence and chain from left to right
— see section 比較 — and exponentiation, which groups from right to
left).

+-------------------------------------------------+---------------------------------------+
| 演算子                                          | 説明                                  |
+=================================================+=======================================+
| "lambda"                                        | ラムダ式                              |
+-------------------------------------------------+---------------------------------------+
| "if" – "else"                                   | 条件式                                |
+-------------------------------------------------+---------------------------------------+
| "or"                                            | ブール演算 OR                         |
+-------------------------------------------------+---------------------------------------+
| "and"                                           | ブール演算 AND                        |
+-------------------------------------------------+---------------------------------------+
| "not" "x"                                       | ブール演算 NOT                        |
+-------------------------------------------------+---------------------------------------+
| "in", "not in", "is", "is not", "<", "<=", ">", | 帰属や同一性のテストを含む比較        |
| ">=", "<>", "!=", "=="                          |                                       |
+-------------------------------------------------+---------------------------------------+
| "|"                                             | ビット単位 OR                         |
+-------------------------------------------------+---------------------------------------+
| "^"                                             | ビット単位 XOR                        |
+-------------------------------------------------+---------------------------------------+
| "&"                                             | ビット単位 AND                        |
+-------------------------------------------------+---------------------------------------+
| "<<", ">>"                                      | シフト演算                            |
+-------------------------------------------------+---------------------------------------+
| "+", "-"                                        | 加算および減算                        |
+-------------------------------------------------+---------------------------------------+
| "*", "/", "//", "%"                             | Multiplication, division, remainder   |
|                                                 | [7]                                   |
+-------------------------------------------------+---------------------------------------+
| "+x", "-x", "~x"                                | 正数、負数、ビット単位 NOT            |
+-------------------------------------------------+---------------------------------------+
| "**"                                            | べき乗 [8]                            |
+-------------------------------------------------+---------------------------------------+
| "x[index]", "x[index:index]",                   | 添字指定、スライス操作、呼び出し、属  |
| "x(arguments...)", "x.attribute"                | 性参照                                |
+-------------------------------------------------+---------------------------------------+
| "(expressions...)", "[expressions...]", "{key:  | Binding or tuple display, list        |
| value...}", "`expressions...`"                  | display, dictionary display, string   |
|                                                 | conversion                            |
+-------------------------------------------------+---------------------------------------+

-[ 脚注 ]-

[1] In Python 2.3 and later releases, a list comprehension 「leaks
    」 the control variables of each "for" it contains into the
    containing scope.  However, this behavior is deprecated, and
    relying on it will not work in Python 3.

[2] "abs(x%y) < abs(y)" は数学的には真となりますが、浮動小数点に対
    する 演算の場合には、値丸め (roundoff) のために数値計算的に真にな
    らない 場合があります。例えば、Python の浮動小数点型が IEEE754 倍
    精度数型 になっているプラットフォームを仮定すると、 "-1e-100 %
    1e100" は "1e100" と同じ符号になるはずなのに、計算結果は "-1e-100
    + 1e100" となります。これは数値計算的には厳密に "1e100" と等価です
    。関数 "math.fmod()" は、最初の引数と符号が一致するような値を返す
    ので、上 記の場合には "-1e-100" を返します。どちらのアプローチが適
    切かは、 アプリケーションに依存します。

[3] If x is very close to an exact integer multiple of y, it’s
    possible for "floor(x/y)" to be one larger than "(x-x%y)/y" due to
    rounding.  In such cases, Python returns the latter result, in
    order to preserve that "divmod(x,y)[0] * y + x % y" be very close
    to "x".

[4] Unicode 標準では、 *コードポイント (code point)* (例えば、
    U+0041) と *抽象文字 (abstract character)* (例えば、」LATIN
    CAPITAL LETTER A」) を区別します。 Unicode のほとんどの抽象文字は
    1 つのコードポ イントだけを使って表現されますが、複数のコードポイ
    ントの列を使って も表現できる抽象文字もたくさんあります。 例えば、
    抽象文字 「LATIN CAPITAL LETTER C WITH CEDILLA」 はコード位置
    U+00C7 にある *合成済 み文字 (precomposed character)* 1 つだけでも
    表現できますし、コード 位置 U+0043 (LATIN CAPITAL LETTER C) にある
    *基底文字 (base character)* の後ろに、コード位置 U+0327 (COMBINING
    CEDILLA) にある *結合文字 (combining character)* が続く列としても
    表現できます。

    The comparison operators on unicode strings compare at the level
    of Unicode code points. This may be counter-intuitive to humans.
    For example, "u"\u00C7" == u"\u0043\u0327"" is "False", even
    though both strings represent the same abstract character 「LATIN
    CAPITAL LETTER C WITH CEDILLA」.

    抽象文字のレベルで (つまり、人間にとって直感的な方法で) 文字列を比
    較するには "unicodedata.normalize()" を使ってください。

[5] Earlier versions of Python used lexicographic comparison of
    the sorted (key, value) lists, but this was very expensive for the
    common case of comparing for equality.  An even earlier version of
    Python compared dictionaries by identity only, but this caused
    surprises because people expected to be able to test a dictionary
    for emptiness by comparing it to "{}".

[6] 自動的なガベージコレクション、フリーリスト、ディスクリプタの動
    的特 性のために、インスタンスメソッドや定数の比較を行うようなとき
    に "is" 演算子の利用は、一見すると普通ではない振る舞いだと気付くか
    も しれません。詳細はそれぞれのドキュメントを確認してください。

[7] "%" 演算子は文字列フォーマットにも使われ、同じ優先順位が当ては
    まり ます。

[8] べき乗演算子 "**" はその右側にある単項演算子かビット単位演算子
    より も優先して結合します。つまり "2**-1" は "0.5" になります。
