"types" --- 動的な型生成と組み込み型に対する名前
************************************************

**ソースコード:** Lib/types.py

======================================================================

このモジュールは新しい型の動的な生成を支援するユーティリティ関数を定義
します。

さらに、標準の Python インタプリタによって使用されているものの、 "int"
や "str" のように組み込みとして公開されていないようないくつかのオブジ
ェクト型の名前を定義しています。

最後に、組み込みになるほど基本的でないような追加の型関連のユーティリテ
ィと関数をいくつか提供しています。


動的な型生成
============

types.new_class(name, bases=(), kwds=None, exec_body=None)

   適切なメタクラスを使用して動的にクラスオブジェクトを生成します。

   最初の3つの引数はクラス定義ヘッダーを構成する—クラス名、基底クラス
   (順番に)、キーワード引数 (例えば "metaclass")—です。

   *exec_body* 引数は、新規に生成されたクラスの名前空間を構築するため
   に使用されるコールバックです。それは唯一の引数としてクラスの名前空
   間を受け取り、クラスの内容で名前空間を直接更新します。コールバック
   が渡されない場合、それは "lambda ns: None" を渡すことと同じ効果があ
   ります。

   バージョン 3.3 で追加.

types.prepare_class(name, bases=(), kwds=None)

   適切なメタクラスを計算してクラスの名前空間を生成します。

   引数はクラス定義ヘッダーを構成する要素—クラス名、基底クラス (順番に
   )、キーワード引数 (例えば "metaclass")—です。

   返り値は "metaclass, namespace, kwds" の3要素のタプルです

   *metaclass* は適切なメタクラスです。*namespace* は用意されたクラス
   の名前空間です。また *kwds* は、"'metaclass'" エントリが削除された
   、渡された *kwds* 引数の更新されたコピーです。*kwds* 引数が渡されな
   ければ、これは空の dict になります。

   バージョン 3.3 で追加.

   バージョン 3.6 で変更: 返されるタプルの "namespace" 要素のデフォル
   ト値が変更されました。 現在では、メタクラスが "__prepare__" メソッ
   ドを持っていないときは、挿入順序を保存するマッピングが使われます。

参考:

  メタクラス
     これらの関数によってサポートされるクラス生成プロセスの完全な詳細

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

types.resolve_bases(bases)

   Resolve MRO entries dynamically as specified by **PEP 560**.

   This function looks for items in *bases* that are not instances of
   "type", and returns a tuple where each such object that has an
   "__mro_entries__" method is replaced with an unpacked result of
   calling this method.  If a *bases* item is an instance of "type",
   or it doesn't have an "__mro_entries__" method, then it is included
   in the return tuple unchanged.

   バージョン 3.7 で追加.

参考: **PEP 560** - typing モジュールとジェネリック型に対する言語コアによ
    るサポート


標準的なインタプリタ型
======================

このモジュールは、Python インタプリタを実装するために必要な多くの型に
対して名前を提供します。それは、"listiterator" 型のような、単に処理中
に付随的に発生するいくつかの型が含まれることを意図的に避けています。

これらの名前は典型的に "isinstance()" や "issubclass()" によるチェック
に使われます。

これらのタイプのいずれかをインスタンス化する場合、シグネチャは Python
のバージョンによって異なる可能性があることに注意してください。

以下の型に対して標準的な名前が定義されています:

types.FunctionType
types.LambdaType

   ユーザ定義の関数と "lambda" 式によって生成された関数の型です。

   引数 "code" を指定して 監査イベント "function.__new__" を送出します
   。

   この監査イベントは、関数オブジェクトを直接インスタンス化した場合に
   のみ発生し、通常のコンパイル時には発生しません。

types.GeneratorType

   ジェネレータ関数によって生成された *ジェネレータ* イテレータオブジ
   ェクトの型です。

types.CoroutineType

   "async def" 関数に生成される *コルーチン* オブジェクトです。

   バージョン 3.5 で追加.

types.AsyncGeneratorType

   非同期ジェネレータ関数によって作成された *非同期ジェネレータ* イテ
   レータオブジェクトの型です。

   バージョン 3.6 で追加.

class types.CodeType(**kwargs)

   "compile()" 関数が返すようなコードオブジェクトの型です。

   引数 "code", "filename", "name", "argcount", "posonlyargcount",
   "kwonlyargcount", "nlocals", "stacksize", "flags" を指定して 監査イ
   ベント "code.__new__" を送出します。

   Note that the audited arguments may not match the names or
   positions required by the initializer.  The audit event only occurs
   for direct instantiation of code objects, and is not raised for
   normal compilation.

   replace(**kwargs)

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

      バージョン 3.8 で追加.

