初期化 (initialization)、終了処理 (finalization)、スレッド
**********************************************************

See also Python Initialization Configuration.


Python 初期化以前
=================

Python が埋め込まれているアプリケーションでは、他の Python/C API 関数
を使う前に "Py_Initialize()" 関数を呼ばなければなりません。これには例
外として、いくつかの関数と グローバルな設定変数 があります。

次の関数は Python の初期化の前でも安全に呼び出せます:

* 設定関数:

  * "PyImport_AppendInittab()"

  * "PyImport_ExtendInittab()"

  * "PyInitFrozenExtensions()"

  * "PyMem_SetAllocator()"

  * "PyMem_SetupDebugHooks()"

  * "PyObject_SetArenaAllocator()"

  * "Py_SetPath()"

  * "Py_SetProgramName()"

  * "Py_SetPythonHome()"

  * "Py_SetStandardStreamEncoding()"

  * "PySys_AddWarnOption()"

  * "PySys_AddXOption()"

  * "PySys_ResetWarnOptions()"

* 情報取得の関数:

  * "Py_IsInitialized()"

  * "PyMem_GetAllocator()"

  * "PyObject_GetArenaAllocator()"

  * "Py_GetBuildInfo()"

  * "Py_GetCompiler()"

  * "Py_GetCopyright()"

  * "Py_GetPlatform()"

  * "Py_GetVersion()"

* ユーティリティ:

  * "Py_DecodeLocale()"

* メモリアロケータ:

  * "PyMem_RawMalloc()"

  * "PyMem_RawRealloc()"

  * "PyMem_RawCalloc()"

  * "PyMem_RawFree()"

注釈:

  The following functions **should not be called** before
  "Py_Initialize()": "Py_EncodeLocale()", "Py_GetPath()",
  "Py_GetPrefix()", "Py_GetExecPrefix()", "Py_GetProgramFullPath()",
  "Py_GetPythonHome()", "Py_GetProgramName()" and
  "PyEval_InitThreads()".


グローバルな設定変数
====================

Python には、様々な機能やオプションを制御するグローバルな設定のための
変数があります。 デフォルトでは、これらのフラグは コマンドラインオプシ
ョン で制御されます。

オプションでフラグがセットされると、フラグの値はそのオプションがセット
された回数になります。 例えば、 "-b" では "Py_BytesWarningFlag" が 1
に設定され、 "-bb" では "Py_BytesWarningFlag" が 2 に設定されます。

int Py_BytesWarningFlag

   "bytes" または "bytearray" を "str" と比較した場合、または、
   "bytes" を "int" と比較した場合に警告を発生させます。 "2" 以上の値
   を設定している場合は、エラーを発生させます。

   "-b" オプションで設定します。

int Py_DebugFlag

   パーサーのデバッグ出力を有効にします。(専門家専用です。コンパイルオ
   プションに依存します)。

   "-d" オプションと "PYTHONDEBUG" 環境変数で設定します。

int Py_DontWriteBytecodeFlag

   非ゼロに設定した場合、Python はソースモジュールのインポート時に
   ".pyc" ファイルの作成を試みません。

   "-B" オプションと "PYTHONDONTWRITEBYTECODE" 環境変数で設定します。

int Py_FrozenFlag

   "Py_GetPath()" の中でモジュール検索パスを割り出しているときのエラー
   メッセージを抑制します。

   "_freeze_module" プログラムと "frozenmain" プログラムが使用する非公
   開フラグです。

int Py_HashRandomizationFlag

   "PYTHONHASHSEED" 環境変数が空でない文字列に設定された場合に、 "1"
   が設定されます。

   フラグがゼロでない場合、 "PYTHONHASHSEED" 環境変数を読みシークレッ
   トハッシュシードを初期化します。

int Py_IgnoreEnvironmentFlag

   Ignore all "PYTHON*" environment variables, e.g. "PYTHONPATH" and
   "PYTHONHOME", that might be set.

   "-E" オプションと "-I" オプションで設定します。

int Py_InspectFlag

   最初の引数にスクリプトが指定されたときや "-c" オプションが利用され
   た際に、 "sys.stdin" がターミナルに出力されないときであっても、スク
   リプトかコマンドを実行した後にインタラクティブモードに入ります。

   "-i" オプションと "PYTHONINSPECT" 環境変数で設定します。

int Py_InteractiveFlag

   "-i" オプションで設定します。

int Py_IsolatedFlag

   Python を隔離モードで実行します。 隔離モードでは "sys.path" はスク
   リプトのディレクトリやユーザのサイトパッケージのディレクトリを含み
   ません。

   "-I" オプションで設定します。

   バージョン 3.4 で追加.

int Py_LegacyWindowsFSEncodingFlag

   If the flag is non-zero, use the "mbcs" encoding with "replace"
   error handler, instead of the UTF-8 encoding with "surrogatepass"
   error handler, for the *filesystem encoding and error handler*.

   "PYTHONLEGACYWINDOWSFSENCODING" 環境変数が空でない文字列に設定され
   た場合に、 "1" に設定されます。

   より詳しくは **PEP 529** を参照してください。

   Availability: Windows.

int Py_LegacyWindowsStdioFlag

   If the flag is non-zero, use "io.FileIO" instead of
   "io._WindowsConsoleIO" for "sys" standard streams.

   "PYTHONLEGACYWINDOWSSTDIO" 環境変数が空でない文字列に設定された場合
   に、 "1" に設定されます。

   より詳しくは **PEP 528** を参照してください。

   Availability: Windows.

int Py_NoSiteFlag

   "site" モジュールの import と、そのモジュールが行なっていた site ご
   との "sys.path" への操作を無効にします。後で "site" を明示的に
   import しても、これらの操作は実行されません (実行したい場合は、
   "site.main()" を呼び出してください)。

   "-S" オプションで設定します。

int Py_NoUserSiteDirectory

   "ユーザのサイトパッケージのディレクトリ" を "sys.path" に追加しませ
   ん。

   "-s" オプション、 "-I" 、 "PYTHONNOUSERSITE" 環境変数で設定します。

int Py_OptimizeFlag

   "-O" オプションと "PYTHONOPTIMIZE" 環境変数で設定します。

int Py_QuietFlag

   インタラクティブモードでも copyright とバージョンのメッセージを表示
   しません。

   "-q" オプションで設定します。

   バージョン 3.2 で追加.

int Py_UnbufferedStdioFlag

   標準出力と標準エラーをバッファリングしないように強制します。

   "-u" オプションと "PYTHONUNBUFFERED" 環境変数で設定します。

int Py_VerboseFlag

   モジュールが初期化されるたびにメッセージを出力し、それがどこ (ファ
   イル名やビルトインモジュール) からロードされたのかを表示します。 値
   が 2 以上の場合は、モジュールを検索するときにチェックしたファイルご
   とにメッセージを出力します。また、終了時のモジュールクリーンアップ
   に関する情報も提供します。

   "-v" オプションと "PYTHONVERBOSE" 環境変数で設定します。


インタープリタの初期化と終了処理
================================

void Py_Initialize()
    * 次に属します: Stable ABI.*

   Python インタープリタを初期化します。 Python の埋め込みを行うアプリ
   ケーションでは、他のあらゆる Python/C API を使用するよりも前にこの
   関数を呼び出さなければなりません。いくつかの例外については Python
   初期化以前 を参照してください。

   This initializes the table of loaded modules ("sys.modules"), and
   creates the fundamental modules "builtins", "__main__" and "sys".
   It also initializes the module search path ("sys.path"). It does
   not set "sys.argv"; use "PySys_SetArgvEx()" for that.  This is a
   no-op when called for a second time (without calling
   "Py_FinalizeEx()" first).  There is no return value; it is a fatal
   error if the initialization fails.

   注釈:

     Windows では "O_TEXT" から "O_BINARY" へコンソールモードが変更さ
     れますが、これはその C ランタイムを使っているコンソールでの
     Python 以外の使い勝手にも影響を及ぼします。

void Py_InitializeEx(int initsigs)
    * 次に属します: Stable ABI.*

   This function works like "Py_Initialize()" if *initsigs* is "1". If
   *initsigs* is "0", it skips initialization registration of signal
   handlers, which might be useful when Python is embedded.

