引数の解釈と値の構築
********************

これらの関数は独自の拡張モジュール用の関数やメソッドを作成する際に便利
です。詳しい情報や用例は Python インタプリタの拡張と埋め込み にありま
す。

最初に説明する 3 つの関数、 "PyArg_ParseTuple()",
"PyArg_ParseTupleAndKeywords()",および "PyArg_Parse()" はいずれも *書
式文字列 (format string)* を使います。書式文字列は、関数が受け取るはず
の引数に関する情報を伝えるのに用いられます。いずれの関数における書式文
字列も、同じ書式を使っています。

書式文字列は、ゼロ個またはそれ以上の 「書式単位 (format unit)」 から成
り立ちます。 1つの書式単位は1つの Python オブジェクトを表します; 通常
は単一の文字か、書式単位からなる文字列を括弧で囲ったものになります。例
外として、括弧で囲われていない書式単位文字列が単一のアドレス引数に対応
する場合がいくつかあります。以下の説明では、引用符のついた形式は書式単
位です; (丸)括弧で囲った部分は書式単位に対応する Python のオブジェクト
型です; [角] 括弧は値をアドレス渡しする際に使う C の変数型です。

These formats allow accessing an object as a contiguous chunk of
memory. You don’t have to provide raw storage for the returned unicode
or bytes area.  Also, you won’t have to release any memory yourself,
except with the "es", "es#", "et" and "et#" formats.

"s" (string or Unicode) [const char *]
   Convert a Python string or Unicode object to a C pointer to a
   character string.  You must not provide storage for the string
   itself; a pointer to an existing string is stored into the
   character pointer variable whose address you pass.  The C string is
   NUL-terminated.  The Python string must not contain embedded NUL
   bytes; if it does, a "TypeError" exception is raised. Unicode
   objects are converted to C strings using the default encoding.  If
   this conversion fails, a "UnicodeError" is raised.

"s#" (string, Unicode or any read buffer compatible object) [const
char *, int (or "Py_ssize_t", see below)]
   This variant on "s" stores into two C variables, the first one a
   pointer to a character string, the second one its length.  In this
   case the Python string may contain embedded null bytes.  Unicode
   objects pass back a pointer to the default encoded string version
   of the object if such a conversion is possible.  All other read-
   buffer compatible objects pass back a reference to the raw internal
   data representation.

   Starting with Python 2.5 the type of the length argument can be
   controlled by defining the macro "PY_SSIZE_T_CLEAN" before
   including "Python.h".  If the macro is defined, length is a
   "Py_ssize_t" rather than an int.

"s*" (string, Unicode, or any buffer compatible object) [Py_buffer]
   Similar to "s#", this code fills a Py_buffer structure provided by
   the caller.  The buffer gets locked, so that the caller can
   subsequently use the buffer even inside a "Py_BEGIN_ALLOW_THREADS"
   block; the caller is responsible for calling "PyBuffer_Release"
   with the structure after it has processed the data.

   バージョン 2.6 で追加.

"z" (string, Unicode  or "None") [const char *]
   "s" に似ていますが、Python オブジェクトは "None" でもよく、その場合
   には C のポインタは *NULL* にセットされます。

"z#" (string, Unicode, "None" or any read buffer compatible object)
[const char *, int]
   This is to "s#" as "z" is to "s".

"z*" (string, Unicode, "None" or any buffer compatible object)
[Py_buffer]
   This is to "s*" as "z" is to "s".

   バージョン 2.6 で追加.

"u" (Unicode) [Py_UNICODE *]
   Convert a Python Unicode object to a C pointer to a NUL-terminated
   buffer of 16-bit Unicode (UTF-16) data.  As with "s", there is no
   need to provide storage for the Unicode data buffer; a pointer to
   the existing Unicode data is stored into the "Py_UNICODE" pointer
   variable whose address you pass.

"u#" (Unicode) [Py_UNICODE *, int]
   This variant on "u" stores into two C variables, the first one a
   pointer to a Unicode data buffer, the second one its length. Non-
   Unicode objects are handled by interpreting their read-buffer
   pointer as pointer to a "Py_UNICODE" array.

