6. 式 (expression)
******************

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

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

   name ::= othername

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


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

以下の算術演算子の記述で、「数値引数は共通の型に変換されます」と書かれ
ているとき、組み込み型に対する演算子の実装は以下の通りに動作します:

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

* otherwise, if either argument is a floating point number, the other
  is converted to floating point;

* それ以外場合は、両方の引数は整数でなければならず、変換の必要はありま
  せん。

特定の演算子 ('%' 演算子の左引数としての文字列) には、さらに別の規則が
適用されます。拡張は、それ自身の型変換のふるまいを定義していなければな
りません。


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

atom は、式の一番基本的な要素です。もっとも単純な atom は、識別子また
はリテラルです。丸括弧、角括弧、または波括弧で囲われた形式 (form) もま
た、構文上アトムに分類されます。atom の構文は以下のようになります:

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


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

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

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

**Private name mangling:** When an identifier that textually occurs in
a class definition begins with two or more underscore characters and
does not end in two or more underscores, it is considered a *private
name* of that class. Private names are transformed to a longer form
before code is generated for them.  The transformation inserts the
class name, with leading underscores removed and a single underscore
inserted, in front of the name.  For example, the identifier "__spam"
occurring in a class named "Ham" will be transformed to "_Ham__spam".
This transformation is independent of the syntactical context in which
the identifier is used.  If the transformed name is extremely long
(longer than 255 characters), implementation defined truncation may
happen. If the class name consists only of underscores, no
transformation is done.


6.2.2. リテラル
---------------

Python では、文字列やバイト列リテラルと、様々な数値リテラルをサポート
しています:

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

