例外処理
********

この章で説明する関数を使うと、 Python の例外の処理や例外の送出ができる
ようになります。 Python の例外処理の基本をいくらか理解することが大切で
す。例外は POSIX "errno" 変数にやや似た機能を果たします: 発生した中で
最も新しいエラーの (スレッド毎の) グローバルなインジケータがあります。
実行に成功した場合にはほとんどの C API 関数がこれをクリアしませんが、
失敗したときにはエラーの原因を示すために設定します。ほとんどの C API
関数はエラーインジケータも返し、通常は関数がポインタを返すことになって
いる場合は "NULL" であり、関数が整数を返す場合は "-1" です。(例外:
"PyArg_*" 関数は実行に成功したときに "1" を返し、失敗したときに "0" を
返します).

具体的には、エラーインジケータは、例外の型、例外の値、トレースバックオ
ブジェクトの３つのオブジェクトポインタで構成されます。これらのポインタ
はどれでも、設定されない場合は "NULL" になりえます（ただし、いくつかの
組み合わせは禁止されており、例えば、例外の型が "NULL" の場合は、トレー
スバックは非 "NULL" の値になりません）

ある関数が呼び出した関数がいくつか失敗したために、その関数が失敗しなけ
ればならないとき、一般的にエラーインジケータを設定しません。呼び出した
関数がすでに設定しています。エラーを処理して例外をクリアするか、あるい
は (オブジェクト参照またはメモリ割り当てのような)それが持つどんなリソ
ースも取り除いた後に戻るかのどちらか一方を行う責任があります。エラーを
処理する準備をしていなければ、普通に続けるべきでは *ありません*。エラ
ーのために戻る場合は、エラーが設定されていると呼び出し元に知らせること
が大切です。エラーが処理されていない場合または丁寧に伝えられている場合
には、Python/C APIのさらなる呼び出しは意図した通りには動かない可能性が
あり、不可解な形で失敗するかもしれません。

注釈:

  The error indicator is **not** the result of "sys.exc_info()". The
  former corresponds to an exception that is not yet caught (and is
  therefore still propagating), while the latter returns an exception
  after it is caught (and has therefore stopped propagating).


出力とクリア
============

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

   エラーインジケータをクリアします。エラーインジケータが設定されてい
   ないならば、効果はありません。

void PyErr_PrintEx(int set_sys_last_vars)
    * 次に属します: Stable ABI.*

   標準のトレースバックを "sys.stderr" に出力し、エラーインジケータを
   クリアします。 ただし、エラーが "SystemExit" **である場合を除いて**
   です。 その場合、トレースバックは出力されず、 Python プロセスは
   "SystemExit" インスタンスで指定されたエラーコードで終了します。

   エラーインジケータが設定されているときに **だけ**、この関数を呼び出
   してください。 それ以外の場合、致命的なエラーを引き起こすでしょう!

   If *set_sys_last_vars* is nonzero, the variables "sys.last_type",
   "sys.last_value" and "sys.last_traceback" will be set to the type,
   value and traceback of the printed exception, respectively.

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

   "PyErr_PrintEx(1)" のエイリアスです。

void PyErr_WriteUnraisable(PyObject *obj)
    * 次に属します: Stable ABI.*

   現在の例外と *obj* 引数で "sys.unraisablehook()" を呼び出します。

   This utility function prints a warning message to "sys.stderr" when
   an exception has been set but it is impossible for the interpreter
   to actually raise the exception.  It is used, for example, when an
   exception occurs in an "__del__()" method.

   The function is called with a single argument *obj* that identifies
   the context in which the unraisable exception occurred. If
   possible, the repr of *obj* will be printed in the warning message.

   この関数を呼び出すときには、例外がセットされていなければなりません
   。


例外の送出
==========

以下の関数は、現在のスレッドのエラーインジケータの設定を補助します。利
便性のため、これらの関数のいくつかは、 "return" 文で利用できるように常
に "NULL" ポインタを返します。

void PyErr_SetString(PyObject *type, const char *message)
    * 次に属します: Stable ABI.*

   This is the most common way to set the error indicator.  The first
   argument specifies the exception type; it is normally one of the
   standard exceptions, e.g. "PyExc_RuntimeError".  You need not
   create a new *strong reference* to it (e.g. with "Py_INCREF()").
   The second argument is an error message; it is decoded from
   "'utf-8'".

void PyErr_SetObject(PyObject *type, PyObject *value)
    * 次に属します: Stable ABI.*

   この関数は "PyErr_SetString()" に似ていますが、例外の "値(value)"
   として任意のPythonオブジェクトを指定することができます。

PyObject *PyErr_Format(PyObject *exception, const char *format, ...)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI.*

   この関数はエラーインジケータを設定し "NULL" を返します。
   *exception* はPython例外クラスであるべきです。 *format* と以降の引
   数はエラーメッセージを作るためのもので, "PyUnicode_FromFormat()" の
   引数と同じ意味を持っています。 *format* は ASCII エンコードされた文
   字列です。

PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI (バージョン 3.5
   より).*

   "PyErr_Format()" と同じですが、可変長引数の代わりに "va_list" 引数
   を受け取ります。

   バージョン 3.5 で追加.

void PyErr_SetNone(PyObject *type)
    * 次に属します: Stable ABI.*

   これは "PyErr_SetObject(type, Py_None)" を省略したものです。

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

   これは "PyErr_SetString(PyExc_TypeError, message)" を省略したもので
   、ここで *message* は組み込み操作が不正な引数で呼び出されたというこ
   とを表しています。主に内部で使用するためのものです。

PyObject *PyErr_NoMemory()
    *戻り値: 常に NULL 。** 次に属します: Stable ABI.*

   これは "PyErr_SetNone(PyExc_MemoryError)" を省略したもので、"NULL"
   を返します。したがって、メモリ不足になったとき、オブジェクト割り当
   て関数は "return PyErr_NoMemory();" と書くことができます。

PyObject *PyErr_SetFromErrno(PyObject *type)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI.*

   This is a convenience function to raise an exception when a C
   library function has returned an error and set the C variable
   "errno".  It constructs a tuple object whose first item is the
   integer "errno" value and whose second item is the corresponding
   error message (gotten from "strerror()"), and then calls
   "PyErr_SetObject(type, object)".  On Unix, when the "errno" value
   is "EINTR", indicating an interrupted system call, this calls
   "PyErr_CheckSignals()", and if that set the error indicator, leaves
   it set to that.  The function always returns "NULL", so a wrapper
   function around a system call can write "return
   PyErr_SetFromErrno(type);" when the system call returns an error.

PyObject *PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI.*

   Similar to "PyErr_SetFromErrno()", with the additional behavior
   that if *filenameObject* is not "NULL", it is passed to the
   constructor of *type* as a third parameter.  In the case of
   "OSError" exception, this is used to define the "filename"
   attribute of the exception instance.

PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI (バージョン 3.7
   より).*

   "PyErr_SetFromErrnoWithFilenameObject()" に似てますが、ファイル名を
   2つ取る関数が失敗したときに例外を送出するために、2つ目のファイル名
   オブジェクトを受け取ります。

   バージョン 3.4 で追加.

PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI.*

   "PyErr_SetFromErrnoWithFilenameObject()" に似ていますが、ファイル名
   は C 文字列として与えられます。 *filename* は *ファイルシステムのエ
   ンコーディングとエラーハンドラ* でデコードされます。

PyObject *PyErr_SetFromWindowsErr(int ierr)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI on Windows (バー
   ジョン 3.7 より).*

   This is a convenience function to raise "WindowsError". If called
   with *ierr* of "0", the error code returned by a call to
   "GetLastError()" is used instead.  It calls the Win32 function
   "FormatMessage()" to retrieve the Windows description of error code
   given by *ierr* or "GetLastError()", then it constructs a tuple
   object whose first item is the *ierr* value and whose second item
   is the corresponding error message (gotten from "FormatMessage()"),
   and then calls "PyErr_SetObject(PyExc_WindowsError, object)". This
   function always returns "NULL".

   Availability: Windows.

PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI on Windows (バー
   ジョン 3.7 より).*

   "PyErr_SetFromWindowsErr()" に似ていますが、送出する例外の型を指定
   する引数が追加されています。

   Availability: Windows.

PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI on Windows (バー
   ジョン 3.7 より).*

   Similar to "PyErr_SetFromWindowsErr()", with the additional
   behavior that if *filename* is not "NULL", it is decoded from the
   filesystem encoding ("os.fsdecode()") and passed to the constructor
   of "OSError" as a third parameter to be used to define the
   "filename" attribute of the exception instance.

   Availability: Windows.

PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI on Windows (バー
   ジョン 3.7 より).*

   Similar to "PyErr_SetExcFromWindowsErr()", with the additional
   behavior that if *filename* is not "NULL", it is passed to the
   constructor of "OSError" as a third parameter to be used to define
   the "filename" attribute of the exception instance.

   Availability: Windows.

PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI on Windows (バー
   ジョン 3.7 より).*

   "PyErr_SetExcFromWindowsErrWithFilenameObject()" に似てますが、2つ
   目のファイル名オブジェクトを受け取ります。

   Availability: Windows.

   バージョン 3.4 で追加.

PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI on Windows (バー
   ジョン 3.7 より).*

   "PyErr_SetFromWindowsErrWithFilename()" に似ていますが、送出する例
   外の型を指定する引数が追加されています。

   Availability: Windows.

PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI (バージョン 3.7
   より).*

   "ImportError" を簡単に送出するための関数です。 *msg* は例外のメッセ
   ージ文字列としてセットされます。 *name* と *path* はどちらも "NULL"
   にしてよく、それぞれ "ImportError" の "name" 属性と "path" 属性とし
   てセットされます。

   バージョン 3.3 で追加.

PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path)
    *戻り値: 常に NULL 。** 次に属します: Stable ABI (バージョン 3.6
   より).*

   "PyErr_SetImportError()" とよく似ていますが、この関数は送出する例外
   として、 "ImportError" のサブクラスを指定できます。

   バージョン 3.6 で追加.

void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)

   現在の例外のファイル、行、オフセットの情報をセットします。 現在の例
   外が "SyntaxError" でない場合は、例外を表示するサブシステムが、例外
   が "SyntaxError" であると思えるように属性を追加します。

   バージョン 3.4 で追加.

void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   "PyErr_SyntaxLocationObject()" と似ていますが、 *filename* は *ファ
   イルシステムのエンコーディングとエラーハンドラ* でデコードされたバ
   イト文字列です。

   バージョン 3.2 で追加.

void PyErr_SyntaxLocation(const char *filename, int lineno)
    * 次に属します: Stable ABI.*

   "PyErr_SyntaxLocationEx()" と似ていますが、 *col_offset* 引数が除去
   されています。

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

   "PyErr_SetString(PyExc_SystemError, message)" を省略したものです。
   ここで *message* は内部操作(例えば、Python/C API関数)が不正な引数と
   ともに呼び出されたということを示しています。主に内部で使用するため
   のものです。


警告
====

以下の関数を使い、 C コードで起きた警告を報告します。 Python の
"warnings" モジュールで公開されている同様の関数とよく似てます。 これら
の関数は通常警告メッセージを *sys.stderr* へ出力しますが、ユーザが警告
をエラーへ変更するように指定することもでき、その場合は、関数は例外を送
出します。 警告機構がもつ問題のためにその関数が例外を送出するというこ
とも有り得ます。 例外が送出されない場合は戻り値は "0" で、例外が送出さ
れた場合は "-1" です。 (警告メッセージが実際に出力されるか、およびその
例外の原因が何かについては判断できません; これは意図的なものです。) 例
外が送出された場合、呼び出し元は通常の例外処理を行います (例えば、保持
していた参照に対し "Py_DECREF()" を行い、エラー値を返します)。

int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
    * 次に属します: Stable ABI.*

   警告メッセージを発行します。 *category* 引数は警告カテゴリ(以下を参
   照) かまたは "NULL" で、 *message* 引数は UTF-8 エンコードされた文
   字列です。 *stacklevel* はスタックフレームの数を示す正の整数です;
   警告はそのスタックフレームの中の実行している行から発行されます。
   *stacklevel* が 1 だと "PyErr_WarnEx()" を呼び出している関数が、2
   だとその上の関数が Warning の発行元になります。

   警告カテゴリは "PyExc_Warning" のサブクラスでなければなりません。
   "PyExc_Warning" は "PyExc_Exception" のサブクラスです。 デフォルト
   の警告カテゴリは "PyExc_RuntimeWarning" です。 標準の Python 警告カ
   テゴリは、 標準警告カテゴリ で名前が列挙されているグローバル変数と
   して利用可能です。

   警告をコントロールするための情報については、 "warnings" モジュール
   のドキュメンテーションとコマンドライン・ドキュメンテーションの "-W"
   オプションを参照してください。警告コントロールのためのC APIはありま
   せん。

int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)

   すべての警告の属性を明示的に制御した警告メッセージを出します。これ
   は Python 関数 "warnings.warn_explicit()" の直接的なラッパーで、さ
   らに情報を得るにはそちらを参照してください。そこに説明されているデ
   フォルトの効果を得るために、 *module* と *registry* 引数は "NULL"
   に設定することができます。

   バージョン 3.4 で追加.

int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
    * 次に属します: Stable ABI.*

   "PyErr_WarnExplicitObject()" に似ていますが、 *message* と *module*
   が UTF-8 エンコードされた文字列であるところが異なり、 *filename* は
   *ファイルシステムのエンコーディングとエラーハンドラ* でデコードされ
   ます。

int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
    * 次に属します: Stable ABI.*

   "PyErr_WarnEx()" に似たような関数ですが、警告メッセージをフォーマッ
   トするのに "PyUnicode_FromFormat()" を使用します。 *format* は
   ASCII にエンコードされた文字列です。

   バージョン 3.2 で追加.

int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
    * 次に属します: Stable ABI (バージョン 3.6 より).*

   Function similar to "PyErr_WarnFormat()", but *category* is
   "ResourceWarning" and it passes *source* to
   "warnings.WarningMessage".

   バージョン 3.6 で追加.