types.CellType

   The type for cell objects: such objects are used as containers for
   a function's free variables.

   バージョン 3.8 で追加.

types.MethodType

   ユーザー定義のクラスのインスタンスのメソッドの型です。

types.BuiltinFunctionType
types.BuiltinMethodType

   "len()" や "sys.exit()" のような組み込み関数や、組み込み型のメソッ
   ドの型です。 (ここでは "組み込み" という単語を "Cで書かれた" という
   意味で使っています)

types.WrapperDescriptorType

   The type of methods of some built-in data types and base classes
   such as "object.__init__()" or "object.__lt__()".

   バージョン 3.7 で追加.

types.MethodWrapperType

   The type of *bound* methods of some built-in data types and base
   classes. For example it is the type of "object().__str__".

   バージョン 3.7 で追加.

types.MethodDescriptorType

   The type of methods of some built-in data types such as
   "str.join()".

   バージョン 3.7 で追加.

types.ClassMethodDescriptorType

   The type of *unbound* class methods of some built-in data types
   such as "dict.__dict__['fromkeys']".

   バージョン 3.7 で追加.

class types.ModuleType(name, doc=None)

   *module* の型です。コンストラクタは生成するモジュールの名前と任意で
   その *docstring* を受け取ります。

   注釈:

     インポートによりコントロールされる様々な属性を設定する場合、
     "importlib.util.module_from_spec()" を使用して新しいモジュールを
     作成してください。

   __doc__

      モジュールの *docstring* です。デフォルトは "None" です。

   __loader__

      モジュールをロードする *loader* です。デフォルトは "None" です。

      This attribute is to match
      "importlib.machinery.ModuleSpec.loader" as stored in the
      attr:*__spec__* object.

      注釈:

        A future version of Python may stop setting this attribute by
        default. To guard against this potential change, preferably
        read from the "__spec__" attribute instead or use
        "getattr(module, "__loader__", None)" if you explicitly need
        to use this attribute.

      バージョン 3.4 で変更: デフォルトが "None" になりました。以前は
      オプションでした。

   __name__

      The name of the module. Expected to match
      "importlib.machinery.ModuleSpec.name".

   __package__

      モジュールがどの *package* に属しているかです。モジュールがトッ
      プレベルである (すなわち、いかなる特定のパッケージの一部でもない
      ) 場合、この属性は "''" に設定されます。そうでない場合、パッケー
      ジ名 (モジュールがパッケージ自身なら "__name__") に設定されます
      。デフォルトは "None" です。

      This attribute is to match
      "importlib.machinery.ModuleSpec.parent" as stored in the
      attr:*__spec__* object.

      注釈:

        A future version of Python may stop setting this attribute by
        default. To guard against this potential change, preferably
        read from the "__spec__" attribute instead or use
        "getattr(module, "__package__", None)" if you explicitly need
        to use this attribute.

      バージョン 3.4 で変更: デフォルトが "None" になりました。以前は
      オプションでした。

   __spec__

      A record of the module's import-system-related state. Expected
      to be an instance of "importlib.machinery.ModuleSpec".

      バージョン 3.4 で追加.

class types.GenericAlias(t_origin, t_args)

   The type of parameterized generics such as "list[int]".

   "t_origin" should be a non-parameterized generic class, such as
   "list", "tuple" or "dict".  "t_args" should be a "tuple" (possibly
   of length 1) of types which parameterize "t_origin":

      >>> from types import GenericAlias

      >>> list[int] == GenericAlias(list, (int,))
      True
      >>> dict[str, int] == GenericAlias(dict, (str, int))
      True

   バージョン 3.9 で追加.

   バージョン 3.9.2 で変更: This type can now be subclassed.

class types.TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)

   "sys.exc_info()[2]" で得られるようなトレースバックオブジェクトの型
   です。

   See the language reference for details of the available attributes
   and operations, and guidance on creating tracebacks dynamically.

types.FrameType

   フレームオブジェクトの型です。トレースバックオブジェクト "tb" の
   "tb.tb_frame" などです。

   See the language reference for details of the available attributes
   and operations.

types.GetSetDescriptorType

   "FrameType.f_locals" や "array.array.typecode" のような、拡張モジュ
   ールにおいて "PyGetSetDef" によって定義されたオブジェクトの型です。
   この型はオブジェクト属性のディスクリプタとして利用されます。
   "property" 型と同じ目的を持った型ですが、こちらは拡張モジュールで定
   義された型のためのものです。

types.MemberDescriptorType

   "datetime.timedelta.days" のような、拡張モジュールにおいて
   "PyMemberDef" によって定義されたオブジェクトの型です。この型は、標
   準の変換関数を利用するような、Cのシンプルなデータメンバで利用されま
   す。 "property" 型と同じ目的を持った型ですが、こちらは拡張モジュー
   ルで定義された型のためのものです。

   **CPython implementation detail:** Pythonの他の実装では、この型は
   "GetSetDescriptorType" と同じかもしれません。

