モジュールオブジェクト (module object)
**************************************

PyTypeObject PyModule_Type
    * Part of the Stable ABI.*

   この "PyTypeObject" のインスタンスは Python のモジュールオブジェク
   ト型を表現します。このオブジェクトは、Python プログラムには
   "types.ModuleType"  として公開されています。

int PyModule_Check(PyObject *p)

   *p* がモジュールオブジェクトかモジュールオブジェクトのサブタイプで
   あるときに真を返します。この関数は常に成功します。

int PyModule_CheckExact(PyObject *p)

   *p* がモジュールオブジェクトで、かつ "PyModule_Type" のサブタイプで
   ないときに真を返します。この関数は常に成功します。

PyObject *PyModule_NewObject(PyObject *name)
    *Return value: New reference.** Part of the Stable ABI since
   version 3.7.*

   "__name__" 属性に *name* が設定された新しいモジュールオブジェクトを
   返します。 モジュールの "__name__", "__doc__", "__package__",
   "__loader__" 属性に値が入っています ("__name__" 以外は全て "None"
   です); "__file__" 属性に値を入れるのは呼び出し側の責任です。

   Added in version 3.3.

   バージョン 3.4 で変更: "__package__" と "__loader__" は "None" に設
   定されます。

PyObject *PyModule_New(const char *name)
    *Return value: New reference.** Part of the Stable ABI.*

   "PyModule_NewObject()" に似ていますが、 name は Unicode オブジェク
   トではなく UTF-8 でエンコードされた文字列です。

PyObject *PyModule_GetDict(PyObject *module)
    *Return value: Borrowed reference.** Part of the Stable ABI.*

   *module* の名前空間を実装する辞書オブジェクトを返します; このオブジ
   ェクトは、モジュールオブジェクトの "__dict__" 属性と同じものです。
   *module* がモジュールオブジェクト (もしくはモジュールオブジェクトの
   サブタイプ) でない場合は、 "SystemError" が送出され "NULL" が返され
   ます。

   拡張モジュールでは、モジュールの "__dict__" を直接操作するよりも、
   "PyModule_*" および "PyObject_*" 関数を使う方が推奨されます。

PyObject *PyModule_GetNameObject(PyObject *module)
    *Return value: New reference.** Part of the Stable ABI since
   version 3.7.*

   *module* の "__name__" の値を返します。モジュールがこの属性を提供し
   ていない場合や文字列型でない場合、 "SystemError" を送出して "NULL"
   を返します。

   Added in version 3.3.

const char *PyModule_GetName(PyObject *module)
    * Part of the Stable ABI.*

   "PyModule_GetNameObject()" に似ていますが、 "'utf-8'" でエンコード
   された name を返します。

void *PyModule_GetState(PyObject *module)
    * Part of the Stable ABI.*

   モジュールの "state"(モジュールを生成したタイミングで確保されるメモ
   リブロックへのポインター) か、なければ "NULL" を返します。
   "PyModuleDef.m_size" を参照してください。

PyModuleDef *PyModule_GetDef(PyObject *module)
    * Part of the Stable ABI.*

   モジュールが作られる元となった "PyModuleDef" 構造体へのポインタを返
   します。 モジュールが定義によって作られていなかった場合は "NULL" を
   返します。

PyObject *PyModule_GetFilenameObject(PyObject *module)
    *Return value: New reference.** Part of the Stable ABI.*

   *module* の "__file__" 属性をもとに *module* がロードされたもとのフ
   ァイル名を返します。もしファイル名が定義されていない場合や、
   Unicode 文字列ではない場合、 "SystemError" を発生させて "NULL" を返
   します。それ以外の場合は Unicode オブジェクトへの参照を返します。

   Added in version 3.2.

const char *PyModule_GetFilename(PyObject *module)
    * Part of the Stable ABI.*

   "PyModule_GetFilenameObject()" と似ていますが、 'utf-8' でエンコー
   ドされたファイル名を返します。

   バージョン 3.2 で非推奨: "PyModule_GetFilename()" raises
   "UnicodeEncodeError" on unencodable filenames, use
   "PyModule_GetFilenameObject()" instead.