Evaluation of a literal yields an object of the given type (string,
bytes, 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.

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


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

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

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

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

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

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


6.2.4. リスト、集合、辞書の表示
-------------------------------

リスト、集合、辞書を構築するために、 Python は "表示 (display)" と呼ば
れる特別な構文を提供していて、次の二種類ずつがあります:

* コンテナの内容を明示的に列挙する

* *内包表記 (comprehension)* と呼ばれる、ループ処理とフィルター処理の
  組み合わせを用いた計算結果

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

   comprehension ::= assignment_expression comp_for
   comp_for      ::= ["async"] "for" target_list "in" or_test [comp_iter]
   comp_iter     ::= comp_for | comp_if
   comp_if       ::= "if" or_test [comp_iter]

内包表記はまず単一の式、続いて少なくとも 1 個の "for" 節、さらに続いて
0 個以上の "for" 節あるいは "if" 節からなります。 この場合、各々の
"for" 節や "if" 節を、左から右へ深くなっていくネストしたブロックとみな
し、ネストの最内のブロックに到達するごとに内包表記の先頭にある式を評価
した結果が、最終的にできあがるコンテナの各要素になります。

ただし、最も左にある "for" 節のイテラブル式を除いて、内包表記は暗黙的
にネストされた個別のスコープで実行されます。 この仕組みのおかげで、対
象のリスト内で代入された名前が外側のスコープに "漏れる" ことはありませ
ん。

最も左にある "for" 節のイテラブル式は、それを直接囲んでいるスコープで
そのまま評価され、暗黙的な入れ子のスコープに引数として渡されます。 後
に続く "for" 節と、最も左にある "for" 節のフィルター条件はイテラブル式
を直接囲んでいるスコープでは評価できません。というのは、それらは最も左
のイテラブルから得られる値に依存しているかもしれないからです。 例えば
次の通りです: "[x*y for x in range(10) for y in range(x, x+10)]" 。

内包表記が常に適切な型のコンテナになるのを保証するために、 "yield" 式
や "yield from" 式は暗黙的な入れ子のスコープでは禁止されています。

Since Python 3.6, in an "async def" function, an "async for" clause
may be used to iterate over a *asynchronous iterator*. A comprehension
in an "async def" function may consist of either a "for" or "async
for" clause following the leading expression, may contain additional
"for" or "async for" clauses, and may also use "await" expressions. If
a comprehension contains either "async for" clauses or "await"
expressions or other asynchronous comprehensions it is called an
*asynchronous comprehension*.  An asynchronous comprehension may
suspend the execution of the coroutine function in which it appears.
See also **PEP 530**.

バージョン 3.6 で追加: 非同期内包表記が導入されました。

バージョン 3.8 で変更: "yield" および "yield from" は暗黙的な入れ子の
スコープでは禁止となりました。

バージョン 3.11 で変更: Asynchronous comprehensions are now allowed
inside comprehensions in asynchronous functions. Outer comprehensions
implicitly become asynchronous.


6.2.5. リスト表示
-----------------

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

   list_display ::= "[" [starred_list | comprehension] "]"

リスト表示は、新しいリストオブジェクトを与えます。リストの内容は、式の
リストまたはリスト内包表記 (list comprehension) で指定されます。 カン
マで区切られた式のリストが与えられたときは、それらの各要素は左から右へ
と順に評価され、その順にリスト内に配置されます。 内包表記が与えられた
ときは、内包表記の結果の要素でリストが構成されます。


6.2.6. 集合表示
---------------

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

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

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

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


6.2.7. 辞書表示
---------------

A dictionary display is a possibly empty series of dict items
(key/value pairs) enclosed in curly braces:

   dict_display       ::= "{" [dict_item_list | dict_comprehension] "}"
   dict_item_list     ::= dict_item ("," dict_item)* [","]
   dict_item          ::= expression ":" expression | "**" or_expr
   dict_comprehension ::= expression ":" expression comp_for

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

If a comma-separated sequence of dict items is given, they are
evaluated from left to right to define the entries of the dictionary:
each key object is used as a key into the dictionary to store the
corresponding value.  This means that you can specify the same key
multiple times in the dict item list, and the final dictionary's value
for that key will be the last one given.

A double asterisk "**" denotes *dictionary unpacking*. Its operand
must be a *mapping*.  Each mapping item is added to the new
dictionary.  Later values replace values already set by earlier dict
items and earlier dictionary unpackings.

バージョン 3.5 で追加: 辞書表示のアンパックは最初に **PEP 448** で提案
されました。

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

Restrictions on the types of the key values are listed earlier in
section 標準型の階層.  (To summarize, the key type should be
*hashable*, which excludes all mutable objects.)  Clashes between
duplicate keys are not detected; the last value (textually rightmost
in the display) stored for a given key value prevails.

バージョン 3.8 で変更: Python 3.8 より前のバージョンでは、辞書内包表記
において、キーと値の評価順序は明示されていませんでした。CPython では、
値がキーより先に評価されていました。バージョン 3.8 からは **PEP 572**
で提案されているように、キーが値より先に評価されます。


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

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

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

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

ジェネレータ式の中で使われている変数は、 (通常のジェネレータと同じよう
に) そのジェネレータオブジェクトに対して "__next__()" メソッドが呼ばれ
るときまで評価が遅延されます。 ただし、最も左にある "for" 節のイテラブ
ル式は直ちに評価されます。そのためそこで生じたエラーは、最初の値が得ら
れた時点ではなく、ジェネレータ式が定義された時点で発せられます。 後に
続く "for" 節と、最も左にある "for" 節のフィルター条件はイテラブル式を
直接囲んでいるスコープでは評価できません。というのは、それらは最も左の
イテラブルから得られる値に依存しているかもしれないからです。 例えば次
の通りです: "(x*y for x in range(10) for y in range(x, x+10))" 。

関数の唯一の引数として渡す場合には、丸括弧を省略できます。詳しくは 呼
び出し (call) 節を参照してください。

ジェネレータ式自身の期待される動作を妨げないために、 "yield" 式や
"yield from" 式は暗黙的に定義されたジェネレータでは禁止されています。

ジェネレータ式が "async for" 節あるいは "await" 式を含んでいる場合、そ
れは *非同期ジェネレータ式* と呼ばれます。 非同期ジェネレータ式は、非
同期イテレータである新しい非同期ジェネレータオブジェクトを返します (非
同期イテレータ (Asynchronous Iterator) を参照してください)。

バージョン 3.6 で追加: 非同期ジェネレータ式が導入されました。

バージョン 3.7 で変更: Python 3.7 より前では、非同期ジェネレータ式は
"async def" コルーチンでしか使えませんでした。 3.7 からは、任意の関数
で非同期ジェネレータ式が使えるようになりました。

バージョン 3.8 で変更: "yield" および "yield from" は暗黙的な入れ子の
スコープでは禁止となりました。


6.2.9. Yield 式
---------------

   yield_atom       ::= "(" yield_expression ")"
   yield_from       ::= "yield" "from" expression
   yield_expression ::= "yield" expression_list | yield_from

yield 式は *ジェネレータ* 関数や *非同期ジェネレータ* 関数を定義すると
きに使われます。従って、関数定義の本体でのみ使えます。 関数の本体で
yield 式 を使用するとその関数はジェネレータ関数になり、 "async def" 関
数の本体で使用するとそのコルーチン関数は非同期ジェネレータ関数になりま
す。 例えば次のようになります:

   def gen():  # defines a generator function
       yield 123

   async def agen(): # defines an asynchronous generator function
       yield 123

含まれているスコープの副作用のため、 "yield" 式は暗黙的に定義されたス
コープの一部として内包表記やジェネレータ式を実装するのに使うことは許可
されていません。

バージョン 3.8 で変更: yield 式は、暗黙的な入れ子のスコープで内包表記
やジェネレータ式を実装するための使用が禁止になりました。

ジェネレータ関数についてはすぐ下で説明されています。非同期ジェネレータ
関数は、 非同期ジェネレータ関数 (asynchronous generator function) 節に
分けて説明されています。

ジェネレータ関数が呼び出された時、ジェネレータとしてのイテレータを返し
ます。ジェネレータはその後ジェネレータ関数の実行を制御します。ジェネレ
ータのメソッドが呼び出されると実行が開始されます。開始されると、最初の
yield 式まで処理して一時停止し、呼び出し元へ "expression_list" の値を
、または "expression_list" が省略されていれば "None" を返します。ここ
で言う一時停止とは、ローカル変数の束縛、命令ポインタや内部の評価スタッ
ク、そして例外処理のを含むすべてのローカル状態が保持されることを意味し
ます。再度、ジェネレータのメソッドが呼び出されて実行を再開した時、ジェ
ネレータは yield 式がただの外部呼び出しであったかのように処理を継続し
ます。再開後の yield 式の値は実行を再開するメソッドに依存します。
"__next__()" を使用した場合 (一般に "for" 文や組み込み関数 "next()" な
ど) の結果は "None" となり、"send()" を使用した場合はそのメソッドに渡
された値が結果になります。

これまで説明した内容から、ジェネレータ関数はコルーチンにとてもよく似て
います。ジェネレータ関数は何度も生成し、1つ以上のエントリポイントを持
ち、その実行は一時停止されます。ジェネレータ関数は yield した後で実行
の継続を制御できないことが唯一の違いです。その制御は常にジェネレータの
呼び出し元へ移されます。

yield 式は "try" 構造内で使用できます。ジェネレータの (参照カウントが
ゼロに達するか、ガベージコレクションによる) 完了前に再開されない場合、
ジェネレータ-イテレータの "close()" メソッドが呼ばれ、"finally" 節が実
行されます。

"yield from <expr>" を使用した場合、与えられた式はイテラブルでなければ
なりません。そのイテラブルをイテレートすることで生成された値は現在のジ
ェネレータのメソッドの呼び出し元へ直接渡されます。"send()" で渡された
あらゆる値と "throw()" で渡されたあらゆる例外は根底のイテレータに適切
なメソッドがあれば渡されます。適切なメソッドがない場合、"send()" は
"AttributeError" か "TypeError" を、"throw()" は渡された例外を即座に送
出します。

根底のイテレータの完了時、引き起こされた "StopIteration" インスタンス
の "value" 属性はその yield 式の値となります。 "StopIteration" を起こ
す際に明示的にセットされるか、サブイテレータがジェネレータであれば (サ
ブイテレータからかえる値で) 自動的にセットされるかのどちらかです。

バージョン 3.3 で変更: サブイテレータに制御フローを委譲するために
"yield from <expr>" が追加されました。

yield 式が代入文の単独の右辺式であるとき、括弧は省略できます。

参考:

  **PEP 255** - 単純なジェネレータ
     Python へのジェネレータと "yield" 文の導入提案。

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

  **PEP 380** - サブジェネレータへの委譲構文
     サブジェネレータの委譲を簡単にするための、 "yield_from" 構文の導
     入提案。

  **PEP 525** - 非同期ジェネレータ
     コルーチン関数へのジェネレータの実装能力の追加による **PEP 492**
     の拡張提案。


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

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

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

generator.__next__()

   ジェネレータ関数の実行を開始するか、最後に yield 式が実行されたとこ
   ろから再開します。ジェネレータ関数が "__next__()" メソッドによって
   再開された時、その時点の "yield" 式の値は常に "None" と評価されます
   。その後次の "yield" 式まで実行し、ジェネレータは一時停止し、
   "expression_list" の値を "__next__()" メソッドの呼び出し元に返しま
   す。ジェネレータが次の値を yield せずに終了した場合、
   "StopIteration" 例外が送出されます。

   このメソッドは通常、例えば "for" ループや組み込みの "next()" 関数に
   よって暗黙に呼び出されます。

generator.send(value)

   ジェネレータ関数の内部へ値を "送り"、実行を再開します。引数の
   *value* はその時点の yield 式の結果になります。 "send()" メソッドは
   次にジェネレータが生成した値を返し、ジェネレータが次の値を生成する
   ことなく終了すると "StopIteration" を送出します。 "send()" が呼び出
   されてジェネレータが開始するときは、値を受け取る yield 式が存在しな
   いので、 "None" を引数として呼び出さなければなりません。

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

   ジェネレータが中断した位置で例外を発生させて、そのジェネレータ関数
   が生成する次の値を返します。ジェネレータが値を生成することなく終了
   すると "StopIteration" が発生します。ジェネレータ関数が渡された例外
   を捕捉しない、もしくは違う例外を発生させるなら、その例外は呼び出し
   元へ伝搬されます。

   In typical use, this is called with a single exception instance
   similar to the way the "raise" keyword is used.

   For backwards compatibility, however, the second signature is
   supported, following a convention from older versions of Python.
   The *type* argument should be an exception class, and *value*
   should be an exception instance. If the *value* is not provided,
   the *type* constructor is called to get an instance. If *traceback*
   is provided, it is set on the exception, otherwise any existing
   "__traceback__" attribute stored in *value* may be cleared.

generator.close()

   Raises a "GeneratorExit" at the point where the generator function
   was paused.  If the generator function then exits gracefully, is
   already closed, or raises "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.


6.2.9.2. 使用例
~~~~~~~~~~~~~~~

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

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

"yield from" の使用例は、"What's New in Python." の PEP 380: サブジェ
ネレータへの委譲構文 を参照してください。


6.2.9.3. 非同期ジェネレータ関数 (asynchronous generator function)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"async def" を使用して定義された関数やメソッドに yield 式があると、そ
の関数は *非同期ジェネレータ* 関数として定義されます。

非同期ジェネレータ関数が呼び出されると、非同期ジェネレータオブジェクト
と呼ばれる非同期イテレータが返されます。 そして、そのオブジェクトはジ
ェネレータ関数の実行を制御します。 通常、非同期ジェネレータオブジェク
トは、コルーチン関数内の "async for" 文で使われ、これはジェネレータオ
ブジェクトが "for" 文で使われる様子に類似します。

非同期ジェネレータのメソッドの 1 つを呼び出すと *awaitable* オブジェク
トが返され、このオブジェクトが動く番になったときに実行が開始されます。
そのときに実行は最初の yield 式まで進み、そこで再び中断され、
"expression_list" の値を待機中のコルーチンに返します。 ジェネレータと
同様に、中断とは、現在のローカル変数束縛、命令ポインタ、内部評価スタッ
ク、および例外処理の状態など、すべてのローカルな状態が保たれることを意
味します。 非同期ジェネレータのメソッドから次のオブジェクトが返された
ことで実行が再開されると、関数はあたかも yield 式が単なる外部呼び出し
であるかのように処理を進めていきます。 再開後の yield 式の値は、実行を
再開したメソッドによって異なります。 "__anext__()" を使った場合は、結
果は "None" になります。 そうではなく、 "asend()" が使用された場合は、
結果はそのメソッドに渡された値になります。

If an asynchronous generator happens to exit early by "break", the
caller task being cancelled, or other exceptions, the generator's
async cleanup code will run and possibly raise exceptions or access
context variables in an unexpected context--perhaps after the lifetime
of tasks it depends, or during the event loop shutdown when the async-
generator garbage collection hook is called. To prevent this, the
caller must explicitly close the async generator by calling "aclose()"
method to finalize the generator and ultimately detach it from the
event loop.

非同期ジェネレータ関数では、 "try" 構造内の任意の場所で yield 式が使用
できます。 ただし、非同期ジェネレータが、(参照カウントがゼロに達するか
、ガベージコレクションによる) 終了処理より前に再開されない場合、 "try"
構造内の yield 式は失敗となり、実行待ちだった "finally" 節が実行されま
す。 このケースでは、非同期ジェネレータが作動しているイベントループや
スケジューラの責務は、非同期ジェネレータの "aclose()" メソッドを呼び出
し、残りのコルーチンオブジェクトを実行し、それによって実行待ちだった
"finally" 節が実行できるようにします。

To take care of finalization upon event loop termination, an event
loop should define a *finalizer* function which takes an asynchronous
generator-iterator and presumably calls "aclose()" and executes the
coroutine. This  *finalizer* may be registered by calling
"sys.set_asyncgen_hooks()". When first iterated over, an asynchronous
generator-iterator will store the registered *finalizer* to be called
upon finalization. For a reference example of a *finalizer* method see
the implementation of "asyncio.Loop.shutdown_asyncgens" in
Lib/asyncio/base_events.py.

"yield from <expr>" 式は、非同期ジェネレータ関数で使われると文法エラー
になります。


6.2.9.4. 非同期ジェネレータイテレータメソッド
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

この小節では、ジェネレータ関数の実行制御に使われる非同期ジェネレータイ
テレータのメソッドについて説明します。

coroutine agen.__anext__()

   Returns an awaitable which when run starts to execute the
   asynchronous generator or resumes it at the last executed yield
   expression.  When an asynchronous generator function is resumed
   with an "__anext__()" method, the current yield expression always
   evaluates to "None" in the returned awaitable, which when run will
   continue to the next yield expression. The value of the
   "expression_list" of the yield expression is the value of the
   "StopIteration" exception raised by the completing coroutine.  If
   the asynchronous generator exits without yielding another value,
   the awaitable instead raises a "StopAsyncIteration" exception,
   signalling that the asynchronous iteration has completed.

   このメソッドは通常、 "for" ループによって暗黙に呼び出されます。

coroutine agen.asend(value)

   Returns an awaitable which when run resumes the execution of the
   asynchronous generator. As with the "send()" method for a
   generator, this "sends" a value into the asynchronous generator
   function, and the *value* argument becomes the result of the
   current yield expression. The awaitable returned by the "asend()"
   method will return the next value yielded by the generator as the
   value of the raised "StopIteration", or raises "StopAsyncIteration"
   if the asynchronous generator exits without yielding another value.
   When "asend()" is called to start the asynchronous generator, it
   must be called with "None" as the argument, because there is no
   yield expression that could receive the value.

coroutine agen.athrow(value)
coroutine agen.athrow(type[, value[, traceback]])

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

coroutine agen.aclose()

   Returns an awaitable that when run will throw a "GeneratorExit"
   into the asynchronous generator function at the point where it was
   paused. If the asynchronous generator function then exits
   gracefully, is already closed, or raises "GeneratorExit" (by not
   catching the exception), then the returned awaitable will raise a
   "StopIteration" exception. Any further awaitables returned by
   subsequent calls to the asynchronous generator will raise a
   "StopAsyncIteration" exception.  If the asynchronous generator
   yields a value, a "RuntimeError" is raised by the awaitable.  If
   the asynchronous generator raises any other exception, it is
   propagated to the caller of the awaitable.  If the asynchronous
   generator has already exited due to an exception or normal exit,
   then further calls to "aclose()" will return an awaitable that does
   nothing.


6.3. プライマリ
===============

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

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


6.3.1. 属性参照
---------------

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

   attributeref ::= primary "." identifier

The primary must evaluate to an object of a type that supports
attribute references, which most objects do.  This object is then
asked to produce the attribute whose name is the identifier. The type
and value produced is determined by the object.  Multiple evaluations
of the same attribute reference may yield different objects.

This production can be customized by overriding the
"__getattribute__()" method or the "__getattr__()" method.  The
"__getattribute__()" method is called first and either returns a value
or raises "AttributeError" if the attribute is not available.

If an "AttributeError" is raised and the object has a "__getattr__()"
method, that method is called as a fallback.


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

The subscription of an instance of a container class will generally
select an element from the container. The subscription of a *generic
class* will generally return a GenericAlias object.

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

When an object is subscripted, the interpreter will evaluate the
primary and the expression list.

The primary must evaluate to an object that supports subscription. An
object may support subscription through defining one or both of
"__getitem__()" and "__class_getitem__()". When the primary is
subscripted, the evaluated result of the expression list will be
passed to one of these methods. For more details on when
"__class_getitem__" is called instead of "__getitem__", see
__class_getitem__ versus __getitem__.

If the expression list contains at least one comma, it will evaluate
to a "tuple" containing the items of the expression list. Otherwise,
the expression list will evaluate to the value of the list's sole
member.

組み込みオブジェクトでは、"__getitem__()"　によって添字表記をサポート
するオブジェクトには 2 種類あります:

1. マッピング。プライマリが *マッピング* であれば、式リストの値評価結
   果はマップ内のいずれかのキー値に相当するオブジェクトにならなければ
   なりません。添字表記は、そのキーに対応するマッピング内の値 (value)
   を選択します。組み込みのマッピングクラスの例は "dict" クラスです。

2. シーケンス。プライマリが *シーケンス* であれば、式リストの評価結果
   は "int" または "slice" (以下の節で論じます) でなければなりません。
   組み込みのシーケンスクラスの例には "str"、"list"、"tuple" クラスが
   含まれます。

The formal syntax makes no special provision for negative indices in
*sequences*. However, built-in sequences all provide a "__getitem__()"
method that interprets negative indices by adding the length of the
sequence to the index so that, for example, "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). Since the
support for negative indices and slicing occurs in the object's
"__getitem__()" method, subclasses overriding this method will need to
explicitly add that support.

"文字列" は文字 (*character*) を要素とする特別な種類のシーケンスです。
文字は個別の型ではなく、 1 文字だけからなる文字列です。


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

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

   slicing      ::= primary "[" slice_list "]"
   slice_list   ::= slice_item ("," slice_item)* [","]
   slice_item   ::= expression | proper_slice
   proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
   lower_bound  ::= expression
   upper_bound  ::= expression
   stride       ::= expression

上記の形式的な構文法にはあいまいなところがあります: 式リストに見えるも
のは、スライスリストにも見えるため、添字表記はスライス表記としても解釈
されうるということです。(スライスリストが適切なスライスを含まない場合)
、これ以上の構文の複雑化はせず、スライス表記としての解釈よりも添字表記
としての解釈が優先されるように定義することで、あいまいさを取り除いてい
ます。

The semantics for a slicing are as follows.  The primary is indexed
(using the same "__getitem__()" method as normal subscription) 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 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.


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

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

   call                 ::= primary "(" [argument_list [","] | comprehension] ")"
   argument_list        ::= positional_arguments ["," starred_and_keywords]
                       ["," keywords_arguments]
                     | starred_and_keywords ["," keywords_arguments]
                     | keywords_arguments
   positional_arguments ::= positional_item ("," positional_item)*
   positional_item      ::= assignment_expression | "*" expression
   starred_and_keywords ::= ("*" expression | keyword_item)
                            ("," "*" expression | "," keyword_item)*
   keywords_arguments   ::= (keyword_item | "**" expression)
                          ("," keyword_item | "," "**" expression)*
   keyword_item         ::= identifier "=" expression

最後の位置引数やキーワード引数の後にカンマをつけてもかまいません。構文
の意味付けに影響を及ぼすことはありません。

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 all objects having a
"__call__()" method are callable).  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 実装の詳細:** 実装では、名前を持たない位置引数を受け取る組み
込み関数を提供されるかもしれません。そういった引数がドキュメント化のた
めに '名付けられて' いたとしても、実際には名付けられていないのでキーワ
ードでは提供されません。 CPython では、C 言語で実装された関数の、名前
を持たない位置引数をパースするために "PyArg_ParseTuple()" を使用します
。

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

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