"es" (string, Unicode or character buffer compatible object) [const
char *encoding, char **buffer]
   This variant on "s" is used for encoding Unicode and objects
   convertible to Unicode into a character buffer. It only works for
   encoded data without embedded NUL bytes.

   This format requires two arguments.  The first is only used as
   input, and must be a "const char*" which points to the name of an
   encoding as a NUL-terminated string, or *NULL*, in which case the
   default encoding is used.  An exception is raised if the named
   encoding is not known to Python. The second argument must be a
   "char**"; the value of the pointer it references will be set to a
   buffer with the contents of the argument text.  The text will be
   encoded in the encoding specified by the first argument.

   "PyArg_ParseTuple()" を使うと、必要なサイズのバッファを確保し、その
   バッファにエンコード後のデータをコピーして、 **buffer* がこの新たに
   確保された記憶領域を指すように変更します。呼び出し側には、確保され
   たバッファを使い終わった後に "PyMem_Free()" で解放する責任がありま
   す。

"et" (string, Unicode or character buffer compatible object) [const
char *encoding, char **buffer]
   Same as "es" except that 8-bit string objects are passed through
   without recoding them.  Instead, the implementation assumes that
   the string object uses the encoding passed in as parameter.

"es#" (string, Unicode or character buffer compatible object) [const
char *encoding, char **buffer, int *buffer_length]
   This variant on "s#" is used for encoding Unicode and objects
   convertible to Unicode into a character buffer.  Unlike the "es"
   format, this variant allows input data which contains NUL
   characters.

   It requires three arguments.  The first is only used as input, and
   must be a "const char*" which points to the name of an encoding as
   a NUL-terminated string, or *NULL*, in which case the default
   encoding is used.  An exception is raised if the named encoding is
   not known to Python. The second argument must be a "char**"; the
   value of the pointer it references will be set to a buffer with the
   contents of the argument text.  The text will be encoded in the
   encoding specified by the first argument.  The third argument must
   be a pointer to an integer; the referenced integer will be set to
   the number of bytes in the output buffer.

   この書式の処理には二つのモードがあります:

   **buffer* が *NULL* ポインタを指している場合、関数は必要なサイズの
   バッファを確保し、そのバッファにエンコード後のデータをコピーして、
   **buffer* がこの新たに確保された記憶領域を指すように変更します。呼
   び出し側には、確保されたバッファを使い終わった後に "PyMem_Free()"
   で解放する責任があります。

   If **buffer* points to a non-*NULL* pointer (an already allocated
   buffer), "PyArg_ParseTuple()" will use this location as the buffer
   and interpret the initial value of **buffer_length* as the buffer
   size.  It will then copy the encoded data into the buffer and NUL-
   terminate it.  If the buffer is not large enough, a "TypeError"
   will be set. Note: starting from Python 3.6 a "ValueError" will be
   set.

   どちらの場合も、 **buffer_length* は終端の NUL バイトを含まないエン
   コード済みデータの長さにセットされます。

"et#" (string, Unicode or character buffer compatible object) [const
char *encoding, char **buffer, int *buffer_length]
   Same as "es#" except that string objects are passed through without
   recoding them. Instead, the implementation assumes that the string
   object uses the encoding passed in as parameter.

"b" (integer) [unsigned char]
   Python の非負の整数を、 C の "unsigned char" 型の小さな符号無し整数
   に変換します。

"B" (integer) [unsigned char]
   Python の整数を、オーバフローチェックを行わずに、 C の "unsigned
   char" 型の小さな整数に変換します。

   バージョン 2.3 で追加.

"h" (integer) [short int]
   Python の整数を、 C の "short int" 型に変換します。

"H" (integer) [unsigned short int]
   Python の整数を、オーバフローチェックを行わずに、 C の "unsigned
   short int" 型に変換します。

   バージョン 2.3 で追加.

