3. データモデル
***************


3.1. オブジェクト、値、および型
===============================

*Objects* are Python's abstraction for data.  All data in a Python
program is represented by objects or by relations between objects.
Even code is represented by objects.

すべてのオブジェクトは、同一性 (identity)、型、値をもっています。 *同
一性* は生成されたあとは変更されません。これはオブジェクトのアドレスの
ようなものだと考えられるかもしれません。 "is" 演算子は2つのオブジェク
トの同一性を比較します。 "id()" 関数は同一性を表す整数を返します。

CPython では、"id(x)" は "x" が格納されているメモリ上のアドレスを返し
ます。

オブジェクトの型はオブジェクトがサポートする操作 (例: "len()" をサポー
トするか) と、オブジェクトが取りうる値を決定します。 "type()" 関数はオ
ブジェクトの型 (型自体もオブジェクトです) を返します。同一性と同じく、
オブジェクトの型(*type*) も変更不可能です。 [1]

オブジェクトによっては *値* を変更することが可能です。値を変更できるオ
ブジェクトのことを *mutable* と呼びます。生成後に値を変更できないオブ
ジェクトのことを *immutable* と呼びます。(mutable なオブジェクトへの参
照を格納している immutableなコンテナオブジェクトの値は、その格納してい
るオブジェクトの値が変化した時に変化しますが、コンテナがどのオブジェク
トを格納しているのかが変化しないのであれば immutable だと考えることが
できます。したがって、immutable かどうかは値が変更可能かどうかと完全に
一致するわけではありません) オブジェクトが mutable かどうかはその型に
よって決まります。例えば、数値型、文字列型とタプル型のインスタンスは
immutable で、dict や list は mutable です。

オブジェクトを明示的に破壊することはできません; しかし、オブジェクトに
到達不能 (unreachable) になると、ガベージコレクション (garbage-
collection) によって処理されるかもしれません。ガベージコレクションを遅
らせたり、全く行わない実装も許されています --- 到達可能なオブジェクト
を処理してしまわないかぎり、ガベージコレクションをどう実装するかは実装
品質の問題です。

現在の CPython 実装では参照カウント (reference-counting) 方式を使って
おり、(オプションとして) 循環参照を行っているガベージオブジェクトを遅
延検出します。この実装ではほとんどのオブジェクトを到達不能になると同時
に処理することができますが、循環参照を含むガベージオブジェクトの収集が
確実に行われるよう保証しているわけではありません。循環参照を持つガベー
ジオブジェクト収集の制御については、 "gc" モジュールを参照してください
。 CPython以外の実装は別の方式を使っており、CPythonも将来は別の方式を
使うかもしれません。オブジェクトが到達不能になったときに即座に終了処理
されることに頼らないでください (ですからファイルは必ず明示的に閉じてく
ださい)。

Note that the use of the implementation's tracing or debugging
facilities may keep objects alive that would normally be collectable.
Also note that catching an exception with a "try"..."except" statement
may keep objects alive.

Some objects contain references to "external" resources such as open
files or windows.  It is understood that these resources are freed
when the object is garbage-collected, but since garbage collection is
not guaranteed to happen, such objects also provide an explicit way to
release the external resource, usually a "close()" method. Programs
are strongly recommended to explicitly close such objects.  The
"try"..."finally" statement and the "with" statement provide
convenient ways to do this.

他のオブジェクトに対する参照をもつオブジェクトもあります; これらは *コ
ンテナ (container)* と呼ばれます。コンテナオブジェクトの例として、タプ
ル、リスト、および辞書が挙げられます。オブジェクトへの参照自体がコンテ
ナの値の一部です。ほとんどの場合、コンテナの値というと、コンテナに入っ
ているオブジェクトの値のことを指し、それらオブジェクトのアイデンティテ
ィではありません; しかしながら、コンテナの変更可能性について述べる場合
、今まさにコンテナに入っているオブジェクトのアイデンティティのことを指
します。したがって、 (タプルのように) 変更不能なオブジェクトが変更可能
なオブジェクトへの参照を含む場合、その値が変化するのは変更可能なオブジ
ェクトが変更された時、ということになります。

Types affect almost all aspects of object behavior.  Even the
importance of object identity is affected in some sense: for immutable
types, operations that compute new values may actually return a
reference to any existing object with the same type and value, while
for mutable objects this is not allowed. For example, after "a = 1; b
= 1", *a* and *b* may or may not refer to the same object with the
value one, depending on the implementation. This is because "int" is
an immutable type, so the reference to "1" can be reused. This
behaviour depends on the implementation used, so should not be relied
upon, but is something to be aware of when making use of object
identity tests. However, after "c = []; d = []", *c* and *d* are
guaranteed to refer to two different, unique, newly created empty
lists. (Note that "e = f = []" assigns the *same* object to both *e*
and *f*.)


3.2. 標準型の階層
=================

以下は Python に組み込まれている型のリストです。(実装によって、C、Java
、またはその他の言語で書かれた) 拡張モジュールで、その他の型が定義され
ていることがあります。新たな型 (有理数や、整数を効率的に記憶する配列、
など) の追加は、たいてい標準ライブラリを通して提供されますが、将来のバ
ージョンの Python では、型の階層構造にこのような追加がなされるかもしれ
ません。

以下に説明する型のいくつかには、 '特殊属性 (special attribute)' を列挙
した段落があります。これらの属性は実装へのアクセス手段を提供するもので
、一般的な用途に利用するためのものではありません。特殊属性の定義は将来
変更される可能性があります。


3.2.1. None
-----------

この型には単一の値しかありません。この値を持つオブジェクトはただ一つし
か存在しません。このオブジェクトは組み込み名 "None" でアクセスされます
。このオブジェクトは、様々な状況で値が存在しないことをしめします。例え
ば、明示的に値を返さない関数は "None" を返します。 "None" の真値
(truth value) は偽 (false) です。


3.2.2. NotImplemented
---------------------

This type has a single value.  There is a single object with this
value. This object is accessed through the built-in name
"NotImplemented". Numeric methods and rich comparison methods should
return this value if they do not implement the operation for the
operands provided.  (The interpreter will then try the reflected
operation, or some other fallback, depending on the operator.)  It
should not be evaluated in a boolean context.

詳細は 算術演算の実装 を参照してください。

バージョン 3.9 で変更: Evaluating "NotImplemented" in a boolean
context was deprecated.

バージョン 3.14 で変更: Evaluating "NotImplemented" in a boolean
context now raises a "TypeError". It previously evaluated to "True"
and emitted a "DeprecationWarning" since Python 3.9.


3.2.3. Ellipsis
---------------

この型には単一の値しかありません。この値を持つオブジェクトはただ一つし
か存在しません。このオブジェクトはリテラル "..." またはPythonで決めら
れている名前 "Ellipsis" でアクセスされます。真理値は真 (true)です。


3.2.4. "numbers.Number"
-----------------------

数値リテラルによって作成されたり、算術演算や組み込みの算術関数によって
返されるオブジェクトです。数値オブジェクトは変更不能です; 一度値が生成
されると、二度と変更されることはありません。Python の数値オブジェクト
はいうまでもなく数学で言うところの数値と強く関係していますが、コンピュ
ータ内で数値を表現する際に伴う制限を受けています。

"__repr__()"  と "__str__()" から計算された数値クラスの文字列表現には
次のような特性があります:

* その文字列は、クラスコンストラクタに渡したときに、元の数値の値を持つ
  オブジェクトを生成する有効な数値リテラルです。

* できるなら、10を底として表現されます。

* 小数点の前にある 1 つのゼロを除いて、上に連なるゼロは表示されません
  。

* 小数点の後にある 1 つのゼロを除いて、下に連なるゼロは表示されません
  。

* 符号は数値が負数のときのみ表示されます。

Python distinguishes between integers, floating-point numbers, and
complex numbers:


3.2.4.1. "numbers.Integral" (整数)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

整数型は、整数(正の数および負の数)を表す数学的集合内における要素を表現
する型です。

注釈:

  整数表現に関する規則は、負の整数を含むシフト演算やマスク演算において
  、最も有意義な解釈ができるように意図されています。

整数には 2 種類あります:

整数 ("int")
   無制限の範囲の数を表現しますが、利用可能な (仮想) メモリサイズの制
   限のみを受けます。シフト演算やマスク演算のために2進数表現を持つと想
   定されます。負の数は符号ビットが左に無限に延びているような錯覚を与
   える 2 の補数表現の変型で表されます。

ブール値 ("bool")
   真偽値の False と True を表します。"False" と "True" を表す 2 つの
   オブジェクトのみがブール値オブジェクトです。ブール型は整数型の派生
   型であり、ほとんどの状況でそれぞれ 0 と 1 のように振る舞いますが、
   例外として文字列に変換されたときはそれぞれ ""False"" および
   ""True"" という文字列が返されます。


3.2.4.2. "numbers.Real" ("float") (実数)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These represent machine-level double precision floating-point numbers.
You are at the mercy of the underlying machine architecture (and C or
Java implementation) for the accepted range and handling of overflow.
Python does not support single-precision floating-point numbers; the
savings in processor and memory usage that are usually the reason for
using these are dwarfed by the overhead of using objects in Python, so
there is no reason to complicate the language with two kinds of
floating-point numbers.


3.2.4.3. "numbers.Complex" ("complex")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These represent complex numbers as a pair of machine-level double
precision floating-point numbers.  The same caveats apply as for
floating-point numbers. The real and imaginary parts of a complex
number "z" can be retrieved through the read-only attributes "z.real"
and "z.imag".


3.2.5. シーケンス型 (sequence)
------------------------------

These represent finite ordered sets indexed by non-negative numbers.
The built-in function "len()" returns the number of items of a
sequence. When the length of a sequence is *n*, the index set contains
the numbers 0, 1, ..., *n*-1.  Item *i* of sequence *a* is selected by
"a[i]". Some sequences, including built-in sequences, interpret
negative subscripts by adding the sequence length. For example,
"a[-2]" equals "a[n-2]", the second to last item of sequence a with
length "n".

Sequences also support slicing: "a[i:j]" selects all items with index
*k* such that *i* "<=" *k* "<" *j*.  When used as an expression, a
slice is a sequence of the same type. The comment above about negative
indexes also applies to negative slice positions.

シーケンスによっては、第三の "ステップ (step)" パラメタを持つ "拡張ス
ライス (extended slice)" もサポートしています: "a[i:j:k]" は、 "x = i
+ n*k", *n* ">=" "0" かつ *i* "<=" *x* "<" *j* であるようなインデクス
*x* を持つような *a* 全ての要素を選択します。

シーケンスは、変更可能なものか、そうでないかで区別されています:


3.2.5.1. 変更不能なシーケンス (immutable sequence)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

変更不能なシーケンス型のオブジェクトは、一度生成されるとその値を変更す
ることができません。 (オブジェクトに他のオブジェクトへの参照が入ってい
る場合、参照されているオブジェクトは変更可能なオブジェクトでもよく、そ
の値は変更される可能性があります; しかし、変更不能なオブジェクトが直接
参照しているオブジェクトの集合自体は、変更することができません。)

以下の型は変更不能なシーケンス型です:

文字列型 (string)
   文字列はUnicodeコードポイントを表現する値の配列です。文字列中のどの
   コードポイントも "U+0000 - U+10FFFF" の範囲で表現されることができま
   す。Pythonは char 型を持ちません。代わりに、文字列中のどのコードポ
   イントも長さ ''1'' の文字列オブジェクトとして表現することができます
   。組み込み関数 "ord()" は文字列形式を "U+0000 - U+10FFFF" の範囲の
   整数に変換します。また、組み込み関数 "chr()" は "0 - 10FFFF" の範囲
   の整数を対応する長さ "1" の文字列に変換します。"str.encode()" はテ
   キストエンコーディングを使うことで "str" を "bytes" に変換するため
   に使うことができます。また、"bytes.decode()" によりその逆が実行する
   ことができます。

タプル型 (tuple)
   タプルの要素は任意の Python オブジェクトです。二つ以上の要素からな
   るタプルは、個々の要素を表現する式をカンマで区切って構成します。単
   一の要素からなるタプル (単集合 'singleton') を作るには、要素を表現
   する式の直後にカンマをつけます (単一の式だけではタプルを形成しませ
   ん。これは、式をグループ化するのに丸括弧を使えるようにしなければな
   らないからです)。要素の全くない丸括弧の対を作ると空のタプルになりま
   す。

bytes
   A bytes object is an immutable array.  The items are 8-bit bytes,
   represented by integers in the range 0 <= x < 256.  Bytes literals
   (like "b'abc'") and the built-in "bytes()" constructor can be used
   to create bytes objects.  Also, bytes objects can be decoded to
   strings via the "decode()" method.


3.2.5.2. 変更可能なシーケンス型 (mutable sequence)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

変更可能なシーケンスは、作成した後で変更することができます。変更可能な
シーケンスでは、添字表記やスライス表記を使って指定された要素に代入を行
うことができ、 "del" (delete) 文を使って要素を削除することができます。

注釈:

  The "collections" and "array" module provide additional examples of
  mutable sequence types.

Python に最初から組み込まれている変更可能なシーケンス型は、今のところ
二つです:

リスト型 (list)
   リストの要素は任意の Python オブジェクトにできます。リストは、角括
   弧の中にカンマで区切られた式を並べて作ります。 (長さが 0 や 1 のシ
   ーケンスを作るために特殊な場合分けは必要ないことに注意してください
   。)

バイト配列
   bytearray オブジェクトは変更可能な配列です。組み込みの
   "bytearray()" コンストラクタによって作成されます。変更可能なことを
   除けば (つまりハッシュ化できない)、 byte array は変更不能な "bytes"
   オブジェクトと同じインターフェースと機能を提供します。


3.2.6. 集合型
-------------

集合型は、順序のない、ユニークで不変なオブジェクトの有限集合を表現しま
す。そのため、(配列の)添字を使ったインデックスアクセスはできません。た
だし、イテレートは可能で、組み込み関数 "len()" は集合の要素数を返しま
す。集合型の一般的な使い方は、集合に属しているかの高速なテスト、シーケ
ンスからの重複の排除、共通集合・和集合・差・対称差といった数学的な演算
の計算です。

集合の要素には、辞書のキーと同じ普遍性に関するルールが適用されます。数
値型は通常の数値比較のルールに従うことに注意してください。もし2つの数
値の比較結果が同値である(例えば、 "1" と "1.0")なら、そのうちの1つのみ
を集合に含めることができます。

現在、2つの組み込み集合型があります:

集合型
   可変な集合型です。組み込みの "set()" コンストラクタで作成され、後か
   ら "add()" などのいくつかのメソッドで更新できます。

Frozen set 型
   不変な集合型です。組み込みの "frozenset()" コンストラクタによって作
   成されます。 frozenset は不変で *ハッシュ可能* なので、別の集合型の
   要素になったり、辞書のキーにすることができます。


3.2.7. マッピング型 (mapping)
-----------------------------

任意のインデクス集合でインデクス化された、オブジェクトからなる有限の集
合を表現します。添字表記 "a[k]" は、 "k" でインデクス指定された要素を
"a" から選択します; 選択された要素は式の中で使うことができ、代入や
"del" 文の対象にすることができます。組み込み関数 "len()" は、マッピン
グ内の要素数を返します。

Python に最初から組み込まれているマッピング型は、今のところ一つだけで
す:


3.2.7.1. 辞書型 (dictionary)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ほぼ任意の値でインデクスされたオブジェクトからなる有限の集合を表します
。 キー (key) として使えない値の唯一の型は、リストや辞書、そしてオブジ
ェクトの同一性でなく値で比較されるその他の変更可能な型です。 これは、
辞書型を効率的に実装する上で、キーのハッシュ値が不変である必要があるた
めです。 数値型をキーに使う場合、キー値は通常の数値比較における規則に
従います: 二つの値が等しくなる場合 (例えば "1" と "1.0")、互いに同じ辞
書のエントリを表すインデクスとして使うことができます。

