인자 구문 분석과 값 구축

이 함수들은 자체 확장 함수와 메서드를 만들 때 유용합니다. 추가 정보와 예제는 파이썬 인터프리터 확장 및 내장에 있습니다.

설명된 이러한 함수 중 처음 세 개인 PyArg_ParseTuple(), PyArg_ParseTupleAndKeywords()PyArg_Parse()는 모두 예상 인자에 관한 사항을 함수에 알리는 데 사용되는 포맷 문자열(format strings)을 사용합니다. 포맷 문자열은 이러한 각 함수에 대해 같은 문법을 사용합니다.

인자 구문 분석

포맷 문자열은 0개 이상의 “포맷 단위(format units)”로 구성됩니다. 포맷 단위는 하나의 파이썬 객체를 설명합니다; 일반적으로 단일 문자나 괄호로 묶인 포맷 단위 시퀀스입니다. 몇 가지 예외를 제외하고, 괄호로 묶인 시퀀스가 아닌 포맷 단위는 일반적으로 이러한 함수에 대한 단일 주소 인자에 대응합니다. 다음 설명에서, 인용된(quoted) 형식은 포맷 단위입니다; (둥근) 괄호 안의 항목은 포맷 단위와 일치하는 파이썬 객체 형입니다; [대괄호] 안의 항목은 주소를 전달해야 하는 C 변수의 형입니다.

문자열과 버퍼

이러한 포맷을 사용하면 연속적인 메모리 청크로 객체에 액세스 할 수 있습니다. 반환된 유니코드나 바이트열 영역에 대한 원시 저장소를 제공할 필요가 없습니다.

달리 명시되지 않는 한, 버퍼는 NUL로 종료되지 않습니다.

There are three ways strings and buffers can be converted to C:

  • Formats such as y* and s* fill a Py_buffer structure. This locks the underlying buffer so that the caller can subsequently use the buffer even inside a Py_BEGIN_ALLOW_THREADS block without the risk of mutable data being resized or destroyed. As a result, you have to call PyBuffer_Release() after you have finished processing the data (or in any early abort case).

  • The es, es#, et and et# formats allocate the result buffer. You have to call PyMem_Free() after you have finished processing the data (or in any early abort case).

  • Other formats take a str or a read-only bytes-like object, such as bytes, and provide a const char * pointer to its buffer. In this case the buffer is “borrowed”: it is managed by the corresponding Python object, and shares the lifetime of this object. You won’t have to release any memory yourself.

    To ensure that the underlying buffer may be safely borrowed, the object’s PyBufferProcs.bf_releasebuffer field must be NULL. This disallows common mutable objects such as bytearray, but also some read-only objects such as memoryview of bytes.

    Besides this bf_releasebuffer requirement, there is no check to verify whether the input object is immutable (e.g. whether it would honor a request for a writable buffer, or whether another thread can mutate the data).

참고

For all # variants of formats (s#, y#, etc.), the macro PY_SSIZE_T_CLEAN must be defined before including Python.h. On Python 3.9 and older, the type of the length argument is Py_ssize_t if the PY_SSIZE_T_CLEAN macro is defined, or int otherwise.

s (str) [const char *]

유니코드 객체를 문자열에 대한 C 포인터로 변환합니다. 기존 문자열에 대한 포인터는 여러분이 주소를 전달한 문자 포인터 변수에 저장됩니다. C 문자열은 NUL로 종료됩니다. 파이썬 문자열은 내장된 널 코드 포인트를 포함하지 않아야 합니다; 그렇다면 ValueError 예외가 발생합니다. 유니코드 객체는 'utf-8' 인코딩을 사용하여 C 문자열로 변환됩니다. 이 변환이 실패하면, UnicodeError가 발생합니다.

참고

이 포맷은 바이트열류 객체를 받아들이지 않습니다. 파일 시스템 경로를 받아들이고 이를 C 문자열로 변환하려면, PyUnicode_FSConverter()converterO& 포맷을 사용하는 것이 좋습니다.