"i" (integer) [int]
   Python の整数を、 C の "int" 型に変換します。

"I" (integer) [unsigned int]
   Python の整数を、オーバフローチェックを行わずに、 C の "unsigned
   int" 型に変換します。

   バージョン 2.3 で追加.

"l" (integer) [long int]
   Python の整数を、 C の "long int" 型に変換します。

"k" (integer) [unsigned long]
   Convert a Python integer or long integer to a C "unsigned long"
   without overflow checking.

   バージョン 2.3 で追加.

"L" (integer) [PY_LONG_LONG]
   Convert a Python integer to a C "long long".  This format is only
   available on platforms that support "long long" (or "_int64" on
   Windows).

"K" (integer) [unsigned PY_LONG_LONG]
   Convert a Python integer or long integer to a C "unsigned long
   long" without overflow checking.  This format is only available on
   platforms that support "unsigned long long" (or "unsigned _int64"
   on Windows).

   バージョン 2.3 で追加.

"n" (integer) [Py_ssize_t]
   Convert a Python integer or long integer to a C "Py_ssize_t".

   バージョン 2.5 で追加.

"c" (string of length 1) [char]
   Convert a Python character, represented as a string of length 1, to
   a C "char".

"f" (float) [float]
   Python の浮動小数点型を、 C の "float" 型に変換します。

"d" (float) [double]
   Python の浮動小数点型を、 C の "double" 型に変換します。

"D" (complex) [Py_complex]
   Python の複素数型を、 C の "Py_complex" 構造体に変換します。

"O" (object) [PyObject *]
   Python オブジェクトを (一切変換を行わずに) C の Python オブジェクト
   型ポインタに保存します。これにより、C プログラムは実際のオブジェク
   トを受け渡しされます。オブジェクトの参照カウントは増加しません。保
   存されるポインタが *NULL* になることはありません。

"O!" (object) [*typeobject*, PyObject *]
   Python オブジェクトを C の Python オブジェクト型ポインタに保存しま
   す。 "O" に似ていますが、二つの C の引数をとります: 一つ目の引数は
   Python の型オブジェクトへのアドレスで、二つ目の引数はオブジェクトへ
   のポインタが保存されている ("PyObject*" の) C の変数へのアドレスで
   す。Python オブジェクトが指定した型ではない場合、 "TypeError" を送
   出します。

"O&" (object) [*converter*, *anything*]
   Convert a Python object to a C variable through a *converter*
   function. This takes two arguments: the first is a function, the
   second is the address of a C variable (of arbitrary type),
   converted to "void *". The *converter* function in turn is called
   as follows:

      status = converter(object, address);

   where *object* is the Python object to be converted and *address*
   is the "void*" argument that was passed to the "PyArg_Parse*()"
   function.  The returned *status* should be "1" for a successful
   conversion and "0" if the conversion has failed.  When the
   conversion fails, the *converter* function should raise an
   exception and leave the content of *address* unmodified.

"S" (string) [PyStringObject *]
   Like "O" but requires that the Python object is a string object.
   Raises "TypeError" if the object is not a string object.  The C
   variable may also be declared as "PyObject*".

"U" (Unicode string) [PyUnicodeObject *]
   Like "O" but requires that the Python object is a Unicode object.
   Raises "TypeError" if the object is not a Unicode object.  The C
   variable may also be declared as "PyObject*".

"t#" (read-only character buffer) [char *, int]
   Like "s#", but accepts any object which implements the read-only
   buffer interface.  The "char*" variable is set to point to the
   first byte of the buffer, and the "int" is set to the length of the
   buffer. Only single-segment buffer objects are accepted;
   "TypeError" is raised for all others.

"w" (read-write character buffer) [char *]
   Similar to "s", but accepts any object which implements the read-
   write buffer interface.  The caller must determine the length of
   the buffer by other means, or use "w#" instead.  Only single-
   segment buffer objects are accepted; "TypeError" is raised for all
   others.