辞書は挿入の順序を保持します。つまり、キーは辞書に追加された順番に生成
されていきます。既存のキーを置き換えても、キーの順序は変わりません。キ
ーを削除したのちに再挿入すると、元の場所ではなく辞書の最後に追加されま
す。

Dictionaries are mutable; they can be created by the "{}" notation
(see section 辞書表示).

拡張モジュール "dbm.ndbm" 、 "dbm.gnu" は、 "collections" モジュールの
ように、別のマッピング型の例を提供しています。

バージョン 3.7 で変更: Pythonのバージョン3.6では、辞書は挿入順序を保持
しませんでした。CPython 3.6では挿入順序は保持されましたが、それは策定
された言語の仕様というより、その当時の実装の細部とみなされていました。


3.2.8. 呼び出し可能型 (callable type)
-------------------------------------

関数呼び出し操作 (呼び出し (call) 参照) を行うことができる型です:


3.2.8.1. ユーザ定義関数 (user-defined function)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ユーザ定義関数オブジェクトは、関数定義を行うことで生成されます (関数定
義 参照)。関数は、仮引数 (formal parameter) リストと同じ数の要素が入っ
た引数リストとともに呼び出されます。


3.2.8.1.1. Special read-only attributes
"""""""""""""""""""""""""""""""""""""""

+----------------------------------------------------+----------------------------------------------------+
| 属性                                               | 意味                                               |
|====================================================|====================================================|
| function.__builtins__                              | A reference to the "dictionary" that holds the     |
|                                                    | function's builtins namespace.  Added in version   |
|                                                    | 3.10.                                              |
+----------------------------------------------------+----------------------------------------------------+
| function.__globals__                               | A reference to the "dictionary" that holds the     |
|                                                    | function's global variables -- the global          |
|                                                    | namespace of the module in which the function was  |
|                                                    | defined.                                           |
+----------------------------------------------------+----------------------------------------------------+
| function.__closure__                               | "None" or a "tuple" of cells that contain bindings |
|                                                    | for the names specified in the "co_freevars"       |
|                                                    | attribute of the function's "code object".  セルオ |
|                                                    | ブジェクトは属性 "cell_contents" を持っています。  |
|                                                    | これはセルの値 を設定するのに加えて、セルの値を得  |
|                                                    | るのにも使えます。                                 |
+----------------------------------------------------+----------------------------------------------------+


3.2.8.1.2. Special writable attributes
""""""""""""""""""""""""""""""""""""""

Most of these attributes check the type of the assigned value:

+----------------------------------------------------+----------------------------------------------------+
| 属性                                               | 意味                                               |
|====================================================|====================================================|
| function.__doc__                                   | 関数のドキュメンテーション文字列です。ドキュメンテ |
|                                                    | ーションがない場合は "None" になります。           |
+----------------------------------------------------+----------------------------------------------------+
| function.__name__                                  | The function's name. See also: "__name__           |
|                                                    | attributes".                                       |
+----------------------------------------------------+----------------------------------------------------+
| function.__qualname__                              | The function's *qualified name*. See also:         |
|                                                    | "__qualname__ attributes".  Added in version 3.3.  |
+----------------------------------------------------+----------------------------------------------------+
| function.__module__                                | 関数が定義されているモジュールの名前です。モジュー |
|                                                    | ル名がない場合は "None" になります。               |
+----------------------------------------------------+----------------------------------------------------+
| function.__defaults__                              | A "tuple" containing default *parameter* values    |
|                                                    | for those parameters that have defaults, or "None" |
|                                                    | if no parameters have a default value.             |
+----------------------------------------------------+----------------------------------------------------+
| function.__code__                                  | The code object representing the compiled function |
|                                                    | body.                                              |
+----------------------------------------------------+----------------------------------------------------+
| function.__dict__                                  | The namespace supporting arbitrary function        |
|                                                    | attributes. See also: "__dict__ attributes".       |
+----------------------------------------------------+----------------------------------------------------+
| function.__annotations__                           | A "dictionary" containing annotations of           |
|                                                    | *parameters*. The keys of the dictionary are the   |
|                                                    | parameter names, and "'return'" for the return     |
|                                                    | annotation, if provided. See also:                 |
|                                                    | "object.__annotations__".  バージョン 3.14 で変更: |
|                                                    | Annotations are now lazily evaluated. See **PEP    |
|                                                    | 649**.                                             |
+----------------------------------------------------+----------------------------------------------------+
| function.__annotate__                              | The *annotate function* for this function, or      |
|                                                    | "None" if the function has no annotations. See     |
|                                                    | "object.__annotate__".  Added in version 3.14.     |
+----------------------------------------------------+----------------------------------------------------+
| function.__kwdefaults__                            | A "dictionary" containing defaults for keyword-    |
|                                                    | only *parameters*.                                 |
+----------------------------------------------------+----------------------------------------------------+
| function.__type_params__                           | A "tuple" containing the type parameters of a      |
|                                                    | generic function.  Added in version 3.12.          |
+----------------------------------------------------+----------------------------------------------------+

Function objects also support getting and setting arbitrary
attributes, which can be used, for example, to attach metadata to
functions.  Regular attribute dot-notation is used to get and set such
attributes.

**CPython 実装の詳細:** CPython's current implementation only supports
function attributes on user-defined functions. Function attributes on
built-in functions may be supported in the future.

Additional information about a function's definition can be retrieved
from its code object (accessible via the "__code__" attribute).


3.2.8.2. インスタンスメソッド
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

インスタンスメソッドオブジェクトは、クラス、クラスインスタンスと任意の
呼び出し可能オブジェクト (通常はユーザ定義関数) を結びつけます。

Special read-only attributes:

+----------------------------------------------------+----------------------------------------------------+
| method.__self__                                    | Refers to the class instance object to which the   |
|                                                    | method is bound                                    |
+----------------------------------------------------+----------------------------------------------------+
| method.__func__                                    | Refers to the original function object             |
+----------------------------------------------------+----------------------------------------------------+
| method.__doc__                                     | The method's documentation (same as                |
|                                                    | "method.__func__.__doc__"). A "string" if the      |
|                                                    | original function had a docstring, else "None".    |
+----------------------------------------------------+----------------------------------------------------+
| method.__name__                                    | The name of the method (same as                    |
|                                                    | "method.__func__.__name__")                        |
+----------------------------------------------------+----------------------------------------------------+
| method.__module__                                  | The name of the module the method was defined in,  |
|                                                    | or "None" if unavailable.                          |
+----------------------------------------------------+----------------------------------------------------+

Methods also support accessing (but not setting) the arbitrary
function attributes on the underlying function object.

User-defined method objects may be created when getting an attribute
of a class (perhaps via an instance of that class), if that attribute
is a user-defined function object or a "classmethod" object.

When an instance method object is created by retrieving a user-defined
function object from a class via one of its instances, its "__self__"
attribute is the instance, and the method object is said to be
*bound*.  The new method's "__func__" attribute is the original
function object.

When an instance method object is created by retrieving a
"classmethod" object from a class or instance, its "__self__"
attribute is the class itself, and its "__func__" attribute is the
function object underlying the class method.

When an instance method object is called, the underlying function
("__func__") is called, inserting the class instance ("__self__") in
front of the argument list.  For instance, when "C" is a class which
contains a definition for a function "f()", and "x" is an instance of
"C", calling "x.f(1)" is equivalent to calling "C.f(x, 1)".

When an instance method object is derived from a "classmethod" object,
the "class instance" stored in "__self__" will actually be the class
itself, so that calling either "x.f(1)" or "C.f(1)" is equivalent to
calling "f(C,1)" where "f" is the underlying function.

It is important to note that user-defined functions which are
attributes of a class instance are not converted to bound methods;
this *only* happens when the function is an attribute of the class.


3.2.8.3. ジェネレータ関数 (generator function)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"yield" 文 (yield 文 の節を参照) を使う関数もしくはメソッドは *ジェネ
レータ関数* と呼ばれます。 そのような関数が呼び出されたときは常に、関
数の本体を実行するのに使える *イテレータ* オブジェクトを返します: イテ
レータの "iterator.__next__()" メソッドを呼び出すと、 "yield" 文を使っ
て値が提供されるまで関数を実行します。 関数の "return" 文を実行するか
終端に達したときは、 "StopIteration" 例外が送出され、イテレータが返す
べき値の最後まで到達しています。


3.2.8.4. コルーチン関数 (coroutine function)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"async def" を使用して定義された関数やメソッドを *コルーチン関数
(coroutine function)* と呼びます。 呼び出された時、そのような関数は
*coroutine* オブジェクトを返します。 コルーチン関数は "async with" や
"async for" 文だけでなく "await" 式を持つことが出来ます。 コルーチンオ
ブジェクト を参照してください。


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

"async def" を使って定義され、 "yield" 文を使用している関数やメソッド
を *asynchronous generator function* と呼びます。 そのような関数は、呼
び出されたとき、*非同期イテレータ* オブジェクトを返します。 このオブジ
ェクトは "async for" 文で関数の本体を実行するのに使えます。

非同期イテレータの "aiterator.__anext__" メソッドを呼び出すと、他の処
理が待たされているときに、 "yield" 式を使い値を提供するところまで処理
を進める *awaitable* を返します。 その関数が空の "return" 文を実行する
、もしくは処理の終わりに到達したときは、 "StopAsyncIteration" 例外が送
出され、非同期イテレータは出力すべき値の最後に到達したことになります。


3.2.8.6. 組み込み関数 (built-in function)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A built-in function object is a wrapper around a C function.  Examples
of built-in functions are "len()" and "math.sin()" ("math" is a
standard built-in module). The number and type of the arguments are
determined by the C function. Special read-only attributes:

* "__doc__" is the function's documentation string, or "None" if
  unavailable. See "function.__doc__".

* "__name__" is the function's name. See "function.__name__".

* "__self__" is set to "None" (but see the next item).

* "__module__" is the name of the module the function was defined in
  or "None" if unavailable. See "function.__module__".


3.2.8.7. 組み込みメソッド (built-in method)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This is really a different disguise of a built-in function, this time
containing an object passed to the C function as an implicit extra
argument.  An example of a built-in method is "alist.append()",
assuming *alist* is a list object. In this case, the special read-only
attribute "__self__" is set to the object denoted by *alist*. (The
attribute has the same semantics as it does with "other instance
methods".)


3.2.8.8. クラス
~~~~~~~~~~~~~~~

Classes are callable.  These objects normally act as factories for new
instances of themselves, but variations are possible for class types
that override "__new__()".  The arguments of the call are passed to
"__new__()" and, in the typical case, to "__init__()" to initialize
the new instance.


3.2.8.9. クラスのインスタンス
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

任意のクラスのインスタンスは、クラスで "__call__()" メソッドを定義する
ことで呼び出し可能になります。


3.2.9. モジュール
-----------------

Modules are a basic organizational unit of Python code, and are
created by the import system as invoked either by the "import"
statement, or by calling functions such as "importlib.import_module()"
and built-in "__import__()".  A module object has a namespace
implemented by a "dictionary" object (this is the dictionary
referenced by the "__globals__" attribute of functions defined in the
module).  Attribute references are translated to lookups in this
dictionary, e.g., "m.x" is equivalent to "m.__dict__["x"]". A module
object does not contain the code object used to initialize the module
(since it isn't needed once the initialization is done).

属性の代入を行うと、モジュールの名前空間辞書の内容を更新します。例えば
、 "m.x = 1" は "m.__dict__["x"] = 1" と同じです。


3.2.9.1. Import-related attributes on module objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Module objects have the following attributes that relate to the import
system. When a module is created using the machinery associated with
the import system, these attributes are filled in based on the
module's *spec*, before the *loader* executes and loads the module.

To create a module dynamically rather than using the import system,
it's recommended to use "importlib.util.module_from_spec()", which
will set the various import-controlled attributes to appropriate
values. It's also possible to use the "types.ModuleType" constructor
to create modules directly, but this technique is more error-prone, as
most attributes must be manually set on the module object after it has
been created when using this approach.

注意:

  With the exception of "__name__", it is **strongly** recommended
  that you rely on "__spec__" and its attributes instead of any of the
  other individual attributes listed in this subsection. Note that
  updating an attribute on "__spec__" will not update the
  corresponding attribute on the module itself:

     >>> import typing
     >>> typing.__name__, typing.__spec__.name
     ('typing', 'typing')
     >>> typing.__spec__.name = 'spelling'
     >>> typing.__name__, typing.__spec__.name
     ('typing', 'spelling')
     >>> typing.__name__ = 'keyboard_smashing'
     >>> typing.__name__, typing.__spec__.name
     ('keyboard_smashing', 'spelling')

module.__name__

   The name used to uniquely identify the module in the import system.
   For a directly executed module, this will be set to ""__main__"".

   This attribute must be set to the fully qualified name of the
   module. It is expected to match the value of
   "module.__spec__.name".

module.__spec__

   A record of the module's import-system-related state.

   Set to the "module spec" that was used when importing the module.
   See Module specs for more details.

   Added in version 3.4.

module.__package__

   The *package* a module belongs to.

   If the module is top-level (that is, not a part of any specific
   package) then the attribute should be set to "''" (the empty
   string). Otherwise, it should be set to the name of the module's
   package (which can be equal to "module.__name__" if the module
   itself is a package). See **PEP 366** for further details.

   This attribute is used instead of "__name__" to calculate explicit
   relative imports for main modules. It defaults to "None" for
   modules created dynamically using the "types.ModuleType"
   constructor; use "importlib.util.module_from_spec()" instead to
   ensure the attribute is set to a "str".

   It is **strongly** recommended that you use
   "module.__spec__.parent" instead of "module.__package__".
   "__package__" is now only used as a fallback if "__spec__.parent"
   is not set, and this fallback path is deprecated.

   バージョン 3.4 で変更: This attribute now defaults to "None" for
   modules created dynamically using the "types.ModuleType"
   constructor. Previously the attribute was optional.

   バージョン 3.6 で変更: The value of "__package__" is expected to be
   the same as "__spec__.parent". "__package__" is now only used as a
   fallback during import resolution if "__spec__.parent" is not
   defined.

   バージョン 3.10 で変更: "ImportWarning" is raised if an import
   resolution falls back to "__package__" instead of
   "__spec__.parent".

   バージョン 3.12 で変更: Raise "DeprecationWarning" instead of
   "ImportWarning" when falling back to "__package__" during import
   resolution.

   Deprecated since version 3.13, will be removed in version 3.15:
   "__package__" will cease to be set or taken into consideration by
   the import system or standard library.

module.__loader__

   The *loader* object that the import machinery used to load the
   module.

   This attribute is mostly useful for introspection, but can be used
   for additional loader-specific functionality, for example getting
   data associated with a loader.

   "__loader__" defaults to "None" for modules created dynamically
   using the "types.ModuleType" constructor; use
   "importlib.util.module_from_spec()" instead to ensure the attribute
   is set to a *loader* object.

   It is **strongly** recommended that you use
   "module.__spec__.loader" instead of "module.__loader__".

   バージョン 3.4 で変更: This attribute now defaults to "None" for
   modules created dynamically using the "types.ModuleType"
   constructor. Previously the attribute was optional.

   Deprecated since version 3.12, will be removed in version 3.16:
   Setting "__loader__" on a module while failing to set
   "__spec__.loader" is deprecated. In Python 3.16, "__loader__" will
   cease to be set or taken into consideration by the import system or
   the standard library.

module.__path__

   A (possibly empty) *sequence* of strings enumerating the locations
   where the package's submodules will be found. Non-package modules
   should not have a "__path__" attribute. See __path__ attributes on
   modules for more details.

   It is **strongly** recommended that you use
   "module.__spec__.submodule_search_locations" instead of
   "module.__path__".

module.__file__

module.__cached__

   "__file__" and "__cached__" are both optional attributes that may
   or may not be set. Both attributes should be a "str" when they are
   available.

   "__file__" indicates the pathname of the file from which the module
   was loaded (if loaded from a file), or the pathname of the shared
   library file for extension modules loaded dynamically from a shared
   library. It might be missing for certain types of modules, such as
   C modules that are statically linked into the interpreter, and the
   import system may opt to leave it unset if it has no semantic
   meaning (for example, a module loaded from a database).

   If "__file__" is set then the "__cached__" attribute might also be
   set,  which is the path to any compiled version of the code (for
   example, a byte-compiled file). The file does not need to exist to
   set this attribute; the path can simply point to where the compiled
   file *would* exist (see **PEP 3147**).

   Note that "__cached__" may be set even if "__file__" is not set.
   However, that scenario is quite atypical.  Ultimately, the *loader*
   is what makes use of the module spec provided by the *finder* (from
   which "__file__" and "__cached__" are derived).  So if a loader can
   load from a cached module but otherwise does not load from a file,
   that atypical scenario may be appropriate.

   It is **strongly** recommended that you use
   "module.__spec__.cached" instead of "module.__cached__".

   Deprecated since version 3.13, will be removed in version 3.15:
   Setting "__cached__" on a module while failing to set
   "__spec__.cached" is deprecated. In Python 3.15, "__cached__" will
   cease to be set or taken into consideration by the import system or
   standard library.


3.2.9.2. Other writable attributes on module objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As well as the import-related attributes listed above, module objects
also have the following writable attributes:

module.__doc__

   The module's documentation string, or "None" if unavailable. See
   also: "__doc__ attributes".

module.__annotations__

   A dictionary containing *variable annotations* collected during
   module body execution.  For best practices on working with
   "__annotations__", see "annotationlib".

   バージョン 3.14 で変更: Annotations are now lazily evaluated. See
   **PEP 649**.

module.__annotate__

   The *annotate function* for this module, or "None" if the module
   has no annotations. See also: "__annotate__" attributes.

   Added in version 3.14.


3.2.9.3. Module dictionaries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Module objects also have the following special read-only attribute:

module.__dict__

   The module's namespace as a dictionary object. Uniquely among the
   attributes listed here, "__dict__" cannot be accessed as a global
   variable from within a module; it can only be accessed as an
   attribute on module objects.

   CPython がモジュール辞書を削除する方法により、モジュール辞書が生き
   た参照を持っていたとしてもその辞書はモジュールがスコープから外れた
   時に削除されます。これを避けるには、辞書をコピーするか、辞書を直接
   使っている間モジュールを保持してください。


3.2.10. カスタムクラス型
------------------------

Custom class types are typically created by class definitions (see
section クラス定義).  A class has a namespace implemented by a
dictionary object. Class attribute references are translated to
lookups in this dictionary, e.g., "C.x" is translated to
"C.__dict__["x"]" (although there are a number of hooks which allow
for other means of locating attributes). When the attribute name is
not found there, the attribute search continues in the base classes.
This search of the base classes uses the C3 method resolution order
which behaves correctly even in the presence of 'diamond' inheritance
structures where there are multiple inheritance paths leading back to
a common ancestor. Additional details on the C3 MRO used by Python can
be found at The Python 2.3 Method Resolution Order.

When a class attribute reference (for class "C", say) would yield a
class method object, it is transformed into an instance method object
whose "__self__" attribute is "C". When it would yield a
"staticmethod" object, it is transformed into the object wrapped by
the static method object. See section デスクリプタ (descriptor) の実装
for another way in which attributes retrieved from a class may differ
from those actually contained in its "__dict__".

クラス属性を代入すると、そのクラスの辞書だけが更新され、基底クラスの辞
書は更新しません。

クラスオブジェクトを呼び出す (上記を参照) と、クラスインスタンスを生成
します (下記を参照)。


3.2.10.1. Special attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+----------------------------------------------------+----------------------------------------------------+
| 属性                                               | 意味                                               |
|====================================================|====================================================|
| type.__name__                                      | The class's name. See also: "__name__ attributes". |
+----------------------------------------------------+----------------------------------------------------+
| type.__qualname__                                  | The class's *qualified name*. See also:            |
|                                                    | "__qualname__ attributes".                         |
+----------------------------------------------------+----------------------------------------------------+
| type.__module__                                    | クラスが定義されているモジュールの名前。           |
+----------------------------------------------------+----------------------------------------------------+
| type.__dict__                                      | A "mapping proxy" providing a read-only view of    |
|                                                    | the class's namespace. See also: "__dict__         |
|                                                    | attributes".                                       |
+----------------------------------------------------+----------------------------------------------------+
| type.__bases__                                     | A "tuple" containing the class's bases. In most    |
|                                                    | cases, for a class defined as "class X(A, B, C)",  |
|                                                    | "X.__bases__" will be exactly equal to "(A, B,     |
|                                                    | C)".                                               |
+----------------------------------------------------+----------------------------------------------------+
| type.__base__                                      | **CPython 実装の詳細:** The single base class in   |
|                                                    | the inheritance chain that is responsible for the  |
|                                                    | memory layout of instances. This attribute         |
|                                                    | corresponds to "tp_base" at the C level.           |
+----------------------------------------------------+----------------------------------------------------+
| type.__doc__                                       | The class's documentation string, or "None" if     |
|                                                    | undefined. Not inherited by subclasses.            |
+----------------------------------------------------+----------------------------------------------------+
| type.__annotations__                               | A dictionary containing *variable annotations*     |
|                                                    | collected during class body execution. See also:   |
|                                                    | "__annotations__ attributes".  For best practices  |
|                                                    | on working with "__annotations__", please see      |
|                                                    | "annotationlib". Use                               |
|                                                    | "annotationlib.get_annotations()" instead of       |
|                                                    | accessing this attribute directly.  警告:          |
|                                                    | Accessing the "__annotations__" attribute directly |
|                                                    | on a class object may return annotations for the   |
|                                                    | wrong class, specifically in certain cases where   |
|                                                    | the class, its base class, or a metaclass is       |
|                                                    | defined under "from __future__ import              |
|                                                    | annotations". See **749** for details.This         |
|                                                    | attribute does not exist on certain builtin        |
|                                                    | classes. On user-defined classes without           |
|                                                    | "__annotations__", it is an empty dictionary.  バ  |
|                                                    | ージョン 3.14 で変更: Annotations are now lazily   |
|                                                    | evaluated. See **PEP 649**.                        |
+----------------------------------------------------+----------------------------------------------------+
| type.__annotate__()                                | The *annotate function* for this class, or "None"  |
|                                                    | if the class has no annotations. See also:         |
|                                                    | "__annotate__ attributes".  Added in version 3.14. |
+----------------------------------------------------+----------------------------------------------------+
| type.__type_params__                               | A "tuple" containing the type parameters of a      |
|                                                    | generic class.  Added in version 3.12.             |
+----------------------------------------------------+----------------------------------------------------+
| type.__static_attributes__                         | A "tuple" containing names of attributes of this   |
|                                                    | class which are assigned through "self.X" from any |
|                                                    | function in its body.  Added in version 3.13.      |
+----------------------------------------------------+----------------------------------------------------+
| type.__firstlineno__                               | The line number of the first line of the class     |
|                                                    | definition, including decorators. Setting the      |
|                                                    | "__module__" attribute removes the                 |
|                                                    | "__firstlineno__" item from the type's dictionary. |
|                                                    | Added in version 3.13.                             |
+----------------------------------------------------+----------------------------------------------------+
| type.__mro__                                       | The "tuple" of classes that are considered when    |
|                                                    | looking for base classes during method resolution. |
+----------------------------------------------------+----------------------------------------------------+


3.2.10.2. Special methods
~~~~~~~~~~~~~~~~~~~~~~~~~

In addition to the special attributes described above, all Python
classes also have the following two methods available:

type.mro()

   This method can be overridden by a metaclass to customize the
   method resolution order for its instances.  It is called at class
   instantiation, and its result is stored in "__mro__".

type.__subclasses__()

   Each class keeps a list of weak references to its immediate
   subclasses. This method returns a list of all those references
   still alive. The list is in definition order. Example:

      >>> class A: pass
      >>> class B(A): pass
      >>> A.__subclasses__()
      [<class 'B'>]


3.2.11. クラスインスタンス (class instance)
-------------------------------------------

A class instance is created by calling a class object (see above).  A
class instance has a namespace implemented as a dictionary which is
the first place in which attribute references are searched.  When an
attribute is not found there, and the instance's class has an
attribute by that name, the search continues with the class
attributes.  If a class attribute is found that is a user-defined
function object, it is transformed into an instance method object
whose "__self__" attribute is the instance.  Static method and class
method objects are also transformed; see above under "Classes".  See
section デスクリプタ (descriptor) の実装 for another way in which
attributes of a class retrieved via its instances may differ from the
objects actually stored in the class's "__dict__".  If no class
attribute is found, and the object's class has a "__getattr__()"
method, that is called to satisfy the lookup.

属性の代入や削除を行うと、インスタンスの辞書を更新しますが、クラスの辞
書を更新することはありません。クラスで "__setattr__()" や
"__delattr__()" メソッドが定義されている場合、直接インスタンスの辞書を
更新する代わりにこれらのメソッドが呼び出されます。

クラスインスタンスは、ある特定の名前のメソッドを持っている場合、数値型
やシーケンス型、あるいはマップ型のように振舞うことができます。 特殊メ
ソッド名 を参照してください。


3.2.11.1. Special attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

object.__class__

   クラスインスタンスが属しているクラスです。

object.__dict__

   A dictionary or other mapping object used to store an object's
   (writable) attributes. Not all instances have a "__dict__"
   attribute; see the section on __slots__ for more details.


3.2.12. I/O オブジェクト (ファイルオブジェクトの別名)
-----------------------------------------------------

*file object* は開かれたファイルを表します。ファイルオブジェクトを作る
ための様々なショートカットがあります: "open()" 組み込み関数、
"os.popen()" 、 "os.fdopen()" 、ソケットオブジェクトの "makefile()" メ
ソッド (あるいは拡張モジュールから提供される他の関数やメソッド) 。

オブジェクト "sys.stdin" 、 "sys.stdout" および "sys.stderr" は、イン
タプリタの標準入力、標準出力、および標準エラー出力ストリームに対応する
ファイルオブジェクトに初期化されます。これらはすべてテキストモードで開
かれ、 "io.TextIOBase" 抽象クラスによって定義されたインターフェースに
従います。


3.2.13. 内部型 (internal type)
------------------------------

インタプリタが内部的に使っているいくつかの型は、ユーザに公開されていま
す。これらの定義は将来のインタプリタのバージョンでは変更される可能性が
ありますが、ここでは記述の完全性のために触れておきます。


3.2.13.1. コードオブジェクト
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

コードオブジェクトは *バイトコンパイルされた (byte-compiled)* 実行可能
な Python コード、別名 *バイトコード* を表現します。コードオブジェクト
と関数オブジェクトの違いは、関数オブジェクトが関数のグローバル変数 (関
数を定義しているモジュールのグローバル) に対して明示的な参照を持ってい
るのに対し、コードオブジェクトにはコンテキストがないということです; ま
た、関数オブジェクトではデフォルト引数値を記憶できますが、コードオブジ
ェクトではできません (実行時に計算される値を表現するため)。関数オブジ
ェクトと違い、コードオブジェクトは変更不可能で、変更可能なオブジェクト
への参照を (直接、間接に関わらず) 含みません。


3.2.13.1.1. Special read-only attributes
""""""""""""""""""""""""""""""""""""""""