int Py_IsInitialized()
    * 次に属します: Stable ABI.*

   Python インタプリタが初期化済みであれば真(非ゼロ)を、さもなければ偽
   (ゼロ)を返します。"Py_FinalizeEx()" を呼び出した後は、
   "Py_Initialize()" を再び呼び出すまで、この関数は偽を返します。

int Py_FinalizeEx()
    * 次に属します: Stable ABI (バージョン 3.6 より).*

   Undo all initializations made by "Py_Initialize()" and subsequent
   use of Python/C API functions, and destroy all sub-interpreters
   (see "Py_NewInterpreter()" below) that were created and not yet
   destroyed since the last call to "Py_Initialize()".  Ideally, this
   frees all memory allocated by the Python interpreter.  This is a
   no-op when called for a second time (without calling
   "Py_Initialize()" again first).  Normally the return value is "0".
   If there were errors during finalization (flushing buffered data),
   "-1" is returned.

   この関数が提供されている理由はいくつかあります。Python の埋め込みを
   行っているアプリケーションでは、アプリケーションを再起動することな
   く Python を再起動したいことがあります。また、動的ロード可能イブラ
   リ (あるいは DLL) から Python インタプリタをロードするアプリケーシ
   ョンでは、DLL をアンロードする前に Python が確保したメモリを全て解
   放したいと考えるかもしれません。アプリケーション内で起きているメモ
   リリークを追跡する際に、開発者は Python が確保したメモリをアプリケ
   ーションの終了前に解放させたいと思う場合もあります。

   **Bugs and caveats:** The destruction of modules and objects in
   modules is done in random order; this may cause destructors
   ("__del__()" methods) to fail when they depend on other objects
   (even functions) or modules.  Dynamically loaded extension modules
   loaded by Python are not unloaded.  Small amounts of memory
   allocated by the Python interpreter may not be freed (if you find a
   leak, please report it).  Memory tied up in circular references
   between objects is not freed.  Some memory allocated by extension
   modules may not be freed.  Some extensions may not work properly if
   their initialization routine is called more than once; this can
   happen if an application calls "Py_Initialize()" and
   "Py_FinalizeEx()" more than once.

   引数無しで 監査イベント "cpython._PySys_ClearAuditHooks" を送出しま
   す。

   バージョン 3.6 で追加.

void Py_Finalize()
    * 次に属します: Stable ABI.*

   この関数は "Py_FinalizeEx()" の後方互換性バージョンで、戻り値があり
   ません。


プロセスワイドのパラメータ
==========================

int Py_SetStandardStreamEncoding(const char *encoding, const char *errors)

   This API is kept for backward compatibility: setting
   "PyConfig.stdio_encoding" and "PyConfig.stdio_errors" should be
   used instead, see Python Initialization Configuration.

   This function should be called before "Py_Initialize()", if it is
   called at all. It specifies which encoding and error handling to
   use with standard IO, with the same meanings as in "str.encode()".

   It overrides "PYTHONIOENCODING" values, and allows embedding code
   to control IO encoding when the environment variable does not work.

   *encoding* and/or *errors* may be "NULL" to use "PYTHONIOENCODING"
   and/or default values (depending on other settings).

   Note that "sys.stderr" always uses the "backslashreplace" error
   handler, regardless of this (or any other) setting.

   If "Py_FinalizeEx()" is called, this function will need to be
   called again in order to affect subsequent calls to
   "Py_Initialize()".

   Returns "0" if successful, a nonzero value on error (e.g. calling
   after the interpreter has already been initialized).

   バージョン 3.4 で追加.

   バージョン 3.11 で非推奨.

void Py_SetProgramName(const wchar_t *name)
    * 次に属します: Stable ABI.*

   This API is kept for backward compatibility: setting
   "PyConfig.program_name" should be used instead, see Python
   Initialization Configuration.

   この関数を呼び出すなら、最初に "Py_Initialize()" を呼び出すよりも前
   に呼び出さなければなりません。この関数はインタプリタにプログラムの
   "main()" 関数に指定した "argv[0]" 引数の値を教えます (ワイドキャラ
   クタに変換されます)。この引数値は、 "Py_GetPath()" や、以下に示すそ
   の他の関数が、インタプリタの実行可能形式から Python ランタイムライ
   ブラリへの相対パスを取得するために使われます。デフォルトの値は
   "'python'" です。引数はゼロ終端されたワイドキャラクタ文字列で、静的
   な記憶領域に入っていなければならず、その内容はプログラムの実行中に
   変更してはなりません。 Python インタプリタ内のコードで、この記憶領
   域の内容を変更するものは一切ありません。

   Use "Py_DecodeLocale()" to decode a bytes string to get a wchar_*
   string.

   バージョン 3.11 で非推奨.

wchar_t *Py_GetProgramName()
    * 次に属します: Stable ABI.*

   Return the program name set with "Py_SetProgramName()", or the
   default. The returned string points into static storage; the caller
   should not modify its value.

   This function should not be called before "Py_Initialize()",
   otherwise it returns "NULL".

   バージョン 3.10 で変更: It now returns "NULL" if called before
   "Py_Initialize()".

wchar_t *Py_GetPrefix()
    * 次に属します: Stable ABI.*

   Return the *prefix* for installed platform-independent files. This
   is derived through a number of complicated rules from the program
   name set with "Py_SetProgramName()" and some environment variables;
   for example, if the program name is "'/usr/local/bin/python'", the
   prefix is "'/usr/local'". The returned string points into static
   storage; the caller should not modify its value.  This corresponds
   to the **prefix** variable in the top-level "Makefile" and the "--
   prefix" argument to the **configure** script at build time.  The
   value is available to Python code as "sys.prefix". It is only
   useful on Unix.  See also the next function.

   This function should not be called before "Py_Initialize()",
   otherwise it returns "NULL".

   バージョン 3.10 で変更: It now returns "NULL" if called before
   "Py_Initialize()".

wchar_t *Py_GetExecPrefix()
    * 次に属します: Stable ABI.*

   Return the *exec-prefix* for installed platform-*dependent* files.
   This is derived through a number of complicated rules from the
   program name set with "Py_SetProgramName()" and some environment
   variables; for example, if the program name is
   "'/usr/local/bin/python'", the exec-prefix is "'/usr/local'".  The
   returned string points into static storage; the caller should not
   modify its value.  This corresponds to the **exec_prefix** variable
   in the top-level "Makefile" and the "--exec-prefix" argument to the
   **configure** script at build  time.  The value is available to
   Python code as "sys.exec_prefix".  It is only useful on Unix.

   背景: プラットフォーム依存のファイル (実行形式や共有ライブラリ) が
   別のディレクトリツリー内にインストールされている場合、 exec-prefix
   は prefix と異なります。典型的なインストール形態では、プラットフォ
   ーム非依存のファイルが "/usr/local" に収められる一方、プラットフォ
   ーム依存のファイルは "/usr/local/plat" サブツリーに収められます。

   一般的に、プラットフォームとは、ハードウェアとソフトウェアファミリ
   の組み合わせを指します。例えば、Solaris 2.x を動作させている Sparc
   マシンは全て同じプラットフォームであるとみなしますが、Solaris 2.x
   を動作させている Intel マシンは違うプラットフォームになりますし、同
   じ Intel マシンでも Linux を動作させているならまた別のプラットフォ
   ームです。一般的には、同じオペレーティングシステムでも、メジャーリ
   ビジョンの違うものは異なるプラットフォームです。非 Unix のオペレー
   ティングシステムの場合は話はまた別です; 非 Unix のシステムでは、イ
   ンストール方法はとても異なっていて、prefix や exec-prefix には意味
   がなく、空文字列が設定されています。コンパイル済みの Python バイト
   コードはプラットフォームに依存しないので注意してください (ただし、
   どのバージョンの Python でコンパイルされたかには依存します!)。

   システム管理者は、 **mount** や **automount** プログラムを使って、
   各プラットフォーム用の "/usr/local/plat" を異なったファイルシステム
   に置き、プラットフォーム間で "/usr/local" を共有するための設定方法
   を知っているでしょう。

   This function should not be called before "Py_Initialize()",
   otherwise it returns "NULL".

   バージョン 3.10 で変更: It now returns "NULL" if called before
   "Py_Initialize()".

wchar_t *Py_GetProgramFullPath()
    * 次に属します: Stable ABI.*

   Return the full program name of the Python executable; this is
   computed as a side-effect of deriving the default module search
   path  from the program name (set by "Py_SetProgramName()" above).
   The returned string points into static storage; the caller should
   not modify its value.  The value is available to Python code as
   "sys.executable".

   This function should not be called before "Py_Initialize()",
   otherwise it returns "NULL".

   バージョン 3.10 で変更: It now returns "NULL" if called before
   "Py_Initialize()".