"w#" (read-write character buffer) [char *, Py_ssize_t]
   Like "s#", but accepts any object which implements the read-write
   buffer interface.  The "char *" variable is set to point to the
   first byte of the buffer, and the "Py_ssize_t" is set to the length
   of the buffer.  Only single-segment buffer objects are accepted;
   "TypeError" is raised for all others.

"w*" (read-write byte-oriented buffer) [Py_buffer]
   This is to "w" what "s*" is to "s".

   バージョン 2.6 で追加.

"(items)" (tuple) [*matching-items*]
   オブジェクトは *items* に入っている書式単位の数だけの長さを持つ
   Python のシーケンス型でなければなりません。各 C 引数は *items* 内の
   個々の書式単位に対応づけできなければなりません。シーケンスの書式単
   位は入れ子構造にできます。

   注釈: Prior to Python version 1.5.2, this format specifier only
     accepted a tuple containing the individual parameters, not an
     arbitrary sequence. Code which previously caused "TypeError" to
     be raised here may now proceed without an exception.  This is not
     expected to be a problem for existing code.

It is possible to pass Python long integers where integers are
requested; however no proper range checking is done — the most
significant bits are silently truncated when the receiving field is
too small to receive the value (actually, the semantics are inherited
from downcasts in C — your mileage may vary).

その他、書式文字列において意味を持つ文字がいくつかあります。それらの文
字は括弧による入れ子内には使えません。以下に文字を示します:

"|"
   Indicates that the remaining arguments in the Python argument list
   are optional.  The C variables corresponding to optional arguments
   should be initialized to their default value — when an optional
   argument is not specified, "PyArg_ParseTuple()" does not touch the
   contents of the corresponding C variable(s).

":"
   この文字があると、書式単位の記述はそこで終わります; コロン以降の文
   字列は、エラーメッセージにおける関数名 ("PyArg_ParseTuple()" が送出
   する例外の 「付属値 (associated value)」) として使われます。

";"
   この文字があると、書式単位の記述はそこで終わります; セミコロン以降
   の文字列は、デフォルトエラーメッセージを *置き換える* エラーメッセ
   ージとして使われます。 ":" と ";" は相互に排他の文字です。

呼び出し側に提供されるオブジェクトへの参照はすべて *借用* 参照
(borrowed reference) になります; これらのオブジェクトの参照カウントを
デクリメントしてはなりません!

以下の関数に渡す補助引数 (additional argument) は、書式文字列から決定
される型へのアドレスでなければなりません; 補助引数に指定したアドレスは
、タプルから入力された値を保存するために使います。上の書式単位のリスト
で説明したように、補助引数を入力値として使う場合がいくつかあります; そ
の場合、対応する書式単位の指定する形式に従うようにしなければなりません
。

変換を正しく行うためには、 *arg* オブジェクトは書式文字に一致しなけれ
ばならず、かつ書式文字列内の書式単位に全て値が入るようにしなければなり
ません。成功すると、 "PyArg_Parse*()" 関数は真を返します。それ以外の場
合には偽を返し、適切な例外を送出します。書式単位のどれかの変換失敗によ
り "PyArg_Parse*()" が失敗した場合、失敗した書式単位に対応するアドレス
とそれ以降のアドレスの内容は変更されません。

int PyArg_ParseTuple(PyObject *args, const char *format, ...)

   位置引数のみを引数にとる関数のパラメタを解釈して、ローカルな変数に
   変換します。成功すると真を返します;失敗すると偽を返し、適切な例外を
   送出します。

int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)

   "PyArg_ParseTuple()" と同じですが、可変長の引数ではなく *va_list*
   を引数にとります。

int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)

   Parse the parameters of a function that takes both positional and
   keyword parameters into local variables.  Returns true on success;
   on failure, it returns false and raises the appropriate exception.

int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)

   "PyArg_ParseTupleAndKeywords()" と同じですが、可変長の引数ではなく
   *va_list* を引数にとります。