エラーインジケータの問い合わせ
==============================

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

   エラーインジケータが設定されているかテストします。設定されている場
   合は、例外の *型* ("PyErr_Set*" 関数の一つあるいは
   "PyErr_Restore()" への最も新しい呼び出しに対する第一引数)を返します
   。設定されていない場合は "NULL" を返します。あなたは戻り値への参照
   を持っていませんので、それに "Py_DECREF()" する必要はありません。

   The caller must hold the GIL.

   注釈:

     戻り値を特定の例外と比較しないでください。その代わりに、下に示す
     "PyErr_ExceptionMatches()" を使ってください。(比較は簡単に失敗す
     るでしょう。なぜなら、例外はクラスではなくインスタンスかもしれな
     いし、あるいは、クラス例外の場合は期待される例外のサブクラスかも
     しれないからです。)

int PyErr_ExceptionMatches(PyObject *exc)
    * 次に属します: Stable ABI.*

   "PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)" と同じ。例外が
   実際に設定されたときにだけ、これを呼び出だすべきです。例外が発生し
   ていないならば、メモリアクセス違反が起きるでしょう。

int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
    * 次に属します: Stable ABI.*

   例外 *given* が *exc* の例外型と適合する場合に真を返します。 *exc*
   がクラスオブジェクトである場合も、 *given* がサブクラスのインスタン
   スであるときに真を返します。 *exc* がタプルの場合は、タプルにある (
   およびそのサブタプルに再帰的にある) すべての例外型が適合するか調べ
   られます。

void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
    * 次に属します: Stable ABI.*

   エラーインジケータをアドレスを渡す三つの変数の中へ取り出します。エ
   ラーインジケータが設定されていない場合は、三つすべての変数を "NULL"
   に設定します。エラーインジケータが設定されている場合はクリアされ、
   あなたは取り出されたそれぞれのオブジェクトへの参照を持つことになり
   ます。型オブジェクトが "NULL" でないときでさえ、その値とトレースバ
   ックオブジェクトは "NULL" かもしれません。

   注釈:

     This function is normally only used by code that needs to catch
     exceptions or by code that needs to save and restore the error
     indicator temporarily, e.g.:

        {
           PyObject *type, *value, *traceback;
           PyErr_Fetch(&type, &value, &traceback);

           /* ... code that might produce other errors ... */

           PyErr_Restore(type, value, traceback);
        }

void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
    * 次に属します: Stable ABI.*

   Set  the error indicator from the three objects.  If the error
   indicator is already set, it is cleared first.  If the objects are
   "NULL", the error indicator is cleared.  Do not pass a "NULL" type
   and non-"NULL" value or traceback.  The exception type should be a
   class.  Do not pass an invalid exception type or value. (Violating
   these rules will cause subtle problems later.)  This call takes
   away a reference to each object: you must own a reference to each
   object before the call and after the call you no longer own these
   references.  (If you don't understand this, don't use this
   function.  I warned you.)

   注釈:

     This function is normally only used by code that needs to save
     and restore the error indicator temporarily.  Use "PyErr_Fetch()"
     to save the current error indicator.

void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
    * 次に属します: Stable ABI.*

   ある状況では、以下の "PyErr_Fetch()" が返す値は "正規化されていない
   " 可能性があります。つまり、 "*exc" はクラスオブジェクトだが "*val"
   は同じクラスのインスタンスではないという意味です。この関数はそのよ
   うな場合にそのクラスをインスタンス化するために使われます。その値が
   すでに正規化されている場合は何も起きません。遅延正規化はパフォーマ
   ンスを改善するために実装されています。

   注釈:

     This function *does not* implicitly set the "__traceback__"
     attribute on the exception value. If setting the traceback
     appropriately is desired, the following additional snippet is
     needed:

        if (tb != NULL) {
          PyException_SetTraceback(val, tb);
        }

PyObject *PyErr_GetHandledException(void)
    * 次に属します: Stable ABI (バージョン 3.11 より).*

   Retrieve the active exception instance, as would be returned by
   "sys.exception()". This refers to an exception that was *already
   caught*, not to an exception that was freshly raised. Returns a new
   reference to the exception or "NULL". Does not modify the
   interpreter's exception state.

   注釈:

     この関数は、通常は例外を扱うコードでは使用されません。正確に言う
     と、これは例外の状態を一時的に保存し、元に戻す必要があるコードで
     使用することができます。例外の状態を元に戻す、もしくはクリアする
     には "PyErr_SetHandledException()" を使ってください。

   バージョン 3.11 で追加.

void PyErr_SetHandledException(PyObject *exc)
    * 次に属します: Stable ABI (バージョン 3.11 より).*

   Set the active exception, as known from "sys.exception()".  This
   refers to an exception that was *already caught*, not to an
   exception that was freshly raised. To clear the exception state,
   pass "NULL".

   注釈:

     この関数は、通常は例外を扱うコードでは使用されません。正確に言う
     と、これは例外の状態を一時的に保存し、元に戻す必要があるコードで
     使用することができます。例外の状態を取得するには
     "PyErr_GetHandledException()" を使ってください。

   バージョン 3.11 で追加.