wchar_t *Py_GetPath()
    * 次に属します: Stable ABI.*

   Return the default module search path; this is computed from the
   program name (set by "Py_SetProgramName()" above) and some
   environment variables. The returned string consists of a series of
   directory names separated by a platform dependent delimiter
   character.  The delimiter character is "':'" on Unix and macOS,
   "';'" on Windows.  The returned string points into static storage;
   the caller should not modify its value.  The list "sys.path" is
   initialized with this value on interpreter startup; it can be (and
   usually is) modified later to change the search path for loading
   modules.

   This function should not be called before "Py_Initialize()",
   otherwise it returns "NULL".

   バージョン 3.10 で変更: It now returns "NULL" if called before
   "Py_Initialize()".

void Py_SetPath(const wchar_t*)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   This API is kept for backward compatibility: setting
   "PyConfig.module_search_paths" and
   "PyConfig.module_search_paths_set" should be used instead, see
   Python Initialization Configuration.

   Set the default module search path.  If this function is called
   before "Py_Initialize()", then "Py_GetPath()" won't attempt to
   compute a default search path but uses the one provided instead.
   This is useful if Python is embedded by an application that has
   full knowledge of the location of all modules.  The path components
   should be separated by the platform dependent delimiter character,
   which is "':'" on Unix and macOS, "';'" on Windows.

   This also causes "sys.executable" to be set to the program full
   path (see "Py_GetProgramFullPath()") and for "sys.prefix" and
   "sys.exec_prefix" to be empty.  It is up to the caller to modify
   these if required after calling "Py_Initialize()".

   Use "Py_DecodeLocale()" to decode a bytes string to get a wchar_*
   string.

   The path argument is copied internally, so the caller may free it
   after the call completes.

   バージョン 3.8 で変更: The program full path is now used for
   "sys.executable", instead of the program name.

   バージョン 3.11 で非推奨.

const char *Py_GetVersion()
    * 次に属します: Stable ABI.*

   Python インタプリタのバージョンを返します。バージョンは、次のような
   形式の文字列です

      "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"

   第一ワード (最初のスペース文字まで) は、現在の Python のバージョン
   です; 最初の文字は、ピリオドで区切られたメジャーバージョンとマイナ
   ーバージョンです。関数が返す文字列ポインタは静的な記憶領域を返しま
   す; 関数の呼び出し側はこの値を変更できません。この値は Python コー
   ドからは "sys.version" として利用できます。

   See also the "Py_Version" constant.

const char *Py_GetPlatform()
    * 次に属します: Stable ABI.*

   現在のプラットフォームのプラットフォーム識別文字列を返します。Unix
   では、オペレーティングシステムの "公式の" 名前を小文字に変換し、後
   ろにメジャーリビジョン番号を付けた構成になっています。例えば
   Solaris 2.x は、SunOS 5.x, としても知られていますが、"'sunos5'" に
   なります。macOS では "'darwin'" です。Windows では "'win'" です。関
   数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し側
   はこの値を変更できません。この値は Python コードからは
   "sys.platform" として利用できます。

const char *Py_GetCopyright()
    * 次に属します: Stable ABI.*

   現在の Python バージョンに対する公式の著作権表示文字列を返します。
   例えば

   "'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'"

   関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し
   側はこの値を変更できません。この値は Python コードからは
   "sys.copyright" として利用できます。

const char *Py_GetCompiler()
    * 次に属します: Stable ABI.*

   現在使っているバージョンの Python をビルドする際に用いたコンパイラ
   を示す文字列を、角括弧で囲った文字列を返します。例えば:

      "[GCC 2.7.2.2]"

   関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し
   側はこの値を変更できません。この値は Python コードからは
   "sys.version" の一部として取り出せます。

const char *Py_GetBuildInfo()
    * 次に属します: Stable ABI.*

   現在使っている Python インタプリタインスタンスの、シーケンス番号と
   ビルド日時に関する情報を返します。例えば

      "#67, Aug  1 1997, 22:34:28"

   関数が返す文字列ポインタは静的な記憶領域を返します; 関数の呼び出し
   側はこの値を変更できません。この値は Python コードからは
   "sys.version" の一部として取り出せます。

void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
    * 次に属します: Stable ABI.*

   This API is kept for backward compatibility: setting
   "PyConfig.argv", "PyConfig.parse_argv" and "PyConfig.safe_path"
   should be used instead, see Python Initialization Configuration.

   *argc* および *argv* に基づいて "sys.argv" を設定します。これらの引
   数はプログラムの "main()" に渡した引数に似ていますが、最初の要素が
   Python インタプリタの宿主となっている実行形式の名前ではなく、実行さ
   れるスクリプト名を参照しなければならない点が違います。実行するスク
   リプトがない場合、 *argv* の最初の要素は空文字列にしてもかまいませ
   ん。この関数が "sys.argv" の初期化に失敗した場合、致命的エラーを
   "Py_FatalError()" で知らせます。

   *updatepath* が 0 の場合、ここまでの動作がこの関数がすることの全て
   です。 *updatepath* が 0 でない場合、この関数は "sys.path" を以下の
   アルゴリズムに基づいて修正します:

   * 存在するスクリプトの名前が "argv[0]" に渡された場合、そのスクリプ
     トがある場所の絶対パスを "sys.path" の先頭に追加します。

   * それ以外の場合 (*argc* が "0" だったり、 "argv[0]" が存在するファ
     イル名を指していない場合)、 "sys.path" の先頭に空の文字列を追加し
     ます。 これは現在の作業ディレクトリ (""."") を先頭に追加するのと
     同じです。

   Use "Py_DecodeLocale()" to decode a bytes string to get a wchar_*
   string.

   See also "PyConfig.orig_argv" and "PyConfig.argv" members of the
   Python Initialization Configuration.

   注釈:

     It is recommended that applications embedding the Python
     interpreter for purposes other than executing a single script
     pass "0" as *updatepath*, and update "sys.path" themselves if
     desired. See CVE-2008-5983.3.1.3 より前のバージョンでは、
     "PySys_SetArgv()" の呼び出しが完了した後に "sys.path" の先頭の要
     素を取り出すことで、同じ効果が得られます。例えばこのように使いま
     す:

        PyRun_SimpleString("import sys; sys.path.pop(0)\n");

   バージョン 3.1.3 で追加.

   バージョン 3.11 で非推奨.

void PySys_SetArgv(int argc, wchar_t **argv)
    * 次に属します: Stable ABI.*

   This API is kept for backward compatibility: setting
   "PyConfig.argv" and "PyConfig.parse_argv" should be used instead,
   see Python Initialization Configuration.

   この関数は、 **python** インタプリタが "-I" オプション付きで実行さ
   れている場合を除き "PySys_SetArgvEx()" の *updatepath* に "1" を設
   定したのと同じように動作します。

   Use "Py_DecodeLocale()" to decode a bytes string to get a wchar_*
   string.

   See also "PyConfig.orig_argv" and "PyConfig.argv" members of the
   Python Initialization Configuration.

   バージョン 3.4 で変更: *updatepath* の値は "-I" オプションに依存し
   ます。

   バージョン 3.11 で非推奨.

void Py_SetPythonHome(const wchar_t *home)
    * 次に属します: Stable ABI.*

   This API is kept for backward compatibility: setting
   "PyConfig.home" should be used instead, see Python Initialization
   Configuration.

   Python の標準ライブラリがある、デフォルトの "home" ディレクトリを設
   定します。引数の文字列の意味については "PYTHONHOME" を参照してくだ
   さい。

   引数は静的なストレージに置かれてプログラム実行中に書き換えられない
   ようなゼロ終端の文字列であるべきです。Python インタプリタはこのスト
   レージの内容を変更しません。

   Use "Py_DecodeLocale()" to decode a bytes string to get a wchar_*
   string.

   バージョン 3.11 で非推奨.

wchar_t *Py_GetPythonHome()
    * 次に属します: Stable ABI.*

   Return the default "home", that is, the value set by a previous
   call to "Py_SetPythonHome()", or the value of the "PYTHONHOME"
   environment variable if it is set.

   This function should not be called before "Py_Initialize()",
   otherwise it returns "NULL".

   バージョン 3.10 で変更: It now returns "NULL" if called before
   "Py_Initialize()".