+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_name                                 | The function name                                  |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_qualname                             | The fully qualified function name  Added in        |
|                                                    | version 3.11.                                      |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_argcount                             | The total number of positional *parameters*        |
|                                                    | (including positional-only parameters and          |
|                                                    | parameters with default values) that the function  |
|                                                    | has                                                |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_posonlyargcount                      | The number of positional-only *parameters*         |
|                                                    | (including arguments with default values) that the |
|                                                    | function has                                       |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_kwonlyargcount                       | The number of keyword-only *parameters* (including |
|                                                    | arguments with default values) that the function   |
|                                                    | has                                                |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_nlocals                              | The number of local variables used by the function |
|                                                    | (including parameters)                             |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_varnames                             | A "tuple" containing the names of the local        |
|                                                    | variables in the function (starting with the       |
|                                                    | parameter names)                                   |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_cellvars                             | A "tuple" containing the names of local variables  |
|                                                    | that are referenced from at least one *nested      |
|                                                    | scope* inside the function                         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_freevars                             | A "tuple" containing the names of *free (closure)  |
|                                                    | variables* that a *nested scope* references in an  |
|                                                    | outer scope. See also "function.__closure__".      |
|                                                    | Note: references to global and builtin names are   |
|                                                    | *not* included.                                    |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_code                                 | A string representing the sequence of *bytecode*   |
|                                                    | instructions in the function                       |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_consts                               | A "tuple" containing the literals used by the      |
|                                                    | *bytecode* in the function                         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_names                                | A "tuple" containing the names used by the         |
|                                                    | *bytecode* in the function                         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_filename                             | The name of the file from which the code was       |
|                                                    | compiled                                           |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_firstlineno                          | The line number of the first line of the function  |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_lnotab                               | A string encoding the mapping from *bytecode*      |
|                                                    | offsets to line numbers. For details, see the      |
|                                                    | source code of the interpreter.  バージョン 3.12   |
|                                                    | で非推奨: This attribute of code objects is        |
|                                                    | deprecated, and may be removed in Python 3.15.     |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_stacksize                            | The required stack size of the code object         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_flags                                | An "integer" encoding a number of flags for the    |
|                                                    | interpreter.                                       |
+----------------------------------------------------+----------------------------------------------------+

The following flag bits are defined for "co_flags": bit "0x04" is set
if the function uses the "*arguments" syntax to accept an arbitrary
number of positional arguments; bit "0x08" is set if the function uses
the "**keywords" syntax to accept arbitrary keyword arguments; bit
"0x20" is set if the function is a generator. See Code Objects Bit
Flags for details on the semantics of each flags that might be
present.