関数呼び出しに "*expression" という構文が現れる場合は、 "expression"
の評価結果は *イテラブル* でなければなりません。 そのイテラブルの要素
は、追加の位置引数であるかのように扱われます。 "f(x1, x2, *y, x3, x4)"
という呼び出しにおいて、 *y* の評価結果がシーケンス *y1*, ..., *yM* だ
った場合は、この呼び出しは M+4 個の位置引数 *x1*, *x2*, *y1*, ...,
*yM*, *x3*, *x4* での呼び出しと同じになります。

この結論としては、 "*expression" 構文がキーワード引数の *後ろ* に来る
こともありますが、キーワード引数 (と任意の "**expression" 引数 -- 下を
参照) よりも *前* にあるものとして処理されます。 従って、このような動
作になります:

   >>> 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" 構文を同じ呼び出しで一緒に使うことはあ
まりないので、実際に上記のような混乱が頻繁に生じることはありません。

関数呼び出しで "**expression" 構文が使われた場合、 "expression" の評価
結果は *マッピング* でなければなりません。その内容は追加のキーワード引
数として扱われます。 キーにマッチする引数が (明示的なキーワード引数に
よって、あるいは他のアンパックの中で) 既に値を与えられていたなら、
"TypeError" 例外が送出されます。

When "**expression" is used, each key in this mapping must be a
string. Each value from the mapping is assigned to the first formal
parameter eligible for keyword assignment whose name is equal to the
key. A key need not be a Python identifier (e.g. ""max-temp °F"" is
acceptable, although it will not match any formal parameter that could
be declared). If there is no match to a formal parameter the key-value
pair is collected by the "**" parameter, if there is one, or if there
is not, a "TypeError" exception is raised.