スレッド状態 (thread state) とグローバルインタプリタロック (global interpreter lock)
====================================================================================

The Python interpreter is not fully thread-safe.  In order to support
multi-threaded Python programs, there's a global lock, called the
*global interpreter lock* or *GIL*, that must be held by the current
thread before it can safely access Python objects. Without the lock,
even the simplest operations could cause problems in a multi-threaded
program: for example, when two threads simultaneously increment the
reference count of the same object, the reference count could end up
being incremented only once instead of twice.

このため、 *GIL* を獲得したスレッドだけが Python オブジェクトを操作し
たり、 Python/C API 関数を呼び出したりできるというルールがあります。並
行処理をエミュレートするために、インタプリタは定期的にロックを解放した
り獲得したりします。 ("sys.setswitchinterval()" を参照) このロックはブ
ロックが起こりうる I/O 操作の付近でも解放・獲得され、 I/O を要求するス
レッドが I/O 操作の完了を待つ間、他のスレッドが動作できるようにしてい
ます。

The Python interpreter keeps some thread-specific bookkeeping
information inside a data structure called "PyThreadState".  There's
also one global variable pointing to the current "PyThreadState": it
can be retrieved using "PyThreadState_Get()".


Releasing the GIL from extension code
-------------------------------------

Most extension code manipulating the *GIL* has the following simple
structure:

   Save the thread state in a local variable.
   Release the global interpreter lock.
   ... Do some blocking I/O operation ...
   Reacquire the global interpreter lock.
   Restore the thread state from the local variable.

この構造は非常に一般的なので、作業を単純にするために2つのマクロが用意
されています:

   Py_BEGIN_ALLOW_THREADS
   ... Do some blocking I/O operation ...
   Py_END_ALLOW_THREADS

"Py_BEGIN_ALLOW_THREADS" マクロは新たなブロックを開始し、隠しローカル
変数を宣言します; "Py_END_ALLOW_THREADS" はブロックを閉じます。

上のブロックは次のコードに展開されます:

   PyThreadState *_save;

   _save = PyEval_SaveThread();
   ... Do some blocking I/O operation ...
   PyEval_RestoreThread(_save);

Here is how these functions work: the global interpreter lock is used
to protect the pointer to the current thread state.  When releasing
the lock and saving the thread state, the current thread state pointer
must be retrieved before the lock is released (since another thread
could immediately acquire the lock and store its own thread state in
the global variable). Conversely, when acquiring the lock and
restoring the thread state, the lock must be acquired before storing
the thread state pointer.

注釈:

  Calling system I/O functions is the most common use case for
  releasing the GIL, but it can also be useful before calling long-
  running computations which don't need access to Python objects, such
  as compression or cryptographic functions operating over memory
  buffers.  For example, the standard "zlib" and "hashlib" modules
  release the GIL when compressing or hashing data.


Python 以外で作られたスレッド
-----------------------------

When threads are created using the dedicated Python APIs (such as the
"threading" module), a thread state is automatically associated to
them and the code showed above is therefore correct.  However, when
threads are created from C (for example by a third-party library with
its own thread management), they don't hold the GIL, nor is there a
thread state structure for them.

If you need to call Python code from these threads (often this will be
part of a callback API provided by the aforementioned third-party
library), you must first register these threads with the interpreter
by creating a thread state data structure, then acquiring the GIL, and
finally storing their thread state pointer, before you can start using
the Python/C API.  When you are done, you should reset the thread
state pointer, release the GIL, and finally free the thread state data
structure.

"PyGILState_Ensure()" と "PyGILState_Release()" はこの処理を自動的に行
います。 Cのスレッドから Python を呼び出す典型的な方法は以下のとおりで
す:

   PyGILState_STATE gstate;
   gstate = PyGILState_Ensure();

   /* Perform Python actions here. */
   result = CallSomeFunction();
   /* evaluate result or handle exception */

   /* Release the thread. No Python API allowed beyond this point. */
   PyGILState_Release(gstate);

Note that the "PyGILState_*" functions assume there is only one global
interpreter (created automatically by "Py_Initialize()").  Python
supports the creation of additional interpreters (using
"Py_NewInterpreter()"), but mixing multiple interpreters and the
"PyGILState_*" API is unsupported.


Cautions about fork()
---------------------

Another important thing to note about threads is their behaviour in
the face of the C "fork()" call. On most systems with "fork()", after
a process forks only the thread that issued the fork will exist.  This
has a concrete impact both on how locks must be handled and on all
stored state in CPython's runtime.

The fact that only the "current" thread remains means any locks held
by other threads will never be released. Python solves this for
"os.fork()" by acquiring the locks it uses internally before the fork,
and releasing them afterwards. In addition, it resets any Lock Objects
in the child. When extending or embedding Python, there is no way to
inform Python of additional (non-Python) locks that need to be
acquired before or reset after a fork. OS facilities such as
"pthread_atfork()" would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling "fork()"
directly rather than through "os.fork()" (and returning to or calling
into Python) may result in a deadlock by one of Python's internal
locks being held by a thread that is defunct after the fork.
"PyOS_AfterFork_Child()" tries to reset the necessary locks, but is
not always able to.

The fact that all other threads go away also means that CPython's
runtime state there must be cleaned up properly, which "os.fork()"
does.  This means finalizing all other "PyThreadState" objects
belonging to the current interpreter and all other
"PyInterpreterState" objects.  Due to this and the special nature of
the "main" interpreter, "fork()" should only be called in that
interpreter's "main" thread, where the CPython global runtime was
originally initialized. The only exception is if "exec()" will be
called immediately after.


高レベルAPI
-----------

C拡張を書いたりPythonインタプリタを埋め込むときに最も一般的に使われる
型や関数は次のとおりです:

type PyInterpreterState
    * 次に属します: Limited API (不透明な構造体として).*

   このデータ構造体は、協調動作する多数のスレッド間で共有されている状
   態を表現します。同じインタプリタに属するスレッドはモジュール管理情
   報やその他いくつかの内部的な情報を共有しています。この構造体には公
   開 (public) のメンバはありません。

   異なるインタプリタに属するスレッド間では、利用可能なメモリ、開かれ
   ているファイルデスクリプタなどといったプロセス状態を除いて、初期状
   態では何も共有されていません。GILもまた、スレッドがどのインタプリタ
   に属しているかに関わらずすべてのスレッドで共有されています。

type PyThreadState
    * 次に属します: Limited API (不透明な構造体として).*

   This data structure represents the state of a single thread.  The
   only public data member is:

   PyInterpreterState *interp

      This thread's interpreter state.

void PyEval_InitThreads()
    * 次に属します: Stable ABI.*

   Deprecated function which does nothing.

   In Python 3.6 and older, this function created the GIL if it didn't
   exist.

   バージョン 3.9 で変更: The function now does nothing.

   バージョン 3.7 で変更: この関数は "Py_Initialize()" から呼び出され
   るようになり、わざわざ呼び出す必要はもう無くなりました。

   バージョン 3.2 で変更: この関数は "Py_Initialize()" より前に呼び出
   すことができなくなりました。

   バージョン 3.9 で非推奨.

int PyEval_ThreadsInitialized()
    * 次に属します: Stable ABI.*

   Returns a non-zero value if "PyEval_InitThreads()" has been called.
   This function can be called without holding the GIL, and therefore
   can be used to avoid calls to the locking API when running single-
   threaded.

   バージョン 3.7 で変更: The *GIL* is now initialized by
   "Py_Initialize()".

   バージョン 3.9 で非推奨.

PyThreadState *PyEval_SaveThread()
    * 次に属します: Stable ABI.*

   Release the global interpreter lock (if it has been created) and
   reset the thread state to "NULL", returning the previous thread
   state (which is not "NULL").  If the lock has been created, the
   current thread must have acquired it.

void PyEval_RestoreThread(PyThreadState *tstate)
    * 次に属します: Stable ABI.*

   Acquire the global interpreter lock (if it has been created) and
   set the thread state to *tstate*, which must not be "NULL".  If the
   lock has been created, the current thread must not have acquired
   it, otherwise deadlock ensues.

   注釈:

     Calling this function from a thread when the runtime is
     finalizing will terminate the thread, even if the thread was not
     created by Python. You can use "_Py_IsFinalizing()" or
     "sys.is_finalizing()" to check if the interpreter is in process
     of being finalized before calling this function to avoid unwanted
     termination.