int PyArg_Parse(PyObject *args, const char *format, ...)

   Function used to deconstruct the argument lists of 「old-style」
   functions — these are functions which use the "METH_OLDARGS"
   parameter parsing method.  This is not recommended for use in
   parameter parsing in new code, and most code in the standard
   interpreter has been modified to no longer use this for that
   purpose.  It does remain a convenient way to decompose other
   tuples, however, and may continue to be used for that purpose.

int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)

   パラメータ取得を簡単にした形式で、引数の型を指定する書式文字列を使
   いません。パラメタの取得にこの手法を使う関数は、関数宣言テーブル、
   またはメソッド宣言テーブル内で "METH_VARARGS" として宣言しなければ
   なりません。実引数の入ったタプルは *args* に渡します; このタプルは
   本当のタプルでなければなりません。タプルの長さは少なくとも *min* で
   、 *max* を超えてはなりません; *min* と *max* が等しくてもかまいま
   せん。補助引数を関数に渡さなければならず、各補助引数は "PyObject*"
   変数へのポインタでなければなりません; これらの補助引数には、 *args*
   の値が入ります; 値の参照は借用参照です。オプションのパラメタに対応
   する変数のうち、 *args* に指定していないものには値が入りません; 呼
   び出し側はそれらの値を初期化しておかなければなりません。この関数は
   成功すると真を返し、 *args* がタプルでない場合や間違った数の要素が
   入っている場合に偽を返します; 何らかの失敗が起きた場合には例外をセ
   ットします。

   この関数の使用例を以下に示します。この例は、弱参照のための
   "_weakref" 補助モジュールのソースコードからとったものです:

      static PyObject *
      weakref_ref(PyObject *self, PyObject *args)
      {
          PyObject *object;
          PyObject *callback = NULL;
          PyObject *result = NULL;

          if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
              result = PyWeakref_NewRef(object, callback);
          }
          return result;
      }

   この例における "PyArg_UnpackTuple()" 呼び出しは、
   "PyArg_ParseTuple()" を使った以下の呼び出しと全く等価です:

      PyArg_ParseTuple(args, "O|O:ref", &object, &callback)

   バージョン 2.2 で追加.

   バージョン 2.5 で変更: This function used an "int" type for *min*
   and *max*. This might require changes in your code for properly
   supporting 64-bit systems.