"*identifier" や "**identifier" 構文を使った仮引数は、位置引数スロット
やキーワード引数名にすることができません。

バージョン 3.5 で変更: 関数呼び出しは任意の数の "*" アンパックと "**"
アンパックを受け取り、位置引数はイテラブルアンパック ("*") の後ろに置
け、キーワード引数は辞書アンパック ("**") の後ろに置けるようになりまし
た。 最初に **PEP 448** で提案されました。

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

各形態では---

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

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

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

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

クラスインスタンス:
   The class must define a "__call__()" method; the effect is then the
   same as if that method was called.


6.4. Await 式
=============

*awaitable* オブジェクトでの *coroutine* 実行を一時停止します。
*coroutine function* 内でのみ使用できます。

   await_expr ::= "await" primary

バージョン 3.5 で追加.


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

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

   power ::= (await_expr | primary) ["**" u_expr]

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

べき乗演算子の意味は、二つの引数で呼び出される組み込み関数 "pow()" と
同じで、左引数を右引数乗して与えます。数値引数はまず共通の型に変換され
、結果はその型です。

整数の被演算子では、第二引数が負でない限り、結果は被演算子と同じ型にな
ります; 第二引数が負の場合、全ての引数は浮動小数点型に変換され、浮動小
数点型が返されます。例えば "10**2" は "100" を返しますが、"10**-2" は
"0.01" を返します。