PyThreadState *PyThreadState_Get()
    * 次に属します: Stable ABI.*

   Return the current thread state.  The global interpreter lock must
   be held. When the current thread state is "NULL", this issues a
   fatal error (so that the caller needn't check for "NULL").

PyThreadState *PyThreadState_Swap(PyThreadState *tstate)
    * 次に属します: Stable ABI.*

   Swap the current thread state with the thread state given by the
   argument *tstate*, which may be "NULL".  The global interpreter
   lock must be held and is not released.

以下の関数はスレッドローカルストレージを利用していて、サブインタプリタ
との互換性がありません:

PyGILState_STATE PyGILState_Ensure()
    * 次に属します: Stable ABI.*

   Ensure that the current thread is ready to call the Python C API
   regardless of the current state of Python, or of the global
   interpreter lock. This may be called as many times as desired by a
   thread as long as each call is matched with a call to
   "PyGILState_Release()". In general, other thread-related APIs may
   be used between "PyGILState_Ensure()" and "PyGILState_Release()"
   calls as long as the thread state is restored to its previous state
   before the Release().  For example, normal usage of the
   "Py_BEGIN_ALLOW_THREADS" and "Py_END_ALLOW_THREADS" macros is
   acceptable.

   The return value is an opaque "handle" to the thread state when
   "PyGILState_Ensure()" was called, and must be passed to
   "PyGILState_Release()" to ensure Python is left in the same state.
   Even though recursive calls are allowed, these handles *cannot* be
   shared - each unique call to "PyGILState_Ensure()" must save the
   handle for its call to "PyGILState_Release()".

   When the function returns, the current thread will hold the GIL and
   be able to call arbitrary Python code.  Failure is a fatal error.

   注釈:

     Calling this function from a thread when the runtime is
     finalizing will terminate the thread, even if the thread was not
     created by Python. You can use "_Py_IsFinalizing()" or
     "sys.is_finalizing()" to check if the interpreter is in process
     of being finalized before calling this function to avoid unwanted
     termination.

void PyGILState_Release(PyGILState_STATE)
    * 次に属します: Stable ABI.*

   獲得したすべてのリソースを解放します。この関数を呼び出すと、Python
   の状態は対応する "PyGILState_Ensure()" を呼び出す前と同じとなります
   (通常、この状態は呼び出し元でははわかりませんので、GILState APIを利
   用するようにしてください)。

   "PyGILState_Ensure()" を呼び出す場合は、必ず同一スレッド内で対応す
   る "PyGILState_Release()" を呼び出してください。

PyThreadState *PyGILState_GetThisThreadState()
    * 次に属します: Stable ABI.*

   Get the current thread state for this thread.  May return "NULL" if
   no GILState API has been used on the current thread.  Note that the
   main thread always has such a thread-state, even if no auto-thread-
   state call has been made on the main thread.  This is mainly a
   helper/diagnostic function.

int PyGILState_Check()

   Return "1" if the current thread is holding the GIL and "0"
   otherwise. This function can be called from any thread at any time.
   Only if it has had its Python thread state initialized and
   currently is holding the GIL will it return "1". This is mainly a
   helper/diagnostic function.  It can be useful for example in
   callback contexts or memory allocation functions when knowing that
   the GIL is locked can allow the caller to perform sensitive actions
   or otherwise behave differently.

   バージョン 3.4 で追加.

以下のマクロは、通常末尾にセミコロンを付けずに使います; Python ソース
配布物内の使用例を見てください。

Py_BEGIN_ALLOW_THREADS
    * 次に属します: Stable ABI.*

   このマクロを展開すると "{ PyThreadState *_save; _save =
   PyEval_SaveThread();" になります。マクロに開き波括弧が入っているこ
   とに注意してください; この波括弧は後で "Py_END_ALLOW_THREADS" マク
   ロと対応させなければなりません。マクロについての詳しい議論は上記を
   参照してください。

Py_END_ALLOW_THREADS
    * 次に属します: Stable ABI.*

   このマクロを展開すると "PyEval_RestoreThread(_save); }" になります
   。マクロに開き波括弧が入っていることに注意してください; この波括弧
   は事前の "Py_BEGIN_ALLOW_THREADS" マクロと対応していなければなりま
   せん。マクロについての詳しい議論は上記を参照してください。

Py_BLOCK_THREADS
    * 次に属します: Stable ABI.*

   このマクロを展開すると "PyEval_RestoreThread(_save);" になります:
   閉じ波括弧のない "Py_END_ALLOW_THREADS" と同じです。

Py_UNBLOCK_THREADS
    * 次に属します: Stable ABI.*

   このマクロを展開すると "_save = PyEval_SaveThread();" になります:
   開き波括弧のない "Py_BEGIN_ALLOW_THREADS" と同じです。


低レベルAPI
-----------

次の全ての関数は "Py_Initialize()" の後に呼び出さなければなりません。

バージョン 3.7 で変更: "Py_Initialize()" now initializes the *GIL*.

PyInterpreterState *PyInterpreterState_New()
    * 次に属します: Stable ABI.*

   Create a new interpreter state object.  The global interpreter lock
   need not be held, but may be held if it is necessary to serialize
   calls to this function.

   引数無しで 監査イベント "cpython.PyInterpreterState_New" を送出しま
   す。

void PyInterpreterState_Clear(PyInterpreterState *interp)
    * 次に属します: Stable ABI.*

   Reset all information in an interpreter state object.  The global
   interpreter lock must be held.

   引数無しで 監査イベント "cpython.PyInterpreterState_Clear" を送出し
   ます。

void PyInterpreterState_Delete(PyInterpreterState *interp)
    * 次に属します: Stable ABI.*

   Destroy an interpreter state object.  The global interpreter lock
   need not be held.  The interpreter state must have been reset with
   a previous call to "PyInterpreterState_Clear()".

PyThreadState *PyThreadState_New(PyInterpreterState *interp)
    * 次に属します: Stable ABI.*

   Create a new thread state object belonging to the given interpreter
   object. The global interpreter lock need not be held, but may be
   held if it is necessary to serialize calls to this function.

void PyThreadState_Clear(PyThreadState *tstate)
    * 次に属します: Stable ABI.*

   Reset all information in a thread state object.  The global
   interpreter lock must be held.

   バージョン 3.9 で変更: This function now calls the
   "PyThreadState.on_delete" callback. Previously, that happened in
   "PyThreadState_Delete()".

void PyThreadState_Delete(PyThreadState *tstate)
    * 次に属します: Stable ABI.*

   Destroy a thread state object.  The global interpreter lock need
   not be held. The thread state must have been reset with a previous
   call to "PyThreadState_Clear()".

void PyThreadState_DeleteCurrent(void)

   Destroy the current thread state and release the global interpreter
   lock. Like "PyThreadState_Delete()", the global interpreter lock
   need not be held. The thread state must have been reset with a
   previous call to "PyThreadState_Clear()".

PyFrameObject *PyThreadState_GetFrame(PyThreadState *tstate)
    * 次に属します: Stable ABI (バージョン 3.10 より).*

   Get the current frame of the Python thread state *tstate*.

   Return a *strong reference*. Return "NULL" if no frame is currently
   executing.

   See also "PyEval_GetFrame()".

   *tstate* must not be "NULL".

   バージョン 3.9 で追加.

uint64_t PyThreadState_GetID(PyThreadState *tstate)
    * 次に属します: Stable ABI (バージョン 3.10 より).*

   Get the unique thread state identifier of the Python thread state
   *tstate*.

   *tstate* must not be "NULL".

   バージョン 3.9 で追加.

PyInterpreterState *PyThreadState_GetInterpreter(PyThreadState *tstate)
    * 次に属します: Stable ABI (バージョン 3.10 より).*

   Get the interpreter of the Python thread state *tstate*.

   *tstate* must not be "NULL".

   バージョン 3.9 で追加.

void PyThreadState_EnterTracing(PyThreadState *tstate)

   Suspend tracing and profiling in the Python thread state *tstate*.

   Resume them using the "PyThreadState_LeaveTracing()" function.

   バージョン 3.11 で追加.

void PyThreadState_LeaveTracing(PyThreadState *tstate)

   Resume tracing and profiling in the Python thread state *tstate*
   suspended by the "PyThreadState_EnterTracing()" function.

   See also "PyEval_SetTrace()" and "PyEval_SetProfile()" functions.

   バージョン 3.11 で追加.

PyInterpreterState *PyInterpreterState_Get(void)
    * 次に属します: Stable ABI (バージョン 3.9 より).*

   Get the current interpreter.

   Issue a fatal error if there no current Python thread state or no
   current interpreter. It cannot return NULL.

   The caller must hold the GIL.

   バージョン 3.9 で追加.

int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   インタプリタの一意な ID を返します。 処理中に何かエラーが起きたら、
   "-1" が返され、エラーがセットされます。

   The caller must hold the GIL.

   バージョン 3.7 で追加.

PyObject *PyInterpreterState_GetDict(PyInterpreterState *interp)
    * 次に属します: Stable ABI (バージョン 3.8 より).*

   インタプリタ固有のデータを保持している辞書を返します。 この関数が
   "NULL" を返した場合は、ここまでで例外は送出されておらず、呼び出し側
   はインタプリタ固有の辞書は利用できないと考えなければなりません。

   この関数は "PyModule_GetState()" を置き換えるものではなく、拡張モジ
   ュールがインタプリタ固有の状態情報を格納するのに使うべきものです。

   バージョン 3.8 で追加.

typedef PyObject *(*_PyFrameEvalFunction)(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)

   Type of a frame evaluation function.

   The *throwflag* parameter is used by the "throw()" method of
   generators: if non-zero, handle the current exception.

   バージョン 3.9 で変更: The function now takes a *tstate* parameter.

   バージョン 3.11 で変更: The *frame* parameter changed from
   "PyFrameObject*" to "_PyInterpreterFrame*".

_PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)

   Get the frame evaluation function.

   See the **PEP 523** "Adding a frame evaluation API to CPython".

   バージョン 3.9 で追加.