Cモジュールの初期化
===================

通常、モジュールオブジェクトは拡張モジュール (初期化関数をエクスポート
している共有ライブラリ) または組み込まれたモジュール
("PyImport_AppendInittab()" を使って初期化関数が追加されているモジュー
ル) から作られます。 詳細については C および C++ 拡張のビルド または
埋め込まれた Python の拡張 を見てください。

初期化関数は、モジュール定義のインスタンスを "PyModule_Create()" に渡
して出来上がったモジュールオブジェクトを返してもよいですし、もしくは定
義構造体そのものを返し"多段階初期化"を要求しても構いません。

type PyModuleDef
    * Part of the Stable ABI (including all members).*

   モジュール定義構造体はモジュールオブジェクトを生成するのに必要なす
   べての情報を保持します。 通常は、それぞれのモジュールごとに静的に初
   期化されたこの型の変数が1つだけ存在します。

   PyModuleDef_Base m_base

      Always initialize this member to "PyModuleDef_HEAD_INIT".

   const char *m_name

      新しいモジュールの名前。

   const char *m_doc

      モジュールの docstring。たいてい docstring は "PyDoc_STRVAR" を
      利用して生成されます。

   Py_ssize_t m_size

      モジュールの状態は、静的なグローバルな領域ではなく
      "PyModule_GetState()" で取得できるモジュールごとのメモリ領域に保
      持されていることがあります。 これによってモジュールは複数のサブ
      ・インタプリターで安全に使えます。

      This memory area is allocated based on *m_size* on module
      creation, and freed when the module object is deallocated, after
      the "m_free" function has been called, if present.

      "m_size" に "-1" を設定すると、そのモジュールはグローバルな状態
      を持つためにサブ・インタープリターをサポートしていないということ
      になります。

      "m_size" を非負の値に設定すると、モジュールは再初期化でき、その
      状態のために必要となる追加のメモリ量を指定できるということになり
      ます。 非負の "m_size" は多段階初期化で必要になります。

      詳細は **PEP 3121** を参照。

   PyMethodDef *m_methods

      "PyMethodDef" で定義される、モジュールレベル関数のテーブルへのポ
      インター。関数が存在しない場合は "NULL" を設定することが可能。

   PyModuleDef_Slot *m_slots

      多段階初期化のためのスロット定義の配列で、 "{0, NULL}" 要素が終
      端となります。 一段階初期化を使うときは、 *m_slots* は "NULL" で
      なければなりません。

      バージョン 3.5 で変更: バージョン 3.5 より前は、このメンバは常に
      "NULL" に設定されていて、次のものとして定義されていました:

         inquiry m_reload

   traverseproc m_traverse

      GC走査がモジュールオブジェクトを走査する際に呼び出される走査関数
      。必要ない場合は "NULL".

      This function is not called if the module state was requested
      but is not allocated yet. This is the case immediately after the
      module is created and before the module is executed
      ("Py_mod_exec" function). More precisely, this function is not
      called if "m_size" is greater than 0 and the module state (as
      returned by "PyModule_GetState()") is "NULL".

      バージョン 3.9 で変更: No longer called before the module state
      is allocated.

   inquiry m_clear

      GCがこのモジュールオブジェクトをクリアーする時に呼び出されるクリ
      アー関数。必要ない場合は、"NULL".

      This function is not called if the module state was requested
      but is not allocated yet. This is the case immediately after the
      module is created and before the module is executed
      ("Py_mod_exec" function). More precisely, this function is not
      called if "m_size" is greater than 0 and the module state (as
      returned by "PyModule_GetState()") is "NULL".

      Like "PyTypeObject.tp_clear", this function is not *always*
      called before a module is deallocated. For example, when
      reference counting is enough to determine that an object is no
      longer used, the cyclic garbage collector is not involved and
      "m_free" is called directly.

      バージョン 3.9 で変更: No longer called before the module state
      is allocated.

   freefunc m_free

      GCがこのモジュールオブジェクトを解放するときに呼び出される関数。
      必要ない場合は "NULL".

      This function is not called if the module state was requested
      but is not allocated yet. This is the case immediately after the
      module is created and before the module is executed
      ("Py_mod_exec" function). More precisely, this function is not
      called if "m_size" is greater than 0 and the module state (as
      returned by "PyModule_GetState()") is "NULL".

      バージョン 3.9 で変更: No longer called before the module state
      is allocated.