"0.0" を負の数でべき乗すると "ZeroDivisionError" を送出します。負の数
を小数でべき乗した結果は複素数 ("complex" number) になります。 (以前の
バージョンでは "ValueError" を送出していました)

This operation can be customized using the special "__pow__()" method.


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

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

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

The unary "-" (minus) operator yields the negation of its numeric
argument; the operation can be overridden with the "__neg__()" special
method.

The unary "+" (plus) operator yields its numeric argument unchanged;
the operation can be overridden with the "__pos__()" special method.

The unary "~" (invert) operator yields the bitwise inversion of its
integer argument.  The bitwise inversion of "x" is defined as
"-(x+1)".  It only applies to integral numbers or to custom objects
that override the "__invert__()" special method.

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


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

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

   m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_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

"*" (乗算: multiplication) 演算子は、引数同士の積を与えます。引数は、
両方とも数値であるか、片方が整数で他方がシーケンスかのどちらかでなけれ
ばなりません。前者の場合、数値は共通の型に変換された後乗算されます。後
者の場合、シーケンスの繰り返し操作が行われます。繰り返し数を負にすると
、空のシーケンスを与えます。

This operation can be customized using the special "__mul__()" and
"__rmul__()" methods.

"@" (at) 演算子は行列の乗算に対し使用されます。 Python の組み込み型は
この演算子を実装していません。