void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)

   Set the frame evaluation function.

   See the **PEP 523** "Adding a frame evaluation API to CPython".

   バージョン 3.9 で追加.

PyObject *PyThreadState_GetDict()
    *戻り値: 借用参照。** 次に属します: Stable ABI.*

   Return a dictionary in which extensions can store thread-specific
   state information.  Each extension should use a unique key to use
   to store state in the dictionary.  It is okay to call this function
   when no current thread state is available. If this function returns
   "NULL", no exception has been raised and the caller should assume
   no current thread state is available.

int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
    * 次に属します: Stable ABI.*

   Asynchronously raise an exception in a thread. The *id* argument is
   the thread id of the target thread; *exc* is the exception object
   to be raised. This function does not steal any references to *exc*.
   To prevent naive misuse, you must write your own C extension to
   call this.  Must be called with the GIL held. Returns the number of
   thread states modified; this is normally one, but will be zero if
   the thread id isn't found.  If *exc* is "NULL", the pending
   exception (if any) for the thread is cleared. This raises no
   exceptions.

   バージョン 3.7 で変更: *id* 引数の型が long から unsigned long へ変
   更されました。

void PyEval_AcquireThread(PyThreadState *tstate)
    * 次に属します: Stable ABI.*

   Acquire the global interpreter lock and set the current thread
   state to *tstate*, which must not be "NULL".  The lock must have
   been created earlier. If this thread already has the lock, deadlock
   ensues.

   注釈:

     Calling this function from a thread when the runtime is
     finalizing will terminate the thread, even if the thread was not
     created by Python. You can use "_Py_IsFinalizing()" or
     "sys.is_finalizing()" to check if the interpreter is in process
     of being finalized before calling this function to avoid unwanted
     termination.

   バージョン 3.8 で変更: Updated to be consistent with
   "PyEval_RestoreThread()", "Py_END_ALLOW_THREADS()", and
   "PyGILState_Ensure()", and terminate the current thread if called
   while the interpreter is finalizing.

   "PyEval_RestoreThread()" はいつでも (スレッドが初期化されたいないと
   きでも) 利用可能な高レベル関数です。

void PyEval_ReleaseThread(PyThreadState *tstate)
    * 次に属します: Stable ABI.*

   Reset the current thread state to "NULL" and release the global
   interpreter lock.  The lock must have been created earlier and must
   be held by the current thread.  The *tstate* argument, which must
   not be "NULL", is only used to check that it represents the current
   thread state --- if it isn't, a fatal error is reported.

   "PyEval_SaveThread()" はより高レベルな関数で常に (スレッドが初期化
   されていないときでも) 利用できます。

void PyEval_AcquireLock()
    * 次に属します: Stable ABI.*

   Acquire the global interpreter lock.  The lock must have been
   created earlier. If this thread already has the lock, a deadlock
   ensues.

   バージョン 3.2 で非推奨: This function does not update the current
   thread state.  Please use "PyEval_RestoreThread()" or
   "PyEval_AcquireThread()" instead.

   注釈:

     Calling this function from a thread when the runtime is
     finalizing will terminate the thread, even if the thread was not
     created by Python. You can use "_Py_IsFinalizing()" or
     "sys.is_finalizing()" to check if the interpreter is in process
     of being finalized before calling this function to avoid unwanted
     termination.

   バージョン 3.8 で変更: Updated to be consistent with
   "PyEval_RestoreThread()", "Py_END_ALLOW_THREADS()", and
   "PyGILState_Ensure()", and terminate the current thread if called
   while the interpreter is finalizing.

void PyEval_ReleaseLock()
    * 次に属します: Stable ABI.*

   Release the global interpreter lock.  The lock must have been
   created earlier.

   バージョン 3.2 で非推奨: This function does not update the current
   thread state.  Please use "PyEval_SaveThread()" or
   "PyEval_ReleaseThread()" instead.


サブインタプリタサポート
========================

ほとんどの場合は埋め込む Python インタプリタは1つだけですが、いくつか
の場合に同一プロセス内、あるいは同一スレッド内で、複数の独立したインタ
プリタを作成する必要があります。 これを可能にするのがサブインタプリタ
です。

"メイン" インタプリタとは、ランタイムが初期化を行ったときに最初に作成
されたインタプリタのことです。 サブインタプリタと違い、メインインタプ
リタにはシグナルハンドリングのような、プロセス全域で唯一な責務がありま
す。 メインインタプリタにはランタイムの初期化中の処理実行という責務も
あり、通常はランタイムの終了処理中に動いているランタイムでもあります。
"PyInterpreterState_Main()" 関数は、メインインタプリタの状態へのポイン
タを返します。

サブインタプリタを切り替えが "PyThreadState_Swap()" 関数でできます。
次の関数を使ってサブインタプリタの作成と削除が行えます:

PyThreadState *Py_NewInterpreter()
    * 次に属します: Stable ABI.*

   新しいサブインタプリタ (sub-interpreter) を生成します。サブインタプ
   リタとは、(ほぼ完全に) 個別に分割された Python コードの実行環境です
   。特に、新しいサブインタプリタは、 import されるモジュール全てにつ
   いて個別のバージョンを持ち、これには基盤となるモジュール
   "builtins", "__main__" および "sys" も含まれます。ロード済みのモジ
   ュールからなるテーブル ("sys.modules")  およびモジュール検索パス
   ("sys.path") もサブインタプリタ毎に別個のものになります。新たなサブ
   インタプリタ環境には "sys.argv" 変数がありません。また、サブインタ
   プリタは新たな標準 I/O ストリーム "sys.stdin", "sys.stdout",
   "sys.stderr" を持ちます (とはいえ、これらのストリームは根底にある同
   じファイル記述子を参照しています)。

   The return value points to the first thread state created in the
   new sub-interpreter.  This thread state is made in the current
   thread state. Note that no actual thread is created; see the
   discussion of thread states below.  If creation of the new
   interpreter is unsuccessful, "NULL" is returned; no exception is
   set since the exception state is stored in the current thread state
   and there may not be a current thread state.  (Like all other
   Python/C API functions, the global interpreter lock must be held
   before calling this function and is still held when it returns;
   however, unlike most other Python/C API functions, there needn't be
   a current thread state on entry.)

   Extension modules are shared between (sub-)interpreters as follows:

   * For modules using multi-phase initialization, e.g.
     "PyModule_FromDefAndSpec()", a separate module object is created
     and initialized for each interpreter. Only C-level static and
     global variables are shared between these module objects.

   * For modules using single-phase initialization, e.g.
     "PyModule_Create()", the first time a particular extension is
     imported, it is initialized normally, and a (shallow) copy of its
     module's dictionary is squirreled away. When the same extension
     is imported by another (sub-)interpreter, a new module is
     initialized and filled with the contents of this copy; the
     extension's "init" function is not called. Objects in the
     module's dictionary thus end up shared across (sub-)interpreters,
     which might cause unwanted behavior (see Bugs and caveats below).

     Note that this is different from what happens when an extension
     is imported after the interpreter has been completely re-
     initialized by calling "Py_FinalizeEx()" and "Py_Initialize()";
     in that case, the extension's "initmodule" function *is* called
     again. As with multi-phase initialization, this means that only
     C-level static and global variables are shared between these
     modules.