PyObject* Py_BuildValue(const char *format, ...)
    *Return value: New reference.*

   Create a new value based on a format string similar to those
   accepted by the "PyArg_Parse*()" family of functions and a sequence
   of values. Returns the value or *NULL* in the case of an error; an
   exception will be raised if *NULL* is returned.

   "Py_BuildValue()" does not always build a tuple.  It builds a tuple
   only if its format string contains two or more format units.  If
   the format string is empty, it returns "None"; if it contains
   exactly one format unit, it returns whatever object is described by
   that format unit.  To force it to return a tuple of size "0" or
   one, parenthesize the format string.

   When memory buffers are passed as parameters to supply data to
   build objects, as for the "s" and "s#" formats, the required data
   is copied. Buffers provided by the caller are never referenced by
   the objects created by "Py_BuildValue()".  In other words, if your
   code invokes "malloc()" and passes the allocated memory to
   "Py_BuildValue()", your code is responsible for calling "free()"
   for that memory once "Py_BuildValue()" returns.

   以下の説明では、引用符のついた形式は書式単位です; (丸)括弧で囲った
   部分は書式単位が返す Python のオブジェクト型です; [角] 括弧は関数に
   渡す値の C 変数型です。

   書式文字列内では、("s#" のような書式単位を除いて) スペース、タブ、
   コロンおよびコンマは無視されます。これらの文字を使うと、長い書式文
   字列をちょっとだけ読みやすくできます。

   "s" (string) [char *]
      Convert a null-terminated C string to a Python object.  If the C
      string pointer is *NULL*, "None" is used.

   "s#" (string) [char *, int]
      Convert a C string and its length to a Python object.  If the C
      string pointer is *NULL*, the length is ignored and "None" is
      returned.

   "z" (string or "None") [char *]
      "s" と同じです。

   "z#" (string or "None") [char *, int]
      "s#" と同じです。

   "u" (Unicode string) [Py_UNICODE *]
      null 終端された Unicode (UCS-2 または UCS-4) データのバッファか
      ら Python Unicode オブジェクトに変換します。 Unicode バッファポ
      インタが *NULL* の場合、 "None" になります。

   "u#" (Unicode string) [Py_UNICODE *, int]
      Unicode (UCS-2 または UCS-4) データのバッファとその長さから
      Python Unicode オブジェクトに変換します。 Unicode バッファポイン
      タが *NULL* の場合、長さは無視され "None" になります。

   "i" (integer) [int]
      通常の C の "int" を Python の整数オブジェクトに変換します。

   "b" (integer) [char]
      通常のC の "char" を Python の整数オブジェクトに変換します。

   "h" (integer) [short int]
      通常のC の "short int" を Python の整数オブジェクトに変換します
      。

   "l" (integer) [long int]
      C の "long int" を Python の整数オブジェクトに変換します。

   "B" (integer) [unsigned char]
      C の "unsigned char" を Python の整数オブジェクトに変換します。

   "H" (integer) [unsigned short int]
      C の "unsigned short int" を Python の整数オブジェクトに変換しま
      す。

   "I" (integer/long) [unsigned int]
      Convert a C "unsigned int" to a Python integer object or a
      Python long integer object, if it is larger than "sys.maxint".

   "k" (integer/long) [unsigned long]
      Convert a C "unsigned long" to a Python integer object or a
      Python long integer object, if it is larger than "sys.maxint".

   "L" (long) [PY_LONG_LONG]
      Convert a C "long long" to a Python long integer object. Only
      available on platforms that support "long long".

   "K" (long) [unsigned PY_LONG_LONG]
      Convert a C "unsigned long long" to a Python long integer
      object. Only available on platforms that support "unsigned long
      long".

   "n" (int) [Py_ssize_t]
      Convert a C "Py_ssize_t" to a Python integer or long integer.

      バージョン 2.5 で追加.

   "c" (string of length 1) [char]
      Convert a C "int" representing a character to a Python string of
      length 1.

   "d" (float) [double]
      C の "double" を Python の浮動小数点数に変換します。

   "f" (float) [float]
      Same as "d".

   "D" (complex) [Py_complex *]
      C の "Py_complex" 構造体を Python の複素数型に変換します。

   "O" (object) [PyObject *]
      Python オブジェクトを手を加えずに渡します (ただし、参照カウント
      は 1 インクリメントします)。渡したオブジェクトが *NULL* ポインタ
      の場合、この引数を生成するのに使った何らかの呼び出しがエラーにな
      ったのが原因であると仮定して、例外をセットします。従ってこのとき
      "Py_BuildValue()" は *NULL* を返しますが例外は送出しません。例外
      をまだ送出していなければ "SystemError" をセットします。

   "S" (object) [PyObject *]
      "O" と同じです。

   "N" (object) [PyObject *]
      Same as "O", except it doesn’t increment the reference count on
      the object.  Useful when the object is created by a call to an
      object constructor in the argument list.

   "O&" (object) [*converter*, *anything*]
      Convert *anything* to a Python object through a *converter*
      function. The function is called with *anything* (which should
      be compatible with "void *") as its argument and should return a
      「new」 Python object, or *NULL* if an error occurred.

   "(items)" (tuple) [*matching-items*]
      C の値からなる配列を、同じ要素数を持つ Python のタプルに変換しま
      す。

   "[items]" (list) [*matching-items*]
      C の値からなる配列を、同じ要素数を持つ Python のリストに変換しま
      す。

   "{items}" (dictionary) [*matching-items*]
      C の値からなる配列を Python の辞書に変換します。一連のペアからな
      る C の値が、それぞれキーおよび値となって辞書に追加されます。

   書式文字列に関するエラーが生じると、 "SystemError" 例外をセットして
   *NULL* を返します。

PyObject* Py_VaBuildValue(const char *format, va_list vargs)

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