버전 3.5에서 변경: 이전에는, 파이썬 문자열에서 내장된 널 코드 포인트가 발견되면 TypeError가 발생했습니다.

s* (str 또는 바이트열류 객체) [Py_buffer]

이 포맷은 바이트열류 객체뿐만 아니라 유니코드 객체를 받아들입니다. 호출자가 제공한 Py_buffer 구조체를 채웁니다. 이 경우 결과 C 문자열은 내장된 NUL 바이트를 포함할 수 있습니다. 유니코드 객체는 'utf-8' 인코딩을 사용하여 C 문자열로 변환됩니다.

s# (str, read-only bytes-like object) [const char *, Py_ssize_t]

Like s*, except that it provides a borrowed buffer. The result is stored into two C variables, the first one a pointer to a C string, the second one its length. The string may contain embedded null bytes. Unicode objects are converted to C strings using 'utf-8' encoding.

z (str 또는 None) [const char *]

s와 비슷하지만, 파이썬 객체가 None일 수도 있는데, 이 경우 C 포인터가 NULL로 설정됩니다.

z* (str, 바이트열류 객체 또는 None) [Py_buffer]

s*와 비슷하지만, 파이썬 객체는 None일 수도 있습니다, 이 경우 Py_buffer 구조체의 buf 멤버가 NULL로 설정됩니다.

z# (str, read-only bytes-like object or None) [const char *, Py_ssize_t]

s#와 비슷하지만, 파이썬 객체는 None일 수도 있습니다, 이 경우 C 포인터가 NULL로 설정됩니다.

y (읽기 전용 바이트열류 객체) [const char *]

This format converts a bytes-like object to a C pointer to a borrowed character string; it does not accept Unicode objects. The bytes buffer must not contain embedded null bytes; if it does, a ValueError exception is raised.

버전 3.5에서 변경: 이전에는, 바이트열 버퍼에서 내장 널 바이트가 발견되면 TypeError가 발생했습니다.

y* (바이트열류 객체) [Py_buffer]

s*의 이 변형은 유니코드 객체가 아니라 바이트열류 객체만 받아들입니다. 바이너리 데이터를 받아들이는 권장 방법입니다.

y# (read-only bytes-like object) [const char *, Py_ssize_t]

s#의 이 변형은 유니코드 객체가 아니라 바이트열류 객체만 받아들입니다.

S (bytes) [PyBytesObject *]

Requires that the Python object is a bytes object, without attempting any conversion. Raises TypeError if the object is not a bytes object. The C variable may also be declared as PyObject*.

Y (bytearray) [PyByteArrayObject *]

Requires that the Python object is a bytearray object, without attempting any conversion. Raises TypeError if the object is not a bytearray object. The C variable may also be declared as PyObject*.

U (str) [PyObject *]

Requires that the Python object is a Unicode object, without attempting any conversion. Raises TypeError if the object is not a Unicode object. The C variable may also be declared as PyObject*.

w* (읽기-쓰기 바이트열류 객체) [Py_buffer]

이 포맷은 읽기-쓰기 버퍼 인터페이스를 구현하는 모든 객체를 허용합니다. 호출자가 제공한 Py_buffer 구조체를 채웁니다. 버퍼에는 내장 널 바이트가 포함될 수 있습니다. 호출자는 버퍼로 할 일을 마치면 PyBuffer_Release()를 호출해야 합니다.

es (str) [const char *encoding, char **buffer]

s의 이 변형은 유니코드를 문자 버퍼로 인코딩하는 데 사용됩니다. 내장 NUL 바이트가 포함되지 않은 인코딩된 데이터에 대해서만 작동합니다.

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 'utf-8' 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 (str, bytes 또는 bytearray) [const char *encoding, char **buffer]

바이트 문자열 객체를 다시 코딩하지 않고 통과시킨다는 점을 제외하면 es와 같습니다. 대신, 구현은 바이트 문자열 객체가 매개 변수로 전달된 인코딩을 사용한다고 가정합니다.

es# (str) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]