void Py_EndInterpreter(PyThreadState *tstate)
    * 次に属します: Stable ABI.*

   Destroy the (sub-)interpreter represented by the given thread
   state. The given thread state must be the current thread state.
   See the discussion of thread states below.  When the call returns,
   the current thread state is "NULL".  All thread states associated
   with this interpreter are destroyed.  (The global interpreter lock
   must be held before calling this function and is still held when it
   returns.)  "Py_FinalizeEx()" will destroy all sub-interpreters that
   haven't been explicitly destroyed at that point.


バグと注意事項
--------------

Because sub-interpreters (and the main interpreter) are part of the
same process, the insulation between them isn't perfect --- for
example, using low-level file operations like  "os.close()" they can
(accidentally or maliciously) affect each other's open files.  Because
of the way extensions are shared between (sub-)interpreters, some
extensions may not work properly; this is especially likely when using
single-phase initialization or (static) global variables. It is
possible to insert objects created in one sub-interpreter into a
namespace of another (sub-)interpreter; this should be avoided if
possible.

Special care should be taken to avoid sharing user-defined functions,
methods, instances or classes between sub-interpreters, since import
operations executed by such objects may affect the wrong
(sub-)interpreter's dictionary of loaded modules. It is equally
important to avoid sharing objects from which the above are reachable.

サブインタプリタを "PyGILState_*" API と組み合わせるのが難しいことにも
注意してください。これらのAPIはPythonのスレッド状態とOSレベルスレッド
が1対1で対応していることを前提にしていて、サブインタプリタが存在すると
その前提が崩れるからです。対応する "PyGILState_Ensure()" と
"PyGILState_Release()" の呼び出しのペアの間では、サブインタプリタの切
り替えを行わないことを強く推奨します。さらに、("ctypes" のような)これ
らのAPIを使ってPythonの外で作られたスレッドから Pythonコードを実行して
いる拡張モジュールはサブインタプリタを使うと壊れる可能性があります。


非同期通知
==========

インタプリタのメインスレッドに非同期な通知を行うために提供されている仕
組みです。これらの通知は関数ポインタと void ポインタ引数という形態を取
ります。

int Py_AddPendingCall(int (*func)(void*), void *arg)
    * 次に属します: Stable ABI.*

   インタプリタのメインスレッドから関数が呼び出される予定を組みます。
   成功すると "0" が返り、*func* はメインスレッドの呼び出しキューに詰
   められます。失敗すると、例外をセットせずに "-1" が返ります。

   無事にキューに詰められると、*func* は *いつかは必ず* インタプリタの
   メインスレッドから、*arg* を引数として呼び出されます。この関数は、
   通常の実行中の Python コードに対して非同期に呼び出されますが、次の
   両方の条件に合致したときに呼び出されます:

   * *bytecode* 境界上にいるとき、

   * with the main thread holding the *global interpreter lock*
     (*func* can therefore use the full C API).

   *func* must return "0" on success, or "-1" on failure with an
   exception set.  *func* won't be interrupted to perform another
   asynchronous notification recursively, but it can still be
   interrupted to switch threads if the global interpreter lock is
   released.

   This function doesn't need a current thread state to run, and it
   doesn't need the global interpreter lock.

   To call this function in a subinterpreter, the caller must hold the
   GIL. Otherwise, the function *func* can be scheduled to be called
   from the wrong interpreter.

   警告:

     これは、非常に特別な場合にのみ役立つ、低レベルな関数です。 *func*
     が可能な限り早く呼び出される保証はありません。メインスレッドがシ
     ステムコールを実行するのに忙しい場合は、 *func* はシステムコール
     が返ってくるまで呼び出されないでしょう。この関数は一般的には、任
     意の C スレッドから Python コードを呼び出すのには **向きません**
     。これの代わりに、 PyGILState API を使用してください。

   バージョン 3.1 で追加.

   バージョン 3.9 で変更: If this function is called in a
   subinterpreter, the function *func* is now scheduled to be called
   from the subinterpreter, rather than being called from the main
   interpreter. Each subinterpreter now has its own list of scheduled
   calls.


プロファイルとトレース (profiling and tracing)
==============================================

Python インタプリタは、プロファイル: 分析 (profile) や実行のトレース:
追跡 (trace) といった機能を組み込むために低水準のサポートを提供してい
ます。このサポートは、プロファイルやデバッグ、適用範囲分析 (coverage
analysis) ツールなどに使われます。

この C インターフェースは、プロファイルやトレース作業時に、Python レベ
ルの呼び出し可能オブジェクトが呼び出されることによるオーバヘッドを避け
、直接 C 関数呼び出しが行えるようにしています。プロファイルやトレース
機能の本質的な特性は変わっていません; インターフェースではトレース関数
をスレッドごとにインストールでき、トレース関数に報告される基本イベント
(basic event) は以前のバージョンにおいて Python レベルのトレース関数で
報告されていたものと同じです。

typedef int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)

   The type of the trace function registered using
   "PyEval_SetProfile()" and "PyEval_SetTrace()". The first parameter
   is the object passed to the registration function as *obj*, *frame*
   is the frame object to which the event pertains, *what* is one of
   the constants "PyTrace_CALL", "PyTrace_EXCEPTION", "PyTrace_LINE",
   "PyTrace_RETURN", "PyTrace_C_CALL", "PyTrace_C_EXCEPTION",
   "PyTrace_C_RETURN", or "PyTrace_OPCODE", and *arg* depends on the
   value of *what*:

   +---------------------------------+------------------------------------------+
   | *what* の値                     | *arg* の意味                             |
   |=================================|==========================================|
   | "PyTrace_CALL"                  | 常に "Py_None" 。                        |
   +---------------------------------+------------------------------------------+
   | "PyTrace_EXCEPTION"             | "sys.exc_info()" の返す例外情報です。    |
   +---------------------------------+------------------------------------------+
   | "PyTrace_LINE"                  | 常に "Py_None" 。                        |
   +---------------------------------+------------------------------------------+
   | "PyTrace_RETURN"                | 呼び出し側に返される予定の値か、例外によ |
   |                                 | って関数を抜ける場合は "NULL" です。     |
   +---------------------------------+------------------------------------------+
   | "PyTrace_C_CALL"                | 呼び出される関数オブジェクト。           |
   +---------------------------------+------------------------------------------+
   | "PyTrace_C_EXCEPTION"           | 呼び出される関数オブジェクト。           |
   +---------------------------------+------------------------------------------+
   | "PyTrace_C_RETURN"              | 呼び出される関数オブジェクト。           |
   +---------------------------------+------------------------------------------+
   | "PyTrace_OPCODE"                | 常に "Py_None" 。                        |
   +---------------------------------+------------------------------------------+

int PyTrace_CALL

   関数やメソッドが新たに呼び出されたり、ジェネレータが新たなエントリ
   の処理に入ったことを報告する際の、 "Py_tracefunc" の *what* の値で
   す。イテレータやジェネレータ関数の生成は、対応するフレーム内の
   Python バイトコードに制御の委譲 (control transfer) が起こらないため
   報告されないので注意してください。

int PyTrace_EXCEPTION

   例外が送出された際の "Py_tracefunc" の *what* の値です。現在実行さ
   れているフレームで例外がセットされ、何らかのバイトコードが処理され
   た後に、 *what* にこの値がセットされた状態でコールバック関数が呼び
   出されます。この結果、例外の伝播によって Python が呼び出しスタック
   を逆戻りする際に、各フレームから処理が戻るごとにコールバック関数が
   呼び出されます。トレース関数だけがこれらのイベントを受け取ります;
   プロファイラはこの種のイベントを必要としません。