一段階初期化
------------

モジュールの初期化関数が直接モジュールオブジェクトを生成して返す場合が
あります。 これは"一段階初期化"と呼ばれ、次の2つのモジュール生成関数の
どちらか1つを使います:

PyObject *PyModule_Create(PyModuleDef *def)
    *Return value: New reference.*

   Create a new module object, given the definition in *def*.  This
   behaves like "PyModule_Create2()" with *module_api_version* set to
   "PYTHON_API_VERSION".

PyObject *PyModule_Create2(PyModuleDef *def, int module_api_version)
    *Return value: New reference.** Part of the Stable ABI.*

   APIバージョンを *module_api_version* として *def* での定義に従って
   新しいモジュールオブジェクトを生成します。 もし指定されたバージョン
   が実行しているインタープリターのバージョンと異なる場合は、
   "RuntimeWarning" を発生させます。

   注釈:

     ほとんどの場合、この関数ではなく "PyModule_Create()" を利用するべ
     きです。この関数は、この関数の必要性を理解しているときにだけ利用
     してください。

モジュールオブジェクトが初期化関数から返される前に、たいていは
"PyModule_AddObjectRef()" などの関数を使ってモジュールオブジェクトにメ
ンバを所属させます。


多段階初期化
------------

An alternate way to specify extensions is to request "multi-phase
initialization". Extension modules created this way behave more like
Python modules: the initialization is split between the *creation
phase*, when the module object is created, and the *execution phase*,
when it is populated. The distinction is similar to the "__new__()"
and "__init__()" methods of classes.

Unlike modules created using single-phase initialization, these
modules are not singletons: if the *sys.modules* entry is removed and
the module is re-imported, a new module object is created, and the old
module is subject to normal garbage collection -- as with Python
modules. By default, multiple modules created from the same definition
should be independent: changes to one should not affect the others.
This means that all state should be specific to the module object
(using e.g. using "PyModule_GetState()"), or its contents (such as the
module's "__dict__" or individual classes created with
"PyType_FromSpec()").

多段階初期化を使って生成される全てのモジュールは サブ・インタプリター
をサポートすることが求められます。 複数のモジュールが独立していること
を保証するのには、たいていはこのサポートをするだけで十分です。

多段階初期化を要求するために、初期化関数 (PyInit_modulename) は空でな
い "m_slots" を持つ "PyModuleDef" を返します。 これを返す前に、
"PyModuleDef" インスタンスは次の関数で初期化されなくてはいけません:

PyObject *PyModuleDef_Init(PyModuleDef *def)
    *Return value: Borrowed reference.** Part of the Stable ABI since
   version 3.5.*

   モジュール定義が型と参照カウントを正しく報告する、適切に初期化され
   た Python オブジェクトであること保証します。

   "PyObject*" にキャストされた *def* を返します。エラーが発生した場合
   "NULL" を返します。

   Added in version 3.5.

モジュール定義の *m_slots* メンバは "PyModuleDef_Slot" 構造体の配列を
指さなければなりません:

type PyModuleDef_Slot

   int slot

      スロット ID で、以下で説明されている利用可能な値から選ばれます。

   void *value

      スロットの値で、意味はスロット ID に依存します。

   Added in version 3.5.

*m_slots* 配列はID 0 のスロットで終端されていなければなりません。

利用可能なスロットの型は以下です:

Py_mod_create

   モジュールオブジェクト自身を生成するために呼ばれる関数を指定します
   。 このスロットの *value* ポインタは次のシグネチャを持つ関数を指し
   ていなくてはいけません:

   PyObject *create_module(PyObject *spec, PyModuleDef *def)

   **PEP 451** で定義された "ModuleSpec" インスタンスと、モジュール定
   義を受け取る関数です。 これは新しいモジュールオブジェクトを返すか、
   エラーを設定して "NULL" を返すべきです。

   この関数は最小限に留めておくべきです。 特に任意のPythonコードを呼び
   出すべきではなく、同じモジュールをインポートしようとすると無限ルー
   プに陥るでしょう。

   複数の "Py_mod_create" スロットを1つのモジュール定義に設定しない方
   がよいです。

   "Py_mod_create" が設定されていない場合は、インポート機構は
   "PyModule_New()" を使って通常のモジュールオブジェクトを生成します。
   モジュールの名前は定義ではなく *spec* から取得され、これによって拡
   張モジュールが動的にモジュール階層における位置を調整できたり、シン
   ボリックリンクを通して同一のモジュール定義を共有しつつ別の名前でイ
   ンポートできたりします。

   返されるオブジェクトが "PyModule_Type" のインスタンスである必要はあ
   りません。 インポートに関連する属性の設定と取得ができる限りは、どん
   な型でも使えます。 しかし、 "PyModuleDef" が "NULL" でない
   "m_traverse", "m_clear", "m_free" 、もしくはゼロでない "m_size" 、
   もしくは "Py_mod_create" 以外のスロットを持つ場合は、
   "PyModule_Type" インスタンスのみが返されるでしょう。

Py_mod_exec

   モジュールを *実行する* ときに呼ばれる関数を指定します。 これは
   Pythonモジュールのコードを実行するのと同等です: この関数はたいてい
   はクラスと定数をモジュールにします。 この関数のシグネチャは以下です
   :

   int exec_module(PyObject *module)

   複数の "Py_mod_exec" スロットが設定されていた場合は、 *m_slots* 配
   列に現れた順に処理されていきます。

Py_mod_multiple_interpreters

   Specifies one of the following values:

   Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED

      The module does not support being imported in subinterpreters.

   Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED

      The module supports being imported in subinterpreters, but only
      when they share the main interpreter's GIL. (See 拡張モジュール
      を分離する.)

   Py_MOD_PER_INTERPRETER_GIL_SUPPORTED

      The module supports being imported in subinterpreters, even when
      they have their own GIL. (See 拡張モジュールを分離する.)

   This slot determines whether or not importing this module in a
   subinterpreter will fail.

   Multiple "Py_mod_multiple_interpreters" slots may not be specified
   in one module definition.

   If "Py_mod_multiple_interpreters" is not specified, the import
   machinery defaults to "Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED".

   Added in version 3.12.

多段階初期化についてより詳しくは **PEP 489** を見てください。


低水準モジュール作成関数
------------------------

以下の関数は、多段階初期化を使うときに裏側で呼び出されます。 例えばモ
ジュールオブジェクトを動的に生成するときに、これらの関数を直接使えます
。 "PyModule_FromDefAndSpec" および "PyModule_ExecDef" のどちらも、呼
び出した後にはモジュールが完全に初期化されていなければなりません。

PyObject *PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)
    *Return value: New reference.*

   Create a new module object, given the definition in *def* and the
   ModuleSpec *spec*.  This behaves like "PyModule_FromDefAndSpec2()"
   with *module_api_version* set to "PYTHON_API_VERSION".

   Added in version 3.5.

PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)
    *Return value: New reference.** Part of the Stable ABI since
   version 3.7.*

   APIバージョンを *module_api_version* として、 *def* と ModuleSpec
   オブジェクトの *spec* で定義されたとおりに新しいモジュールオブジェ
   クトを生成します。 もし指定されたバージョンが実行しているインタープ
   リターのバージョンと異なる場合は、 "RuntimeWarning" を発生させます
   。

   注釈:

     ほとんどの場合、この関数ではなく "PyModule_FromDefAndSpec()" を利
     用するべきです。 この関数は、この関数の必要性を理解しているときに
     だけ利用してください。

   Added in version 3.5.