s#의 이 변형은 유니코드를 문자 버퍼로 인코딩하는 데 사용됩니다. es 포맷과 달리, 이 변형은 NUL 문자를 포함하는 입력 데이터를 허용합니다.

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 'utf-8' 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.

두 가지 작동 모드가 있습니다:

*bufferNULL 포인터를 가리키면, 함수는 필요한 크기의 버퍼를 할당하고, 이 버퍼로 인코딩된 데이터를 복사하고 *buffer를 새로 할당된 스토리지를 참조하도록 설정합니다. 호출자는 사용 후 할당된 버퍼를 해제하기 위해 PyMem_Free()를 호출해야 합니다.

*bufferNULL이 아닌 포인터를 가리키면 (이미 할당된 버퍼), PyArg_ParseTuple()은 이 위치를 버퍼로 사용하고 *buffer_length의 초깃값을 버퍼 크기로 해석합니다. 그런 다음 인코딩된 데이터를 버퍼에 복사하고 NUL 종료합니다. 버퍼가 충분히 크지 않으면, ValueError가 설정됩니다.

두 경우 모두, *buffer_length는 후행 NUL 바이트를 제외한 인코딩된 데이터의 길이로 설정됩니다.

et# (str, bytes or bytearray) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]

바이트 문자열 객체를 다시 코딩하지 않고 통과시킨다는 점을 제외하면 es#와 같습니다. 대신, 구현은 바이트 문자열 객체가 매개 변수로 전달된 인코딩을 사용한다고 가정합니다.

버전 3.12에서 변경: u, u#, Z, and Z# are removed because they used a legacy Py_UNICODE* representation.

숫자

b (int) [unsigned char]

Convert a nonnegative Python integer to an unsigned tiny int, stored in a C unsigned char.

B (int) [unsigned char]

Convert a Python integer to a tiny int without overflow checking, stored in a C unsigned char.

h (int) [short int]

Convert a Python integer to a C short int.

H (int) [unsigned short int]

Convert a Python integer to a C unsigned short int, without overflow checking.

i (int) [int]

Convert a Python integer to a plain C int.

I (int) [unsigned int]

Convert a Python integer to a C unsigned int, without overflow checking.

l (int) [long int]

Convert a Python integer to a C long int.

k (int) [unsigned long]

Convert a Python integer to a C unsigned long without overflow checking.

L (int) [long long]

Convert a Python integer to a C long long.

K (int) [unsigned long long]

Convert a Python integer to a C unsigned long long without overflow checking.

n (int) [Py_ssize_t]

파이썬 정수를 C Py_ssize_t로 변환합니다.

c (길이 1의 bytes 또는 bytearray) [char]

Convert a Python byte, represented as a bytes or bytearray object of length 1, to a C char.

버전 3.3에서 변경: bytearray 객체를 허용합니다.

C (길이 1의 str) [int]

Convert a Python character, represented as a str object of length 1, to a C int.

f (float) [float]

Convert a Python floating point number to a C float.

d (float) [double]

Convert a Python floating point number to a C double.

D (complex) [Py_complex]

파이썬 복소수를 C Py_complex 구조체로 변환합니다.

기타 객체

O (object) [PyObject *]

Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. A new strong reference to the object is not created (i.e. its reference count is not increased). The pointer stored is not NULL.

O! (object) [typeobject, PyObject *]

Store a Python object in a C object pointer. This is similar to O, but takes two C arguments: the first is the address of a Python type object, the second is the address of the C variable (of type PyObject*) into which the object pointer is stored. If the Python object does not have the required type, TypeError is raised.

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.

converterPy_CLEANUP_SUPPORTED를 반환하면, 인자 구문 분석이 결국 실패하면 두 번째로 호출되어 변환기에 이미 할당된 메모리를 해제할 기회를 제공할 수 있습니다. 이 두 번째 호출에서, object 매개 변수는 NULL이 됩니다; address는 원래 호출과 같은 값을 갖습니다.

버전 3.1에서 변경: Py_CLEANUP_SUPPORTED가 추가되었습니다.

p (bool) [int]