Future feature declarations (for example, "from __future__ import
division") also use bits in "co_flags" to indicate whether a code
object was compiled with a particular feature enabled. See
"compiler_flag".

Other bits in "co_flags" are reserved for internal use.

If a code object represents a function and has a docstring, the
"CO_HAS_DOCSTRING" bit is set in "co_flags" and the first item in
"co_consts" is the docstring of the function.


3.2.13.1.2. Methods on code objects
"""""""""""""""""""""""""""""""""""

codeobject.co_positions()

   Returns an iterable over the source code positions of each
   *bytecode* instruction in the code object.

   The iterator returns "tuple"s containing the "(start_line,
   end_line, start_column, end_column)". The *i-th* tuple corresponds
   to the position of the source code that compiled to the *i-th* code
   unit. Column information is 0-indexed utf-8 byte offsets on the
   given source line.

   This positional information can be missing. A non-exhaustive lists
   of cases where this may happen:

   * Running the interpreter with "-X" "no_debug_ranges".

   * Loading a pyc file compiled while using "-X" "no_debug_ranges".

   * Position tuples corresponding to artificial instructions.

   * Line and column numbers that can't be represented due to
     implementation specific limitations.

   When this occurs, some or all of the tuple elements can be "None".

   Added in version 3.11.

   注釈:

     This feature requires storing column positions in code objects
     which may result in a small increase of disk usage of compiled
     Python files or interpreter memory usage. To avoid storing the
     extra information and/or deactivate printing the extra traceback
     information, the "-X" "no_debug_ranges" command line flag or the
     "PYTHONNODEBUGRANGES" environment variable can be used.

codeobject.co_lines()

   Returns an iterator that yields information about successive ranges
   of *bytecode*s. Each item yielded is a "(start, end, lineno)"
   "tuple":

   * "start" (an "int") represents the offset (inclusive) of the start
     of the *bytecode* range

   * "end" (an "int") represents the offset (exclusive) of the end of
     the *bytecode* range

   * "lineno" is an "int" representing the line number of the
     *bytecode* range, or "None" if the bytecodes in the given range
     have no line number

   The items yielded will have the following properties:

   * The first range yielded will have a "start" of 0.

   * The "(start, end)" ranges will be non-decreasing and consecutive.
     That is, for any pair of "tuple"s, the "start" of the second will
     be equal to the "end" of the first.

   * No range will be backwards: "end >= start" for all triples.

   * The last "tuple" yielded will have "end" equal to the size of the
     *bytecode*.

   Zero-width ranges, where "start == end", are allowed. Zero-width
   ranges are used for lines that are present in the source code, but
   have been eliminated by the *bytecode* compiler.

   Added in version 3.10.

   参考:

     **PEP 626** - Precise line numbers for debugging and other tools.
        The PEP that introduced the "co_lines()" method.

codeobject.replace(**kwargs)

   Return a copy of the code object with new values for the specified
   fields.

   Code objects are also supported by the generic function
   "copy.replace()".

   Added in version 3.8.


3.2.13.2. フレーム (frame) オブジェクト
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Frame objects represent execution frames.  They may occur in traceback
objects, and are also passed to registered trace functions.


3.2.13.2.1. Special read-only attributes
""""""""""""""""""""""""""""""""""""""""

+----------------------------------------------------+----------------------------------------------------+
| frame.f_back                                       | Points to the previous stack frame (towards the    |
|                                                    | caller), or "None" if this is the bottom stack     |
|                                                    | frame                                              |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_code                                       | The code object being executed in this frame.      |
|                                                    | Accessing this attribute raises an auditing event  |
|                                                    | "object.__getattr__" with arguments "obj" and      |
|                                                    | ""f_code"".                                        |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_locals                                     | The mapping used by the frame to look up local     |
|                                                    | variables. If the frame refers to an *optimized    |
|                                                    | scope*, this may return a write-through proxy      |
|                                                    | object.  バージョン 3.13 で変更: Return a proxy    |
|                                                    | for optimized scopes.                              |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_globals                                    | The dictionary used by the frame to look up global |
|                                                    | variables                                          |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_builtins                                   | The dictionary used by the frame to look up built- |
|                                                    | in (intrinsic) names                               |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_lasti                                      | The "precise instruction" of the frame object      |
|                                                    | (this is an index into the *bytecode* string of    |
|                                                    | the code object)                                   |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_generator                                  | The *generator* or *coroutine* object that owns    |
|                                                    | this frame, or "None" if the frame is a normal     |
|                                                    | function.  Added in version 3.14.                  |
+----------------------------------------------------+----------------------------------------------------+


3.2.13.2.2. Special writable attributes
"""""""""""""""""""""""""""""""""""""""

+----------------------------------------------------+----------------------------------------------------+
| frame.f_trace                                      | If not "None", this is a function called for       |
|                                                    | various events during code execution (this is used |
|                                                    | by debuggers). Normally an event is triggered for  |
|                                                    | each new source line (see "f_trace_lines").        |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_trace_lines                                | Set this attribute to "False" to disable           |
|                                                    | triggering a tracing event for each source line.   |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_trace_opcodes                              | Set this attribute to "True" to allow per-opcode   |
|                                                    | events to be requested. Note that this may lead to |
|                                                    | undefined interpreter behaviour if exceptions      |
|                                                    | raised by the trace function escape to the         |
|                                                    | function being traced.                             |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_lineno                                     | The current line number of the frame -- writing to |
|                                                    | this from within a trace function jumps to the     |
|                                                    | given line (only for the bottom-most frame).  A    |
|                                                    | debugger can implement a Jump command (aka Set     |
|                                                    | Next Statement) by writing to this attribute.      |
+----------------------------------------------------+----------------------------------------------------+


3.2.13.2.3. Frame object methods
""""""""""""""""""""""""""""""""

フレームオブジェクトはメソッドを一つサポートします:

frame.clear()

   This method clears all references to local variables held by the
   frame.  Also, if the frame belonged to a *generator*, the generator
   is finalized.  This helps break reference cycles involving frame
   objects (for example when catching an exception and storing its
   traceback for later use).

   "RuntimeError" is raised if the frame is currently executing or
   suspended.

   Added in version 3.4.

   バージョン 3.13 で変更: Attempting to clear a suspended frame
   raises "RuntimeError" (as has always been the case for executing
   frames).


3.2.13.3. トレースバック (traceback) オブジェクト
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Traceback objects represent the stack trace of an exception. A
traceback object is implicitly created when an exception occurs, and
may also be explicitly created by calling "types.TracebackType".

バージョン 3.7 で変更: Traceback objects can now be explicitly
instantiated from Python code.

For implicitly created tracebacks, when the search for an exception
handler unwinds the execution stack, at each unwound level a traceback
object is inserted in front of the current traceback.  When an
exception handler is entered, the stack trace is made available to the
program. (See section try 文.) It is accessible as the third item of
the tuple returned by "sys.exc_info()", and as the "__traceback__"
attribute of the caught exception.

When the program contains no suitable handler, the stack trace is
written (nicely formatted) to the standard error stream; if the
interpreter is interactive, it is also made available to the user as
"sys.last_traceback".

For explicitly created tracebacks, it is up to the creator of the
traceback to determine how the "tb_next" attributes should be linked
to form a full stack trace.

Special read-only attributes:

+----------------------------------------------------+----------------------------------------------------+
| traceback.tb_frame                                 | Points to the execution frame of the current       |
|                                                    | level.  Accessing this attribute raises an         |
|                                                    | auditing event "object.__getattr__" with arguments |
|                                                    | "obj" and ""tb_frame"".                            |
+----------------------------------------------------+----------------------------------------------------+
| traceback.tb_lineno                                | Gives the line number where the exception occurred |
+----------------------------------------------------+----------------------------------------------------+
| traceback.tb_lasti                                 | Indicates the "precise instruction".               |
+----------------------------------------------------+----------------------------------------------------+

The line number and last instruction in the traceback may differ from
the line number of its frame object if the exception occurred in a
"try" statement with no matching except clause or with a "finally"
clause.

traceback.tb_next

   The special writable attribute "tb_next" is the next level in the
   stack trace (towards the frame where the exception occurred), or
   "None" if there is no next level.

   バージョン 3.7 で変更: This attribute is now writable


3.2.13.4. スライス (slice) オブジェクト
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

スライスオブジェクトは、 "__getitem__()" メソッドのためのスライスを表
すのに使われます。スライスオブジェクトは組み込みの "slice()" 関数でも
生成されます。

読み出し専用の特殊属性: "start" は下限です; "stop" は上限です; "step"
はステップの値です; それぞれ省略された場合は "None" となっています。こ
れらの属性は任意の型を持てます。

スライスオブジェクトはメソッドを一つサポートします:

slice.indices(self, length)

   このメソッドは単一の整数引数 *length* を取り、スライスオブジェクト
   が *length* 要素のシーケンスに適用されたときに表現する、スライスに
   関する情報を計算します。このメソッドは 3 つの整数からなるタプルを返
   します; それぞれ *start* および *stop* のインデックスと、*step* す
   なわちスライスのまたぎ幅です。インデックス値がないか、範囲外の値で
   あれば、通常のスライスと変わらないやりかたで扱われます。


3.2.13.5. 静的メソッド (static method) オブジェクト
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

静的メソッドは、上で説明したような関数オブジェクトからメソッドオブジェ
クトへの変換を阻止するための方法を提供します。静的メソッドオブジェクト
は他の何らかのオブジェクト、通常はユーザ定義メソッドオブジェクトを包む
ラッパです。静的メソッドをクラスやクラスインスタンスから取得すると、実
際に返されるオブジェクトはラップされたオブジェクトになり、それ以上は変
換の対象にはなりません。静的メソッドオブジェクトは通常呼び出し可能なオ
ブジェクトをラップしますが、静的オブジェクト自体は呼び出し可能です。静
的オブジェクトは組み込みコンストラクタ "staticmethod()" で生成されます
。


3.2.13.6. クラスメソッドオブジェクト
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A class method object, like a static method object, is a wrapper
around another object that alters the way in which that object is
retrieved from classes and class instances. The behaviour of class
method objects upon such retrieval is described above, under "instance
methods". Class method objects are created by the built-in
"classmethod()" constructor.


3.3. 特殊メソッド名
===================

クラスは、特殊な名前のメソッドを定義して、特殊な構文 (算術演算や添え字
表記、スライス表記など) による特定の演算を実装できます。これは、Python
の演算子オーバロード (*operator overloading*) へのアプローチです。これ
により、クラスは言語の演算子に対する独自の振る舞いを定義できます。例え
ば、あるクラスが "__getitem__()" という名前のメソッドを定義しており、
"x" がこのクラスのインスタンスであるとすると、 "x[i]" は
"type(x).__getitem__(x, i)" とほぼ等価です。特に注釈のない限り、適切な
メソッドが定義されていないとき、このような演算を試みると例外 (たいてい
は "AttributeError" か "TypeError") が送出されます。

特殊メソッドに "None" を設定することは、それに対応する演算が利用できな
いことを意味します。 例えば、クラスの "__iter__()" を "None" に設定し
た場合、そのクラスはイテラブルにはならず、そのインスタンスに対し
"iter()" を呼び出すと ("__getitem__()" に処理が戻されずに) "TypeError"
を送出します。 [2]

When implementing a class that emulates any built-in type, it is
important that the emulation only be implemented to the degree that it
makes sense for the object being modelled.  For example, some
sequences may work well with retrieval of individual elements, but
extracting a slice may not make sense. (One example of this is the
NodeList interface in the W3C's Document Object Model.)


3.3.1. 基本的なカスタマイズ
---------------------------

object.__new__(cls[, ...])

   クラス *cls* の新しいインスタンスを作るために呼び出されます。
   "__new__()" は静的メソッドで (このメソッドは特別扱いされているので
   、明示的に静的メソッドと宣言する必要はありません)、インスタンスを生
   成するよう要求されているクラスを第一引数にとります。残りの引数はオ
   ブジェクトのコンストラクタの式 (クラスの呼び出し文) に渡されます。
   "__new__()" の戻り値は新しいオブジェクトのインスタンス (通常は
   *cls* のインスタンス) でなければなりません。

   典型的な実装では、クラスの新たなインスタンスを生成するときには
   "super().__new__(cls[, ...])" に適切な引数を指定してスーパクラスの
   "__new__()" メソッドを呼び出し、新たに生成されたインスタンスに必要
   な変更を加えてから返します。

   もし "__new__()" が オブジェクトの作成中に呼び出され、*cls* のイン
   スタンスを返した場合には、 "__init__(self[, ...])" のようにして新し
   いインスタンスの "__init__()" が呼び出されます。このとき、 *self*
   は新たに生成されたインスタンスで、残りの引数はオブジェクトコンスト
   ラクタに渡された引数と同じになります。

   "__new__()" が *cls* のインスタンスを返さない場合、インスタンスの
   "__init__()" メソッドは呼び出されません。

   "__new__()" の主な目的は、変更不能な型 (int, str, tuple など) のサ
   ブクラスでインスタンス生成をカスタマイズすることにあります。また、
   クラス生成をカスタマイズするために、カスタムのメタクラスでよくオー
   バーライドされます。

object.__init__(self[, ...])

   インスタンスが ("__new__()" によって) 生成された後、それが呼び出し
   元に返される前に呼び出されます。引数はクラスのコンストラクタ式に渡
   したものです。基底クラスとその派生クラスがともに "__init__()" メソ
   ッドを持つ場合、派生クラスの "__init__()" メソッドは基底クラスの
   "__init__()" メソッドを明示的に呼び出して、インスタンスの基底クラス
   部分が適切に初期化されること保証しなければなりません。例えば、
   "super().__init__([args...])" 。

   "__new__()" と "__init__()" は連携してオブジェクトを構成する
   ("__new__()" が作成し、 "__init__()" がそれをカスタマイズする) ので
   、 "__init__()" から非 "None" 値を返してはいけません; そうしてしま
   うと、実行時に "TypeError" が送出されてしまいます。

object.__del__(self)

   インスタンスが破棄されるときに呼び出されます。 これはファイナライザ
   や (適切ではありませんが) デストラクタとも呼ばれます。 基底クラスが
   "__del__()" メソッドを持っている場合は、派生クラスの "__del__()" メ
   ソッドは何であれ、基底クラスの "__del__()"  メソッドを明示的に呼び
   出して、インスタンスの基底クラス部分をきちんと確実に削除しなければ
   なりません。

   "__del__()" メソッドが破棄しようとしているインスタンスへの新しい参
   照を作り、破棄を送らせることは (推奨されないものの) 可能です。 これ
   はオブジェクトの *復活* と呼ばれます。 復活したオブジェクトが再度破
   棄される直前に "__del__()" が呼び出されるかどうかは実装依存です; 現
   在の *CPython* の実装では最初の一回しか呼び出されません。

   It is not guaranteed that "__del__()" methods are called for
   objects that still exist when the interpreter exits.
   "weakref.finalize" provides a straightforward way to register a
   cleanup function to be called when an object is garbage collected.

   注釈:

     "del x" は直接 "x.__del__()" を呼び出しません --- 前者は "x" の参
     照カウントを 1 つ減らし、後者は "x" の参照カウントが 0 まで落ちた
     ときのみ呼び出されます。

   **CPython 実装の詳細:** It is possible for a reference cycle to
   prevent the reference count of an object from going to zero.  In
   this case, the cycle will be later detected and deleted by the
   *cyclic garbage collector*.  A common cause of reference cycles is
   when an exception has been caught in a local variable.  The frame's
   locals then reference the exception, which references its own
   traceback, which references the locals of all frames caught in the
   traceback.

   参考: "gc" モジュールのドキュメント。

   警告:

     メソッド "__del__()" は不安定な状況で呼び出されるため、実行中に発
     生した例外は無視され、代わりに "sys.stderr" に警告が表示されます
     。特に:

     * "__del__()" は、任意のコードが実行されているときに、任意のスレ
       ッドから呼び出せます。 "__del__()" で、ロックを取ったり、ブロッ
       クするリソースを呼び出したりする必要がある場合、 "__del__()" の
       実行により中断されたコードにより、そのリソースが既に取得されて
       いて、デッドロックが起きるかもしれません。

     * "__del__()" は、インタプリタのシャットダウン中に実行できます。
       従って、(他のモジュールも含めた) アクセスする必要があるグローバ
       ル変数はすでに削除されているか、 "None" に設定されているかもし
       れません。 Python は、単一のアンダースコアで始まる名前のグロー
       バルオブジェクトは、他のグローバル変数が削除される前にモジュー
       ルから削除されることを保証します; そのようなグローバル変数への
       他からの参照が存在しない場合、"__del__()" メソッドが呼ばれた時
       点で、インポートされたモジュールがまだ利用可能であることを保証
       するのに役立つかもしれません。

object.__repr__(self)

   "repr()" 組み込み関数によって呼び出され、オブジェクトを表す「公式の
   (official)」文字列を計算します。可能なら、これは (適切な環境が与え
   られれば) 同じ値のオブジェクトを再生成するのに使える、有効な Python
   式のようなものであるべきです。できないなら、 "<...some useful
   description...>" 形式の文字列が返されるべきです。戻り値は文字列オブ
   ジェクトでなければなりません。クラスが "__repr__()" を定義していて
   "__str__()" は定義していなければ、そのクラスのインスタンスの「非公
   式の (informal)」文字列表現が要求されたときにも "__repr__()" が使わ
   れます。

   This is typically used for debugging, so it is important that the
   representation is information-rich and unambiguous. A default
   implementation is provided by the "object" class itself.

object.__str__(self)

   Called by "str(object)", the default "__format__()" implementation,
   and the built-in function "print()", to compute the "informal" or
   nicely printable string representation of an object.  The return
   value must be a str object.

   "__str__()" が有効な Python 表現を返すことが期待されないという点で
   、このメソッドは "object.__repr__()" とは異なります: より便利な、ま
   たは簡潔な表現を使用することができます。

   組み込み型 "object" によって定義されたデフォルト実装は、
   "object.__repr__()" を呼び出します。

object.__bytes__(self)

   Called by bytes to compute a byte-string representation of an
   object. This should return a "bytes" object. The "object" class
   itself does not provide this method.

object.__format__(self, format_spec)

   "format()" 組み込み関数、さらには フォーマット済み文字列リテラル の
   評価、 "str.format()" メソッドによって呼び出され、オブジェクトの "
   フォーマット化された (formatted)" 文字列表現を作ります。
   *format_spec* 引数は、 必要なフォーマット化オプションの記述を含む文
   字列です。 *format_spec* 引数の解釈は、 "__format__()" を実装する型
   によりますが、 ほとんどのクラスは組み込み型のいずれかにフォーマット
   化を委譲したり、 同じようなフォーマット化オプション構文を使います。

   標準のフォーマット構文の解説は、 書式指定ミニ言語仕様 を参照してく
   ださい。

   戻り値は文字列オブジェクトでなければなりません。

   The default implementation by the "object" class should be given an
   empty *format_spec* string. It delegates to "__str__()".

   バージョン 3.4 で変更: 空でない文字列が渡された場合 "object" 自身の
   __format__ メソッドは "TypeError" を送出します。

   バージョン 3.7 で変更: "object.__format__(x, '')" は
   "format(str(x), '')" ではなく "str(x)" と等価になりました。

object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)

   これらはいわゆる "拡張比較 (rich comparison)" メソッドです。演算子
   シンボルとメソッド名の対応は以下の通りです: "x<y" は "x.__lt__(y)"
   を呼び出します; "x<=y" は "x.__le__(y)" を呼び出します; "x==y" は
   "x.__eq__(y)" を呼び出します; "x!=y" は "x.__ne__(y)" を呼び出しま
   す; "x>y" は "x.__gt__(y)" を呼び出します; "x>=y" は "x.__ge__(y)"
   を呼び出します。

   A rich comparison method may return the singleton "NotImplemented"
   if it does not implement the operation for a given pair of
   arguments. By convention, "False" and "True" are returned for a
   successful comparison. However, these methods can return any value,
   so if the comparison operator is used in a Boolean context (e.g.,
   in the condition of an "if" statement), Python will call "bool()"
   on the value to determine if the result is true or false.

   By default, "object" implements "__eq__()" by using "is", returning
   "NotImplemented" in the case of a false comparison: "True if x is y
   else NotImplemented". For "__ne__()", by default it delegates to
   "__eq__()" and inverts the result unless it is "NotImplemented".
   There are no other implied relationships among the comparison
   operators or default implementations; for example, the truth of
   "(x<y or x==y)" does not imply "x<=y". To automatically generate
   ordering operations from a single root operation, see
   "functools.total_ordering()".

   By default, the "object" class provides implementations consistent
   with 値の比較: equality compares according to object identity, and
   order comparisons raise "TypeError". Each default method may
   generate these results directly, but may also return
   "NotImplemented".

   カスタムの比較演算をサポートしていて、辞書のキーに使うことができる
   *ハッシュ可能* オブジェクトを作るときの重要な注意点について、
   "__hash__()" のドキュメント内に書かれているので参照してください。

   There are no swapped-argument versions of these methods (to be used
   when the left argument does not support the operation but the right
   argument does); rather, "__lt__()" and "__gt__()" are each other's
   reflection, "__le__()" and "__ge__()" are each other's reflection,
   and "__eq__()" and "__ne__()" are their own reflection. If the
   operands are of different types, and the right operand's type is a
   direct or indirect subclass of the left operand's type, the
   reflected method of the right operand has priority, otherwise the
   left operand's method has priority.  Virtual subclassing is not
   considered.

   When no appropriate method returns any value other than
   "NotImplemented", the "==" and "!=" operators will fall back to
   "is" and "is not", respectively.

object.__hash__(self)

   組み込みの "hash()" 関数や、 "set", "frozenset", "dict" のようなハ
   ッシュを使ったコレクション型の要素に対する操作から呼び出されます。
   "__hash__()" メソッドは整数を返さなければなりません。 このメソッド
   に必要な性質は、比較結果が等しいオブジェクトは同じハッシュ値を持つ
   ということです; オブジェクトを比較するときでも利用される要素をタプ
   ルに詰めてハッシュ値を計算することで、それぞれの要素のハッシュ値を
   混合することをおすすめします。

      def __hash__(self):
          return hash((self.name, self.nick, self.color))

   注釈:

     "hash()" はオブジェクト独自の "__hash__()"  メソッドが返す値を
     "Py_ssize_t" のサイズに切り詰めます。 これは 64-bit でビルドされ
     ていると 8 バイトで、 32-bit でビルドされていると 4 バイトです。
     オブジェクトの "__hash__()" が異なる bit サイズのビルドでも可搬性
     が必要である場合は、必ず全てのサポートするビルドの bit 幅をチェッ
     クしてください。 そうする簡単な方法は "python -c "import sys;
     print(sys.hash_info.width)"" を実行することです。

   クラスが "__eq__()" メソッドを定義していないなら、 "__hash__()" メ
   ソッドも定義してはなりません; クラスが "__eq__()" を定義していても
   "__hash__()" を定義していないなら、そのインスタンスはハッシュ可能コ
   レクションの要素として使えません。クラスがミュータブルなオブジェク
   トを定義しており、 "__eq__()" メソッドを実装しているなら、
   "__hash__()" を定義してはなりません。これは、*ハッシュ可能* コレク
   ションの実装においてキーのハッシュ値がイミュータブルであることが要
   求されているからです (オブジェクトのハッシュ値が変化すると、誤った
   ハッシュバケツ: hash bucket に入ってしまいます)。

   User-defined classes have "__eq__()" and "__hash__()" methods by
   default (inherited from the "object" class); with them, all objects
   compare unequal (except with themselves) and "x.__hash__()" returns
   an appropriate value such that "x == y" implies both that "x is y"
   and "hash(x) == hash(y)".

   "__eq__()" をオーバーライドしていて "__hash__()" を定義していないク
   ラスでは、 "__hash__()" は暗黙的に "None" に設定されます。 クラスの
   "__hash__()" メソッドが "None" の場合、そのクラスのインスタンスのハ
   ッシュ値を取得しようとすると適切な "TypeError" が送出され、
   "isinstance(obj, collections.abc.Hashable)" でチェックするとハッシ
   ュ不能なものとして正しく認識されます。

   "__eq__()" をオーバーライドしたクラスが親クラスからの "__hash__()"
   の 実装を保持したいなら、明示的に "__hash__ =
   <ParentClass>.__hash__" を設定することで、それをインタプリタに伝え
   なければなりません。

   "__eq__()" をオーバーライドしていないクラスがハッシュサポートを抑制
   したい場合、クラス定義に "__hash__ = None" を含めてください。クラス
   自身で明示的に "TypeError" を送出する "__hash__()" を定義すると、
   "isinstance(obj, collections.abc.Hashable)" 呼び出しで誤ってハッシ
   ュ可能と識別されるでしょう。

   注釈:

     デフォルトでは、文字列とバイト列の "__hash__()" 値は予測不可能な
     ランダム値で "ソルト" されます。 ハッシュ値は単独の Python プロセ
     ス内では定数であり続けますが、Python を繰り返し起動する毎に、予測
     できなくなります。This is intended to provide protection against
     a denial-of-service caused by carefully chosen inputs that
     exploit the worst case performance of a dict insertion,
     *O*(*n*^2) complexity.  See
     http://ocert.org/advisories/ocert-2011-003.html for details.ハッ
     シュ値の変更は、集合のイテレーション順序に影響します。Python はこ
     の順序付けを保証していません (そして通常 32-bit と 64-bit の間で
     も異なります)。"PYTHONHASHSEED" も参照してください。

   バージョン 3.3 で変更: ハッシュのランダム化がデフォルトで有効になり
   ました。

object.__bool__(self)

   Called to implement truth value testing and the built-in operation
   "bool()"; should return "False" or "True".  When this method is not
   defined, "__len__()" is called, if it is defined, and the object is
   considered true if its result is nonzero.  If a class defines
   neither "__len__()" nor "__bool__()" (which is true of the "object"
   class itself), all its instances are considered true.


3.3.2. 属性値アクセスをカスタマイズする
---------------------------------------

以下のメソッドを定義して、クラスインスタンスへの属性アクセス (
"x.name" の使用、 "x.name" への代入、 "x.name" の削除) の意味をカスタ
マイズすることができます。

object.__getattr__(self, name)

   Called when the default attribute access fails with an
   "AttributeError" (either "__getattribute__()" raises an
   "AttributeError" because *name* is not an instance attribute or an
   attribute in the class tree for "self"; or "__get__()" of a *name*
   property raises "AttributeError").  This method should either
   return the (computed) attribute value or raise an "AttributeError"
   exception. The "object" class itself does not provide this method.

   Note that if the attribute is found through the normal mechanism,
   "__getattr__()" is not called.  (This is an intentional asymmetry
   between "__getattr__()" and "__setattr__()".) This is done both for
   efficiency reasons and because otherwise "__getattr__()" would have
   no way to access other attributes of the instance.  Note that at
   least for instance variables, you can take total control by not
   inserting any values in the instance attribute dictionary (but
   instead inserting them in another object).  See the
   "__getattribute__()" method below for a way to actually get total
   control over attribute access.

object.__getattribute__(self, name)

   クラスのインスタンスに対する属性アクセスを実装するために、無条件に
   呼び出されます。クラスが "__getattr__()" も定義している場合、
   "__getattr__()" は、 "__getattribute__()" で明示的に呼び出すか、
   "AttributeError" 例外を送出しない限り呼ばれません。このメソッドは (
   計算された) 属性値を返すか、 "AttributeError" 例外を送出します。こ
   のメソッドが再帰的に際限なく呼び出されてしまうのを防ぐため、実装の
   際には常に、必要な属性全てへのアクセスで、例えば
   "object.__getattribute__(self, name)" のように基底クラスのメソッド
   を同じ属性名を使って呼び出さなければなりません。

   注釈:

     This method may still be bypassed when looking up special methods
     as the result of implicit invocation via language syntax or
     built-in functions. See 特殊メソッド検索.

   セキュリティに関わるような "obj" と "name" を渡しての
   "object.__getattr__" を使った属性アクセスは 監査イベント を送出しま
   す。

object.__setattr__(self, name, value)

   属性の代入が試みられた際に呼び出されます。これは通常の代入の過程 (
   すなわち、インスタンス辞書への値の代入) の代わりに呼び出されます。
   *name* は属性名で、*value* はその属性に代入する値です。

   "__setattr__()" の中でインスタンス属性への代入が必要なら、基底クラ
   スのこれと同じ名前のメソッドを呼び出さなければなりません。例えば、
   "object.__setattr__(self, name, value)" とします。

   セキュリティに関わるような "obj" と "name" と "value" を渡しての
   "object.__setattr__" を使った属性のアサインは 監査イベント を送出し
   ます。

object.__delattr__(self, name)

   "__setattr__()" に似ていますが、代入ではなく値の削除を行います。こ
   のメソッドを実装するのは、オブジェクトにとって "del obj.name" が意
   味がある場合だけにしなければなりません。

   セキュリティに関わるような "obj" と "name" を渡しての
   "object.__getattr__" を使った属性の削除は 監査イベント を送出します
   。

object.__dir__(self)

   Called when "dir()" is called on the object. An iterable must be
   returned. "dir()" converts the returned iterable to a list and
   sorts it.


3.3.2.1. モジュールの属性値アクセスをカスタマイズする
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

module.__getattr__()
module.__dir__()

特殊な名前の "__getattr__" と "__dir__" も、モジュール属性へのアクセス
をカスタマイズするのに使えます。 モジュールレベルの "__getattr__" 関数
は属性名である 1 引数を受け取り、計算した値を返すか "AttributeError"
を送出します。 属性がモジュールオブジェクトから、通常の検索、つまり
"object.__getattribute__()" で見付からなかった場合は、
"AttributeError" を送出する前に、モジュールの "__dict__" から
"__getattr__" が検索されます。 見付かった場合は、その属性名で呼び出さ
れ、結果が返されます。

The "__dir__" function should accept no arguments, and return an
iterable of strings that represents the names accessible on module. If
present, this function overrides the standard "dir()" search on a
module.

module.__class__

より細かい粒度でのモジュールの動作 (属性やプロパティの設定など) のカス
タマイズのために、モジュールオブジェクトの "__class__" 属性に
"types.ModuleType" のサブクラスが設定できます。 例えば次のようになりま
す:

   import sys
   from types import ModuleType

   class VerboseModule(ModuleType):
       def __repr__(self):
           return f'Verbose {self.__name__}'

       def __setattr__(self, attr, value):
           print(f'Setting {attr}...')
           super().__setattr__(attr, value)

   sys.modules[__name__].__class__ = VerboseModule

注釈:

  モジュールの "__getattr__" を定義したり "__class__" を設定したりして
  も、影響があるのは属性アクセスの構文が使われる検索だけです -- モジュ
  ールの globals への直接アクセスは (モジュール内のコードからとモジュ
  ールの globals のどちらでも) 影響を受けません。

バージョン 3.5 で変更: モジュールの属性 "__class__" が書き込み可能にな
りました。

Added in version 3.7: "__getattr__" モジュール属性と "__dir__" モジュ
ール属性。

参考:

  **PEP 562** - モジュールの __getattr__ と __dir__
     モジュールの "__getattr__" 関数および "__dir__" 関数の説明。


3.3.2.2. デスクリプタ (descriptor) の実装
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following methods only apply when an instance of the class
containing the method (a so-called *descriptor* class) appears in an
*owner* class (the descriptor must be in either the owner's class
dictionary or in the class dictionary for one of its parents).  In the
examples below, "the attribute" refers to the attribute whose name is
the key of the property in the owner class' "__dict__".  The "object"
class itself does not implement any of these protocols.

object.__get__(self, instance, owner=None)

   オーナークラス（クラス属性アクセスの場合）や、クラスのインスタンス
   （インスタンス属性アクセスの場合）の属性取得時に呼び出されます。
   *instance*  を通じて属性をアクセスする時に、オプションの *owner* 引
   数はオーナークラスです。 *owner* を通じて属性アクセスするときは
   "None" です。

   このメソッドは、算出された属性値を返すか、 "AttributeError" 例外を
   送出します。

   **PEP 252** は "__get__()" は1つや2つの引数を持つ呼び出し可能オブジ
   ェクトであると定義しています。Pythonの組み込みのデスクリプタはこの
   仕様をサポートしていますが、サードパーティ製のツールの中には両方の
   引数を必要とするものもあります。Pythonの "__getattribute__()" 実装
   は必要かどうかに関わらず、両方の引数を常に渡します。

object.__set__(self, instance, value)

   オーナークラスのインスタンス *instance* 上の属性を新たな値 *value*
   に設定する際に呼び出されます。

   "__set__()" あるいは "__delete__()" を追加すると、デスクリプタは「
   データデスクリプタ」に変わります。詳細は デスクリプタの呼び出し を
   参照してください。

object.__delete__(self, instance)

   オーナークラスのインスタンス *instance* 上の属性を削除する際に呼び
   出されます。

Instances of descriptors may also have the "__objclass__" attribute
present:

object.__objclass__

   The attribute "__objclass__" is interpreted by the "inspect" module
   as specifying the class where this object was defined (setting this
   appropriately can assist in runtime introspection of dynamic class
   attributes). For callables, it may indicate that an instance of the
   given type (or a subclass) is expected or required as the first
   positional argument (for example, CPython sets this attribute for
   unbound methods that are implemented in C).


3.3.2.3. デスクリプタの呼び出し
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

一般にデスクリプタとは、特殊な "束縛に関する動作 (binding behaviour)"
をもつオブジェクト属性のことです。デスクリプタは、デスクリプタプロトコ
ル (descriptor protocol) のメソッド: "__get__()", "__set__()", および
"__delete__()" を使って、属性アクセスをオーバーライドしているものです
。これらのメソッドのいずれかがオブジェクトに対して定義されている場合、
オブジェクトはデスクリプタであるといいます。

属性アクセスのデフォルトの動作は、オブジェクトの辞書から値を取り出した
り、値を設定したり、削除したりするというものです。例えば、 "a.x" によ
る属性の検索では、まず "a.__dict__['x']" 、次に
"type(a).__dict__['x']" 、そして "type(a)" の基底クラスでメタクラスで
ないものに続く、といった具合に連鎖が起こります。

しかし、検索対象の値が、デスクリプタメソッドのいずれかを定義しているオ
ブジェクトであれば、Python はデフォルトの動作をオーバーライドして、代
わりにデスクリプタメソッドを呼び出します。先述の連鎖の中のどこでデスク
リプタメソッドが呼び出されるかは、どのデスクリプタメソッドが定義されて
いて、どのように呼び出されたかに依存します。

デスクリプタ呼び出しの基点となるのは、属性名への束縛 (binding) 、すな
わち "a.x" です。引数がどのようにデスクリプタに結合されるかは "a" に依
存します:

直接呼び出し (Direct Call)
   最も単純で、かつめったに使われない呼び出し操作は、コード中で直接デ
   スクリプタメソッドの呼び出し: "x.__get__(a)" を行うというものです。

インスタンス束縛 (Instance Binding)
   オブジェクトインスタンスへ束縛すると、"a.x" は呼び出し
   "type(a).__dict__['x'].__get__(a, type(a))" に変換されます。

クラス束縛 (Class Binding)
   クラスへ束縛すると、"A.x" は呼び出し "A.__dict__['x'].__get__(None,
   A)" に変換されます。

super 束縛 (Super Binding)
   "super(A, a).x" のようなドットを使ったルックアップは
   "a.__class__.__mro__" を探索して、 "A" の前のクラス "B" をまず探し
   、 "B.__dict__['x'].__get__(a, A)" を返します。もしデスクリプタでな
   ければ "x" を変更せずに返します。

For instance bindings, the precedence of descriptor invocation depends
on which descriptor methods are defined.  A descriptor can define any
combination of "__get__()", "__set__()" and "__delete__()".  If it
does not define "__get__()", then accessing the attribute will return
the descriptor object itself unless there is a value in the object's
instance dictionary.  If the descriptor defines "__set__()" and/or
"__delete__()", it is a data descriptor; if it defines neither, it is
a non-data descriptor.  Normally, data descriptors define both
"__get__()" and "__set__()", while non-data descriptors have just the
"__get__()" method.  Data descriptors with "__get__()" and "__set__()"
(and/or "__delete__()") defined always override a redefinition in an
instance dictionary.  In contrast, non-data descriptors can be
overridden by instances.

Python methods (including those decorated with "@staticmethod" and
"@classmethod") are implemented as non-data descriptors.  Accordingly,
instances can redefine and override methods.  This allows individual
instances to acquire behaviors that differ from other instances of the
same class.

"property()" 関数はデータデスクリプタとして実装されています。従って、
インスタンスはあるプロパティの動作をオーバーライドすることができません
。


3.3.2.4. __slots__
~~~~~~~~~~~~~~~~~~

*__slots__* を使うと、(プロパティのように) データメンバを明示的に宣言
し、 (明示的に *__slots__* で宣言しているか親クラスに存在しているかで
ない限り) "__dict__" や *__weakref__* を作成しないようにできます。

"__dict__" を使うのに比べて、節約できるメモリ空間はかなり大きいです。
属性探索のスピードもかなり向上できます。

object.__slots__

   このクラス変数には、インスタンスが用いる変数名を表す、文字列、イテ
   ラブル、または文字列のシーケンスを代入できます。*__slots__* は、各
   インスタンスに対して宣言された変数に必要な記憶領域を確保し、
   "__dict__" と *__weakref__* が自動的に生成されないようにします。

Notes on using *__slots__*:

* *__slots__* を持たないクラスから継承するとき、インスタンスの
  "__dict__" 属性と *__weakref__* 属性は常に利用可能です。

* "__dict__" 変数がない場合、 *__slots__* に列挙されていない新たな変数
  をインスタンスに代入することはできません。列挙されていない変数名を使
  って代入しようとした場合、 "AttributeError" が送出されます。新たな変
  数を動的に代入したいのなら、 *__slots__* を宣言する際に "'__dict__'"
  を変数名のシーケンスに追加してください。

* *__slots__* を定義しているクラスの各インスタンスに *__weakref__* 変
  数がない場合、インスタンスに対する弱参照 ("weak references") はサポ
  ートされません。弱参照のサポートが必要なら、 *__slots__* を宣言する
  際に "'__weakref__'" を変数名のシーケンスに追加してください。

* *__slots__* は、クラスのレベルで各変数に対する デスクリプタ を使って
  実装されます。その結果、 *__slots__* に定義されているインスタンス変
  数のデフォルト値はクラス属性を使って設定できなくなっています; そうし
  ないと、デスクリプタによる代入をクラス属性が上書きしてしまうからです
  。

* The action of a *__slots__* declaration is not limited to the class
  where it is defined.  *__slots__* declared in parents are available
  in child classes. However, instances of a child subclass will get a
  "__dict__" and *__weakref__* unless the subclass also defines
  *__slots__* (which should only contain names of any *additional*
  slots).

* あるクラスで、基底クラスですでに定義されているスロットを定義した場合
  、基底クラスのスロットで定義されているインスタンス変数は (デスクリプ
  タを基底クラスから直接取得しない限り) アクセスできなくなります。これ
  により、プログラムの趣意が不定になってしまいます。将来は、この問題を
  避けるために何らかのチェックが追加されるかもしれません。

* "TypeError" will be raised if nonempty *__slots__* are defined for a
  class derived from a ""variable-length" built-in type" such as
  "int", "bytes", and "tuple".

* Any non-string *iterable* may be assigned to *__slots__*.

* If a "dictionary" is used to assign *__slots__*, the dictionary keys
  will be used as the slot names. The values of the dictionary can be
  used to provide per-attribute docstrings that will be recognised by
  "inspect.getdoc()" and displayed in the output of "help()".

* "__class__" assignment works only if both classes have the same
  *__slots__*.

* 複数のスロットを持つ親クラスを使った 多重継承 はできますが、スロット
  で作成された属性を持つ親クラスは 1 つに限られます (他の基底クラスの
  スロットは空でなければなりません) - それに違反すると "TypeError" が
  送出されます。

* もし *__slots__* に対して *イテレータ* を使用すると、イテレータの値
  ごとに *デスクリプタ* が作られます。しかし、 *__slots__* 属性は空の
  イテレータとなります。


3.3.3. クラス生成をカスタマイズする
-----------------------------------

クラスが他のクラスを継承するときに必ず、親クラスの
"__init_subclass__()" が呼び出されます。これを利用すると、サブクラスの
挙動を変更するクラスを書くことができます。これは、クラスデコレータとと
ても良く似ていますが、クラスデコレータが、それが適用された特定のクラス
にのみに影響するのに対して、 "__init_subclass__" は、もっぱら、このメ
ソッドを定義したクラスの将来のサブクラスに適用されます。

classmethod object.__init_subclass__(cls)

   このメソッドは、それが定義されたクラスが継承された際に必ず呼び出さ
   れます。*cls* は新しいサブクラスです。もし、このメソッドがインスタ
   ンスメソッドとして定義されると、暗黙的にクラスメソッドに変換されま
   す。

   Keyword arguments which are given to a new class are passed to the
   parent class's "__init_subclass__". For compatibility with other
   classes using "__init_subclass__", one should take out the needed
   keyword arguments and pass the others over to the base class, as
   in:

      class Philosopher:
          def __init_subclass__(cls, /, default_name, **kwargs):
              super().__init_subclass__(**kwargs)
              cls.default_name = default_name

      class AustralianPhilosopher(Philosopher, default_name="Bruce"):
          pass

   "object.__init_subclass__" のデフォルト実装は何も行いませんが、何ら
   かの引数とともに呼び出された場合は、エラーを送出します。

   注釈:

     メタクラスのヒント "metaclass" は残りの型機構によって消費され、
     "__init_subclass__" 実装に渡されることはありません。 実際のメタク
     ラス (明示的なヒントではなく) は、 "type(cls)" としてアクセスでき
     ます。

   Added in version 3.6.

When a class is created, "type.__new__()" scans the class variables
and makes callbacks to those with a "__set_name__()" hook.

object.__set_name__(self, owner, name)

   オーナーとなるクラス *owner* が作成された時点で自動的に呼び出されま
   す。 オブジェクトはそのクラスの *name* に割り当てられます。

      class A:
          x = C()  # Automatically calls: x.__set_name__(A, 'x')

   If the class variable is assigned after the class is created,
   "__set_name__()" will not be called automatically. If needed,
   "__set_name__()" can be called directly:

      class A:
         pass

      c = C()
      A.x = c                  # The hook is not called
      c.__set_name__(A, 'x')   # Manually invoke the hook

   詳細は クラスオブジェクトの作成 を参照してください。

   Added in version 3.6.


3.3.3.1. メタクラス
~~~~~~~~~~~~~~~~~~~

デフォルトでは、クラスは "type()" を使って構築されます。 クラス本体は
新しい名前空間で実行され、クラス名が "type(name, bases, namespace)" の
結果にローカルに束縛されます。

クラス生成プロセスはカスタマイズできます。 そのためにはクラス定義行で
"metaclass" キーワード引数を渡すか、そのような引数を定義行に含む既存の
クラスを継承します。 次の例で "MyClass" と "MySubclass" は両方とも
"Meta" のインスタンスです:

   class Meta(type):
       pass

   class MyClass(metaclass=Meta):
       pass

   class MySubclass(MyClass):
       pass

クラス定義の中で指定された他のキーワード引数は、後述するすべてのメタク
ラス操作に渡されます。

クラス定義が実行される際に、以下のステップが生じます:

* MRO エントリの解決が行われる;

* 適切なメタクラスが決定される;

* クラスの名前空間が準備される;

* クラスの本体が実行される;

* クラスオブジェクトが作られる。


3.3.3.2. MRO エントリの解決
~~~~~~~~~~~~~~~~~~~~~~~~~~~

object.__mro_entries__(self, bases)

   If a base that appears in a class definition is not an instance of
   "type", then an "__mro_entries__()" method is searched on the base.
   If an "__mro_entries__()" method is found, the base is substituted
   with the result of a call to "__mro_entries__()" when creating the
   class. The method is called with the original bases tuple passed to
   the *bases* parameter, and must return a tuple of classes that will
   be used instead of the base. The returned tuple may be empty: in
   these cases, the original base is ignored.

参考:

  "types.resolve_bases()"
     Dynamically resolve bases that are not instances of "type".

  "types.get_original_bases()"
     Retrieve a class's "original bases" prior to modifications by
     "__mro_entries__()".

  **PEP 560**
     Core support for typing module and generic types.


3.3.3.3. 適切なメタクラスの決定
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

クラス定義に対して適切なメタクラスは、以下のように決定されます:

* 基底も明示的なメタクラスも与えられていない場合は、 "type()" が使われ
  ます;

* 明示的なメタクラスが与えられていて、それが "type()" のインスタンス *
  ではない* 場合、それをメタクラスとして直接使います;

* 明示的なメタクラスとして "type()" のインスタンスが与えられたか、基底
  が定義されていた場合は、最も派生した (継承関係で最も下の) メタクラス
  が使われます。

最も派生的なメタクラスは、(もしあれば) 明示的に指定されたメタクラスと
、指定されたすべてのベースクラスのメタクラスから選ばれます。最も派生的
なメタクラスは、これらのメタクラス候補のすべてのサブタイプであるような
ものです。メタクラス候補のどれもその基準を満たさなければ、クラス定義は
"TypeError" で失敗します。


3.3.3.4. クラスの名前空間の準備
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

適切なメタクラスが指定されると、クラスの名前空間が用意されます。もしメ
タクラスが "__prepare__" 属性を持っている場合、 "namespace =
metaclass.__prepare__(name, bases, **kwds)" が呼ばれます。追加のキーワ
ード引数は、もしクラス定義にあれば設定されます。 "__prepare__" メソッ
ドは "クラスメソッド" として実装する必要があります。 "__prepare__" が
作成して返した名前空間は "__new__" に渡されますが、最終的なクラスオブ
ジェクトは新しい "dict" にコピーして作成されます。

メタクラスに "__prepare__" 属性がない場合、クラスの名前空間は空の 順序
付きマッピングとして初期化されます。

参考:

  **PEP 3115** - Metaclasses in Python 3000
     "__prepare__" 名前空間フックの導入


3.3.3.5. クラス本体の実行
~~~~~~~~~~~~~~~~~~~~~~~~~

クラス本体が (大まかには) "exec(body, globals(), namespace)" として実
行されます。通常の呼び出しと "exec()" の重要な違いは、クラス定義が関数
内部で行われる場合、レキシカルスコープによってクラス本体 (任意のメソッ
ドを含む) が現在のスコープと外側のスコープから名前を参照できるという点
です。

しかし、クラス定義が関数内部で行われる時でさえ、クラス内部で定義された
メソッドはクラススコープで定義された名前を見ることはできません。クラス
変数はインスタンスメソッドかクラスメソッドの最初のパラメータからアクセ
スするか、次の節で説明する、暗黙的に静的スコープが切られている
"__class__" 参照からアクセスしなければなりません。


3.3.3.6. クラスオブジェクトの作成
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

クラス本体の実行によってクラスの名前空間が初期化されたら、
"metaclass(name, bases, namespace, **kwds)" を呼び出すことでクラスオブ
ジェクトが作成されます (ここで渡される追加のキーワードは "__prepare__"
に渡されるものと同じです)。

このクラスオブジェクトは、 "super()" の無引数形式によって参照されるも
のです。 "__class__" は、クラス本体中のメソッドが "__class__" または
"super" のいずれかを参照している場合に、コンパイラによって作成される暗
黙のクロージャー参照です。これは、メソッドに渡された最初の引数に基づい
て現在の呼び出しを行うために使用されるクラスまたはインスタンスが識別さ
れる一方、 "super()" の無引数形式がレキシカルスコープに基づいて定義さ
れているクラスを正確に識別することを可能にします。

CPython 3.6 以降では、 "__class__" セルは、クラス名前空間にある
"__classcell__" エントリーとしてメタクラスに渡されます。 "__class__"
セルが存在していた場合は、そのクラスが正しく初期化されるために、
"type.__new__" の呼び出しに到達するまで上に伝搬されます。 失敗した場合
は、Python 3.8 では "RuntimeError" になります。

デフォルトのメタクラス "type" や最終的には "type.__new__" を呼び出すメ
タクラスを使っているときは、クラスオブジェクトを作成した後に次のカスタ
ム化の手順が起動されます:

1. "type.__new__" メソッドが "__set_name__()" が定義されているクラスの
   名前空間にある全ての属性を収集します;

2. それらの "__set_name__" メソッドが、そのメソッドが定義されているク
   ラス、およびそこに属する属性に割り当てられている名前を引数として呼
   び出されます;

3. 新しいクラスのメソッド解決順序ですぐ上に位置する親クラスで
   "__init_subclass__()" フックが呼び出されます。

クラスオブジェクトが作成された後には、クラス定義に含まれているクラスデ
コレータ (もしあれば) にクラスオブジェクトが渡され、デコレータが返すオ
ブジェクトがここで定義されたクラスとしてローカルの名前空間に束縛されま
す。

When a new class is created by "type.__new__", the object provided as
the namespace parameter is copied to a new ordered mapping and the
original object is discarded. The new copy is wrapped in a read-only
proxy, which becomes the "__dict__" attribute of the class object.

参考:

  **PEP 3135** - New super
     暗黙の "__class__" クロージャ参照について記述しています


3.3.3.7. メタクラスの用途
~~~~~~~~~~~~~~~~~~~~~~~~~

メタクラスは限りない潜在的利用価値を持っています。これまで試されてきた
アイデアには、列挙型、ログ記録、インターフェースのチェック、 自動デリ
ゲーション、自動プロパティ生成、プロキシ、フレームワーク、そして自動リ
ソースロック／同期といったものがあります。


3.3.4. インスタンスのカスタマイズとサブクラスチェック
-----------------------------------------------------

以下のメソッドは組み込み関数 "isinstance()" と "issubclass()" のデフォ
ルトの動作を上書きするのに利用します。

特に、 "abc.ABCMeta" メタクラスは、抽象基底クラス (ABCs) を"仮想基底ク
ラス (virtual base classes)" として、他の ABC を含む、任意のクラスや (
組み込み型を含む) 型に追加するために、これらのメソッドを実装しています
。

type.__instancecheck__(self, instance)

   *instance* が (直接、または間接的に) *class* のインスタンスと考えら
   れる場合に true を返します。定義されていれば、
   "isinstance(instance, class)" の実装のために呼び出されます。

type.__subclasscheck__(self, subclass)

   *subclass* が (直接、または間接的に) *class* のサブクラスと考えられ
   る場合に true を返します。定義されていれば、 "issubclass(subclass,
   class)" の実装のために呼び出されます。

なお、これらのメソッドは、クラスの型 (メタクラス) 上で検索されます。実
際のクラスにクラスメソッドとして定義することはできません。これは、イン
スタンスそれ自体がクラスであるこの場合にのみ、インスタンスに呼び出され
る特殊メソッドの検索と一貫しています。

参考:

  **PEP 3119** - 抽象基底クラスの導入
     Includes the specification for customizing "isinstance()" and
     "issubclass()" behavior through "__instancecheck__()" and
     "__subclasscheck__()", with motivation for this functionality in
     the context of adding Abstract Base Classes (see the "abc"
     module) to the language.


3.3.5. ジェネリック型をエミュレートする
---------------------------------------

When using *type annotations*, it is often useful to *parameterize* a
*generic type* using Python's square-brackets notation. For example,
the annotation "list[int]" might be used to signify a "list" in which
all the elements are of type "int".

参考:

  **PEP 484** - 型ヒント
     Introducing Python's framework for type annotations

  Generic Alias Types
     Documentation for objects representing parameterized generic
     classes

  ジェネリクス, user-defined generics and "typing.Generic"
     実行時にパラメータ設定が可能であり、かつ静的な型チェッカーが理解
     できるジェネリッククラスを実装する方法のドキュメントです。

A class can *generally* only be parameterized if it defines the
special class method "__class_getitem__()".

classmethod object.__class_getitem__(cls, key)

   *key* にある型引数で特殊化されたジェネリッククラスを表すオブジェク
   トを返します。

   When defined on a class, "__class_getitem__()" is automatically a
   class method. As such, there is no need for it to be decorated with
   "@classmethod" when it is defined.


3.3.5.1. The purpose of *__class_getitem__*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The purpose of "__class_getitem__()" is to allow runtime
parameterization of standard-library generic classes in order to more
easily apply *type hints* to these classes.

To implement custom generic classes that can be parameterized at
runtime and understood by static type-checkers, users should either
inherit from a standard library class that already implements
"__class_getitem__()", or inherit from "typing.Generic", which has its
own implementation of "__class_getitem__()".

Custom implementations of "__class_getitem__()" on classes defined
outside of the standard library may not be understood by third-party
type-checkers such as mypy. Using "__class_getitem__()" on any class
for purposes other than type hinting is discouraged.


3.3.5.2. *__class_getitem__* versus *__getitem__*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Usually, the subscription of an object using square brackets will call
the "__getitem__()" instance method defined on the object's class.
However, if the object being subscribed is itself a class, the class
method "__class_getitem__()" may be called instead.
"__class_getitem__()" should return a GenericAlias object if it is
properly defined.

Presented with the *expression* "obj[x]", the Python interpreter
follows something like the following process to decide whether
"__getitem__()" or "__class_getitem__()" should be called:

   from inspect import isclass

   def subscribe(obj, x):
       """Return the result of the expression 'obj[x]'"""

       class_of_obj = type(obj)

       # If the class of obj defines __getitem__,
       # call class_of_obj.__getitem__(obj, x)
       if hasattr(class_of_obj, '__getitem__'):
           return class_of_obj.__getitem__(obj, x)

       # Else, if obj is a class and defines __class_getitem__,
       # call obj.__class_getitem__(x)
       elif isclass(obj) and hasattr(obj, '__class_getitem__'):
           return obj.__class_getitem__(x)

       # Else, raise an exception
       else:
           raise TypeError(
               f"'{class_of_obj.__name__}' object is not subscriptable"
           )

In Python, all classes are themselves instances of other classes. The
class of a class is known as that class's *metaclass*, and most
classes have the "type" class as their metaclass. "type" does not
define "__getitem__()", meaning that expressions such as "list[int]",
"dict[str, float]" and "tuple[str, bytes]" all result in
"__class_getitem__()" being called:

   >>> # list has class "type" as its metaclass, like most classes:
   >>> type(list)
   <class 'type'>
   >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
   True
   >>> # "list[int]" calls "list.__class_getitem__(int)"
   >>> list[int]
   list[int]
   >>> # list.__class_getitem__ returns a GenericAlias object:
   >>> type(list[int])
   <class 'types.GenericAlias'>

However, if a class has a custom metaclass that defines
"__getitem__()", subscribing the class may result in different
behaviour. An example of this can be found in the "enum" module:

   >>> from enum import Enum
   >>> class Menu(Enum):
   ...     """A breakfast menu"""
   ...     SPAM = 'spam'
   ...     BACON = 'bacon'
   ...
   >>> # Enum classes have a custom metaclass:
   >>> type(Menu)
   <class 'enum.EnumMeta'>
   >>> # EnumMeta defines __getitem__,
   >>> # so __class_getitem__ is not called,
   >>> # and the result is not a GenericAlias object:
   >>> Menu['SPAM']
   <Menu.SPAM: 'spam'>
   >>> type(Menu['SPAM'])
   <enum 'Menu'>

参考:

  **PEP 560** - typing モジュールとジェネリック型に対する言語コアによ
  るサポート
     Introducing "__class_getitem__()", and outlining when a
     subscription results in "__class_getitem__()" being called
     instead of "__getitem__()"


3.3.6. 呼び出し可能オブジェクトをエミュレートする
-------------------------------------------------

object.__call__(self[, args...])

   Called when the instance is "called" as a function; if this method
   is defined, "x(arg1, arg2, ...)" roughly translates to
   "type(x).__call__(x, arg1, ...)". The "object" class itself does
   not provide this method.


3.3.7. コンテナをエミュレートする
---------------------------------

The following methods can be defined to implement container objects.
None of them are provided by the "object" class itself. Containers
usually are *sequences* (such as "lists" or "tuples") or *mappings*
(like *dictionaries*), but can represent other containers as well.
The first set of methods is used either to emulate a sequence or to
emulate a mapping; the difference is that for a sequence, the
allowable keys should be the integers *k* for which "0 <= k < N" where
*N* is the length of the sequence, or "slice" objects, which define a
range of items.  It is also recommended that mappings provide the
methods "keys()", "values()", "items()", "get()", "clear()",
"setdefault()", "pop()", "popitem()", "copy()", and "update()"
behaving similar to those for Python's standard "dictionary" objects.
The "collections.abc" module provides a "MutableMapping" *abstract
base class* to help create those methods from a base set of
"__getitem__()", "__setitem__()", "__delitem__()", and "keys()".

Mutable sequences should provide methods "append()", "clear()",
"count()", "extend()", "index()", "insert()", "pop()", "remove()", and
"reverse()", like Python standard "list" objects. Finally, sequence
types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods
"__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
"__imul__()" described below; they should not define other numerical
operators.

It is recommended that both mappings and sequences implement the
"__contains__()" method to allow efficient use of the "in" operator;
for mappings, "in" should search the mapping's keys; for sequences, it
should search through the values.  It is further recommended that both
mappings and sequences implement the "__iter__()" method to allow
efficient iteration through the container; for mappings, "__iter__()"
should iterate through the object's keys; for sequences, it should
iterate through the values.

object.__len__(self)

   Called to implement the built-in function "len()".  Should return
   the length of the object, an integer ">=" 0.  Also, an object that
   doesn't define a "__bool__()" method and whose "__len__()" method
   returns zero is considered to be false in a Boolean context.

   **CPython 実装の詳細:** In CPython, the length is required to be at
   most "sys.maxsize". If the length is larger than "sys.maxsize" some
   features (such as "len()") may raise "OverflowError".  To prevent
   raising "OverflowError" by truth value testing, an object must
   define a "__bool__()" method.

object.__length_hint__(self)

   Called to implement "operator.length_hint()". Should return an
   estimated length for the object (which may be greater or less than
   the actual length). The length must be an integer ">=" 0. The
   return value may also be "NotImplemented", which is treated the
   same as if the "__length_hint__" method didn't exist at all. This
   method is purely an optimization and is never required for
   correctness.

   Added in version 3.4.

注釈:

  スライシングは、以下の 3 メソッドによって排他的に行われます。次のよ
  うな呼び出しは

     a[1:2] = b

  次のように翻訳され

     a[slice(1, 2, None)] = b

  以下も同様です。存在しないスライスの要素は "None" で埋められます。

object.__getitem__(self, key)

   Called to implement evaluation of "self[key]". For *sequence*
   types, the accepted keys should be integers. Optionally, they may
   support "slice" objects as well.  Negative index support is also
   optional. If *key* is of an inappropriate type, "TypeError" may be
   raised; if *key* is a value outside the set of indexes for the
   sequence (after any special interpretation of negative values),
   "IndexError" should be raised. For *mapping* types, if *key* is
   missing (not in the container), "KeyError" should be raised.

   注釈:

     "for" ループでは、シーケンスの終端を正しく検出できるようにするた
     めに、不正なインデクスに対して "IndexError" が送出されるものと期
     待しています。

   注釈:

     When subscripting a *class*, the special class method
     "__class_getitem__()" may be called instead of "__getitem__()".
     See __class_getitem__ versus __getitem__ for more details.

object.__setitem__(self, key, value)

   "self[key]" に対する代入を実装するために呼び出されます。
   "__getitem__()" と同じ注意事項があてはまります。このメソッドを実装
   できるのは、あるキーに対する値の変更をサポートしているか、新たなキ
   ーを追加できるようなマップの場合と、ある要素を置き換えることができ
   るシーケンスの場合だけです。不正な *key* に対しては、
   "__getitem__()" メソッドと同様の例外の送出を行わなければなりません
   。

object.__delitem__(self, key)

   "self[key]" の削除を実装するために呼び出されます。 "__getitem__()"
   と同じ注意事項があてはまります。このメソッドを実装できるのは、キー
   の削除をサポートしているマップの場合と、要素を削除できるシーケンス
   の場合だけです。不正な *key* に対しては、 "__getitem__()" メソッド
   と同様の例外の送出を行わなければなりません。

object.__missing__(self, key)

   "self[key]" の実装において辞書内にキーが存在しなかった場合に、 dict
   のサブクラスのために "dict"."__getitem__()" によって呼び出されます
   。

object.__iter__(self)

   このメソッドは、コンテナに対して *イテレータ* が要求された際に呼び
   出されます。このメソッドは、コンテナ内の全てのオブジェクトに渡って
   反復処理できるような、新たなイテレータオブジェクトを返さなければな
   りません。マッピングでは、コンテナ内のキーに渡って反復処理しなけれ
   ばなりません。

object.__reversed__(self)

   "reversed()" 組み込み関数が逆方向イテレーションを実装するために、(
   存在すれば)呼び出します。コンテナ内の全要素を逆順にイテレートする、
   新しいイテレータを返すべきです。

   "__reversed__()" メソッドが定義されていない場合、 "reversed()" 組込
   み関数は sequence プロトコル ("__len__()" と "__getitem__()") を使
   った方法にフォールバックします。 sequence プロトコルをサポートした
   オブジェクトは、 "reversed()" よりも効率のいい実装を提供できる場合
   にのみ "__reversed__()" を定義するべきです。

帰属テスト演算子 ("in" および "not in") は通常、コンテナの要素に対する
反復処理のように実装されます。しかし、コンテナオブジェクトで以下の特殊
メソッドを定義して、より効率的な実装を行ったり、オブジェクトがイテラブ
ルでなくてもよいようにできます。

object.__contains__(self, item)

   帰属テスト演算を実装するために呼び出されます。 *item* が *self* 内
   に存在する場合には真を、そうでない場合には偽を返さなければなりませ
   ん。マップオブジェクトの場合、値やキーと値の組ではなく、キーに対す
   る帰属テストを考えなければなりません。

   "__contains__()" を定義しないオブジェクトに対しては、メンバシップテ
   ストはまず、 "__iter__()" を使った反復を試みます、次に古いシーケン
   ス反復プロトコル "__getitem__()" を使います、 言語レファレンスのこ
   の節 を参照して下さい。


3.3.8. 数値型をエミュレートする
-------------------------------

以下のメソッドを定義して、数値型オブジェクトをエミュレートすることがで
きます。特定の種類の数値型ではサポートされていないような演算に対応する
メソッド (非整数の数値に対するビット単位演算など) は、未定義のままにし
ておかなければなりません。

object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__matmul__(self, other)
object.__truediv__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
object.__pow__(self, other[, modulo])
object.__lshift__(self, other)
object.__rshift__(self, other)
object.__and__(self, other)
object.__xor__(self, other)
object.__or__(self, other)

   These methods are called to implement the binary arithmetic
   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
   "pow()", "**", "<<", ">>", "&", "^", "|").  For instance, to
   evaluate the expression "x + y", where *x* is an instance of a
   class that has an "__add__()" method, "type(x).__add__(x, y)" is
   called.  The "__divmod__()" method should be the equivalent to
   using "__floordiv__()" and "__mod__()"; it should not be related to
   "__truediv__()".  Note that "__pow__()" should be defined to accept
   an optional third argument if the three-argument version of the
   built-in "pow()" function is to be supported.

   If one of those methods does not support the operation with the
   supplied arguments, it should return "NotImplemented".

object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rmatmul__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other[, modulo])
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)

   These methods are called to implement the binary arithmetic
   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
   "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)
   operands.  These functions are only called if the operands are of
   different types, when the left operand does not support the
   corresponding operation [3], or the right operand's class is
   derived from the left operand's class. [4] For instance, to
   evaluate the expression "x - y", where *y* is an instance of a
   class that has an "__rsub__()" method, "type(y).__rsub__(y, x)" is
   called if "type(x).__sub__(x, y)" returns "NotImplemented" or
   "type(y)" is a subclass of "type(x)". [5]

   Note that "__rpow__()" should be defined to accept an optional
   third argument if the three-argument version of the built-in
   "pow()" function is to be supported.

   バージョン 3.14 で変更: Three-argument "pow()" now try calling
   "__rpow__()" if necessary. Previously it was only called in two-
   argument "pow()" and the binary power operator.

   注釈:

     右側の被演算子の型が左側の被演算子の型のサブクラスであり、このサ
     ブクラスであるメソッドに対する反射メソッドと異なる実装が定義され
     ている場合には、左側の被演算子の非反射メソッドが呼ばれる前に、こ
     のメソッドが呼ばれます。この振る舞いにより、サブクラスが親の演算
     をオーバーライドすることが可能になります。

object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__imatmul__(self, other)
object.__itruediv__(self, other)
object.__ifloordiv__(self, other)
object.__imod__(self, other)
object.__ipow__(self, other[, modulo])
object.__ilshift__(self, other)
object.__irshift__(self, other)
object.__iand__(self, other)
object.__ixor__(self, other)
object.__ior__(self, other)

   These methods are called to implement the augmented arithmetic
   assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",
   "<<=", ">>=", "&=", "^=", "|=").  These methods should attempt to
   do the operation in-place (modifying *self*) and return the result
   (which could be, but does not have to be, *self*).  If a specific
   method is not defined, or if that method returns "NotImplemented",
   the augmented assignment falls back to the normal methods.  For
   instance, if *x* is an instance of a class with an "__iadd__()"
   method, "x += y" is equivalent to "x = x.__iadd__(y)" . If
   "__iadd__()" does not exist, or if "x.__iadd__(y)" returns
   "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are
   considered, as with the evaluation of "x + y". In certain
   situations, augmented assignment can result in unexpected errors
   (see なぜ加算はされるのに a_tuple[i] += ['item'] は例外を送出するの
   ですか?), but this behavior is in fact part of the data model.

object.__neg__(self)
object.__pos__(self)
object.__abs__(self)
object.__invert__(self)

   呼び出して単項算術演算 ("-", "+", "abs()" および "~") を実装します
   。

object.__complex__(self)
object.__int__(self)
object.__float__(self)

   組み込み関数の "complex()", "int()", "float()" の実装から呼び出され
   ます。 適切な型の値を返さなければなりません。

object.__index__(self)

   呼び出して "operator.index()" を実装します。 Python が数値オブジェ
   クトを整数オブジェクトに損失なく変換する必要がある場合 (たとえばス
   ライシングや、組み込みの "bin()" 、 "hex()" 、 "oct()" 関数) は常に
   呼び出されます。 このメソッドがあるとその数値オブジェクトが整数型で
   あることが示唆されます。 整数を返さなければなりません。

   もし "__int__()", "__float__()", "__complex__()" が定義されていない
   場合、組み込み関数の "int()", "float()", "complex()" は
   "__index__()" にフォールバックします。

object.__round__(self[, ndigits])
object.__trunc__(self)
object.__floor__(self)
object.__ceil__(self)

   組み込み関数の "round()" と "math" モジュール関数の "trunc()",
   "floor()", "ceil()" の実装から呼び出されます。 *ndigits* が
   "__round__()" に渡されない限りは、これらの全てのメソッドは
   "Integral" (たいていは "int") に切り詰められたオブジェクトの値を返
   すべきです。

   バージョン 3.14 で変更: "int()" no longer delegates to the
   "__trunc__()" method.


3.3.9. with文とコンテキストマネージャ
-------------------------------------

コンテキストマネージャ(*context manager*) とは、 "with" 文の実行時にラ
ンタイムコンテキストを定義するオブジェクトです。コンテキストマネージャ
は、コードブロックを実行するために必要な入り口および出口の処理を扱いま
す。コンテキストマネージャは通常、 "with" 文（ with 文 の章を参照）に
より起動されますが、これらのメソッドを直接呼び出すことで起動することも
できます。

コンテキストマネージャの代表的な使い方としては、様々なグローバル情報の
保存および更新、リソースのロックとアンロック、ファイルのオープンとクロ
ーズなどが挙げられます。

For more information on context managers, see コンテキストマネージャ型
. The "object" class itself does not provide the context manager
methods.

object.__enter__(self)

   コンテキストマネージャのの入り口で実行される処理です。 "with" 文は
   、文の "as" 節で規定された値を返すこのメソッドを呼び出します。

object.__exit__(self, exc_type, exc_value, traceback)

   コンテキストマネージャの出口で実行される処理です。パラメータは、コ
   ンテキストが終了した原因となった例外について説明しています。コンテ
   キストが例外を送出せず終了した場合は、全ての引き数に "None" が設定
   されます。

   もし、例外が送出され、かつメソッドが例外を抑制したい場合（すなわち
   、例外が伝播されるのを防ぎたい場合）、このメソッドは True を返す必
   要があります。そうでなければ、このメソッドの終了後、例外は通常通り
   伝播することになります。

   Note that "__exit__()" methods should not reraise the passed-in
   exception; this is the caller's responsibility.

参考:

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


3.3.10. クラスパターンマッチの位置引数のカスタマイズ
----------------------------------------------------

パターンの中でクラス名を利用する場合、位置引数はデフォルトでは利用でき
ません。 "MyClass" で特別なサポートがないと、 "case MyClass(x, y)" は
通常無効です。このようなパターンを利用するには、 *__match_args__* 属性
をクラスに定義する必要があります。

object.__match_args__

   このクラス変数には文字列のタプルがアサイン可能です。このクラスがク
   ラスパターンの位置引数の中で利用されると、それぞれの位置引数は対応
   する *__match_args__* の中の値をキーワードとする、キーワード引数に
   変換されます。この属性がない時は、 "()" が設定されているのと同義で
   す。

例えば、もし "MyClass.__match_args__" に "("left", "center", "right")"
が定義されていた場合、  "case MyClass(x, y)" は "case MyClass(left=x,
center=y)" と同義です。パターンの引数の数は、 *__match_args__* の要素
数と同等かそれ以下でなければならない点に注意してください。もし、多かっ
た場合には、パターンマッチは "TypeError" を送出します。

Added in version 3.10.

参考:

  **PEP 634** - 構造的パターンマッチ
     "match" 文の詳細。


3.3.11. Emulating buffer types
------------------------------

The buffer protocol provides a way for Python objects to expose
efficient access to a low-level memory array. This protocol is
implemented by builtin types such as "bytes" and "memoryview", and
third-party libraries may define additional buffer types.

While buffer types are usually implemented in C, it is also possible
to implement the protocol in Python.

object.__buffer__(self, flags)

   Called when a buffer is requested from *self* (for example, by the
   "memoryview" constructor). The *flags* argument is an integer
   representing the kind of buffer requested, affecting for example
   whether the returned buffer is read-only or writable.
   "inspect.BufferFlags" provides a convenient way to interpret the
   flags. The method must return a "memoryview" object.

object.__release_buffer__(self, buffer)

   Called when a buffer is no longer needed. The *buffer* argument is
   a "memoryview" object that was previously returned by
   "__buffer__()". The method must release any resources associated
   with the buffer. This method should return "None". Buffer objects
   that do not need to perform any cleanup are not required to
   implement this method.

Added in version 3.12.

参考:

  **PEP 688** - Making the buffer protocol accessible in Python
     Introduces the Python "__buffer__" and "__release_buffer__"
     methods.

  "collections.abc.Buffer"
     ABC for buffer types.


3.3.12. Annotations
-------------------

Functions, classes, and modules may contain *annotations*, which are a
way to associate information (usually *type hints*) with a symbol.

object.__annotations__

   This attribute contains the annotations for an object. It is lazily
   evaluated, so accessing the attribute may execute arbitrary code
   and raise exceptions. If evaluation is successful, the attribute is
   set to a dictionary mapping from variable names to annotations.

   バージョン 3.14 で変更: Annotations are now lazily evaluated.

object.__annotate__(format)

   An *annotate function*. Returns a new dictionary object mapping
   attribute/parameter names to their annotation values.

   Takes a format parameter specifying the format in which annotations
   values should be provided. It must be a member of the
   "annotationlib.Format" enum, or an integer with a value
   corresponding to a member of the enum.

   If an annotate function doesn't support the requested format, it
   must raise "NotImplementedError". Annotate functions must always
   support "VALUE" format; they must not raise "NotImplementedError()"
   when called with this format.

   When called with  "VALUE" format, an annotate function may raise
   "NameError"; it must not raise "NameError" when called requesting
   any other format.

   If an object does not have any annotations, "__annotate__" should
   preferably be set to "None" (it can’t be deleted), rather than set
   to a function that returns an empty dict.

   Added in version 3.14.

参考:

  **PEP 649** --- Deferred evaluation of annotation using descriptors
     Introduces lazy evaluation of annotations and the "__annotate__"
     function.


3.3.13. 特殊メソッド検索
------------------------

カスタムクラスでは、特殊メソッドの暗黙の呼び出しは、オブジェクトのイン
スタンス辞書ではなく、オブジェクトの型で定義されているときにのみ正しく
動作することが保証されます。この動作のため、以下のコードは例外を送出し
ます:

   >>> class C:
   ...     pass
   ...
   >>> c = C()
   >>> c.__len__ = lambda: 5
   >>> len(c)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: object of type 'C' has no len()

この動作の背景となる理由は、 "__hash__()" と "__repr__()" といった
type オブジェクトを含むすべてのオブジェクトで定義されている特殊メソッ
ドにあります。これらのメソッドの暗黙の検索が通常の検索プロセスを使った
場合、 type オブジェクト自体に対して実行されたときに失敗してしまいます
:

   >>> 1 .__hash__() == hash(1)
   True
   >>> int.__hash__() == hash(int)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: descriptor '__hash__' of 'int' object needs an argument

クラスの非結合メソッドをこのようにして実行しようとすることは、
'metaclass confusion' と呼ばれることもあり、特殊メソッドを検索するとき
はインスタンスをバイパスすることで回避されます:

   >>> type(1).__hash__(1) == hash(1)
   True
   >>> type(int).__hash__(int) == hash(int)
   True

正確性のためにインスタンス属性をスキップするのに加えて、特殊メソッド検
索はオブジェクトのメタクラスを含めて、 "__getattribute__()" メソッドも
バイパスします:

   >>> class Meta(type):
   ...     def __getattribute__(*args):
   ...         print("Metaclass getattribute invoked")
   ...         return type.__getattribute__(*args)
   ...
   >>> class C(object, metaclass=Meta):
   ...     def __len__(self):
   ...         return 10
   ...     def __getattribute__(*args):
   ...         print("Class getattribute invoked")
   ...         return object.__getattribute__(*args)
   ...
   >>> c = C()
   >>> c.__len__()                 # Explicit lookup via instance
   Class getattribute invoked
   10
   >>> type(c).__len__(c)          # Explicit lookup via type
   Metaclass getattribute invoked
   10
   >>> len(c)                      # Implicit lookup
   10

このように "__getattribute__()" 機構をバイパスすることで、特殊メソッド
の扱いに関するある程度の自由度と引き換えに (特殊メソッドはインタプリタ
から一貫して実行されるためにクラスオブジェクトに設定 *しなければならな
い*)、インタープリタを高速化するための大きな余地が手に入ります。


3.4. コルーチン
===============


3.4.1. 待機可能オブジェクト (Awaitable Object)
----------------------------------------------

*awaitable* オブジェクトは一般的には "__await__()" メソッドが実装され
ています。 "async def" 関数が返す *Coroutineオブジェクト* は待機可能で
す。

注釈:

  "types.coroutine()" デコレータでデコレータが付けられたジェネレータか
  ら返される *generator iterator* オブジェクトも待機可能ですが、
  "__await__()" は実装されていません。

object.__await__(self)

   Must return an *iterator*.  Should be used to implement *awaitable*
   objects.  For instance, "asyncio.Future" implements this method to
   be compatible with the "await" expression. The "object" class
   itself is not awaitable and does not provide this method.

   注釈:

     The language doesn't place any restriction on the type or value
     of the objects yielded by the iterator returned by "__await__",
     as this is specific to the implementation of the asynchronous
     execution framework (e.g. "asyncio") that will be managing the
     *awaitable* object.

Added in version 3.5.

参考: 待機可能オブジェクトについてより詳しくは **PEP 492** を参照してくだ
    さい。


3.4.2. コルーチンオブジェクト
-----------------------------

*Coroutineオブジェクト* は *awaitable* オブジェクトです。"__await__()"
を呼び出し、その返り値に対し反復処理をすることでコルーチンの実行を制御
できます。コルーチンの実行が完了し制御を戻したとき、イテレータは
"StopIteration" を送出し、その例外の "value" 属性に返り値を持たせます
。コルーチンが例外を送出した場合は、イテレータにより伝搬されます。コル
ーチンから "StopIteration" 例外を外に送出すべきではありません。

コルーチンには以下に挙げるメソッドもあり、これらはジェネレータのメソッ
ドからの類似です (ジェネレータ-イテレータメソッド を参照してください)
。 ただし、ジェネレータと違って、コルーチンは反復処理を直接はサポート
していません。

バージョン 3.5.2 で変更: コルーチンで2回以上待機 (await) すると
"RuntimeError" となります。

coroutine.send(value)

   Starts or resumes execution of the coroutine.  If *value* is
   "None", this is equivalent to advancing the iterator returned by
   "__await__()".  If *value* is not "None", this method delegates to
   the "send()" method of the iterator that caused the coroutine to
   suspend.  The result (return value, "StopIteration", or other
   exception) is the same as when iterating over the "__await__()"
   return value, described above.

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

   コルーチンで指定された例外を送出します。 このメソッドは、イテレータ
   にコルーチンを一時停止する "throw()" メソッドがある場合に処理を委任
   します。 そうでない場合には、中断した地点から例外が送出されます。
   結果 (返り値か "StopIteration" かその他の例外) は、上で解説したよう
   な "__await__()" の返り値に対して反復処理を行ったときと同じです。
   例外がコルーチンの中で捕捉されなかった場合、呼び出し元へ伝搬されま
   す。

   バージョン 3.12 で変更: The second signature (type[, value[,
   traceback]]) is deprecated and may be removed in a future version
   of Python.

coroutine.close()

   コルーチンが自分自身の後片付けをし終了します。 コルーチンが一時停止
   している場合は、コルーチンを一時停止させたイテレータに "close()" メ
   ソッドがあれば、まずはそれに処理を委任します。 そして一時停止した地
   点から "GeneratorExit" が送出され、ただちにコルーチンが自分自身の後
   片付けを行います。 最後に、実行が開始されていなかった場合でも、コル
   ーチンに実行が完了した印を付けます。

   コルーチンオブジェクトが破棄されるときには、上記の手順を経て自動的
   に閉じられます。


3.4.3. 非同期イテレータ (Asynchronous Iterator)
-----------------------------------------------

*非同期イテレータ* の "__anext__" メソッドからは非同期のコードが呼べま
す。

非同期イテレータは "async for" 文の中で使えます。

The "object" class itself does not provide these methods.

object.__aiter__(self)

   *非同期イテレータ* オブジェクトを返さなくてはなりません。

object.__anext__(self)

   イテレータの次の値を返す *待機可能オブジェクト* を返さなければなり
   ません。 反復処理が終了したときには "StopAsyncIteration" エラーを送
   出すべきです。

非同期イテラブルオブジェクトの例:

   class Reader:
       async def readline(self):
           ...

       def __aiter__(self):
           return self

       async def __anext__(self):
           val = await self.readline()
           if val == b'':
               raise StopAsyncIteration
           return val

Added in version 3.5.

バージョン 3.7 で変更: Python 3.7 より前では、 "__aiter__()" は *非同
期イテレータ* になる *awaitable* を返せました。Python 3.7 からは、
"__aiter__()" は非同期イテレータオブジェクトを返さなければなりません。
それ以外のものを返すと "TypeError" になります。


3.4.4. 非同期コンテキストマネージャ (Asynchronous Context Manager)
------------------------------------------------------------------

*非同期コンテキストマネージャ* は、 "__aenter__" メソッドと
"__aexit__" メソッド内部で実行を一時停止できる *コンテキストマネージャ
* です。

非同期コンテキストマネージャは "async with" 文の中で使えます。

The "object" class itself does not provide these methods.

object.__aenter__(self)

   Semantically similar to "__enter__()", the only difference being
   that it must return an *awaitable*.

object.__aexit__(self, exc_type, exc_value, traceback)

   Semantically similar to "__exit__()", the only difference being
   that it must return an *awaitable*.

非同期コンテキストマネージャクラスの例:

   class AsyncContextManager:
       async def __aenter__(self):
           await log('entering context')

       async def __aexit__(self, exc_type, exc, tb):
           await log('exiting context')

Added in version 3.5.

-[ 脚注 ]-

[1] 特定の条件が満たされた場合、オブジェクトの type を変更することが *
    できます* 。これは、正しく扱われなかった場合にとても奇妙な動作を引
    き起こすので、一般的には良い考えではありません。

[2] The "__hash__()", "__iter__()", "__reversed__()",
    "__contains__()", "__class_getitem__()" and "__fspath__()" methods
    have special handling for this. Others will still raise a
    "TypeError", but may do so by relying on the behavior that "None"
    is not callable.

[3] "Does not support" here means that the class has no such method,
    or the method returns "NotImplemented".  Do not set the method to
    "None" if you want to force fallback to the right operand's
    reflected method—that will instead have the opposite effect of
    explicitly *blocking* such fallback.

[4] For operands of the same type, it is assumed that if the non-
    reflected method (such as "__add__()") fails then the operation is
    not supported, which is why the reflected method is not called.

[5] If the right operand's type is a subclass of the left operand's
    type, the reflected method having precedence allows subclasses to
    override their ancestors' operations.