int PyModule_ExecDef(PyObject *module, PyModuleDef *def)
    * Part of the Stable ABI since version 3.7.*

   *def* で与えられた任意の実行スロット ("Py_mod_exec") を実行します。

   Added in version 3.5.

int PyModule_SetDocString(PyObject *module, const char *docstring)
    * Part of the Stable ABI since version 3.7.*

   *module* の docstring を *docstring* に設定します。 この関数は、
   "PyModuleDef" から "PyModule_Create" もしくは
   "PyModule_FromDefAndSpec" を使ってモジュールを生成するときに自動的
   に呼び出されます。

   Added in version 3.5.

int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)
    * Part of the Stable ABI since version 3.7.*

   終端が "NULL" になっている *functions* 配列にある関数を *module* に
   追加します。 "PyMethodDef" 構造体の個々のエントリについては
   PyMethodDef の説明を参照してください (モジュールの名前空間が共有さ
   れていないので、 C で実装されたモジュールレベル "関数" はたいていモ
   ジュールを1つ目の引数として受け取り、 Python クラスのインスタンスメ
   ソッドに似た形にします)。 この関数は、 "PyModuleDef" から
   "PyModule_Create" もしくは "PyModule_FromDefAndSpec" を使ってモジュ
   ールを生成するときに自動的に呼び出されます。

   Added in version 3.5.


サポート関数
------------

モジュールの初期化関数 (一段階初期化を使う場合) 、あるいはモジュールの
実行スロットから呼び出される関数 (多段階初期化を使う場合) は次の関数を
使うと、モジュールの state の初期化を簡単にできます:

int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
    * Part of the Stable ABI since version 3.10.*

   *module* にオブジェクトを *name* として追加します。 この関数はモジ
   ュールの初期化関数から利用される便利関数です。

   On success, return "0". On error, raise an exception and return
   "-1".

   Return "NULL" if *value* is "NULL". It must be called with an
   exception raised in this case.

   使用例:

      static int
      add_spam(PyObject *module, int value)
      {
          PyObject *obj = PyLong_FromLong(value);
          if (obj == NULL) {
              return -1;
          }
          int res = PyModule_AddObjectRef(module, "spam", obj);
          Py_DECREF(obj);
          return res;
       }

   The example can also be written without checking explicitly if
   *obj* is "NULL":

      static int
      add_spam(PyObject *module, int value)
      {
          PyObject *obj = PyLong_FromLong(value);
          int res = PyModule_AddObjectRef(module, "spam", obj);
          Py_XDECREF(obj);
          return res;
       }

   Note that "Py_XDECREF()" should be used instead of "Py_DECREF()" in
   this case, since *obj* can be "NULL".

   Added in version 3.10.

int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
    * Part of the Stable ABI.*

   Similar to "PyModule_AddObjectRef()", but steals a reference to
   *value* on success (if it returns "0").

   The new "PyModule_AddObjectRef()" function is recommended, since it
   is easy to introduce reference leaks by misusing the
   "PyModule_AddObject()" function.

   注釈:

     Unlike other functions that steal references,
     "PyModule_AddObject()" only releases the reference to *value*
     **on success**.This means that its return value must be checked,
     and calling code must "Py_DECREF()" *value* manually on error.

   使用例:

      static int
      add_spam(PyObject *module, int value)
      {
          PyObject *obj = PyLong_FromLong(value);
          if (obj == NULL) {
              return -1;
          }
          if (PyModule_AddObject(module, "spam", obj) < 0) {
              Py_DECREF(obj);
              return -1;
          }
          // PyModule_AddObject() stole a reference to obj:
          // Py_DECREF(obj) is not needed here
          return 0;
      }

   The example can also be written without checking explicitly if
   *obj* is "NULL":

      static int
      add_spam(PyObject *module, int value)
      {
          PyObject *obj = PyLong_FromLong(value);
          if (PyModule_AddObject(module, "spam", obj) < 0) {
              Py_XDECREF(obj);
              return -1;
          }
          // PyModule_AddObject() stole a reference to obj:
          // Py_DECREF(obj) is not needed here
          return 0;
      }

   Note that "Py_XDECREF()" should be used instead of "Py_DECREF()" in
   this case, since *obj* can be "NULL".