전달된 값의 논리값을 테스트(불리언 predicate)하고 결과를 동등한 C 참/거짓 정숫값으로 변환합니다. 표현식이 참이면 int를 1로, 거짓이면 0으로 설정합니다. 모든 유효한 파이썬 값을 허용합니다. 파이썬이 논리값을 테스트하는 방법에 대한 자세한 내용은 논리값 검사를 참조하십시오.

버전 3.3에 추가.

(items) (tuple) [matching-items]

객체는 길이가 items에 있는 포맷 단위의 수인 파이썬 시퀀스여야 합니다. C 인자들은 items의 개별 포맷 단위에 대응해야 합니다. 시퀀스의 포맷 단위는 중첩될 수 있습니다.

It is possible to pass “long” integers (integers whose value exceeds the platform’s LONG_MAX) 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).

몇 가지 다른 문자는 포맷 문자열에서 의미가 있습니다. 중첩된 괄호 안에서는 나타날 수 없습니다. 그들은:

|

파이썬 인자 리스트의 나머지 인자가 선택 사항임을 나타냅니다. 선택적 인자에 해당하는 C 변수는 기본값으로 초기화되어야 합니다 — 선택적 인자가 지정되지 않을 때, PyArg_ParseTuple()은 해당 C 변수의 내용을 건드리지 않습니다.

$

PyArg_ParseTupleAndKeywords() 전용: 파이썬 인자 리스트의 나머지 인자가 키워드 전용임을 나타냅니다. 현재, 모든 키워드 전용 인자는 선택적 인자여야 하므로, |는 항상 포맷 문자열에서 $ 앞에 지정되어야 합니다.

버전 3.3에 추가.

:

포맷 단위 리스트는 여기에서 끝납니다; 콜론 뒤의 문자열은 에러 메시지에서 함수 이름으로 사용됩니다 (PyArg_ParseTuple()이 발생시키는 예외의 “연관된 값”).

;

포맷 단위 리스트는 여기에서 끝납니다; 세미콜론 뒤의 문자열은 기본 에러 메시지의 에러 메시지 대신 에러 메시지로 사용됩니다. :;는 서로를 배제합니다.

Note that any Python object references which are provided to the caller are borrowed references; do not release them (i.e. do not decrement their reference count)!

이러한 함수에 전달되는 추가 인자는 포맷 문자열에 의해 형이 결정되는 변수의 주소여야 합니다; 이들은 입력 튜플의 값을 저장하는 데 사용됩니다. 위의 포맷 단위 리스트에서 설명된 대로, 이러한 매개 변수가 입력값으로 사용되는 몇 가지 경우가 있습니다; 이 경우 해당 포맷 단위에 대해 지정된 것과 일치해야 합니다.

For the conversion to succeed, the arg object must match the format and the format must be exhausted. On success, the PyArg_Parse* functions return true, otherwise they return false and raise an appropriate exception. When the PyArg_Parse* functions fail due to conversion failure in one of the format units, the variables at the addresses corresponding to that and the following format units are left untouched.

API 함수

int PyArg_ParseTuple(PyObject *args, const char *format, ...)
Part of the Stable ABI.

위치 매개 변수만 지역 변수로 취하는 함수의 매개 변수를 구문 분석합니다. 성공하면 참을 반환합니다; 실패하면, 거짓을 반환하고 적절한 예외를 발생시킵니다.

int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
Part of the Stable ABI.

가변 개수의 인자가 아닌 va_list를 받아들인다는 점을 제외하면, PyArg_ParseTuple()과 동일합니다.

int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)
Part of the Stable ABI.

위치와 키워드 매개 변수를 모두 지역 변수로 취하는 함수의 매개 변수를 구문 분석합니다. keywords 인자는 키워드 매개 변수 이름의 NULL-종료 배열입니다. 빈 이름은 위치-전용 매개 변수를 나타냅니다. 성공하면 참을 반환합니다; 실패하면, 거짓을 반환하고 적절한 예외를 발생시킵니다.

버전 3.6에서 변경: 위치-전용 매개 변수에 대한 지원이 추가되었습니다.