void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   Retrieve the old-style representation of the exception info, as
   known from "sys.exc_info()".  This refers to an exception that was
   *already caught*, not to an exception that was freshly raised.
   Returns new references for the three objects, any of which may be
   "NULL".  Does not modify the exception info state.  This function
   is kept for backwards compatibility. Prefer using
   "PyErr_GetHandledException()".

   注釈:

     この関数は、通常は例外を扱うコードでは使用されません。正確に言う
     と、これは例外の状態を一時的に保存し、元に戻す必要があるコードで
     使用することができます。例外の状態を元に戻す、もしくはクリアする
     には "PyErr_SetExcInfo()" を使ってください。

   バージョン 3.3 で追加.

void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
    * 次に属します: Stable ABI (バージョン 3.7 より).*

   Set the exception info, as known from "sys.exc_info()".  This
   refers to an exception that was *already caught*, not to an
   exception that was freshly raised.  This function steals the
   references of the arguments. To clear the exception state, pass
   "NULL" for all three arguments. This function is kept for backwards
   compatibility. Prefer using "PyErr_SetHandledException()".

   注釈:

     この関数は、通常は例外を扱うコードでは使用されません。正確に言う
     と、これは例外の状態を一時的に保存し、元に戻す必要があるコードで
     使用することができます。例外の状態を取得するには
     "PyErr_GetExcInfo()" を使ってください。

   バージョン 3.3 で追加.

   バージョン 3.11 で変更: The "type" and "traceback" arguments are no
   longer used and can be NULL. The interpreter now derives them from
   the exception instance (the "value" argument). The function still
   steals references of all three arguments.


シグナルハンドリング
====================

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

   This function interacts with Python's signal handling.

   If the function is called from the main thread and under the main
   Python interpreter, it checks whether a signal has been sent to the
   processes and if so, invokes the corresponding signal handler.  If
   the "signal" module is supported, this can invoke a signal handler
   written in Python.

   The function attempts to handle all pending signals, and then
   returns "0". However, if a Python signal handler raises an
   exception, the error indicator is set and the function returns "-1"
   immediately (such that other pending signals may not have been
   handled yet: they will be on the next "PyErr_CheckSignals()"
   invocation).

   If the function is called from a non-main thread, or under a non-
   main Python interpreter, it does nothing and returns "0".

   This function can be called by long-running C code that wants to be
   interruptible by user requests (such as by pressing Ctrl-C).

   注釈:

     The default Python signal handler for "SIGINT" raises the
     "KeyboardInterrupt" exception.

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

   Simulate the effect of a "SIGINT" signal arriving. This is
   equivalent to "PyErr_SetInterruptEx(SIGINT)".

   注釈:

     This function is async-signal-safe.  It can be called without the
     *GIL* and from a C signal handler.

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

   シグナルが到達した効果をシミュレートします。 次に
   "PyErr_CheckSignals()" が呼ばれたとき、与えられたシグナル番号用の
   Python のシグナルハンドラが呼び出されます。

   This function can be called by C code that sets up its own signal
   handling and wants Python signal handlers to be invoked as expected
   when an interruption is requested (for example when the user
   presses Ctrl-C to interrupt an operation).

   If the given signal isn't handled by Python (it was set to
   "signal.SIG_DFL" or "signal.SIG_IGN"), it will be ignored.

   If *signum* is outside of the allowed range of signal numbers, "-1"
   is returned.  Otherwise, "0" is returned.  The error indicator is
   never changed by this function.

   注釈:

     This function is async-signal-safe.  It can be called without the
     *GIL* and from a C signal handler.

   バージョン 3.10 で追加.

int PySignal_SetWakeupFd(int fd)

   このユーティリティ関数は、シグナルを受け取ったときにシグナル番号を
   バイトとして書き込むファイル記述子を指定します。 *fd* はノンブロッ
   キングでなければなりません。 この関数は、1つ前のファイル記述子を返
   します。

   値 "-1" を渡すと、この機能を無効にします; これが初期状態です。 この
   関数は Python の "signal.set_wakeup_fd()" と同等ですが、どんなエラ
   ーチェックも行いません。 *fd* は有効なファイル記述子であるべきです
   。 この関数はメインスレッドからのみ呼び出されるべきです。

   バージョン 3.5 で変更: Windowsで、この関数はソケットハンドルをサポ
   ートするようになりました。


例外クラス
==========