バージョン 3.5 で追加.

"/" (除算: division) および "//" (切り捨て除算: floor division) は、引
数同士の商を与えます。数値引数はまず共通の型に変換されます。整数の除算
結果は浮動小数点になりますが、整数の切り捨て除算結果は整数になります;
この場合、結果は数学的な除算に 'floor' 関数 を適用したものになります。
ゼロによる除算を行うと "ZeroDivisionError" 例外を送出します。

This operation can be customized using the special "__truediv__()" and
"__floordiv__()" methods.

The "%" (modulo) operator yields the remainder from the division of
the first argument by the second.  The numeric arguments are first
converted to a common type.  A zero right argument raises the
"ZeroDivisionError" exception.  The arguments may be floating point
numbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals "4*0.7 +
0.34".)  The modulo operator always yields a result with the same sign
as its second operand (or zero); the absolute value of the result is
strictly smaller than the absolute value of the second operand [1].

切り捨て除算演算と剰余演算は、恒等式: "x == (x//y)*y + (x%y)" の関係に
あります。切り捨て除算や剰余はまた、組み込み関数 "divmod()":
"divmod(x, y) == (x//y, x%y)" とも関係しています。 [2] 。

"%" 演算子は、数値に対する剰余演算を行うのに加えて、文字列 (string) オ
ブジェクトにオーバーロードされ、旧式の文字列の書式化 (いわゆる補間) を
行います。文字列の書式化の構文は Python ライブラリリファレンス printf
形式の文字列書式化 節を参照してください。

The *modulo* operation can be customized using the special "__mod__()"
method.

The floor division operator, the modulo operator, and the "divmod()"
function are not defined for complex numbers.  Instead, convert to a
floating point number using the "abs()" function if appropriate.

"+" (加算) 演算は、引数同士の和を与えます。引数は双方とも数値型か、双
方とも同じ型のシーケンスでなければなりません。前者の場合、数値は共通の
型に変換され、加算されます。後者の場合、シーケンスは結合 (concatenate)
されます。

This operation can be customized using the special "__add__()" and
"__radd__()" methods.

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

This operation can be customized using the special "__sub__()" method.


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

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

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

これらは整数を引数にとります。引数は共通の型に変換されます。シフト演算
は第一引数を、第二引数で与えられたビット数だけ、左または右にビットシフ
トします。

This operation can be customized using the special "__lshift__()" and
"__rshift__()" methods.

*n* ビットの右シフトは "pow(2,n)" による除算として定義されます。*n* ビ
ットの左シフトは "pow(2,n)" による乗算として定義されます。