int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)
Part of the Stable ABI.

가변 개수의 인자가 아닌 va_list를 받아들인다는 점을 제외하면, PyArg_ParseTupleAndKeywords() 와 동일합니다.

int PyArg_ValidateKeywordArguments(PyObject*)
Part of the Stable ABI.

키워드 인자 딕셔너리의 키가 문자열인지 확인합니다. PyArg_ParseTupleAndKeywords() 가 사용되지 않는 경우에만 필요합니다, 여기서는 이미 이 검사를 수행하기 때문입니다.

버전 3.2에 추가.

int PyArg_Parse(PyObject *args, const char *format, ...)
Part of the Stable ABI.

“이전 스타일” 함수의 인자 리스트를 분해하는 데 사용되는 함수 — 이들은 파이썬 3에서 제거된 METH_OLDARGS 매개 변수 구문 분석 메서드를 사용하는 함수입니다. 새 코드에서 매개 변수 구문 분석에 사용하는 것은 권장되지 않고, 표준 인터프리터에 있는 대부분의 코드는 더는 이런 목적으로 사용하지 않도록 수정되었습니다. 그러나, 다른 튜플을 분해하는 편리한 방법으로 남아 있으며, 그런 목적으로 계속 사용할 수 있습니다.

int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
Part of the Stable ABI.

A simpler form of parameter retrieval which does not use a format string to specify the types of the arguments. Functions which use this method to retrieve their parameters should be declared as METH_VARARGS in function or method tables. The tuple containing the actual parameters should be passed as args; it must actually be a tuple. The length of the tuple must be at least min and no more than max; min and max may be equal. Additional arguments must be passed to the function, each of which should be a pointer to a PyObject* variable; these will be filled in with the values from args; they will contain borrowed references. The variables which correspond to optional parameters not given by args will not be filled in; these should be initialized by the caller. This function returns true on success and false if args is not a tuple or contains the wrong number of elements; an exception will be set if there was a failure.

This is an example of the use of this function, taken from the sources for the _weakref helper module for weak references:

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)

값 구축

PyObject *Py_BuildValue(const char *format, ...)
Return value: New reference. Part of the Stable ABI.

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()는 항상 튜플을 구축하지는 않습니다. 포맷 문자열에 둘 이상의 포맷 단위가 포함되었을 때만 튜플을 구축합니다. 포맷 문자열이 비어 있으면, None을 반환합니다; 정확히 하나의 포맷 단위를 포함하면, 해당 포맷 단위가 기술하는 객체가 무엇이건 반환합니다. 크기가 0이나 1인 튜플을 반환하도록 하려면, 포맷 문자열을 괄호로 묶으십시오.

ss# 포맷의 경우처럼, 메모리 버퍼가 데이터를 빌드 객체에 제공하기 위해 매개 변수로 전달될 때, 필요한 데이터가 복사됩니다. 호출자가 제공하는 버퍼는 Py_BuildValue()가 만든 객체에 의해 참조되지 않습니다. 즉, 여러분의 코드가 malloc()을 호출하고 할당된 메모리를 Py_BuildValue()에 전달하면, 인단 Py_BuildValue()가 반환되면 여러분이 코드가 해당 메모리에 대해 free()를 호출해야 합니다.

다음 설명에서, 인용된 형식은 포맷 단위입니다; (둥근) 괄호 안의 항목은 포맷 단위가 반환할 파이썬 객체 형입니다; [대괄호] 안의 항목은 전달할 C 값의 형입니다.