int PyModule_AddIntConstant(PyObject *module, const char *name, long value)
    * Part of the Stable ABI.*

   *module* に整数定数を *name* として追加します。この便宜関数はモジュ
   ールの初期化関数から利用されています。エラーのときには "-1" を、成
   功したときには "0" を返します。

int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
    * Part of the Stable ABI.*

   *module* に文字列定数を *name* として追加します。 この便利関数はモ
   ジュールの初期化関数から利用されています。 文字列 *value* は "NULL"
   終端されていなければなりません。 エラーのときには "-1" を、成功した
   ときには "0" を返します。

PyModule_AddIntMacro(module, macro)

   *module* に int 定数を追加します。名前と値は *macro* から取得されま
   す。例えば、 "PyModule_AddIntMacro(module, AF_INET)" とすると、
   *AF_INET* という名前の int 型定数を *AF_INET* の値で *module* に追
   加します。エラー時には "-1" を、成功時には "0" を返します。

PyModule_AddStringMacro(module, macro)

   文字列定数を *module* に追加します。

int PyModule_AddType(PyObject *module, PyTypeObject *type)
    * Part of the Stable ABI since version 3.10.*

   Add a type object to *module*. The type object is finalized by
   calling internally "PyType_Ready()". The name of the type object is
   taken from the last component of "tp_name" after dot. Return "-1"
   on error, "0" on success.

   Added in version 3.9.


モジュール検索
==============

一段階初期化は、現在のインタプリタのコンテキストから探せるシングルトン
のモジュールを生成します。 これによって、後からモジュール定義への参照
だけでモジュールオブジェクトが取得できます。

多段階初期化を使うと単一の定義から複数のモジュールが作成できるので、こ
れらの関数は多段階初期化を使って作成されたモジュールには使えません。

PyObject *PyState_FindModule(PyModuleDef *def)
    *Return value: Borrowed reference.** Part of the Stable ABI.*

   現在のインタプリタの *def* から作られたモジュールオブジェクトを返し
   ます。このメソッドの前提条件として、前もって "PyState_AddModule()"
   でインタプリタの state にモジュールオブジェクトを連結しておくことを
   要求します。対応するモジュールオブジェクトが見付からない、もしくは
   事前にインタプリタの state に連結されていない場合は、 "NULL" を返し
   ます。

int PyState_AddModule(PyObject *module, PyModuleDef *def)
    * Part of the Stable ABI since version 3.3.*

   関数に渡されたモジュールオブジェクトを、インタプリタの state に連結
   します。この関数を使うことで "PyState_FindModule()" からモジュール
   オブジェクトにアクセスできるようになります。

   一段階初期化を使って作成されたモジュールにのみ有効です。

   Python calls "PyState_AddModule" automatically after importing a
   module, so it is unnecessary (but harmless) to call it from module
   initialization code. An explicit call is needed only if the
   module's own init code subsequently calls "PyState_FindModule". The
   function is mainly intended for implementing alternative import
   mechanisms (either by calling it directly, or by referring to its
   implementation for details of the required state updates).

   呼び出し側はGILを獲得しなければなりません。

   成功したら 0 を、失敗したら -1 を返します。

   Added in version 3.3.

int PyState_RemoveModule(PyModuleDef *def)
    * Part of the Stable ABI since version 3.3.*

   *def* から作られたモジュールオブジェクトをインタプリタ state から削
   除します。成功したら 0 を、失敗したら -1 を返します。

   呼び出し側はGILを獲得しなければなりません。

   Added in version 3.3.