int PyTrace_LINE

   The value passed as the *what* parameter to a "Py_tracefunc"
   function (but not a profiling function) when a line-number event is
   being reported. It may be disabled for a frame by setting
   "f_trace_lines" to *0* on that frame.

int PyTrace_RETURN

   呼び出しが返るときに "Py_tracefunc" 関数に *what* 引数として渡す値
   です。

int PyTrace_C_CALL

   C関数を呼び出す直前に "Py_tracefunc" 関数の *what* 引数として渡す値
   です。

int PyTrace_C_EXCEPTION

   C関数が例外を送出したときに "Py_tracefunc" 関数の *what* 引数として
   渡す値です。

int PyTrace_C_RETURN

   C関数から戻るときに "Py_tracefunc" 関数の *what* 引数として渡す値で
   す。

int PyTrace_OPCODE

   The value for the *what* parameter to "Py_tracefunc" functions (but
   not profiling functions) when a new opcode is about to be executed.
   This event is not emitted by default: it must be explicitly
   requested by setting "f_trace_opcodes" to *1* on the frame.

void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)

   Set the profiler function to *func*.  The *obj* parameter is passed
   to the function as its first parameter, and may be any Python
   object, or "NULL".  If the profile function needs to maintain
   state, using a different value for *obj* for each thread provides a
   convenient and thread-safe place to store it.  The profile function
   is called for all monitored events except "PyTrace_LINE"
   "PyTrace_OPCODE" and "PyTrace_EXCEPTION".

   "sys.setprofile()" 関数も参照してください。

   The caller must hold the *GIL*.

void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)

   Set the tracing function to *func*.  This is similar to
   "PyEval_SetProfile()", except the tracing function does receive
   line-number events and per-opcode events, but does not receive any
   event related to C function objects being called.  Any trace
   function registered using "PyEval_SetTrace()" will not receive
   "PyTrace_C_CALL", "PyTrace_C_EXCEPTION" or "PyTrace_C_RETURN" as a
   value for the *what* parameter.

   "sys.settrace()" 関数も参照してください。

   The caller must hold the *GIL*.


高度なデバッガサポート (advanced debugger support)
==================================================

以下の関数は高度なデバッグツールでの使用のためだけのものです。

PyInterpreterState *PyInterpreterState_Head()

   インタプリタ状態オブジェクトからなるリストのうち、先頭にあるものを
   返します。

PyInterpreterState *PyInterpreterState_Main()

   メインインタプリタの状態オブジェクトを返します。

PyInterpreterState *PyInterpreterState_Next(PyInterpreterState *interp)

   インタプリタ状態オブジェクトからなるリストのうち、*interp* の次にあ
   るものを返します。

PyThreadState *PyInterpreterState_ThreadHead(PyInterpreterState *interp)

   インタプリタ *interp* に関連付けられているスレッドからなるリストの
   うち、先頭にある "PyThreadState" オブジェクトを返します。

PyThreadState *PyThreadState_Next(PyThreadState *tstate)

   *tstate* と同じ "PyInterpreterState" オブジェクトに属しているスレッ
   ド状態オブジェクトのうち、 *tstate* の次にあるものを返します。


スレッドローカルストレージのサポート
====================================

Python インタプリタは、スレッドローカルストレージ (thread-local
storage, TLS) の低レベルサポートを提供していて、ネイティブの TLS 実装
を内部にラップして Python レベルのスレッドローカルストレージ API
("threading.local") をサポートしています。 CPython の C レベル API は
pthreads や Windows で与えられる TLS と同様です: スレッドキーとスレッ
ドごとに void* 値を関係付ける関数を使います。

The GIL does *not* need to be held when calling these functions; they
supply their own locking.

"Python.h" は TLS API の宣言を include せず、スレッドローカルストレー
ジを使うには "pythread.h" を include する必要があることに注意してくだ
さい。

注釈:

  この API 関数はどれも void* 値の代わりにメモリ管理を行うことはしませ
  ん。 メモリの確保と解放は自前で行う必要があります。 void* 値がたまた
  ま PyObject* だった場合は、 API 関数はそれぞれの値の参照カウントの操
  作は行いません。


スレッド固有ストレージ (Thread Specific Storage, TSS) API
---------------------------------------------------------

TSS API は、 CPython インタプリタに含まれている既存の TLS API を置き換
えるために導入されました。 この API は、スレッドキーの表現に int の代
わりに新しい型 "Py_tss_t" を使います。

バージョン 3.7 で追加.

参考: "CPython のスレッドローカルストレージのための新しい C API" (**PEP
    539**)

type Py_tss_t

   このデータ構造体はスレッドキーの状態を表現しています。この構造体の
   定義は、根底の TLS 実装に依存し、キーの初期化状態を表現する内部フィ
   ールドを持ちます。 この構造体には公開 (public) のメンバはありません
   。

   Py_LIMITED_API が定義されていないときは、この型の
   "Py_tss_NEEDS_INIT" による静的メモリ確保ができます。

Py_tss_NEEDS_INIT

   このマクロは "Py_tss_t" 変数の初期化子に展開されます。 このマクロは
   Py_LIMITED_API があるときは定義されません。


動的メモリ確保
~~~~~~~~~~~~~~

動的な "Py_tss_t" のメモリ確保は Py_LIMITED_API でビルドされた拡張モジ
ュールで必要になりますが、その実装がビルド時に不透明なために、この型の
静的なメモリ確保は不可能です。

Py_tss_t *PyThread_tss_alloc()
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   Return a value which is the same state as a value initialized with
   "Py_tss_NEEDS_INIT", or "NULL" in the case of dynamic allocation
   failure.

void PyThread_tss_free(Py_tss_t *key)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   Free the given *key* allocated by "PyThread_tss_alloc()", after
   first calling "PyThread_tss_delete()" to ensure any associated
   thread locals have been unassigned. This is a no-op if the *key*
   argument is "NULL".

   注釈:

     A freed key becomes a dangling pointer. You should reset the key
     to "NULL".


メソッド
~~~~~~~~

The parameter *key* of these functions must not be "NULL".  Moreover,
the behaviors of "PyThread_tss_set()" and "PyThread_tss_get()" are
undefined if the given "Py_tss_t" has not been initialized by
"PyThread_tss_create()".

int PyThread_tss_is_created(Py_tss_t *key)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   Return a non-zero value if the given "Py_tss_t" has been
   initialized by "PyThread_tss_create()".

int PyThread_tss_create(Py_tss_t *key)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   Return a zero value on successful initialization of a TSS key.  The
   behavior is undefined if the value pointed to by the *key* argument
   is not initialized by "Py_tss_NEEDS_INIT".  This function can be
   called repeatedly on the same key -- calling it on an already
   initialized key is a no-op and immediately returns success.

void PyThread_tss_delete(Py_tss_t *key)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   Destroy a TSS key to forget the values associated with the key
   across all threads, and change the key's initialization state to
   uninitialized.  A destroyed key is able to be initialized again by
   "PyThread_tss_create()". This function can be called repeatedly on
   the same key -- calling it on an already destroyed key is a no-op.

int PyThread_tss_set(Py_tss_t *key, void *value)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   Return a zero value to indicate successfully associating a void*
   value with a TSS key in the current thread.  Each thread has a
   distinct mapping of the key to a void* value.

void *PyThread_tss_get(Py_tss_t *key)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   Return the void* value associated with a TSS key in the current
   thread.  This returns "NULL" if no value is associated with the key
   in the current thread.


スレッドローカルストレージ (TLS) API
------------------------------------

バージョン 3.7 で非推奨: This API is superseded by Thread Specific
Storage (TSS) API.

注釈:

  This version of the API does not support platforms where the native
  TLS key is defined in a way that cannot be safely cast to "int".  On
  such platforms, "PyThread_create_key()" will return immediately with
  a failure status, and the other TLS functions will all be no-ops on
  such platforms.

前述の互換性の問題により、このバージョンのAPIは新規のコードで利用すべ
きではありません。

int PyThread_create_key()
    * 次に属します: Stable ABI.*

void PyThread_delete_key(int key)
    * 次に属します: Stable ABI.*

int PyThread_set_key_value(int key, void *value)
    * 次に属します: Stable ABI.*

void *PyThread_get_key_value(int key)
    * 次に属します: Stable ABI.*

void PyThread_delete_key_value(int key)
    * 次に属します: Stable ABI.*

void PyThread_ReInitTLS()
    * 次に属します: Stable ABI.*