문자 스페이스, 탭, 콜론 및 쉼표는 포맷 문자열에서 무시됩니다 (하지만 s#와 같은 포맷 단위 내에서는 아닙니다). 이것은 긴 포맷 문자열을 좀 더 읽기 쉽게 만드는 데 사용할 수 있습니다.

s (str 또는 None) [const char *]

'utf-8' 인코딩을 사용하여 널-종료 C 문자열을 파이썬 str 객체로 변환합니다. C 문자열 포인터가 NULL이면, None이 사용됩니다.

s# (str or None) [const char *, Py_ssize_t]

'utf-8' 인코딩을 사용하여 C 문자열과 그 길이를 파이썬 str 객체로 변환합니다. C 문자열 포인터가 NULL이면, 길이가 무시되고 None이 반환됩니다.

y (bytes) [const char *]

이것은 C 문자열을 파이썬 bytes 객체로 변환합니다. C 문자열 포인터가 NULL이면, None이 반환됩니다.

y# (bytes) [const char *, Py_ssize_t]

이것은 C 문자열과 그 길이를 파이썬 객체로 변환합니다. C 문자열 포인터가 NULL이면, None이 반환됩니다.

z (str 또는 None) [const char *]

s와 같습니다.

z# (str or None) [const char *, Py_ssize_t]

s#과 같습니다.

u (str) [const wchar_t *]

유니코드 (UTF-16 또는 UCS-4) 데이터의 널-종료 wchar_t 버퍼를 파이썬 유니코드 객체로 변환합니다. 유니코드 버퍼 포인터가 NULL이면, None이 반환됩니다.

u# (str) [const wchar_t *, Py_ssize_t]

유니코드 (UTF-16 또는 UCS-4) 데이터 버퍼와 그 길이를 파이썬 유니코드 객체로 변환합니다. 유니코드 버퍼 포인터가 NULL이면, 길이가 무시되고 None이 반환됩니다.

U (str 또는 None) [const char *]

s와 같습니다.

U# (str or None) [const char *, Py_ssize_t]

s#과 같습니다.

i (int) [int]

Convert a plain C int to a Python integer object.

b (int) [char]

Convert a plain C char to a Python integer object.

h (int) [short int]

Convert a plain C short int to a Python integer object.

l (int) [long int]

Convert a C long int to a Python integer object.

B (int) [unsigned char]

Convert a C unsigned char to a Python integer object.

H (int) [unsigned short int]

Convert a C unsigned short int to a Python integer object.

I (int) [unsigned int]

Convert a C unsigned int to a Python integer object.

k (int) [unsigned long]

Convert a C unsigned long to a Python integer object.

L (int) [long long]

Convert a C long long to a Python integer object.

K (int) [unsigned long long]

Convert a C unsigned long long to a Python integer object.

n (int) [Py_ssize_t]

C Py_ssize_t를 파이썬 정수로 변환합니다.

c (길이 1의 bytes) [char]

Convert a C int representing a byte to a Python bytes object of length 1.

C (길이 1의 str) [int]

Convert a C int representing a character to Python str object of length 1.

d (float) [double]

Convert a C double to a Python floating point number.

f (float) [float]

Convert a C float to a Python floating point number.

D (complex) [Py_complex *]

C Py_complex 구조체를 파이썬 복소수로 변환합니다.

O (object) [PyObject *]

Pass a Python object untouched but create a new strong reference to it (i.e. its reference count is incremented by one). If the object passed in is a NULL pointer, it is assumed that this was caused because the call producing the argument found an error and set an exception. Therefore, Py_BuildValue() will return NULL but won’t raise an exception. If no exception has been raised yet, SystemError is set.

S (object) [PyObject *]

O와 같습니다.

N (object) [PyObject *]

Same as O, except it doesn’t create a new strong reference. 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값의 시퀀스를 항목 수가 같은 파이썬 튜플로 변환합니다.

[items] (list) [matching-items]

C값의 시퀀스를 항목 수가 같은 파이썬 리스트로 변환합니다.

{items} (dict) [matching-items]

C값의 시퀀스를 파이썬 딕셔너리로 변환합니다. 연속된 C 값의 각 쌍은 딕셔너리에 하나의 항목을 추가하여, 각각 키와 값으로 사용됩니다.

포맷 문자열에 에러가 있으면, SystemError 예외가 설정되고 NULL이 반환됩니다.

PyObject *Py_VaBuildValue(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI.

가변 개수의 인자가 아닌 va_list를 받아들인다는 점을 제외하면, Py_BuildValue()와 동일합니다.