PyObject *PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
    *戻り値: 新しい参照。** 次に属します: Stable ABI.*

   このユーティリティ関数は新しい例外クラスを作成して返します。 *name*
   引数は新しい例外の名前、 "module.classname" 形式の C文字列でなけれ
   ばならない。 *base* と *dict* 引数は通常 "NULL" です。これはすべて
   の例外のためのルート、組み込み名 "Exception" (Cでは
   "PyExc_Exception" としてアクセス可能)をルートとして派生したクラスオ
   ブジェクトを作成します。

   The "__module__" attribute of the new class is set to the first
   part (up to the last dot) of the *name* argument, and the class
   name is set to the last part (after the last dot).  The *base*
   argument can be used to specify alternate base classes; it can
   either be only one class or a tuple of classes. The *dict* argument
   can be used to specify a dictionary of class variables and methods.

PyObject *PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)
    *戻り値: 新しい参照。** 次に属します: Stable ABI.*

   "PyErr_NewException()" とほぼ同じですが、新しい例外クラスに簡単に
   docstring を設定できます。 *doc* が "NULL" で無い場合、それが例外ク
   ラスの docstring になります。

   バージョン 3.2 で追加.


例外オブジェクト
================

PyObject *PyException_GetTraceback(PyObject *ex)
    *戻り値: 新しい参照。** 次に属します: Stable ABI.*

   Python で "__traceback__" 属性からアクセスできるものと同じ、例外に
   関する traceback の新しい参照を返します。関係する traceback が無い
   場合は、 "NULL" を返します。

int PyException_SetTraceback(PyObject *ex, PyObject *tb)
    * 次に属します: Stable ABI.*

   その例外に関する traceback に *tb* をセットします。クリアするには
   "Py_None" を使用してください。

PyObject *PyException_GetContext(PyObject *ex)
    *戻り値: 新しい参照。** 次に属します: Stable ABI.*

   Return the context (another exception instance during whose
   handling *ex* was raised) associated with the exception as a new
   reference, as accessible from Python through the "__context__"
   attribute. If there is no context associated, this returns "NULL".

void PyException_SetContext(PyObject *ex, PyObject *ctx)
    * 次に属します: Stable ABI.*

   例外に関するコンテキストに *ctx* をセットします。クリアするには
   "NULL" を使用してください。*ctx* が例外インスタンスかどうかを確かめ
   る型チェックは行われません。これは *ctx* への参照を盗みます。

PyObject *PyException_GetCause(PyObject *ex)
    *戻り値: 新しい参照。** 次に属します: Stable ABI.*

   Return the cause (either an exception instance, or "None", set by
   "raise ... from ...") associated with the exception as a new
   reference, as accessible from Python through the "__cause__"
   attribute.

void PyException_SetCause(PyObject *ex, PyObject *cause)
    * 次に属します: Stable ABI.*

   Set the cause associated with the exception to *cause*.  Use "NULL"
   to clear it.  There is no type check to make sure that *cause* is
   either an exception instance or "None".  This steals a reference to
   *cause*.

   The "__suppress_context__" attribute is implicitly set to "True" by
   this function.


Unicode 例外オブジェクト
========================

以下の関数は C言語から Unicode 例外を作ったり修正したりするために利用
します。

PyObject *PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
    *戻り値: 新しい参照。** 次に属します: Stable ABI.*

   *encoding*, *object*, *length*, *start*, *end*, *reason* 属性をもっ
   た "UnicodeDecodeError" オブジェクトを作成します。 *encoding* およ
   び *reason* は UTF-8 エンコードされた文字列です。

PyObject *PyUnicodeDecodeError_GetEncoding(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetEncoding(PyObject *exc)
    *戻り値: 新しい参照。** 次に属します: Stable ABI.*

   与えられた例外オブジェクトの *encoding* 属性を返します。

PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc)
    *戻り値: 新しい参照。** 次に属します: Stable ABI.*

   与えられた例外オブジェクトの *object* 属性を返します。

int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
    * 次に属します: Stable ABI.*

   渡された例外オブジェクトから *start* 属性を取得して **start* に格納
   します。*start* は "NULL" であってはなりません。成功したら "0" を、
   失敗したら "-1" を返します。

int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
    * 次に属します: Stable ABI.*

   Set the *start* attribute of the given exception object to *start*.
   Return "0" on success, "-1" on failure.

int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
    * 次に属します: Stable ABI.*

   渡された例外オブジェクトから *end* 属性を取得して **end* に格納しま
   す。*end* は "NULL" であってはなりません。成功したら "0" を、失敗し
   たら "-1" を返します。

int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
    * 次に属します: Stable ABI.*

   渡された例外オブジェクトの *end* 属性を *end* に設定します。成功し
   たら "0" を、失敗したら "-1" を返します。

PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc)
PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc)
    *戻り値: 新しい参照。** 次に属します: Stable ABI.*

   渡された例外オブジェクトの *reason* 属性を返します。

int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
    * 次に属します: Stable ABI.*

   渡された例外オブジェクトの *reason* 属性を *reason* に設定します。
   成功したら "0" を、失敗したら "-1" を返します。