6.9. ビット単位演算の二項演算 (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 integers or one of them must be a custom object overriding
"__and__()" or "__rand__()" special methods.

The "^" operator yields the bitwise XOR (exclusive OR) of its
arguments, which must be integers or one of them must be a custom
object overriding "__xor__()" or "__rxor__()" special methods.

The "|" operator yields the bitwise (inclusive) OR of its arguments,
which must be integers or one of them must be a custom object
overriding "__or__()" or "__ror__()" special methods.


6.10. 比較
==========

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

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

Comparisons yield boolean values: "True" or "False". Custom *rich
comparison methods* may return non-boolean values. In this case Python
will call "bool()" on such value in boolean contexts.

比較はいくらでも連鎖することができます。例えば "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" は (
きれいな書き方ではありませんが) 完全に正しい文法です。


6.10.1. 値の比較
----------------

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

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

Because all types are (direct or indirect) subtypes of "object", they
inherit the default comparison behavior from "object".  Types can
customize their comparison behavior by implementing *rich comparison
methods* like "__lt__()", described in 基本的なカスタマイズ.

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

デフォルトの順序比較 ("<", ">", "<=", ">=") は提供されません; 比較しよ
うとすると "TypeError" が送出されます。 この振る舞いをデフォルトの振る
舞いにした動機は、等価性と同じような不変性が欠けているからです。

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

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

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

  非数値である "float('NaN')" と "decimal.Decimal('NaN')" は特別です。
  数と非数値との任意の順序比較は偽です。 直観に反する帰結として、非数
  値は自分自身と等価ではないことになります。 例えば "x = float('NaN')"
  ならば、 "3 < x", "x < 3", "x == x" は全て偽で、"x != x" は真です。
  この振る舞いは IEEE 754 に従ったものです。

* "None" and "NotImplemented" are singletons.  **PEP 8** advises that
  comparisons for singletons should always be done with "is" or "is
  not", never the equality operators.

* バイナリシーケンス ("bytes" または "bytearray" のインスタンス) は、
  これらの型の範囲で異なる型とも比較できます。 比較は要素の数としての
  値を使った辞書式順序で行われます。

* 文字列 ("str" のインスタンス) の比較は、文字の Unicode のコードポイ
  ントの数としての値 (組み込み関数 "ord()" の返り値) を使った辞書式順
  序で行われます。 [3]

  文字列とバイナリシーケンスは直接には比較できません。

* シーケンス ("tuple", "list", or "range" のインスタンス) の比較は、同
  じ型どうしでしか行えず、 range は順序比較をサポートしていません。 異
  なる型どうしの等価比較の結果は等価でないとなり、異なる型どうしの順序
  比較は "TypeError" を送出します。

  Sequences compare lexicographically using comparison of
  corresponding elements.  The built-in containers typically assume
  identical objects are equal to themselves.  That lets them bypass
  equality tests for identical objects to improve performance and to
  maintain their internal invariants.

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

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

  * 順序比較をサポートしているコレクションの順序は、最初の等価でない要
    素の順序と同じになります (例えば、 "[1,2,x] <= [1,2,y]" は "x <=
    y" と同じ値になります)。 対応する要素が存在しない場合、短い方のコ
    レクションの方が先の順序となります (例えば、 "[1,2] < [1,2,3]" は
    真です)。

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

  順序比較 ("<", ">", "<=", ">=") は "TypeError" を送出します。

* 集合 ("set" または "frozenset" のインスタンス) の比較は、これらの型
  の範囲で異なる型とも行えます。

  集合には、部分集合あるいは上位集合かどうかを基準とする順序比較が定義
  されています。 この関係は全順序を定義しません (例えば、 "{1,2}" と
  "{2,3}" という2つの集合は片方がもう一方の部分集合でもなく上位集合で
  もありません)。 従って、集合は全順序性に依存する関数の引数として適切
  ではありません (例えば、 "min()", "max()", "sorted()" は集合のリスト
  を入力として与えると未定義な結果となります)。

  集合の比較では、その要素の反射性が強制されます。

* 他の組み込み型のほとんどは比較メソッドが実装されておらず、デフォルト
  の比較の振る舞いを継承します。

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

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

     "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 はこの一貫性規則を強制しません。 事実、非数値がこの規則に従わな
い例となります。


6.10.2. 所属検査演算
--------------------

演算子 "in" および "not in" は所属関係を調べます。 "x in s" の評価は、
*x* が *s* の要素であれば "True" となり、そうでなければ "False" となり
ます。 "x not in s" は "x in s" の否定を返します。 すべての組み込みの
シーケンス型と集合型に加えて、辞書も "in" を辞書が与えられたキーを持っ
ているかを調べる演算子としてサポートしています。 リスト、タプル、集合
、凍結集合、辞書、 collections.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" を返すことになります。

For user-defined classes which define the "__contains__()" method, "x
in y" returns "True" if "y.__contains__(x)" returns a true value, and
"False" otherwise.

For user-defined classes which do not define "__contains__()" but do
define "__iter__()", "x in y" is "True" if some value "z", for which
the expression "x is z or x == z" is true, is produced while iterating
over "y". If an exception is raised during the iteration, it is as if
"in" raised that exception.

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 is y[i] or x == y[i]", and no
lower integer index raises the "IndexError" exception.  (If any other
exception is raised, it is as if "in" raised that exception).

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


6.10.3. 同一性の比較
--------------------

演算子 "is" および "is not" は、オブジェクトの同一性に対するテストを行
います: "x is y" は、 *x* と *y* が同じオブジェクトを指すとき、かつそ
のときに限り真になります。 オブジェクトの同一性は "id()" 関数を使って
判定されます。 "x is not y" は "is" の真値を反転したものになります。
[4]


6.11. ブール演算 (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.  User-defined objects can customize their truth value by
providing a "__bool__()" method.

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

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

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

なお、 "and" も "or" も、返す値を "True" や "False" に制限せず、最後に
評価した引数を返します。 この仕様が便利なときもあります。例えば "s" が
文字列で、空文字列ならデフォルトの値に置き換えたいとき、式 "s or
'foo'" は望んだ値を与えます。 "not" は必ず新しい値を作成するので、引数
の型に関係なくブール値を返します (例えば、 "not 'foo'" は "''" ではな
く "False" になります)。


6.12. 代入式
============

   assignment_expression ::= [identifier ":="] expression

An assignment expression (sometimes also called a "named expression"
or "walrus") assigns an "expression" to an "identifier", while also
returning the value of the "expression".

One common use case is when handling matched regular expressions:

   if matching := pattern.search(data):
       do_something(matching)

Or, when processing a file stream in chunks:

   while chunk := file.read(9000):
       process(chunk)

Assignment expressions must be surrounded by parentheses when used as
expression statements and when used as sub-expressions in slicing,
conditional, lambda, keyword-argument, and comprehension-if
expressions and in "assert", "with", and "assignment" statements. In
all other places where they can be used, parentheses are not required,
including in "if" and "while" statements.

バージョン 3.8 で追加: 代入式に関してより詳しくは **PEP 572** を参照し
てください。


6.13. 条件式 (Conditional Expressions)
======================================

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

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

"x if C else y" という式は最初に *x* ではなく条件 *C* を評価します。
*C* が true の場合 *x* が評価され値が返されます。 それ以外の場合には
*y* が評価され返されます。

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


6.14. ラムダ (lambda)
=====================

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

ラムダ式 (ラムダ形式とも呼ばれます) は無名関数を作成するのに使います。
式 "lambda parameters: expression" は関数オブジェクトになります。 この
無名オブジェクトは以下に定義されている関数オブジェクト同様に動作します
:

   def <lambda>(parameters):
       return expression

引数の一覧の構文は 関数定義 を参照してください。ラムダ式で作成された関
数は文やアノテーションを含むことができない点に注意してください。


6.15. 式のリスト
================

   expression_list    ::= expression ("," expression)* [","]
   starred_list       ::= starred_item ("," starred_item)* [","]
   starred_expression ::= expression | (starred_item ",")* [starred_item]
   starred_item       ::= assignment_expression | "*" or_expr

リスト表示や辞書表示の一部になっているものを除き、少なくとも一つのカン
マを含む式のリストはタプルになります。 タプルの長さは、リストにある式
の数に等しくなります。 式は左から右へ評価されます。

アスタリスク "*" は *イテラブルのアンパック* を意味します。 この被演算
子は *イテラブル* でなければなりません。 このイテラブルはアンパックさ
れた位置で要素のシーケンスに展開され、新しいタプル、リスト、集合に入れ
込まれます。

バージョン 3.5 で追加: 式リストでのイテラブルのアンパックは最初に
**PEP 448** で提案されました。

A trailing comma is required only to create a one-item tuple, such as
"1,"; it is optional in all other cases. A single expression without a
trailing comma doesn't create a tuple, but rather yields the value of
that expression. (To create an empty tuple, use an empty pair of
parentheses: "()".)


6.16. 評価順序
==============

Python は、式を左から右へと順に評価します。 ただし、代入式を評価すると
きは、右辺が左辺よりも先に評価されます。

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

   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


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

以下の表は Python における演算子の優先順位を要約したものです。優先順位
の最も高い (結合が最も強い) ものから最も低い (結合が最も弱い) ものに並
べてあります。同じボックス内の演算子の優先順位は同じです。構文が明示的
に示されていないものは二項演算子です。同じボックス内の演算子は、左から
右へとグループ化されます (例外として、べき乗および条件式は右から左にグ
ループ化されます)。

比較 節で述べられているように、比較、所属、同一性のテストは全てが同じ
優先順位を持っていて、左から右に連鎖するという特徴を持っていることに注
意してください。

+-------------------------------------------------+---------------------------------------+
| 演算子                                          | 説明                                  |
|=================================================|=======================================|
| "(expressions...)",  "[expressions...]", "{key: | 結合式または括弧式、リスト表示、辞書  |
| value...}", "{expressions...}"                  | 表示、集合表示                        |
+-------------------------------------------------+---------------------------------------+
| "x[index]", "x[index:index]",                   | 添字指定、スライス操作、呼び出し、属  |
| "x(arguments...)", "x.attribute"                | 性参照                                |
+-------------------------------------------------+---------------------------------------+
| "await x"                                       | Await 式                              |
+-------------------------------------------------+---------------------------------------+
| "**"                                            | べき乗 [5]                            |
+-------------------------------------------------+---------------------------------------+
| "+x", "-x", "~x"                                | 正数、負数、ビット単位 NOT            |
+-------------------------------------------------+---------------------------------------+
| "*", "@", "/", "//", "%"                        | 乗算、行列乗算、除算、切り捨て除算、  |
|                                                 | 剰余 [6]                              |
+-------------------------------------------------+---------------------------------------+
| "+", "-"                                        | 加算および減算                        |
+-------------------------------------------------+---------------------------------------+
| "<<", ">>"                                      | シフト演算                            |
+-------------------------------------------------+---------------------------------------+
| "&"                                             | ビット単位 AND                        |
+-------------------------------------------------+---------------------------------------+
| "^"                                             | ビット単位 XOR                        |
+-------------------------------------------------+---------------------------------------+
| "|"                                             | ビット単位 OR                         |
+-------------------------------------------------+---------------------------------------+
| "in", "not in", "is", "is not", "<", "<=", ">", | 所属や同一性のテストを含む比較        |
| ">=", "!=", "=="                                |                                       |
+-------------------------------------------------+---------------------------------------+
| "not x"                                         | ブール演算 NOT                        |
+-------------------------------------------------+---------------------------------------+
| "and"                                           | ブール演算 AND                        |
+-------------------------------------------------+---------------------------------------+
| "or"                                            | ブール演算 OR                         |
+-------------------------------------------------+---------------------------------------+
| "if" -- "else"                                  | 条件式                                |
+-------------------------------------------------+---------------------------------------+
| "lambda"                                        | ラムダ式                              |
+-------------------------------------------------+---------------------------------------+
| ":="                                            | 代入式                                |
+-------------------------------------------------+---------------------------------------+

-[ 脚注 ]-

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

[2] x が y の正確な整数倍に非常に近いと、丸めのために "x//y" が
    "(x-x%y)//y" よりも 1 だけ大きくなる可能性があります。そのような場
    合、Python は "divmod(x,y)[0] * y + x % y" が "x" に非常に近くなる
    という関係を保つために、後者の値を返します。

[3] 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)* が続く列としても表現できます。

    文字列の比較操作は Unicode のコードポイントのレベルで行われます。
    これは人間にとっては直感的ではないかもしれません。 例えば、
    ""\u00C7" == "\u0043\u0327"" は、どちらの文字も同じ抽象文字 "LATIN
    CAPITAL LETTER C WITH CEDILLA" を表現しているにもかかわらず、その
    結果は "False" となります。

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

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

[5] べき乗演算子 "**" は、右側にある単項算術演算子あるいは単項ビット演
    算子より弱い結合優先順位となります。 つまり "2**-1" は "0.5" にな
    ります。

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