解析自变量和构建值

这些函数在创建自己的扩展函数和方法时很有用。额外信息和范例可用于 扩展和嵌入 Python 解释器 .

描述这些函数中的前 3, PyArg_ParseTuple() , PyArg_ParseTupleAndKeywords() ,和 PyArg_Parse() ,全部使用 格式字符串 用于告诉函数有关期望自变量。格式字符串使用相同句法,对于这些函数中的每个而言。

剖析自变量

A format string consists of zero or more “format units.” A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a parenthesized sequence normally corresponds to a single address argument to these functions. In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that matches the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed.

字符串和缓冲

注意

On Python 3.12 and older, the macro PY_SSIZE_T_CLEAN must be defined before including Python.h to use all # variants of formats ( s# , y# , etc.) explained below. This is not necessary on Python 3.13 and later.

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.

除非另有说明,缓冲不以 NULL 结尾。

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 , 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).

s ( str ) [const char *]

Convert a Unicode object to a C pointer to a character string. A pointer to an existing string is stored in the character pointer variable whose address you pass. The C string is NUL-terminated. The Python string must not contain embedded null code points; if it does, a ValueError exception is raised. Unicode objects are converted to C strings using 'utf-8' encoding. If this conversion fails, a UnicodeError 被引发。

注意

这种格式不接受 像字节对象 . If you want to accept filesystem paths and convert them to C character strings, it is preferable to use the O& format with PyUnicode_FSConverter() as converter .

3.5 版改变: 先前, TypeError was raised when embedded null code points were encountered in the Python string.

s* ( str or 像字节对象 ) [Py_buffer]

This format accepts Unicode objects as well as bytes-like objects. It fills a Py_buffer structure provided by the caller. In this case the resulting C string may contain embedded NUL bytes. Unicode objects are converted to C strings using 'utf-8' 编码。

s# ( str , read-only 像字节对象 ) [const char *, Py_ssize_t ]

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' 编码。

z ( str or None ) [const char *]

s , but the Python object may also be None , in which case the C pointer is set to NULL .

z* ( str , 像字节对象 or None ) [Py_buffer]

s* , but the Python object may also be None , in which case the buf 成员对于 Py_buffer structure is set to NULL .

z# ( str , read-only 像字节对象 or None ) [const char *, Py_ssize_t ]

s# , but the Python object may also be None , in which case the C pointer is set to NULL .

y (read-only 像字节对象 ) [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 异常被引发。

3.5 版改变: 先前, TypeError was raised when embedded null bytes were encountered in the bytes buffer.

y* ( 像字节对象 ) [Py_buffer]

This variant on s* doesn’t accept Unicode objects, only bytes-like objects. This is the recommended way to accept binary data.

y# (read-only 像字节对象 ) [const char *, Py_ssize_t ]

This variant on s# doesn’t accept Unicode objects, only bytes-like objects.

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* (read-write 像字节对象 ) [Py_buffer]

This format accepts any object which implements the read-write buffer interface. It fills a Py_buffer structure provided by the caller. The buffer may contain embedded null bytes. The caller have to call PyBuffer_Release() when it is done with the buffer.

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

This variant on s is used for encoding 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 ,在这种情况下 '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() will allocate a buffer of the needed size, copy the encoded data into this buffer and adjust *buffer to reference the newly allocated storage. The caller is responsible for calling PyMem_Free() to free the allocated buffer after use.

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

如同 es except that byte string objects are passed through without recoding them. Instead, the implementation assumes that the byte string object uses the encoding passed in as parameter.

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

This variant on s# is used for encoding 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 ,在这种情况下 '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.

There are two modes of operation:

*buffer points a NULL pointer, the function will allocate a buffer of the needed size, copy the encoded data into this buffer and set *buffer to reference the newly allocated storage. The caller is responsible for calling PyMem_Free() to free the allocated buffer after usage.

*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 ValueError will be set.

In both cases, *buffer_length is set to the length of the encoded data without the trailing NUL byte.

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

如同 es# except that byte string objects are passed through without recoding them. Instead, the implementation assumes that the byte string object uses the encoding passed in as parameter.

3.12 版改变: u , u# , Z ,和 Z# are removed because they used a legacy Py_UNICODE* 表示。