再帰の管理
==========

These two functions provide a way to perform safe recursive calls at
the C level, both in the core and in extension modules.  They are
needed if the recursive code does not necessarily invoke Python code
(which tracks its recursion depth automatically). They are also not
needed for *tp_call* implementations because the call protocol takes
care of recursion handling.

int Py_EnterRecursiveCall(const char *where)
    * 次に属します: Stable ABI (バージョン 3.9 より).*

   C レベルの再帰呼び出しをしようとしているところに印を付けます。

   If "USE_STACKCHECK" is defined, this function checks if the OS
   stack overflowed using "PyOS_CheckStack()".  If this is the case,
   it sets a "MemoryError" and returns a nonzero value.

   The function then checks if the recursion limit is reached.  If
   this is the case, a "RecursionError" is set and a nonzero value is
   returned. Otherwise, zero is returned.

   *where* は "" in instance check"" のような UTF-8 エンコードされた文
   字列にして、再帰の深さの限界に達したことで送出される
   "RecursionError" のメッセージに連結できるようにすべきです。

   バージョン 3.9 で変更: This function is now also available in the
   limited API.

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

   "Py_EnterRecursiveCall()" を終了させます。
   "Py_EnterRecursiveCall()" の *成功した* 呼び出しに対し 1 回呼ばなけ
   ればなりません。

   バージョン 3.9 で変更: This function is now also available in the
   limited API.

コンテナ型に対し "tp_repr" を適切に実装するには、特殊な再帰の処理が求
められます。スタックの防護に加え、 "tp_repr" は循環処理を避けるために
オブジェクトを辿っていく必要があります。次の 2 つの関数はその機能を容
易にします。実質的には、これらは "reprlib.recursive_repr()" と同等な C
の実装です。

int Py_ReprEnter(PyObject *object)
    * 次に属します: Stable ABI.*

   循環処理を検知するために、 "tp_repr" の実装の先頭で呼び出します。

   そのオブジェクトが既に処理されたものだった場合、この関数は正の整数
   を返します。その場合、 "tp_repr" の実装は、循環を示す文字列オブジェ
   クトを返すべきです。例えば、 "dict" オブジェクトは "{...}" を返しま
   すし、  "list" オブジェクトは "[...]" を返します。

   再帰回数の上限に達した場合は、この関数は負の整数を返します。この場
   合、 "tp_repr" の実装は一般的には "NULL" を返すべきです。

   それ以外の場合は、関数はゼロを返し、 "tp_repr" の実装は通常どおり処
   理を続けてかまいません。

void Py_ReprLeave(PyObject *object)
    * 次に属します: Stable ABI.*

   "Py_ReprEnter()" を終了させます。 0 を返した "Py_ReprEnter()" の呼
   び出しに対し 1 回呼ばなければなりません。


標準例外
========

"PyExc_" の後ろにPythonの例外名が続く名前をもつグローバル変数として、
すべての標準Python例外が利用可能です。これらは型 PyObject* を持ち、す
べてクラスオブジェクトです。完璧を期するために、すべての変数を以下に列
挙します:

+-------------------------------------------+-----------------------------------+------------+
| C名                                       | Python名                          | 注釈       |
|===========================================|===================================|============|
| "PyExc_BaseException"                     | "BaseException"                   | [1]        |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_Exception"                         | "Exception"                       | [1]        |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ArithmeticError"                   | "ArithmeticError"                 | [1]        |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_AssertionError"                    | "AssertionError"                  |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_AttributeError"                    | "AttributeError"                  |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_BlockingIOError"                   | "BlockingIOError"                 |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_BrokenPipeError"                   | "BrokenPipeError"                 |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_BufferError"                       | "BufferError"                     |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ChildProcessError"                 | "ChildProcessError"               |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ConnectionAbortedError"            | "ConnectionAbortedError"          |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ConnectionError"                   | "ConnectionError"                 |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ConnectionRefusedError"            | "ConnectionRefusedError"          |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ConnectionResetError"              | "ConnectionResetError"            |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_EOFError"                          | "EOFError"                        |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_FileExistsError"                   | "FileExistsError"                 |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_FileNotFoundError"                 | "FileNotFoundError"               |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_FloatingPointError"                | "FloatingPointError"              |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_GeneratorExit"                     | "GeneratorExit"                   |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ImportError"                       | "ImportError"                     |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_IndentationError"                  | "IndentationError"                |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_IndexError"                        | "IndexError"                      |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_InterruptedError"                  | "InterruptedError"                |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_IsADirectoryError"                 | "IsADirectoryError"               |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_KeyError"                          | "KeyError"                        |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_KeyboardInterrupt"                 | "KeyboardInterrupt"               |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_LookupError"                       | "LookupError"                     | [1]        |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_MemoryError"                       | "MemoryError"                     |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ModuleNotFoundError"               | "ModuleNotFoundError"             |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_NameError"                         | "NameError"                       |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_NotADirectoryError"                | "NotADirectoryError"              |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_NotImplementedError"               | "NotImplementedError"             |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_OSError"                           | "OSError"                         | [1]        |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_OverflowError"                     | "OverflowError"                   |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_PermissionError"                   | "PermissionError"                 |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ProcessLookupError"                | "ProcessLookupError"              |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_RecursionError"                    | "RecursionError"                  |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ReferenceError"                    | "ReferenceError"                  |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_RuntimeError"                      | "RuntimeError"                    |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_StopAsyncIteration"                | "StopAsyncIteration"              |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_StopIteration"                     | "StopIteration"                   |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_SyntaxError"                       | "SyntaxError"                     |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_SystemError"                       | "SystemError"                     |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_SystemExit"                        | "SystemExit"                      |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_TabError"                          | "TabError"                        |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_TimeoutError"                      | "TimeoutError"                    |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_TypeError"                         | "TypeError"                       |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_UnboundLocalError"                 | "UnboundLocalError"               |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_UnicodeDecodeError"                | "UnicodeDecodeError"              |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_UnicodeEncodeError"                | "UnicodeEncodeError"              |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_UnicodeError"                      | "UnicodeError"                    |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_UnicodeTranslateError"             | "UnicodeTranslateError"           |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ValueError"                        | "ValueError"                      |            |
+-------------------------------------------+-----------------------------------+------------+
| "PyExc_ZeroDivisionError"                 | "ZeroDivisionError"               |            |
+-------------------------------------------+-----------------------------------+------------+