class types.MappingProxyType(mapping)

   読み出し専用のマッピングのプロキシです。マッピングのエントリーに関
   する動的なビューを提供します。つまり、マッピングが変わった場合にビ
   ューがこれらの変更を反映するということです。

   バージョン 3.3 で追加.

   バージョン 3.9 で変更: Updated to support the new union ("|")
   operator from **PEP 584**, which simply delegates to the underlying
   mapping.

   key in proxy

      元になったマッピングが *key* というキーを持っている場合 "True"
      を返します。そうでなければ "False" を返します。

   proxy[key]

      元になったマッピングの *key* というキーに対応するアイテムを返し
      ます。 *key* が存在しなければ、 "KeyError" が発生します。

   iter(proxy)

      元になったマッピングのキーを列挙するイテレータを返します。これは
      "iter(proxy.keys())" のショートカットです。

   len(proxy)

      元になったマッピングに含まれるアイテムの数を返します。

   copy()

      元になったマッピングの浅いコピーを返します。

   get(key[, default])

      *key* が元になったマッピングに含まれている場合 *key* に対する値
      を返し、そうでなければ *default* を返します。もし *default* が与
      えられない場合は、デフォルト値の "None" になります。そのため、こ
      のメソッドが "KeyError" を発生させることはありません。

   items()

      元になったマッピングの items ("(key, value)" ペアの列) に対する
      新しいビューを返します。

   keys()

      元になったマッピングの keys に対する新しいビューを返します。

   values()

      元になったマッピングの values に対する新しいビューを返します。

   reversed(proxy)

      Return a reverse iterator over the keys of the underlying
      mapping.

      バージョン 3.9 で追加.


追加のユーティリティクラスと関数
================================

class types.SimpleNamespace

   名前空間への属性アクセスに加えて意味のある repr を提供するための、
   単純な "object" サブクラスです。

   "object" とは異なり、 "SimpleNamespace" は、属性を追加したり削除し
   たりすることができます。 "SimpleNamespace" オブジェクトがキーワード
   引数で初期化される場合、それらは元になる名前空間に直接追加されます
   。

   この型は以下のコードとほぼ等価です:

      class SimpleNamespace:
          def __init__(self, /, **kwargs):
              self.__dict__.update(kwargs)

          def __repr__(self):
              items = (f"{k}={v!r}" for k, v in self.__dict__.items())
              return "{}({})".format(type(self).__name__, ", ".join(items))

          def __eq__(self, other):
              if isinstance(self, SimpleNamespace) and isinstance(other, SimpleNamespace):
                 return self.__dict__ == other.__dict__
              return NotImplemented

   "SimpleNamespace" は "class NS: pass" を置き換えるものとして有用か
   もしれません。ですが、構造化されたレコード型に対しては、これよりは
   むしろ "namedtuple()" を使用してください。

   バージョン 3.3 で追加.

   バージョン 3.9 で変更: Attribute order in the repr changed from
   alphabetical to insertion (like "dict").

types.DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)

   クラスの属性アクセスを __getattr__ に振り替えます。

   これは記述子で、インスタンス経由のアクセスとクラス経由のアクセスで
   振る舞いが異なる属性を定義するのに使います。インスタンスアクセスは
   通常通りですが、クラス経由の属性アクセスはクラスの __getattr__ メソ
   ッドに振り替えられます。これは AttributeError の送出により行われま
   す。

   これによって、インスタンス上で有効なプロパティを持ち、クラス上で同
   名の仮想属性を持つことができます (例については "enum.Enum" を参照し
   てください)。

   バージョン 3.4 で追加.


コルーチンユーティリティ関数
============================

types.coroutine(gen_func)

   この関数は、 *generator* 関数を、ジェネレータベースのコルーチンを返
   す *coroutine function* に変換します。返されるジェネレータベースの
   コルーチンは依然として *generator iterator* ですが、同時に
   *coroutine* オブジェクトかつ *awaitable* であるとみなされます。ただ
   し、必ずしも "__await__()" メソッドを実装する必要はありません。

   *gen_func* はジェネレータ関数で、インプレースに変更されます。

   *gen_func* がジェネレータ関数でない場合、この関数はラップされます。
   この関数が "collections.abc.Generator" のインスタンスを返す場合、こ
   のインスタンスは *awaitable* なプロキシオブジェクトにラップされます
   。それ以外のすべての型のオブジェクトは、そのまま返されます。

   バージョン 3.5 で追加.
