例外処理¶
The functions described in this chapter will let you handle and raise Python
exceptions. It is important to understand some of the basics of Python
exception handling. It works somewhat like the POSIX errno
variable:
there is a global indicator (per thread) of the last error that occurred. Most
C API functions don't clear this on success, but will set it to indicate the
cause of the error on failure. Most C API functions also return an error
indicator, usually NULL
if they are supposed to return a pointer, or -1
if they return an integer (exception: the PyArg_*
functions
return 1
for success and 0
for failure).
具体的には、エラーインジケータは、例外の型、例外の値、トレースバックオブジェクトの3つのオブジェクトポインタで構成されます。これらのポインタはどれでも、設定されない場合は NULL
になりえます(ただし、いくつかの組み合わせは禁止されており、例えば、例外の型が NULL
の場合は、トレースバックは非 NULL
の値になりません)
ある関数が呼び出した関数がいくつか失敗したために、その関数が失敗しなければならないとき、一般的にエラーインジケータを設定しません。呼び出した関数がすでに設定しています。エラーを処理して例外をクリアするか、あるいは (オブジェクト参照またはメモリ割り当てのような)それが持つどんなリソースも取り除いた後に戻るかのどちらか一方を行う責任があります。エラーを処理する準備をしていなければ、普通に続けるべきでは ありません。エラーのために戻る場合は、エラーが設定されていると呼び出し元に知らせることが大切です。エラーが処理されていない場合または丁寧に伝えられている場合には、Python/C APIのさらなる呼び出しは意図した通りには動かない可能性があり、不可解な形で失敗するかもしれません。
注釈
エラー識別子は sys.exc_info()
の結果 ではありません。エラー識別子はまだ捕捉されていない例外 (したがってまだ伝播します) に対応しているのに対し、 sys.exc_info() の結果は捕捉された後の例外を返します (したがってもう伝播しません)。
出力とクリア¶
-
void PyErr_Clear()¶
- Part of the Stable ABI.
エラーインジケータをクリアします。エラーインジケータが設定されていないならば、効果はありません。
-
void PyErr_PrintEx(int set_sys_last_vars)¶
- Part of the Stable ABI.
Print a standard traceback to
sys.stderr
and clear the error indicator. Unless the error is aSystemExit
, in that case no traceback is printed and the Python process will exit with the error code specified by theSystemExit
instance.エラーインジケータが設定されているときに だけ、この関数を呼び出してください。 それ以外の場合、致命的なエラーを引き起こすでしょう!
set_sys_last_vars が非ゼロであれば、
sys.last_type
,sys.last_value
,sys.last_traceback
変数が、表示される例外のタイプ、値、トレースバックそれぞれに反映されます。
-
void PyErr_Print()¶
- Part of the Stable ABI.
PyErr_PrintEx(1)
のエイリアスです。
-
void PyErr_WriteUnraisable(PyObject *obj)¶
- Part of the Stable ABI.
現在の例外と obj 引数で
sys.unraisablehook()
を呼び出します。例外が設定されているがインタプリタが実際に例外を発生させることができないときに、このユーティリティ関数は警告メッセージを
sys.stderr
へ出力します。例えば、例外が__del__()
メソッドで発生したときに使われます。発生させられない例外が起きたコンテキストを指し示す単一の引数 obj で関数が呼び出されます。 可能な場合は、 obj の repr 文字列が警告メッセージに出力されます。
この関数を呼び出すときには、例外がセットされていなければなりません。
例外の送出¶
以下の関数は、現在のスレッドのエラーインジケータの設定を補助します。利便性のため、これらの関数のいくつかは、 return
文で利用できるように常に NULL
ポインタを返します。
-
void PyErr_SetString(PyObject *type, const char *message)¶
- Part of the 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 increment its reference count. The second argument is an error message; it is decoded from'utf-8'
.
-
void PyErr_SetObject(PyObject *type, PyObject *value)¶
- Part of the Stable ABI.
この関数は
PyErr_SetString()
に似ていますが、例外の "値(value)" として任意のPythonオブジェクトを指定することができます。
-
PyObject *PyErr_Format(PyObject *exception, const char *format, ...)¶
- Return value: Always NULL. Part of the Stable ABI.
この関数はエラーインジケータを設定し
NULL
を返します。 exception はPython例外クラスであるべきです。 format と以降の引数はエラーメッセージを作るためのもので,PyUnicode_FromFormat()
の引数と同じ意味を持っています。 format は ASCII エンコードされた文字列です。
-
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)¶
- Return value: Always NULL. Part of the Stable ABI since version 3.5.
PyErr_Format()
と同じですが、可変長引数の代わりにva_list
引数を受け取ります。バージョン 3.5 で追加.
-
void PyErr_SetNone(PyObject *type)¶
- Part of the Stable ABI.
これは
PyErr_SetObject(type, Py_None)
を省略したものです。
-
int PyErr_BadArgument()¶
- Part of the Stable ABI.
これは
PyErr_SetString(PyExc_TypeError, message)
を省略したもので、ここで message は組み込み操作が不正な引数で呼び出されたということを表しています。主に内部で使用するためのものです。
-
PyObject *PyErr_NoMemory()¶
- Return value: Always NULL. Part of the Stable ABI.
これは
PyErr_SetNone(PyExc_MemoryError)
を省略したもので、NULL
を返します。したがって、メモリ不足になったとき、オブジェクト割り当て関数はreturn PyErr_NoMemory();
と書くことができます。
-
PyObject *PyErr_SetFromErrno(PyObject *type)¶
- Return value: Always NULL. Part of the Stable ABI.
Cライブラリ関数がエラーを返してC変数
errno
を設定したときに、これは例外を発生させるために便利な関数です。第一要素が整数errno
値で、第二要素が (strerror()
から得られる)対応するエラーメッセージであるタプルオブジェクトを構成します。それから、PyErr_SetObject(type, object)
を呼び出します。 Unixでは、errno
値がEINTR
であるとき、すなわち割り込まれたシステムコールを表しているとき、これはPyErr_CheckSignals()
を呼び出し、それがエラーインジケータを設定した場合は設定されたままにしておきます。関数は常にNULL
を返します。したがって、システムコールがエラーを返したとき、システムコールのラッパー関数はreturn PyErr_SetFromErrno(type);
と書くことができます。
-
PyObject *PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)¶
- Return value: Always NULL. Part of the Stable ABI.
PyErr_SetFromErrno()
に似ていますが、 filenameObject がNULL
でない場合に、 type のコンストラクタに第三引数として渡すというふるまいが追加されています。OSError
例外の場合では、 filenameObject が例外インスタンスのfilename
属性を定義するのに使われます。
-
PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)¶
- Return value: Always NULL. Part of the Stable ABI since version 3.7.
PyErr_SetFromErrnoWithFilenameObject()
に似てますが、ファイル名を2つ取る関数が失敗したときに例外を送出するために、2つ目のファイル名オブジェクトを受け取ります。バージョン 3.4 で追加.
-
PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)¶
- Return value: Always NULL. Part of the Stable ABI.
Similar to
PyErr_SetFromErrnoWithFilenameObject()
, but the filename is given as a C string. filename is decoded from the filesystem encoding and error handler.
-
PyObject *PyErr_SetFromWindowsErr(int ierr)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
This is a convenience function to raise
WindowsError
. If called with ierr of0
, the error code returned by a call toGetLastError()
is used instead. It calls the Win32 functionFormatMessage()
to retrieve the Windows description of error code given by ierr orGetLastError()
, then it constructs a tuple object whose first item is the ierr value and whose second item is the corresponding error message (gotten fromFormatMessage()
), and then callsPyErr_SetObject(PyExc_WindowsError, object)
. This function always returnsNULL
.利用可能な環境: Windows 。
-
PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
PyErr_SetFromWindowsErr()
に似ていますが、送出する例外の型を指定する引数が追加されています。利用可能な環境: Windows 。
-
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
PyErr_SetFromWindowsErrWithFilenameObject()
に似ていますが、ファイル名は C 文字列として与えられます。 filename はファイルシステムのエンコーディング (os.fsdecode()
) でデコードされます。利用可能な環境: Windows 。
-
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
PyErr_SetFromWindowsErrWithFilenameObject()
に似ていますが、送出する例外の型を指定する引数が追加されています。利用可能な環境: Windows 。
-
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
PyErr_SetExcFromWindowsErrWithFilenameObject()
に似てますが、2つ目のファイル名オブジェクトを受け取ります。利用可能な環境: Windows 。
バージョン 3.4 で追加.
-
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)¶
- Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7.
PyErr_SetFromWindowsErrWithFilename()
に似ていますが、送出する例外の型を指定する引数が追加されています。利用可能な環境: Windows 。
-
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)¶
- Return value: Always NULL. Part of the Stable ABI since version 3.7.
ImportError
を簡単に送出するための関数です。 msg は例外のメッセージ文字列としてセットされます。 name と path はどちらもNULL
にしてよく、それぞれImportError
のname
属性とpath
属性としてセットされます。バージョン 3.3 で追加.
-
PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path)¶
- Return value: Always NULL. Part of the Stable ABI since version 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)¶
- Part of the Stable ABI since version 3.7.
Like
PyErr_SyntaxLocationObject()
, but filename is a byte string decoded from the filesystem encoding and error handler.バージョン 3.2 で追加.
-
void PyErr_SyntaxLocation(const char *filename, int lineno)¶
- Part of the Stable ABI.
Like
PyErr_SyntaxLocationEx()
, but the col_offset parameter is omitted.
-
void PyErr_BadInternalCall()¶
- Part of the 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)¶
- Part of the 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)¶
Issue a warning message with explicit control over all warning attributes. This is a straightforward wrapper around the Python function
warnings.warn_explicit()
; see there for more information. The module and registry arguments may be set toNULL
to get the default effect described there.バージョン 3.4 で追加.
-
int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)¶
- Part of the Stable ABI.
Similar to
PyErr_WarnExplicitObject()
except that message and module are UTF-8 encoded strings, and filename is decoded from the filesystem encoding and error handler.
-
int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)¶
- Part of the Stable ABI.
PyErr_WarnEx()
に似たような関数ですが、警告メッセージをフォーマットするのにPyUnicode_FromFormat()
を使用します。 format は ASCII にエンコードされた文字列です。バージョン 3.2 で追加.
-
int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)¶
- Part of the Stable ABI since version 3.6.
PyErr_WarnFormat()
に似た関数ですが、category はResourceWarning
になり、source はwarnings.WarningMessage()
に渡されます。バージョン 3.6 で追加.
エラーインジケータの問い合わせ¶
-
PyObject *PyErr_Occurred()¶
- Return value: Borrowed reference. Part of the Stable ABI.
Test whether the error indicator is set. If set, return the exception type (the first argument to the last call to one of the
PyErr_Set*
functions or toPyErr_Restore()
). If not set, returnNULL
. You do not own a reference to the return value, so you do not need toPy_DECREF()
it.呼び出し側はGILを獲得する必要があります
注釈
戻り値を特定の例外と比較しないでください。その代わりに、下に示す
PyErr_ExceptionMatches()
を使ってください。(比較は簡単に失敗するでしょう。なぜなら、例外はクラスではなくインスタンスかもしれないし、あるいは、クラス例外の場合は期待される例外のサブクラスかもしれないからです。)
-
int PyErr_ExceptionMatches(PyObject *exc)¶
- Part of the Stable ABI.
PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)
と同じ。例外が実際に設定されたときにだけ、これを呼び出だすべきです。例外が発生していないならば、メモリアクセス違反が起きるでしょう。
-
int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)¶
- Part of the Stable ABI.
例外 given が exc の例外型と適合する場合に真を返します。 exc がクラスオブジェクトである場合も、 given がサブクラスのインスタンスであるときに真を返します。 exc がタプルの場合は、タプルにある (およびそのサブタプルに再帰的にある) すべての例外型が適合するか調べられます。
-
void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)¶
- Part of the Stable ABI.
エラーインジケータをアドレスを渡す三つの変数の中へ取り出します。エラーインジケータが設定されていない場合は、三つすべての変数を
NULL
に設定します。エラーインジケータが設定されている場合はクリアされ、あなたは取り出されたそれぞれのオブジェクトへの参照を持つことになります。型オブジェクトがNULL
でないときでさえ、その値とトレースバックオブジェクトはNULL
かもしれません。注釈
通常、この関数は例外を捕捉する必要のあるコードや、エラーインジケータを一時的に保存して復元する必要のあるコードでのみ使います。
{ 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)¶
- Part of the Stable ABI.
三つのオブジェクトからエラーインジケータを設定します。エラーインジケータがすでに設定されている場合は、最初にクリアされます。オブジェクトが
NULL
ならば、エラーインジケータがクリアされます。NULL
のtypeと非NULL
のvalueあるいは tracebackを渡してはいけません。例外の型(type)はクラスであるべきです。無効な例外の型(type)あるいは値(value)を渡してはいけません。(これらの規則を破ると後で気付きにくい問題の原因となるでしょう。) この呼び出しはそれぞれのオブジェクトへの参照を取り除きます: あなたは呼び出しの前にそれぞれのオブジェクトへの参照を持たなければならないのであり、また呼び出しの後にはもはやこれらの参照を持っていません。(これを理解していない場合は、この関数を使ってはいけません。注意しておきます。)注釈
通常、この関数はエラーインジケータを一時的に保存し復元する必要のあるコードでのみ使います。 現在のエラーインジケータを保存するためには
PyErr_Fetch()
を使ってください。
-
void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)¶
- Part of the Stable ABI.
ある状況では、以下の
PyErr_Fetch()
が返す値は "正規化されていない" 可能性があります。つまり、*exc
はクラスオブジェクトだが*val
は同じクラスのインスタンスではないという意味です。この関数はそのような場合にそのクラスをインスタンス化するために使われます。その値がすでに正規化されている場合は何も起きません。遅延正規化はパフォーマンスを改善するために実装されています。注釈
この関数は例外値に暗黙的に
__traceback__
属性を設定 しません 。 トレースバックを適切に設定する必要がある場合は、次の追加のコード片が必要です:if (tb != NULL) { PyException_SetTraceback(val, tb); }
-
PyObject *PyErr_GetHandledException(void)¶
- Part of the Stable ABI since version 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 orNULL
. Does not modify the interpreter's exception state.注釈
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use
PyErr_SetHandledException()
to restore or clear the exception state.バージョン 3.11 で追加.
-
void PyErr_SetHandledException(PyObject *exc)¶
- Part of the Stable ABI since version 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, passNULL
.注釈
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use
PyErr_GetHandledException()
to get the exception state.バージョン 3.11 で追加.
-
void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)¶
- Part of the Stable ABI since version 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 beNULL
. Does not modify the exception info state. This function is kept for backwards compatibility. Prefer usingPyErr_GetHandledException()
.注釈
この関数は、通常は例外を扱うコードでは使用されません。正確に言うと、これは例外の状態を一時的に保存し、元に戻す必要があるコードで使用することができます。例外の状態を元に戻す、もしくはクリアするには
PyErr_SetExcInfo()
を使ってください。バージョン 3.3 で追加.
-
void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)¶
- Part of the Stable ABI since version 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, passNULL
for all three arguments. This function is kept for backwards compatibility. Prefer usingPyErr_SetHandledException()
.注釈
この関数は、通常は例外を扱うコードでは使用されません。正確に言うと、これは例外の状態を一時的に保存し、元に戻す必要があるコードで使用することができます。例外の状態を取得するには
PyErr_GetExcInfo()
を使ってください。バージョン 3.3 で追加.
バージョン 3.11 で変更: The
type
andtraceback
arguments are no longer used and can be NULL. The interpreter now derives them from the exception instance (thevalue
argument). The function still steals references of all three arguments.
シグナルハンドリング¶
-
int PyErr_CheckSignals()¶
- Part of the 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 nextPyErr_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 theKeyboardInterrupt
exception.
-
void PyErr_SetInterrupt()¶
- Part of the Stable ABI.
Simulate the effect of a
SIGINT
signal arriving. This is equivalent toPyErr_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)¶
- Part of the Stable ABI since version 3.10.
Simulate the effect of a signal arriving. The next time
PyErr_CheckSignals()
is called, the Python signal handler for the given signal number will be called.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
orsignal.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)¶
- Return value: New reference. Part of the Stable ABI.
このユーティリティ関数は新しい例外クラスを作成して返します。 name 引数は新しい例外の名前、
module.classname
形式の C文字列でなければならない。 base と dict 引数は通常NULL
です。これはすべての例外のためのルート、組み込み名Exception
(CではPyExc_Exception
としてアクセス可能)をルートとして派生したクラスオブジェクトを作成します。新しいクラスの
__module__
属性は name 引数の前半部分(最後のドットまで)に設定され、クラス名は後半部分(最後のドットの後)に設定されます。 base 引数は代わりのベースクラスを指定するために使えます; 一つのクラスでも、クラスのタプルでも構いません。 dict 引数はクラス変数とメソッドの辞書を指定するために使えます。
-
PyObject *PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)¶
- Return value: New reference. Part of the Stable ABI.
PyErr_NewException()
とほぼ同じですが、新しい例外クラスに簡単に docstring を設定できます。 doc がNULL
で無い場合、それが例外クラスの docstring になります。バージョン 3.2 で追加.
例外オブジェクト¶
-
PyObject *PyException_GetTraceback(PyObject *ex)¶
- Return value: New reference. Part of the Stable ABI.
Python で
__traceback__
属性からアクセスできるものと同じ、例外に関する traceback の新しい参照を返します。関係する traceback が無い場合は、NULL
を返します。
-
int PyException_SetTraceback(PyObject *ex, PyObject *tb)¶
- Part of the Stable ABI.
その例外に関する traceback に tb をセットします。クリアするには
Py_None
を使用してください。
-
PyObject *PyException_GetContext(PyObject *ex)¶
- Return value: New reference. Part of the Stable ABI.
Python で
__context__
属性からアクセスできるものと同じ、例外に関するコンテキスト (ex が送出されたときに処理していた別の例外インスタンス) の新しい参照を返します。関係するコンテキストが無い場合は、NULL
を返します。
-
void PyException_SetContext(PyObject *ex, PyObject *ctx)¶
- Part of the Stable ABI.
例外に関するコンテキストに ctx をセットします。クリアするには
NULL
を使用してください。ctx が例外インスタンスかどうかを確かめる型チェックは行われません。これは ctx への参照を盗みます。
-
PyObject *PyException_GetCause(PyObject *ex)¶
- Return value: New reference. Part of the Stable ABI.
Python で
__cause__
属性からアクセスできるものと同じ、例外に関する原因 (raise ... from ...
によってセットされる例外インスタンス、もしくはNone
) の新しい参照を返します。
-
void PyException_SetCause(PyObject *ex, PyObject *cause)¶
- Part of the Stable ABI.
例外に関係する原因に cause をセットします。 クリアするには
NULL
を使用してください。 cause が例外インスタンスかNone
のどちらかであることを確かめる型チェックは行われません。 これは cause への参照を盗みます。この関数によって暗黙的に
__suppress_context__
にTrue
がセットされます。
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)¶
- Return value: New reference. Part of the Stable ABI.
encoding, object, length, start, end, reason 属性をもった
UnicodeDecodeError
オブジェクトを作成します。 encoding および reason は UTF-8 エンコードされた文字列です。
-
PyObject *PyUnicodeDecodeError_GetEncoding(PyObject *exc)¶
-
PyObject *PyUnicodeEncodeError_GetEncoding(PyObject *exc)¶
- Return value: New reference. Part of the Stable ABI.
与えられた例外オブジェクトの encoding 属性を返します。
-
PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc)¶
-
PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc)¶
-
PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc)¶
- Return value: New reference. Part of the 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)¶
- Part of the 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)¶
- Part of the Stable ABI.
渡された例外オブジェクトの start 属性を start に設定します。成功したら
0
を、失敗したら-1
を返します。
-
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)¶
- Part of the 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)¶
- Part of the Stable ABI.
渡された例外オブジェクトの end 属性を end に設定します。成功したら
0
を、失敗したら-1
を返します。
-
PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc)¶
-
PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc)¶
-
PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc)¶
- Return value: New reference. Part of the 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)¶
- Part of the 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)¶
- Part of the Stable ABI since version 3.9.
C レベルの再帰呼び出しをしようとしているところに印を付けます。
USE_STACKCHECK
が定義されている場合、 OS のスタックがオーバーフローがしたかどうかをPyOS_CheckStack()
を使ってチェックします。もしオーバーフローしているなら、MemoryError
をセットしゼロでない値を返します。次にこの関数は再帰の上限に達していないかをチェックします。 上限に達している場合、
RecursionError
をセットしゼロでない値を返します。 そうでない場合はゼロを返します。where should be a UTF-8 encoded string such as
" in instance check"
to be concatenated to theRecursionError
message caused by the recursion depth limit.バージョン 3.9 で変更: This function is now also available in the limited API.
-
void Py_LeaveRecursiveCall(void)¶
- Part of the Stable ABI since version 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)¶
- Part of the Stable ABI.
循環処理を検知するために、
tp_repr
の実装の先頭で呼び出します。そのオブジェクトが既に処理されたものだった場合、この関数は正の整数を返します。その場合、
tp_repr
の実装は、循環を示す文字列オブジェクトを返すべきです。例えば、dict
オブジェクトは{...}
を返しますし、list
オブジェクトは[...]
を返します。再帰回数の上限に達した場合は、この関数は負の整数を返します。この場合、
tp_repr
の実装は一般的にはNULL
を返すべきです。それ以外の場合は、関数はゼロを返し、
tp_repr
の実装は通常どおり処理を続けてかまいません。
-
void Py_ReprLeave(PyObject *object)¶
- Part of the Stable ABI.
Py_ReprEnter()
を終了させます。 0 を返したPy_ReprEnter()
の呼び出しに対し 1 回呼ばなければなりません。
標準例外¶
All standard Python exceptions are available as global variables whose names are
PyExc_
followed by the Python exception name. These have the type
PyObject*; they are all class objects. For completeness, here are all
the variables:
C名 |
Python名 |
注釈 |
---|---|---|
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
バージョン 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名 |
注釈 |
---|---|
|
|
|
|
|
バージョン 3.3 で変更: これらのエイリアスは例外の種類を分けるために使われます。
注釈:
標準警告カテゴリ¶
All standard Python warning categories are available as global variables whose
names are PyExc_
followed by the Python exception name. These have the type
PyObject*; they are all class objects. For completeness, here are all
the variables:
C名 |
Python名 |
注釈 |
---|---|---|
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
バージョン 3.2 で追加: PyExc_ResourceWarning
.
注釈:
- 3
これは別の標準警告カテゴリのためのベースクラスです。