バージョン 3.3 で追加: "PyExc_BlockingIOError" 、
"PyExc_BrokenPipeError" 、 "PyExc_ChildProcessError" 、
"PyExc_ConnectionError" 、 "PyExc_ConnectionAbortedError" 、
"PyExc_ConnectionRefusedError" 、 "PyExc_ConnectionResetError" 、
"PyExc_FileExistsError" 、 "PyExc_FileNotFoundError" 、
"PyExc_InterruptedError" 、 "PyExc_IsADirectoryError" 、
"PyExc_NotADirectoryError" 、 "PyExc_PermissionError" 、
"PyExc_ProcessLookupError"  、 "PyExc_TimeoutError" は **PEP 3151** に
より導入されました。

バージョン 3.5 で追加: "PyExc_StopAsyncIteration" および
"PyExc_RecursionError" 。

バージョン 3.6 で追加: "PyExc_ModuleNotFoundError".

これらは互換性のある "PyExc_OSError" のエイリアスです:

+---------------------------------------+------------+
| C名                                   | 注釈       |
|=======================================|============|
| "PyExc_EnvironmentError"              |            |
+---------------------------------------+------------+
| "PyExc_IOError"                       |            |
+---------------------------------------+------------+
| "PyExc_WindowsError"                  | [2]        |
+---------------------------------------+------------+

バージョン 3.3 で変更: これらのエイリアスは例外の種類を分けるために使
われます。

注釈:

[1] これは別の標準例外のためのベースクラスです。

[2] Windowsでのみ定義されています。プリプロセッサマクロ "MS_WINDOWS"
    が定義されているかテストすることで、これを使うコードを保護してくだ
    さい。


標準警告カテゴリ
================

"PyExc_" の後ろにPythonの例外名が続く名前をもつグローバル変数として、
すべての標準Python警告カテゴリが利用可能です。これらは型 PyObject* を
持ち、すべてクラスオブジェクトです。完璧を期するために、すべての変数を
以下に列挙します:

+--------------------------------------------+-----------------------------------+------------+
| C名                                        | Python名                          | 注釈       |
|============================================|===================================|============|
| "PyExc_Warning"                            | "Warning"                         | [3]        |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_BytesWarning"                       | "BytesWarning"                    |            |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_DeprecationWarning"                 | "DeprecationWarning"              |            |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_FutureWarning"                      | "FutureWarning"                   |            |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_ImportWarning"                      | "ImportWarning"                   |            |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_PendingDeprecationWarning"          | "PendingDeprecationWarning"       |            |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_ResourceWarning"                    | "ResourceWarning"                 |            |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_RuntimeWarning"                     | "RuntimeWarning"                  |            |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_SyntaxWarning"                      | "SyntaxWarning"                   |            |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_UnicodeWarning"                     | "UnicodeWarning"                  |            |
+--------------------------------------------+-----------------------------------+------------+
| "PyExc_UserWarning"                        | "UserWarning"                     |            |
+--------------------------------------------+-----------------------------------+------------+

バージョン 3.2 で追加: "PyExc_ResourceWarning".

注釈:

[3] これは別の標準警告カテゴリのためのベースクラスです。
