diff options
106 files changed, 2573 insertions, 2569 deletions
diff --git a/Doc/c-api/allocation.rst b/Doc/c-api/allocation.rst index b64381b..e8f60bf 100644 --- a/Doc/c-api/allocation.rst +++ b/Doc/c-api/allocation.rst @@ -6,13 +6,13 @@ Allocating Objects on the Heap ============================== -.. cfunction:: PyObject* _PyObject_New(PyTypeObject *type) +.. c:function:: PyObject* _PyObject_New(PyTypeObject *type) -.. cfunction:: PyVarObject* _PyObject_NewVar(PyTypeObject *type, Py_ssize_t size) +.. c:function:: PyVarObject* _PyObject_NewVar(PyTypeObject *type, Py_ssize_t size) -.. cfunction:: PyObject* PyObject_Init(PyObject *op, PyTypeObject *type) +.. c:function:: PyObject* PyObject_Init(PyObject *op, PyTypeObject *type) Initialize a newly-allocated object *op* with its type and initial reference. Returns the initialized object. If *type* indicates that the @@ -21,13 +21,13 @@ Allocating Objects on the Heap affected. -.. cfunction:: PyVarObject* PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size) +.. c:function:: PyVarObject* PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size) - This does everything :cfunc:`PyObject_Init` does, and also initializes the + This does everything :c:func:`PyObject_Init` does, and also initializes the length information for a variable-size object. -.. cfunction:: TYPE* PyObject_New(TYPE, PyTypeObject *type) +.. c:function:: TYPE* PyObject_New(TYPE, PyTypeObject *type) Allocate a new Python object using the C structure type *TYPE* and the Python type object *type*. Fields not defined by the Python object header @@ -36,7 +36,7 @@ Allocating Objects on the Heap the type object. -.. cfunction:: TYPE* PyObject_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) +.. c:function:: TYPE* PyObject_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) Allocate a new Python object using the C structure type *TYPE* and the Python type object *type*. Fields not defined by the Python object header @@ -48,24 +48,24 @@ Allocating Objects on the Heap improving the memory management efficiency. -.. cfunction:: void PyObject_Del(PyObject *op) +.. c:function:: void PyObject_Del(PyObject *op) - Releases memory allocated to an object using :cfunc:`PyObject_New` or - :cfunc:`PyObject_NewVar`. This is normally called from the + Releases memory allocated to an object using :c:func:`PyObject_New` or + :c:func:`PyObject_NewVar`. This is normally called from the :attr:`tp_dealloc` handler specified in the object's type. The fields of the object should not be accessed after this call as the memory is no longer a valid Python object. -.. cvar:: PyObject _Py_NoneStruct +.. c:var:: PyObject _Py_NoneStruct Object which is visible in Python as ``None``. This should only be accessed - using the :cmacro:`Py_None` macro, which evaluates to a pointer to this + using the :c:macro:`Py_None` macro, which evaluates to a pointer to this object. .. seealso:: - :cfunc:`PyModule_Create` + :c:func:`PyModule_Create` To allocate and create extension modules. diff --git a/Doc/c-api/arg.rst b/Doc/c-api/arg.rst index fc64b20..a32dd09 100644 --- a/Doc/c-api/arg.rst +++ b/Doc/c-api/arg.rst @@ -9,8 +9,8 @@ These functions are useful when creating your own extensions functions and methods. Additional information and examples are available in :ref:`extending-index`. -The first three of these functions described, :cfunc:`PyArg_ParseTuple`, -:cfunc:`PyArg_ParseTupleAndKeywords`, and :cfunc:`PyArg_Parse`, all use *format +The first three of these functions described, :c:func:`PyArg_ParseTuple`, +:c:func:`PyArg_ParseTupleAndKeywords`, and :c:func:`PyArg_Parse`, all use *format strings* which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions. @@ -34,23 +34,23 @@ These formats do not expect you to provide raw storage for the returned string or bytes. Also, you won't have to release any memory yourself, except with the ``es``, ``es#``, ``et`` and ``et#`` formats. -However, when a :ctype:`Py_buffer` structure gets filled, the underlying +However, when a :c:type:`Py_buffer` structure gets filled, the underlying buffer is locked so that the caller can subsequently use the buffer even -inside a :ctype:`Py_BEGIN_ALLOW_THREADS` block without the risk of mutable data +inside a :c:type:`Py_BEGIN_ALLOW_THREADS` block without the risk of mutable data being resized or destroyed. As a result, **you have to call** -:cfunc:`PyBuffer_Release` after you have finished processing the data (or +:c:func:`PyBuffer_Release` after you have finished processing the data (or in any early abort case). Unless otherwise stated, buffers are not NUL-terminated. .. note:: For all ``#`` variants of formats (``s#``, ``y#``, etc.), the type of - the length argument (int or :ctype:`Py_ssize_t`) is controlled by - defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before including + the length argument (int or :c:type:`Py_ssize_t`) is controlled by + defining the macro :c:macro:`PY_SSIZE_T_CLEAN` before including :file:`Python.h`. If the macro was defined, length is a - :ctype:`Py_ssize_t` rather than an :ctype:`int`. This behavior will change - in a future Python version to only support :ctype:`Py_ssize_t` and - drop :ctype:`int` support. It is best to always define :cmacro:`PY_SSIZE_T_CLEAN`. + :c:type:`Py_ssize_t` rather than an :c:type:`int`. This behavior will change + in a future Python version to only support :c:type:`Py_ssize_t` and + drop :c:type:`int` support. It is best to always define :c:macro:`PY_SSIZE_T_CLEAN`. ``s`` (:class:`str`) [const char \*] @@ -65,17 +65,17 @@ Unless otherwise stated, buffers are not NUL-terminated. .. note:: This format does not accept bytes-like objects. If you want to accept filesystem paths and convert them to C character strings, it is - preferable to use the ``O&`` format with :cfunc:`PyUnicode_FSConverter` + preferable to use the ``O&`` format with :c:func:`PyUnicode_FSConverter` as *converter*. ``s*`` (:class:`str`, :class:`bytes`, :class:`bytearray` or buffer compatible object) [Py_buffer] This format accepts Unicode objects as well as objects supporting the buffer protocol. - It fills a :ctype:`Py_buffer` structure provided by the caller. + It fills a :c:type:`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'`` encoding. -``s#`` (:class:`str`, :class:`bytes` or read-only buffer compatible object) [const char \*, int or :ctype:`Py_ssize_t`] +``s#`` (:class:`str`, :class:`bytes` or read-only buffer compatible object) [const char \*, int or :c:type:`Py_ssize_t`] Like ``s*``, except that it doesn't accept mutable buffer-like objects such as :class:`bytearray`. The result is stored into two C variables, the first one a pointer to a C string, the second one its length. @@ -88,7 +88,7 @@ Unless otherwise stated, buffers are not NUL-terminated. ``z*`` (:class:`str`, :class:`bytes`, :class:`bytearray`, buffer compatible object or ``None``) [Py_buffer] Like ``s*``, but the Python object may also be ``None``, in which case the - ``buf`` member of the :ctype:`Py_buffer` structure is set to *NULL*. + ``buf`` member of the :c:type:`Py_buffer` structure is set to *NULL*. ``z#`` (:class:`str`, :class:`bytes`, read-only buffer compatible object or ``None``) [const char \*, int] Like ``s#``, but the Python object may also be ``None``, in which case the C @@ -112,18 +112,18 @@ Unless otherwise stated, buffers are not NUL-terminated. ``S`` (:class:`bytes`) [PyBytesObject \*] Requires that the Python object is a :class:`bytes` object, without attempting any conversion. Raises :exc:`TypeError` if the object is not - a bytes object. The C variable may also be declared as :ctype:`PyObject\*`. + a bytes object. The C variable may also be declared as :c:type:`PyObject\*`. ``Y`` (:class:`bytearray`) [PyByteArrayObject \*] Requires that the Python object is a :class:`bytearray` object, without attempting any conversion. Raises :exc:`TypeError` if the object is not - a :class:`bytearray` object. The C variable may also be declared as :ctype:`PyObject\*`. + a :class:`bytearray` object. The C variable may also be declared as :c:type:`PyObject\*`. ``u`` (:class:`str`) [Py_UNICODE \*] Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of - Unicode characters. You must pass the address of a :ctype:`Py_UNICODE` + Unicode characters. You must pass the address of a :c:type:`Py_UNICODE` pointer variable, which will be filled with the pointer to an existing - Unicode buffer. Please note that the width of a :ctype:`Py_UNICODE` + Unicode buffer. Please note that the width of a :c:type:`Py_UNICODE` character depends on compilation options (it is either 16 or 32 bits). The Python string must not contain embedded NUL characters; if it does, a :exc:`TypeError` exception is raised. @@ -139,38 +139,38 @@ Unless otherwise stated, buffers are not NUL-terminated. ``Z`` (:class:`str` or ``None``) [Py_UNICODE \*] Like ``u``, but the Python object may also be ``None``, in which case the - :ctype:`Py_UNICODE` pointer is set to *NULL*. + :c:type:`Py_UNICODE` pointer is set to *NULL*. ``Z#`` (:class:`str` or ``None``) [Py_UNICODE \*, int] Like ``u#``, but the Python object may also be ``None``, in which case the - :ctype:`Py_UNICODE` pointer is set to *NULL*. + :c:type:`Py_UNICODE` pointer is set to *NULL*. ``U`` (:class:`str`) [PyUnicodeObject \*] Requires that the Python object is a Unicode object, without attempting any conversion. Raises :exc:`TypeError` if the object is not a Unicode - object. The C variable may also be declared as :ctype:`PyObject\*`. + object. The C variable may also be declared as :c:type:`PyObject\*`. ``w*`` (:class:`bytearray` or read-write byte-oriented buffer) [Py_buffer] This format accepts any object which implements the read-write buffer - interface. It fills a :ctype:`Py_buffer` structure provided by the caller. + interface. It fills a :c:type:`Py_buffer` structure provided by the caller. The buffer may contain embedded null bytes. The caller have to call - :cfunc:`PyBuffer_Release` when it is done with the buffer. + :c:func:`PyBuffer_Release` when it is done with the buffer. ``es`` (:class:`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 :ctype:`const char\*` which points to the name of an encoding as a + must be a :c:type:`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 :ctype:`char\*\*`; the value of the pointer it + second argument must be a :c:type:`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. - :cfunc:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy the + :c:func:`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 :cfunc:`PyMem_Free` to + allocated storage. The caller is responsible for calling :c:func:`PyMem_Free` to free the allocated buffer after use. ``et`` (:class:`str`, :class:`bytes` or :class:`bytearray`) [const char \*encoding, char \*\*buffer] @@ -184,10 +184,10 @@ Unless otherwise stated, buffers are not NUL-terminated. characters. It requires three arguments. The first is only used as input, and must be a - :ctype:`const char\*` which points to the name of an encoding as a + :c:type:`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 :ctype:`char\*\*`; the value of the pointer it + second argument must be a :c:type:`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 @@ -198,10 +198,10 @@ Unless otherwise stated, buffers are not NUL-terminated. If *\*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 - :cfunc:`PyMem_Free` to free the allocated buffer after usage. + :c:func:`PyMem_Free` to free the allocated buffer after usage. If *\*buffer* points to a non-*NULL* pointer (an already allocated buffer), - :cfunc:`PyArg_ParseTuple` will use this location as the buffer and interpret the + :c:func:`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 :exc:`ValueError` will be set. @@ -219,62 +219,62 @@ Numbers ``b`` (:class:`int`) [unsigned char] Convert a nonnegative Python integer to an unsigned tiny int, stored in a C - :ctype:`unsigned char`. + :c:type:`unsigned char`. ``B`` (:class:`int`) [unsigned char] Convert a Python integer to a tiny int without overflow checking, stored in a C - :ctype:`unsigned char`. + :c:type:`unsigned char`. ``h`` (:class:`int`) [short int] - Convert a Python integer to a C :ctype:`short int`. + Convert a Python integer to a C :c:type:`short int`. ``H`` (:class:`int`) [unsigned short int] - Convert a Python integer to a C :ctype:`unsigned short int`, without overflow + Convert a Python integer to a C :c:type:`unsigned short int`, without overflow checking. ``i`` (:class:`int`) [int] - Convert a Python integer to a plain C :ctype:`int`. + Convert a Python integer to a plain C :c:type:`int`. ``I`` (:class:`int`) [unsigned int] - Convert a Python integer to a C :ctype:`unsigned int`, without overflow + Convert a Python integer to a C :c:type:`unsigned int`, without overflow checking. ``l`` (:class:`int`) [long int] - Convert a Python integer to a C :ctype:`long int`. + Convert a Python integer to a C :c:type:`long int`. ``k`` (:class:`int`) [unsigned long] - Convert a Python integer to a C :ctype:`unsigned long` without + Convert a Python integer to a C :c:type:`unsigned long` without overflow checking. ``L`` (:class:`int`) [PY_LONG_LONG] - Convert a Python integer to a C :ctype:`long long`. This format is only - available on platforms that support :ctype:`long long` (or :ctype:`_int64` on + Convert a Python integer to a C :c:type:`long long`. This format is only + available on platforms that support :c:type:`long long` (or :c:type:`_int64` on Windows). ``K`` (:class:`int`) [unsigned PY_LONG_LONG] - Convert a Python integer to a C :ctype:`unsigned long long` + Convert a Python integer to a C :c:type:`unsigned long long` without overflow checking. This format is only available on platforms that - support :ctype:`unsigned long long` (or :ctype:`unsigned _int64` on Windows). + support :c:type:`unsigned long long` (or :c:type:`unsigned _int64` on Windows). ``n`` (:class:`int`) [Py_ssize_t] - Convert a Python integer to a C :ctype:`Py_ssize_t`. + Convert a Python integer to a C :c:type:`Py_ssize_t`. ``c`` (:class:`bytes` of length 1) [char] Convert a Python byte, represented as a :class:`bytes` object of length 1, - to a C :ctype:`char`. + to a C :c:type:`char`. ``C`` (:class:`str` of length 1) [int] Convert a Python character, represented as a :class:`str` object of - length 1, to a C :ctype:`int`. + length 1, to a C :c:type:`int`. ``f`` (:class:`float`) [float] - Convert a Python floating point number to a C :ctype:`float`. + Convert a Python floating point number to a C :c:type:`float`. ``d`` (:class:`float`) [double] - Convert a Python floating point number to a C :ctype:`double`. + Convert a Python floating point number to a C :c:type:`double`. ``D`` (:class:`complex`) [Py_complex] - Convert a Python complex number to a C :ctype:`Py_complex` structure. + Convert a Python complex number to a C :c:type:`Py_complex` structure. Other objects ------------- @@ -287,20 +287,20 @@ Other objects ``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 :ctype:`PyObject\*`) into which + second is the address of the C variable (of type :c:type:`PyObject\*`) into which the object pointer is stored. If the Python object does not have the required type, :exc:`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 :ctype:`void \*`. The *converter* + variable (of arbitrary type), converted to :c:type:`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 - :ctype:`void\*` argument that was passed to the :cfunc:`PyArg_Parse\*` function. + :c:type:`void\*` argument that was passed to the :c:func:`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. @@ -332,13 +332,13 @@ inside nested parentheses. They are: 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, - :cfunc:`PyArg_ParseTuple` does not touch the contents of the corresponding C + :c:func:`PyArg_ParseTuple` does not touch the contents of the corresponding C variable(s). ``:`` The list of format units ends here; the string after the colon is used as the function name in error messages (the "associated value" of the exception that - :cfunc:`PyArg_ParseTuple` raises). + :c:func:`PyArg_ParseTuple` raises). ``;`` The list of format units ends here; the string after the semicolon is used as @@ -356,52 +356,52 @@ what is specified for the corresponding format unit in that case. For the conversion to succeed, the *arg* object must match the format and the format must be exhausted. On success, the -:cfunc:`PyArg_Parse\*` functions return true, otherwise they return +:c:func:`PyArg_Parse\*` functions return true, otherwise they return false and raise an appropriate exception. When the -:cfunc:`PyArg_Parse\*` functions fail due to conversion failure in one +:c:func:`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 Functions ------------- -.. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...) +.. c:function:: int PyArg_ParseTuple(PyObject *args, const char *format, ...) Parse the parameters of a function that takes only positional parameters into local variables. Returns true on success; on failure, it returns false and raises the appropriate exception. -.. cfunction:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs) +.. c:function:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs) - Identical to :cfunc:`PyArg_ParseTuple`, except that it accepts a va_list rather + Identical to :c:func:`PyArg_ParseTuple`, except that it accepts a va_list rather than a variable number of arguments. -.. cfunction:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...) +.. c:function:: 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. -.. cfunction:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs) +.. c:function:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs) - Identical to :cfunc:`PyArg_ParseTupleAndKeywords`, except that it accepts a + Identical to :c:func:`PyArg_ParseTupleAndKeywords`, except that it accepts a va_list rather than a variable number of arguments. -.. cfunction:: int PyArg_ValidateKeywordArguments(PyObject *) +.. c:function:: int PyArg_ValidateKeywordArguments(PyObject *) Ensure that the keys in the keywords argument dictionary are strings. This - is only needed if :cfunc:`PyArg_ParseTupleAndKeywords` is not used, since the + is only needed if :c:func:`PyArg_ParseTupleAndKeywords` is not used, since the latter already does this check. .. versionadded:: 3.2 .. XXX deprecated, will be removed -.. cfunction:: int PyArg_Parse(PyObject *args, const char *format, ...) +.. c:function:: 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 :const:`METH_OLDARGS` parameter parsing @@ -411,7 +411,7 @@ API Functions however, and may continue to be used for that purpose. -.. cfunction:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) +.. c:function:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) 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 @@ -420,7 +420,7 @@ API Functions *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 - :ctype:`PyObject\*` variable; these will be filled in with the values from + :c:type:`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 @@ -443,8 +443,8 @@ API Functions return result; } - The call to :cfunc:`PyArg_UnpackTuple` in this example is entirely equivalent to - this call to :cfunc:`PyArg_ParseTuple`:: + The call to :c:func:`PyArg_UnpackTuple` in this example is entirely equivalent to + this call to :c:func:`PyArg_ParseTuple`:: PyArg_ParseTuple(args, "O|O:ref", &object, &callback) @@ -453,14 +453,14 @@ API Functions Building values --------------- -.. cfunction:: PyObject* Py_BuildValue(const char *format, ...) +.. c:function:: PyObject* Py_BuildValue(const char *format, ...) Create a new value based on a format string similar to those accepted by the - :cfunc:`PyArg_Parse\*` family of functions and a sequence of values. Returns + :c:func:`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. - :cfunc:`Py_BuildValue` does not always build a tuple. It builds a tuple only if + :c:func:`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 @@ -469,10 +469,10 @@ Building values 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 - :cfunc:`Py_BuildValue`. In other words, if your code invokes :cfunc:`malloc` - and passes the allocated memory to :cfunc:`Py_BuildValue`, your code is - responsible for calling :cfunc:`free` for that memory once - :cfunc:`Py_BuildValue` returns. + :c:func:`Py_BuildValue`. In other words, if your code invokes :c:func:`malloc` + and passes the allocated memory to :c:func:`Py_BuildValue`, your code is + responsible for calling :c:func:`free` for that memory once + :c:func:`Py_BuildValue` returns. In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that the format unit will return; @@ -521,64 +521,64 @@ Building values Same as ``s#``. ``i`` (:class:`int`) [int] - Convert a plain C :ctype:`int` to a Python integer object. + Convert a plain C :c:type:`int` to a Python integer object. ``b`` (:class:`int`) [char] - Convert a plain C :ctype:`char` to a Python integer object. + Convert a plain C :c:type:`char` to a Python integer object. ``h`` (:class:`int`) [short int] - Convert a plain C :ctype:`short int` to a Python integer object. + Convert a plain C :c:type:`short int` to a Python integer object. ``l`` (:class:`int`) [long int] - Convert a C :ctype:`long int` to a Python integer object. + Convert a C :c:type:`long int` to a Python integer object. ``B`` (:class:`int`) [unsigned char] - Convert a C :ctype:`unsigned char` to a Python integer object. + Convert a C :c:type:`unsigned char` to a Python integer object. ``H`` (:class:`int`) [unsigned short int] - Convert a C :ctype:`unsigned short int` to a Python integer object. + Convert a C :c:type:`unsigned short int` to a Python integer object. ``I`` (:class:`int`) [unsigned int] - Convert a C :ctype:`unsigned int` to a Python integer object. + Convert a C :c:type:`unsigned int` to a Python integer object. ``k`` (:class:`int`) [unsigned long] - Convert a C :ctype:`unsigned long` to a Python integer object. + Convert a C :c:type:`unsigned long` to a Python integer object. ``L`` (:class:`int`) [PY_LONG_LONG] - Convert a C :ctype:`long long` to a Python integer object. Only available - on platforms that support :ctype:`long long` (or :ctype:`_int64` on + Convert a C :c:type:`long long` to a Python integer object. Only available + on platforms that support :c:type:`long long` (or :c:type:`_int64` on Windows). ``K`` (:class:`int`) [unsigned PY_LONG_LONG] - Convert a C :ctype:`unsigned long long` to a Python integer object. Only - available on platforms that support :ctype:`unsigned long long` (or - :ctype:`unsigned _int64` on Windows). + Convert a C :c:type:`unsigned long long` to a Python integer object. Only + available on platforms that support :c:type:`unsigned long long` (or + :c:type:`unsigned _int64` on Windows). ``n`` (:class:`int`) [Py_ssize_t] - Convert a C :ctype:`Py_ssize_t` to a Python integer. + Convert a C :c:type:`Py_ssize_t` to a Python integer. ``c`` (:class:`bytes` of length 1) [char] - Convert a C :ctype:`int` representing a byte to a Python :class:`bytes` object of + Convert a C :c:type:`int` representing a byte to a Python :class:`bytes` object of length 1. ``C`` (:class:`str` of length 1) [int] - Convert a C :ctype:`int` representing a character to Python :class:`str` + Convert a C :c:type:`int` representing a character to Python :class:`str` object of length 1. ``d`` (:class:`float`) [double] - Convert a C :ctype:`double` to a Python floating point number. + Convert a C :c:type:`double` to a Python floating point number. ``f`` (:class:`float`) [float] - Convert a C :ctype:`float` to a Python floating point number. + Convert a C :c:type:`float` to a Python floating point number. ``D`` (:class:`complex`) [Py_complex \*] - Convert a C :ctype:`Py_complex` structure to a Python complex number. + Convert a C :c:type:`Py_complex` structure to a Python complex number. ``O`` (object) [PyObject \*] Pass a Python object untouched (except for its reference count, which 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, :cfunc:`Py_BuildValue` will return *NULL* but won't + set an exception. Therefore, :c:func:`Py_BuildValue` will return *NULL* but won't raise an exception. If no exception has been raised yet, :exc:`SystemError` is set. @@ -592,7 +592,7 @@ Building values ``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 :ctype:`void + function is called with *anything* (which should be compatible with :c:type:`void \*`) as its argument and should return a "new" Python object, or *NULL* if an error occurred. @@ -610,7 +610,7 @@ Building values If there is an error in the format string, the :exc:`SystemError` exception is set and *NULL* returned. -.. cfunction:: PyObject* Py_VaBuildValue(const char *format, va_list vargs) +.. c:function:: PyObject* Py_VaBuildValue(const char *format, va_list vargs) - Identical to :cfunc:`Py_BuildValue`, except that it accepts a va_list + Identical to :c:func:`Py_BuildValue`, except that it accepts a va_list rather than a variable number of arguments. diff --git a/Doc/c-api/bool.rst b/Doc/c-api/bool.rst index 4479bc6..a9fb342 100644 --- a/Doc/c-api/bool.rst +++ b/Doc/c-api/bool.rst @@ -11,36 +11,36 @@ creation and deletion functions don't apply to booleans. The following macros are available, however. -.. cfunction:: int PyBool_Check(PyObject *o) +.. c:function:: int PyBool_Check(PyObject *o) - Return true if *o* is of type :cdata:`PyBool_Type`. + Return true if *o* is of type :c:data:`PyBool_Type`. -.. cvar:: PyObject* Py_False +.. c:var:: PyObject* Py_False The Python ``False`` object. This object has no methods. It needs to be treated just like any other object with respect to reference counts. -.. cvar:: PyObject* Py_True +.. c:var:: PyObject* Py_True The Python ``True`` object. This object has no methods. It needs to be treated just like any other object with respect to reference counts. -.. cmacro:: Py_RETURN_FALSE +.. c:macro:: Py_RETURN_FALSE Return :const:`Py_False` from a function, properly incrementing its reference count. -.. cmacro:: Py_RETURN_TRUE +.. c:macro:: Py_RETURN_TRUE Return :const:`Py_True` from a function, properly incrementing its reference count. -.. cfunction:: PyObject* PyBool_FromLong(long v) +.. c:function:: PyObject* PyBool_FromLong(long v) Return a new reference to :const:`Py_True` or :const:`Py_False` depending on the truth value of *v*. diff --git a/Doc/c-api/buffer.rst b/Doc/c-api/buffer.rst index 56bb897..64e8360 100644 --- a/Doc/c-api/buffer.rst +++ b/Doc/c-api/buffer.rst @@ -34,12 +34,12 @@ selectively allow or reject exporting of read-write and read-only buffers. There are two ways for a consumer of the buffer interface to acquire a buffer over a target object: -* call :cfunc:`PyObject_GetBuffer` with the right parameters; +* call :c:func:`PyObject_GetBuffer` with the right parameters; -* call :cfunc:`PyArg_ParseTuple` (or one of its siblings) with one of the +* call :c:func:`PyArg_ParseTuple` (or one of its siblings) with one of the ``y*``, ``w*`` or ``s*`` :ref:`format codes <arg-parsing>`. -In both cases, :cfunc:`PyBuffer_Release` must be called when the buffer +In both cases, :c:func:`PyBuffer_Release` must be called when the buffer isn't needed anymore. Failure to do so could lead to various issues such as resource leaks. @@ -47,7 +47,7 @@ resource leaks. .. index:: single: PyBufferProcs How the buffer interface is exposed by a type object is described in the -section :ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`. +section :ref:`buffer-structs`, under the description for :c:type:`PyBufferProcs`. The buffer structure @@ -63,55 +63,55 @@ operating system library, or it could be used to pass around structured data in its native, in-memory format. Contrary to most data types exposed by the Python interpreter, buffers -are not :ctype:`PyObject` pointers but rather simple C structures. This +are not :c:type:`PyObject` pointers but rather simple C structures. This allows them to be created and copied very simply. When a generic wrapper around a buffer is needed, a :ref:`memoryview <memoryview-objects>` object can be created. -.. ctype:: Py_buffer +.. c:type:: Py_buffer - .. cmember:: void *buf + .. c:member:: void *buf A pointer to the start of the memory for the object. - .. cmember:: Py_ssize_t len + .. c:member:: Py_ssize_t len :noindex: The total length of the memory in bytes. - .. cmember:: int readonly + .. c:member:: int readonly An indicator of whether the buffer is read only. - .. cmember:: const char *format + .. c:member:: const char *format :noindex: A *NULL* terminated string in :mod:`struct` module style syntax giving the contents of the elements available through the buffer. If this is *NULL*, ``"B"`` (unsigned bytes) is assumed. - .. cmember:: int ndim + .. c:member:: int ndim The number of dimensions the memory represents as a multi-dimensional - array. If it is 0, :cdata:`strides` and :cdata:`suboffsets` must be + array. If it is 0, :c:data:`strides` and :c:data:`suboffsets` must be *NULL*. - .. cmember:: Py_ssize_t *shape + .. c:member:: Py_ssize_t *shape - An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the + An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim` giving the shape of the memory as a multi-dimensional array. Note that ``((*shape)[0] * ... * (*shape)[ndims-1])*itemsize`` should be equal to - :cdata:`len`. + :c:data:`len`. - .. cmember:: Py_ssize_t *strides + .. c:member:: Py_ssize_t *strides - An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the + An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim` giving the number of bytes to skip to get to a new element in each dimension. - .. cmember:: Py_ssize_t *suboffsets + .. c:member:: Py_ssize_t *suboffsets - An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim`. If these + An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim`. If these suboffset numbers are greater than or equal to 0, then the value stored along the indicated dimension is a pointer and the suboffset value dictates how many bytes to add to the pointer after de-referencing. A @@ -136,16 +136,16 @@ can be created. } - .. cmember:: Py_ssize_t itemsize + .. c:member:: Py_ssize_t itemsize This is a storage for the itemsize (in bytes) of each element of the shared memory. It is technically un-necessary as it can be obtained - using :cfunc:`PyBuffer_SizeFromFormat`, however an exporter may know + using :c:func:`PyBuffer_SizeFromFormat`, however an exporter may know this information without parsing the format string and it is necessary to know the itemsize for proper interpretation of striding. Therefore, storing it is more convenient and faster. - .. cmember:: void *internal + .. c:member:: void *internal This is for use internally by the exporting object. For example, this might be re-cast as an integer by the exporter and used to store flags @@ -158,32 +158,32 @@ Buffer-related functions ======================== -.. cfunction:: int PyObject_CheckBuffer(PyObject *obj) +.. c:function:: int PyObject_CheckBuffer(PyObject *obj) Return 1 if *obj* supports the buffer interface otherwise 0. When 1 is - returned, it doesn't guarantee that :cfunc:`PyObject_GetBuffer` will + returned, it doesn't guarantee that :c:func:`PyObject_GetBuffer` will succeed. -.. cfunction:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) +.. c:function:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) Export a view over some internal data from the target object *obj*. *obj* must not be NULL, and *view* must point to an existing - :ctype:`Py_buffer` structure allocated by the caller (most uses of + :c:type:`Py_buffer` structure allocated by the caller (most uses of this function will simply declare a local variable of type - :ctype:`Py_buffer`). The *flags* argument is a bit field indicating + :c:type:`Py_buffer`). The *flags* argument is a bit field indicating what kind of buffer is requested. The buffer interface allows for complicated memory layout possibilities; however, some callers won't want to handle all the complexity and instead request a simple - view of the target object (using :cmacro:`PyBUF_SIMPLE` for a read-only - view and :cmacro:`PyBUF_WRITABLE` for a read-write view). + view of the target object (using :c:macro:`PyBUF_SIMPLE` for a read-only + view and :c:macro:`PyBUF_WRITABLE` for a read-write view). Some exporters may not be able to share memory in every possible way and may need to raise errors to signal to some consumers that something is just not possible. These errors should be a :exc:`BufferError` unless there is another error that is actually causing the problem. The exporter can use flags information to simplify how much of the - :cdata:`Py_buffer` structure is filled in with non-default values and/or + :c:data:`Py_buffer` structure is filled in with non-default values and/or raise an error if the object can't support a simpler view of its memory. On success, 0 is returned and the *view* structure is filled with useful @@ -192,7 +192,7 @@ Buffer-related functions The following are the possible values to the *flags* arguments. - .. cmacro:: PyBUF_SIMPLE + .. c:macro:: PyBUF_SIMPLE This is the default flag. The returned buffer exposes a read-only memory area. The format of data is assumed to be raw unsigned bytes, @@ -200,45 +200,45 @@ Buffer-related functions constant. It never needs to be '|'d to the others. The exporter will raise an error if it cannot provide such a contiguous buffer of bytes. - .. cmacro:: PyBUF_WRITABLE + .. c:macro:: PyBUF_WRITABLE - Like :cmacro:`PyBUF_SIMPLE`, but the returned buffer is writable. If + Like :c:macro:`PyBUF_SIMPLE`, but the returned buffer is writable. If the exporter doesn't support writable buffers, an error is raised. - .. cmacro:: PyBUF_STRIDES + .. c:macro:: PyBUF_STRIDES - This implies :cmacro:`PyBUF_ND`. The returned buffer must provide + This implies :c:macro:`PyBUF_ND`. The returned buffer must provide strides information (i.e. the strides cannot be NULL). This would be used when the consumer can handle strided, discontiguous arrays. Handling strides automatically assumes you can handle shape. The exporter can raise an error if a strided representation of the data is not possible (i.e. without the suboffsets). - .. cmacro:: PyBUF_ND + .. c:macro:: PyBUF_ND The returned buffer must provide shape information. The memory will be assumed C-style contiguous (last dimension varies the fastest). The exporter may raise an error if it cannot provide this kind of contiguous buffer. If this is not given then shape will be *NULL*. - .. cmacro:: PyBUF_C_CONTIGUOUS + .. c:macro:: PyBUF_C_CONTIGUOUS PyBUF_F_CONTIGUOUS PyBUF_ANY_CONTIGUOUS These flags indicate that the contiguity returned buffer must be respectively, C-contiguous (last dimension varies the fastest), Fortran contiguous (first dimension varies the fastest) or either one. All of - these flags imply :cmacro:`PyBUF_STRIDES` and guarantee that the + these flags imply :c:macro:`PyBUF_STRIDES` and guarantee that the strides buffer info structure will be filled in correctly. - .. cmacro:: PyBUF_INDIRECT + .. c:macro:: PyBUF_INDIRECT This flag indicates the returned buffer must have suboffsets information (which can be NULL if no suboffsets are needed). This can be used when the consumer can handle indirect array referencing implied - by these suboffsets. This implies :cmacro:`PyBUF_STRIDES`. + by these suboffsets. This implies :c:macro:`PyBUF_STRIDES`. - .. cmacro:: PyBUF_FORMAT + .. c:macro:: PyBUF_FORMAT The returned buffer must have true format information if this flag is provided. This would be used when the consumer is going to be checking @@ -247,54 +247,54 @@ Buffer-related functions explicitly requested then the format must be returned as *NULL* (which means ``'B'``, or unsigned bytes). - .. cmacro:: PyBUF_STRIDED + .. c:macro:: PyBUF_STRIDED This is equivalent to ``(PyBUF_STRIDES | PyBUF_WRITABLE)``. - .. cmacro:: PyBUF_STRIDED_RO + .. c:macro:: PyBUF_STRIDED_RO This is equivalent to ``(PyBUF_STRIDES)``. - .. cmacro:: PyBUF_RECORDS + .. c:macro:: PyBUF_RECORDS This is equivalent to ``(PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE)``. - .. cmacro:: PyBUF_RECORDS_RO + .. c:macro:: PyBUF_RECORDS_RO This is equivalent to ``(PyBUF_STRIDES | PyBUF_FORMAT)``. - .. cmacro:: PyBUF_FULL + .. c:macro:: PyBUF_FULL This is equivalent to ``(PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE)``. - .. cmacro:: PyBUF_FULL_RO + .. c:macro:: PyBUF_FULL_RO This is equivalent to ``(PyBUF_INDIRECT | PyBUF_FORMAT)``. - .. cmacro:: PyBUF_CONTIG + .. c:macro:: PyBUF_CONTIG This is equivalent to ``(PyBUF_ND | PyBUF_WRITABLE)``. - .. cmacro:: PyBUF_CONTIG_RO + .. c:macro:: PyBUF_CONTIG_RO This is equivalent to ``(PyBUF_ND)``. -.. cfunction:: void PyBuffer_Release(Py_buffer *view) +.. c:function:: void PyBuffer_Release(Py_buffer *view) Release the buffer *view*. This should be called when the buffer is no longer being used as it may free memory from it. -.. cfunction:: Py_ssize_t PyBuffer_SizeFromFormat(const char *) +.. c:function:: Py_ssize_t PyBuffer_SizeFromFormat(const char *) - Return the implied :cdata:`~Py_buffer.itemsize` from the struct-stype - :cdata:`~Py_buffer.format`. + Return the implied :c:data:`~Py_buffer.itemsize` from the struct-stype + :c:data:`~Py_buffer.format`. -.. cfunction:: int PyObject_CopyToObject(PyObject *obj, void *buf, Py_ssize_t len, char fortran) +.. c:function:: int PyObject_CopyToObject(PyObject *obj, void *buf, Py_ssize_t len, char fortran) Copy *len* bytes of data pointed to by the contiguous chunk of memory pointed to by *buf* into the buffer exported by obj. The buffer must of @@ -308,21 +308,21 @@ Buffer-related functions matter and the copy will be made in whatever way is more efficient. -.. cfunction:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran) +.. c:function:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran) Return 1 if the memory defined by the *view* is C-style (*fortran* is ``'C'``) or Fortran-style (*fortran* is ``'F'``) contiguous or either one (*fortran* is ``'A'``). Return 0 otherwise. -.. cfunction:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran) +.. c:function:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran) Fill the *strides* array with byte-strides of a contiguous (C-style if *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'`` array of the given shape with the given number of bytes per element. -.. cfunction:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int infoflags) +.. c:function:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int infoflags) Fill in a buffer-info structure, *view*, correctly for an exporter that can only share a contiguous chunk of memory of "unsigned bytes" of the given diff --git a/Doc/c-api/bytearray.rst b/Doc/c-api/bytearray.rst index 4bc5459..61b29ff 100644 --- a/Doc/c-api/bytearray.rst +++ b/Doc/c-api/bytearray.rst @@ -8,26 +8,26 @@ Byte Array Objects .. index:: object: bytearray -.. ctype:: PyByteArrayObject +.. c:type:: PyByteArrayObject - This subtype of :ctype:`PyObject` represents a Python bytearray object. + This subtype of :c:type:`PyObject` represents a Python bytearray object. -.. cvar:: PyTypeObject PyByteArray_Type +.. c:var:: PyTypeObject PyByteArray_Type - This instance of :ctype:`PyTypeObject` represents the Python bytearray type; + This instance of :c:type:`PyTypeObject` represents the Python bytearray type; it is the same object as ``bytearray`` in the Python layer. Type check macros ^^^^^^^^^^^^^^^^^ -.. cfunction:: int PyByteArray_Check(PyObject *o) +.. c:function:: int PyByteArray_Check(PyObject *o) Return true if the object *o* is a bytearray object or an instance of a subtype of the bytearray type. -.. cfunction:: int PyByteArray_CheckExact(PyObject *o) +.. c:function:: int PyByteArray_CheckExact(PyObject *o) Return true if the object *o* is a bytearray object, but not an instance of a subtype of the bytearray type. @@ -36,7 +36,7 @@ Type check macros Direct API functions ^^^^^^^^^^^^^^^^^^^^ -.. cfunction:: PyObject* PyByteArray_FromObject(PyObject *o) +.. c:function:: PyObject* PyByteArray_FromObject(PyObject *o) Return a new bytearray object from any object, *o*, that implements the buffer protocol. @@ -44,29 +44,29 @@ Direct API functions .. XXX expand about the buffer protocol, at least somewhere -.. cfunction:: PyObject* PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len) +.. c:function:: PyObject* PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len) Create a new bytearray object from *string* and its length, *len*. On failure, *NULL* is returned. -.. cfunction:: PyObject* PyByteArray_Concat(PyObject *a, PyObject *b) +.. c:function:: PyObject* PyByteArray_Concat(PyObject *a, PyObject *b) Concat bytearrays *a* and *b* and return a new bytearray with the result. -.. cfunction:: Py_ssize_t PyByteArray_Size(PyObject *bytearray) +.. c:function:: Py_ssize_t PyByteArray_Size(PyObject *bytearray) Return the size of *bytearray* after checking for a *NULL* pointer. -.. cfunction:: char* PyByteArray_AsString(PyObject *bytearray) +.. c:function:: char* PyByteArray_AsString(PyObject *bytearray) Return the contents of *bytearray* as a char array after checking for a *NULL* pointer. -.. cfunction:: int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len) +.. c:function:: int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len) Resize the internal buffer of *bytearray* to *len*. @@ -75,11 +75,11 @@ Macros These macros trade safety for speed and they don't check pointers. -.. cfunction:: char* PyByteArray_AS_STRING(PyObject *bytearray) +.. c:function:: char* PyByteArray_AS_STRING(PyObject *bytearray) - Macro version of :cfunc:`PyByteArray_AsString`. + Macro version of :c:func:`PyByteArray_AsString`. -.. cfunction:: Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray) +.. c:function:: Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray) - Macro version of :cfunc:`PyByteArray_Size`. + Macro version of :c:func:`PyByteArray_Size`. diff --git a/Doc/c-api/bytes.rst b/Doc/c-api/bytes.rst index c1a82b2..b7d57fa 100644 --- a/Doc/c-api/bytes.rst +++ b/Doc/c-api/bytes.rst @@ -11,48 +11,48 @@ called with a non-bytes parameter. .. index:: object: bytes -.. ctype:: PyBytesObject +.. c:type:: PyBytesObject - This subtype of :ctype:`PyObject` represents a Python bytes object. + This subtype of :c:type:`PyObject` represents a Python bytes object. -.. cvar:: PyTypeObject PyBytes_Type +.. c:var:: PyTypeObject PyBytes_Type .. index:: single: BytesType (in module types) - This instance of :ctype:`PyTypeObject` represents the Python bytes type; it + This instance of :c:type:`PyTypeObject` represents the Python bytes type; it is the same object as ``bytes`` in the Python layer. . -.. cfunction:: int PyBytes_Check(PyObject *o) +.. c:function:: int PyBytes_Check(PyObject *o) Return true if the object *o* is a bytes object or an instance of a subtype of the bytes type. -.. cfunction:: int PyBytes_CheckExact(PyObject *o) +.. c:function:: int PyBytes_CheckExact(PyObject *o) Return true if the object *o* is a bytes object, but not an instance of a subtype of the bytes type. -.. cfunction:: PyObject* PyBytes_FromString(const char *v) +.. c:function:: PyObject* PyBytes_FromString(const char *v) Return a new bytes object with a copy of the string *v* as value on success, and *NULL* on failure. The parameter *v* must not be *NULL*; it will not be checked. -.. cfunction:: PyObject* PyBytes_FromStringAndSize(const char *v, Py_ssize_t len) +.. c:function:: PyObject* PyBytes_FromStringAndSize(const char *v, Py_ssize_t len) Return a new bytes object with a copy of the string *v* as value and length *len* on success, and *NULL* on failure. If *v* is *NULL*, the contents of the bytes object are uninitialized. -.. cfunction:: PyObject* PyBytes_FromFormat(const char *format, ...) +.. c:function:: PyObject* PyBytes_FromFormat(const char *format, ...) - Take a C :cfunc:`printf`\ -style *format* string and a variable number of + Take a C :c:func:`printf`\ -style *format* string and a variable number of arguments, calculate the size of the resulting Python bytes object and return a bytes object with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the @@ -112,44 +112,44 @@ called with a non-bytes parameter. copied as-is to the result string, and any extra arguments discarded. -.. cfunction:: PyObject* PyBytes_FromFormatV(const char *format, va_list vargs) +.. c:function:: PyObject* PyBytes_FromFormatV(const char *format, va_list vargs) - Identical to :cfunc:`PyBytes_FromFormat` except that it takes exactly two + Identical to :c:func:`PyBytes_FromFormat` except that it takes exactly two arguments. -.. cfunction:: PyObject* PyBytes_FromObject(PyObject *o) +.. c:function:: PyObject* PyBytes_FromObject(PyObject *o) Return the bytes representation of object *o* that implements the buffer protocol. -.. cfunction:: Py_ssize_t PyBytes_Size(PyObject *o) +.. c:function:: Py_ssize_t PyBytes_Size(PyObject *o) Return the length of the bytes in bytes object *o*. -.. cfunction:: Py_ssize_t PyBytes_GET_SIZE(PyObject *o) +.. c:function:: Py_ssize_t PyBytes_GET_SIZE(PyObject *o) - Macro form of :cfunc:`PyBytes_Size` but without error checking. + Macro form of :c:func:`PyBytes_Size` but without error checking. -.. cfunction:: char* PyBytes_AsString(PyObject *o) +.. c:function:: char* PyBytes_AsString(PyObject *o) Return a NUL-terminated representation of the contents of *o*. The pointer refers to the internal buffer of *o*, not a copy. The data must not be modified in any way, unless the string was just created using ``PyBytes_FromStringAndSize(NULL, size)``. It must not be deallocated. If - *o* is not a string object at all, :cfunc:`PyBytes_AsString` returns *NULL* + *o* is not a string object at all, :c:func:`PyBytes_AsString` returns *NULL* and raises :exc:`TypeError`. -.. cfunction:: char* PyBytes_AS_STRING(PyObject *string) +.. c:function:: char* PyBytes_AS_STRING(PyObject *string) - Macro form of :cfunc:`PyBytes_AsString` but without error checking. + Macro form of :c:func:`PyBytes_AsString` but without error checking. -.. cfunction:: int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length) +.. c:function:: int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length) Return a NUL-terminated representation of the contents of the object *obj* through the output variables *buffer* and *length*. @@ -160,11 +160,11 @@ called with a non-bytes parameter. The buffer refers to an internal string buffer of *obj*, not a copy. The data must not be modified in any way, unless the string was just created using ``PyBytes_FromStringAndSize(NULL, size)``. It must not be deallocated. If - *string* is not a string object at all, :cfunc:`PyBytes_AsStringAndSize` + *string* is not a string object at all, :c:func:`PyBytes_AsStringAndSize` returns ``-1`` and raises :exc:`TypeError`. -.. cfunction:: void PyBytes_Concat(PyObject **bytes, PyObject *newpart) +.. c:function:: void PyBytes_Concat(PyObject **bytes, PyObject *newpart) Create a new bytes object in *\*bytes* containing the contents of *newpart* appended to *bytes*; the caller will own the new reference. The reference to @@ -173,14 +173,14 @@ called with a non-bytes parameter. of *\*bytes* will be set to *NULL*; the appropriate exception will be set. -.. cfunction:: void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart) +.. c:function:: void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart) Create a new string object in *\*bytes* containing the contents of *newpart* appended to *bytes*. This version decrements the reference count of *newpart*. -.. cfunction:: int _PyBytes_Resize(PyObject **bytes, Py_ssize_t newsize) +.. c:function:: int _PyBytes_Resize(PyObject **bytes, Py_ssize_t newsize) A way to resize a bytes object even though it is "immutable". Only use this to build up a brand new bytes object; don't use this if the bytes may already diff --git a/Doc/c-api/capsule.rst b/Doc/c-api/capsule.rst index 2939314..6f6250f 100644 --- a/Doc/c-api/capsule.rst +++ b/Doc/c-api/capsule.rst @@ -10,33 +10,33 @@ Capsules Refer to :ref:`using-capsules` for more information on using these objects. -.. ctype:: PyCapsule +.. c:type:: PyCapsule - This subtype of :ctype:`PyObject` represents an opaque value, useful for C - extension modules who need to pass an opaque value (as a :ctype:`void\*` + This subtype of :c:type:`PyObject` represents an opaque value, useful for C + extension modules who need to pass an opaque value (as a :c:type:`void\*` pointer) through Python code to other C code. It is often used to make a C function pointer defined in one module available to other modules, so the regular import mechanism can be used to access C APIs defined in dynamically loaded modules. -.. ctype:: PyCapsule_Destructor +.. c:type:: PyCapsule_Destructor The type of a destructor callback for a capsule. Defined as:: typedef void (*PyCapsule_Destructor)(PyObject *); - See :cfunc:`PyCapsule_New` for the semantics of PyCapsule_Destructor + See :c:func:`PyCapsule_New` for the semantics of PyCapsule_Destructor callbacks. -.. cfunction:: int PyCapsule_CheckExact(PyObject *p) +.. c:function:: int PyCapsule_CheckExact(PyObject *p) - Return true if its argument is a :ctype:`PyCapsule`. + Return true if its argument is a :c:type:`PyCapsule`. -.. cfunction:: PyObject* PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor) +.. c:function:: PyObject* PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor) - Create a :ctype:`PyCapsule` encapsulating the *pointer*. The *pointer* + Create a :c:type:`PyCapsule` encapsulating the *pointer*. The *pointer* argument may not be *NULL*. On failure, set an exception and return *NULL*. @@ -50,91 +50,91 @@ Refer to :ref:`using-capsules` for more information on using these objects. If this capsule will be stored as an attribute of a module, the *name* should be specified as ``modulename.attributename``. This will enable other modules - to import the capsule using :cfunc:`PyCapsule_Import`. + to import the capsule using :c:func:`PyCapsule_Import`. -.. cfunction:: void* PyCapsule_GetPointer(PyObject *capsule, const char *name) +.. c:function:: void* PyCapsule_GetPointer(PyObject *capsule, const char *name) Retrieve the *pointer* stored in the capsule. On failure, set an exception and return *NULL*. The *name* parameter must compare exactly to the name stored in the capsule. If the name stored in the capsule is *NULL*, the *name* passed in must also - be *NULL*. Python uses the C function :cfunc:`strcmp` to compare capsule + be *NULL*. Python uses the C function :c:func:`strcmp` to compare capsule names. -.. cfunction:: PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule) +.. c:function:: PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule) Return the current destructor stored in the capsule. On failure, set an exception and return *NULL*. It is legal for a capsule to have a *NULL* destructor. This makes a *NULL* - return code somewhat ambiguous; use :cfunc:`PyCapsule_IsValid` or - :cfunc:`PyErr_Occurred` to disambiguate. + return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or + :c:func:`PyErr_Occurred` to disambiguate. -.. cfunction:: void* PyCapsule_GetContext(PyObject *capsule) +.. c:function:: void* PyCapsule_GetContext(PyObject *capsule) Return the current context stored in the capsule. On failure, set an exception and return *NULL*. It is legal for a capsule to have a *NULL* context. This makes a *NULL* - return code somewhat ambiguous; use :cfunc:`PyCapsule_IsValid` or - :cfunc:`PyErr_Occurred` to disambiguate. + return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or + :c:func:`PyErr_Occurred` to disambiguate. -.. cfunction:: const char* PyCapsule_GetName(PyObject *capsule) +.. c:function:: const char* PyCapsule_GetName(PyObject *capsule) Return the current name stored in the capsule. On failure, set an exception and return *NULL*. It is legal for a capsule to have a *NULL* name. This makes a *NULL* return - code somewhat ambiguous; use :cfunc:`PyCapsule_IsValid` or - :cfunc:`PyErr_Occurred` to disambiguate. + code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or + :c:func:`PyErr_Occurred` to disambiguate. -.. cfunction:: void* PyCapsule_Import(const char *name, int no_block) +.. c:function:: void* PyCapsule_Import(const char *name, int no_block) Import a pointer to a C object from a capsule attribute in a module. The *name* parameter should specify the full name to the attribute, as in ``module.attribute``. The *name* stored in the capsule must match this string exactly. If *no_block* is true, import the module without blocking - (using :cfunc:`PyImport_ImportModuleNoBlock`). If *no_block* is false, - import the module conventionally (using :cfunc:`PyImport_ImportModule`). + (using :c:func:`PyImport_ImportModuleNoBlock`). If *no_block* is false, + import the module conventionally (using :c:func:`PyImport_ImportModule`). Return the capsule's internal *pointer* on success. On failure, set an - exception and return *NULL*. However, if :cfunc:`PyCapsule_Import` failed to + exception and return *NULL*. However, if :c:func:`PyCapsule_Import` failed to import the module, and *no_block* was true, no exception is set. -.. cfunction:: int PyCapsule_IsValid(PyObject *capsule, const char *name) +.. c:function:: int PyCapsule_IsValid(PyObject *capsule, const char *name) Determines whether or not *capsule* is a valid capsule. A valid capsule is - non-*NULL*, passes :cfunc:`PyCapsule_CheckExact`, has a non-*NULL* pointer + non-*NULL*, passes :c:func:`PyCapsule_CheckExact`, has a non-*NULL* pointer stored in it, and its internal name matches the *name* parameter. (See - :cfunc:`PyCapsule_GetPointer` for information on how capsule names are + :c:func:`PyCapsule_GetPointer` for information on how capsule names are compared.) - In other words, if :cfunc:`PyCapsule_IsValid` returns a true value, calls to - any of the accessors (any function starting with :cfunc:`PyCapsule_Get`) are + In other words, if :c:func:`PyCapsule_IsValid` returns a true value, calls to + any of the accessors (any function starting with :c:func:`PyCapsule_Get`) are guaranteed to succeed. Return a nonzero value if the object is valid and matches the name passed in. Return 0 otherwise. This function will not fail. -.. cfunction:: int PyCapsule_SetContext(PyObject *capsule, void *context) +.. c:function:: int PyCapsule_SetContext(PyObject *capsule, void *context) Set the context pointer inside *capsule* to *context*. Return 0 on success. Return nonzero and set an exception on failure. -.. cfunction:: int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor) +.. c:function:: int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor) Set the destructor inside *capsule* to *destructor*. Return 0 on success. Return nonzero and set an exception on failure. -.. cfunction:: int PyCapsule_SetName(PyObject *capsule, const char *name) +.. c:function:: int PyCapsule_SetName(PyObject *capsule, const char *name) Set the name inside *capsule* to *name*. If non-*NULL*, the name must outlive the capsule. If the previous *name* stored in the capsule was not @@ -142,7 +142,7 @@ Refer to :ref:`using-capsules` for more information on using these objects. Return 0 on success. Return nonzero and set an exception on failure. -.. cfunction:: int PyCapsule_SetPointer(PyObject *capsule, void *pointer) +.. c:function:: int PyCapsule_SetPointer(PyObject *capsule, void *pointer) Set the void pointer inside *capsule* to *pointer*. The pointer may not be *NULL*. diff --git a/Doc/c-api/cell.rst b/Doc/c-api/cell.rst index 3562ed9..427259c 100644 --- a/Doc/c-api/cell.rst +++ b/Doc/c-api/cell.rst @@ -15,39 +15,39 @@ generated byte-code; these are not automatically de-referenced when accessed. Cell objects are not likely to be useful elsewhere. -.. ctype:: PyCellObject +.. c:type:: PyCellObject The C structure used for cell objects. -.. cvar:: PyTypeObject PyCell_Type +.. c:var:: PyTypeObject PyCell_Type The type object corresponding to cell objects. -.. cfunction:: int PyCell_Check(ob) +.. c:function:: int PyCell_Check(ob) Return true if *ob* is a cell object; *ob* must not be *NULL*. -.. cfunction:: PyObject* PyCell_New(PyObject *ob) +.. c:function:: PyObject* PyCell_New(PyObject *ob) Create and return a new cell object containing the value *ob*. The parameter may be *NULL*. -.. cfunction:: PyObject* PyCell_Get(PyObject *cell) +.. c:function:: PyObject* PyCell_Get(PyObject *cell) Return the contents of the cell *cell*. -.. cfunction:: PyObject* PyCell_GET(PyObject *cell) +.. c:function:: PyObject* PyCell_GET(PyObject *cell) Return the contents of the cell *cell*, but without checking that *cell* is non-*NULL* and a cell object. -.. cfunction:: int PyCell_Set(PyObject *cell, PyObject *value) +.. c:function:: int PyCell_Set(PyObject *cell, PyObject *value) Set the contents of the cell object *cell* to *value*. This releases the reference to any current content of the cell. *value* may be *NULL*. *cell* @@ -55,7 +55,7 @@ Cell objects are not likely to be useful elsewhere. success, ``0`` will be returned. -.. cfunction:: void PyCell_SET(PyObject *cell, PyObject *value) +.. c:function:: void PyCell_SET(PyObject *cell, PyObject *value) Sets the value of the cell object *cell* to *value*. No reference counts are adjusted, and no checks are made for safety; *cell* must be non-*NULL* and must diff --git a/Doc/c-api/code.rst b/Doc/c-api/code.rst index c6ca8c5..7d9b4b6 100644 --- a/Doc/c-api/code.rst +++ b/Doc/c-api/code.rst @@ -15,35 +15,35 @@ Code objects are a low-level detail of the CPython implementation. Each one represents a chunk of executable code that hasn't yet been bound into a function. -.. ctype:: PyCodeObject +.. c:type:: PyCodeObject The C structure of the objects used to describe code objects. The fields of this type are subject to change at any time. -.. cvar:: PyTypeObject PyCode_Type +.. c:var:: PyTypeObject PyCode_Type - This is an instance of :ctype:`PyTypeObject` representing the Python + This is an instance of :c:type:`PyTypeObject` representing the Python :class:`code` type. -.. cfunction:: int PyCode_Check(PyObject *co) +.. c:function:: int PyCode_Check(PyObject *co) Return true if *co* is a :class:`code` object -.. cfunction:: int PyCode_GetNumFree(PyObject *co) +.. c:function:: int PyCode_GetNumFree(PyObject *co) Return the number of free variables in *co*. -.. cfunction:: PyCodeObject *PyCode_New(int argcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab) +.. c:function:: PyCodeObject *PyCode_New(int argcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab) Return a new code object. If you need a dummy code object to - create a frame, use :cfunc:`PyCode_NewEmpty` instead. Calling - :cfunc:`PyCode_New` directly can bind you to a precise Python + create a frame, use :c:func:`PyCode_NewEmpty` instead. Calling + :c:func:`PyCode_New` directly can bind you to a precise Python version since the definition of the bytecode changes often. -.. cfunction:: int PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno) +.. c:function:: int PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno) Return a new empty code object with the specified filename, function name, and first line number. It is illegal to diff --git a/Doc/c-api/complex.rst b/Doc/c-api/complex.rst index 3508a03..c66587a 100644 --- a/Doc/c-api/complex.rst +++ b/Doc/c-api/complex.rst @@ -21,7 +21,7 @@ them as results do so *by value* rather than dereferencing them through pointers. This is consistent throughout the API. -.. ctype:: Py_complex +.. c:type:: Py_complex The C structure which corresponds to the value portion of a Python complex number object. Most of the functions for dealing with complex number objects @@ -34,39 +34,39 @@ pointers. This is consistent throughout the API. } Py_complex; -.. cfunction:: Py_complex _Py_c_sum(Py_complex left, Py_complex right) +.. c:function:: Py_complex _Py_c_sum(Py_complex left, Py_complex right) - Return the sum of two complex numbers, using the C :ctype:`Py_complex` + Return the sum of two complex numbers, using the C :c:type:`Py_complex` representation. -.. cfunction:: Py_complex _Py_c_diff(Py_complex left, Py_complex right) +.. c:function:: Py_complex _Py_c_diff(Py_complex left, Py_complex right) Return the difference between two complex numbers, using the C - :ctype:`Py_complex` representation. + :c:type:`Py_complex` representation. -.. cfunction:: Py_complex _Py_c_neg(Py_complex complex) +.. c:function:: Py_complex _Py_c_neg(Py_complex complex) Return the negation of the complex number *complex*, using the C - :ctype:`Py_complex` representation. + :c:type:`Py_complex` representation. -.. cfunction:: Py_complex _Py_c_prod(Py_complex left, Py_complex right) +.. c:function:: Py_complex _Py_c_prod(Py_complex left, Py_complex right) - Return the product of two complex numbers, using the C :ctype:`Py_complex` + Return the product of two complex numbers, using the C :c:type:`Py_complex` representation. -.. cfunction:: Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor) +.. c:function:: Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor) - Return the quotient of two complex numbers, using the C :ctype:`Py_complex` + Return the quotient of two complex numbers, using the C :c:type:`Py_complex` representation. -.. cfunction:: Py_complex _Py_c_pow(Py_complex num, Py_complex exp) +.. c:function:: Py_complex _Py_c_pow(Py_complex num, Py_complex exp) - Return the exponentiation of *num* by *exp*, using the C :ctype:`Py_complex` + Return the exponentiation of *num* by *exp*, using the C :c:type:`Py_complex` representation. @@ -74,52 +74,52 @@ Complex Numbers as Python Objects ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -.. ctype:: PyComplexObject +.. c:type:: PyComplexObject - This subtype of :ctype:`PyObject` represents a Python complex number object. + This subtype of :c:type:`PyObject` represents a Python complex number object. -.. cvar:: PyTypeObject PyComplex_Type +.. c:var:: PyTypeObject PyComplex_Type - This instance of :ctype:`PyTypeObject` represents the Python complex number + This instance of :c:type:`PyTypeObject` represents the Python complex number type. It is the same object as ``complex`` and ``types.ComplexType``. -.. cfunction:: int PyComplex_Check(PyObject *p) +.. c:function:: int PyComplex_Check(PyObject *p) - Return true if its argument is a :ctype:`PyComplexObject` or a subtype of - :ctype:`PyComplexObject`. + Return true if its argument is a :c:type:`PyComplexObject` or a subtype of + :c:type:`PyComplexObject`. -.. cfunction:: int PyComplex_CheckExact(PyObject *p) +.. c:function:: int PyComplex_CheckExact(PyObject *p) - Return true if its argument is a :ctype:`PyComplexObject`, but not a subtype of - :ctype:`PyComplexObject`. + Return true if its argument is a :c:type:`PyComplexObject`, but not a subtype of + :c:type:`PyComplexObject`. -.. cfunction:: PyObject* PyComplex_FromCComplex(Py_complex v) +.. c:function:: PyObject* PyComplex_FromCComplex(Py_complex v) - Create a new Python complex number object from a C :ctype:`Py_complex` value. + Create a new Python complex number object from a C :c:type:`Py_complex` value. -.. cfunction:: PyObject* PyComplex_FromDoubles(double real, double imag) +.. c:function:: PyObject* PyComplex_FromDoubles(double real, double imag) - Return a new :ctype:`PyComplexObject` object from *real* and *imag*. + Return a new :c:type:`PyComplexObject` object from *real* and *imag*. -.. cfunction:: double PyComplex_RealAsDouble(PyObject *op) +.. c:function:: double PyComplex_RealAsDouble(PyObject *op) - Return the real part of *op* as a C :ctype:`double`. + Return the real part of *op* as a C :c:type:`double`. -.. cfunction:: double PyComplex_ImagAsDouble(PyObject *op) +.. c:function:: double PyComplex_ImagAsDouble(PyObject *op) - Return the imaginary part of *op* as a C :ctype:`double`. + Return the imaginary part of *op* as a C :c:type:`double`. -.. cfunction:: Py_complex PyComplex_AsCComplex(PyObject *op) +.. c:function:: Py_complex PyComplex_AsCComplex(PyObject *op) - Return the :ctype:`Py_complex` value of the complex number *op*. + Return the :c:type:`Py_complex` value of the complex number *op*. If *op* is not a Python complex number object but has a :meth:`__complex__` method, this method will first be called to convert *op* to a Python complex diff --git a/Doc/c-api/concrete.rst b/Doc/c-api/concrete.rst index dc08967..65904ee 100644 --- a/Doc/c-api/concrete.rst +++ b/Doc/c-api/concrete.rst @@ -11,7 +11,7 @@ The functions in this chapter are specific to certain Python object types. Passing them an object of the wrong type is not a good idea; if you receive an object from a Python program and you are not sure that it has the right type, you must perform a type check first; for example, to check that an object is a -dictionary, use :cfunc:`PyDict_Check`. The chapter is structured like the +dictionary, use :c:func:`PyDict_Check`. The chapter is structured like the "family tree" of Python object types. .. warning:: diff --git a/Doc/c-api/conversion.rst b/Doc/c-api/conversion.rst index e5f83ff..dfc0a3a 100644 --- a/Doc/c-api/conversion.rst +++ b/Doc/c-api/conversion.rst @@ -8,20 +8,20 @@ String conversion and formatting Functions for number conversion and formatted string output. -.. cfunction:: int PyOS_snprintf(char *str, size_t size, const char *format, ...) +.. c:function:: int PyOS_snprintf(char *str, size_t size, const char *format, ...) Output not more than *size* bytes to *str* according to the format string *format* and the extra arguments. See the Unix man page :manpage:`snprintf(2)`. -.. cfunction:: int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) +.. c:function:: int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) Output not more than *size* bytes to *str* according to the format string *format* and the variable argument list *va*. Unix man page :manpage:`vsnprintf(2)`. -:cfunc:`PyOS_snprintf` and :cfunc:`PyOS_vsnprintf` wrap the Standard C library -functions :cfunc:`snprintf` and :cfunc:`vsnprintf`. Their purpose is to +:c:func:`PyOS_snprintf` and :c:func:`PyOS_vsnprintf` wrap the Standard C library +functions :c:func:`snprintf` and :c:func:`vsnprintf`. Their purpose is to guarantee consistent behavior in corner cases, which the Standard C functions do not. @@ -30,7 +30,7 @@ never write more than *size* bytes (including the trailing ``'\0'``) into str. Both functions require that ``str != NULL``, ``size > 0`` and ``format != NULL``. -If the platform doesn't have :cfunc:`vsnprintf` and the buffer size needed to +If the platform doesn't have :c:func:`vsnprintf` and the buffer size needed to avoid truncation exceeds *size* by more than 512 bytes, Python aborts with a *Py_FatalError*. @@ -51,9 +51,9 @@ The return value (*rv*) for these functions should be interpreted as follows: The following functions provide locale-independent string to number conversions. -.. cfunction:: double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception) +.. c:function:: double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception) - Convert a string ``s`` to a :ctype:`double`, raising a Python + Convert a string ``s`` to a :c:type:`double`, raising a Python exception on failure. The set of accepted strings corresponds to the set of strings accepted by Python's :func:`float` constructor, except that ``s`` must not have leading or trailing whitespace. @@ -85,9 +85,9 @@ The following functions provide locale-independent string to number conversions. .. versionadded:: 3.1 -.. cfunction:: char* PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype) +.. c:function:: char* PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype) - Convert a :ctype:`double` *val* to a string using supplied + Convert a :c:type:`double` *val* to a string using supplied *format_code*, *precision*, and *flags*. *format_code* must be one of ``'e'``, ``'E'``, ``'f'``, ``'F'``, @@ -105,7 +105,7 @@ The following functions provide locale-independent string to number conversions. like an integer. * *Py_DTSF_ALT* means to apply "alternate" formatting rules. See the - documentation for the :cfunc:`PyOS_snprintf` ``'#'`` specifier for + documentation for the :c:func:`PyOS_snprintf` ``'#'`` specifier for details. If *ptype* is non-NULL, then the value it points to will be set to one of @@ -114,18 +114,18 @@ The following functions provide locale-independent string to number conversions. The return value is a pointer to *buffer* with the converted string or *NULL* if the conversion failed. The caller is responsible for freeing the - returned string by calling :cfunc:`PyMem_Free`. + returned string by calling :c:func:`PyMem_Free`. .. versionadded:: 3.1 -.. cfunction:: char* PyOS_stricmp(char *s1, char *s2) +.. c:function:: char* PyOS_stricmp(char *s1, char *s2) Case insensitive comparison of strings. The function works almost - identically to :cfunc:`strcmp` except that it ignores the case. + identically to :c:func:`strcmp` except that it ignores the case. -.. cfunction:: char* PyOS_strnicmp(char *s1, char *s2, Py_ssize_t size) +.. c:function:: char* PyOS_strnicmp(char *s1, char *s2, Py_ssize_t size) Case insensitive comparison of strings. The function works almost - identically to :cfunc:`strncmp` except that it ignores the case. + identically to :c:func:`strncmp` except that it ignores the case. diff --git a/Doc/c-api/datetime.rst b/Doc/c-api/datetime.rst index 6515bab..fcd1395 100644 --- a/Doc/c-api/datetime.rst +++ b/Doc/c-api/datetime.rst @@ -8,93 +8,93 @@ DateTime Objects Various date and time objects are supplied by the :mod:`datetime` module. Before using any of these functions, the header file :file:`datetime.h` must be included in your source (note that this is not included by :file:`Python.h`), -and the macro :cmacro:`PyDateTime_IMPORT` must be invoked, usually as part of +and the macro :c:macro:`PyDateTime_IMPORT` must be invoked, usually as part of the module initialisation function. The macro puts a pointer to a C structure -into a static variable, :cdata:`PyDateTimeAPI`, that is used by the following +into a static variable, :c:data:`PyDateTimeAPI`, that is used by the following macros. Type-check macros: -.. cfunction:: int PyDate_Check(PyObject *ob) +.. c:function:: int PyDate_Check(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_DateType` or a subtype of - :cdata:`PyDateTime_DateType`. *ob* must not be *NULL*. + Return true if *ob* is of type :c:data:`PyDateTime_DateType` or a subtype of + :c:data:`PyDateTime_DateType`. *ob* must not be *NULL*. -.. cfunction:: int PyDate_CheckExact(PyObject *ob) +.. c:function:: int PyDate_CheckExact(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_DateType`. *ob* must not be + Return true if *ob* is of type :c:data:`PyDateTime_DateType`. *ob* must not be *NULL*. -.. cfunction:: int PyDateTime_Check(PyObject *ob) +.. c:function:: int PyDateTime_Check(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType` or a subtype of - :cdata:`PyDateTime_DateTimeType`. *ob* must not be *NULL*. + Return true if *ob* is of type :c:data:`PyDateTime_DateTimeType` or a subtype of + :c:data:`PyDateTime_DateTimeType`. *ob* must not be *NULL*. -.. cfunction:: int PyDateTime_CheckExact(PyObject *ob) +.. c:function:: int PyDateTime_CheckExact(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType`. *ob* must not + Return true if *ob* is of type :c:data:`PyDateTime_DateTimeType`. *ob* must not be *NULL*. -.. cfunction:: int PyTime_Check(PyObject *ob) +.. c:function:: int PyTime_Check(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_TimeType` or a subtype of - :cdata:`PyDateTime_TimeType`. *ob* must not be *NULL*. + Return true if *ob* is of type :c:data:`PyDateTime_TimeType` or a subtype of + :c:data:`PyDateTime_TimeType`. *ob* must not be *NULL*. -.. cfunction:: int PyTime_CheckExact(PyObject *ob) +.. c:function:: int PyTime_CheckExact(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_TimeType`. *ob* must not be + Return true if *ob* is of type :c:data:`PyDateTime_TimeType`. *ob* must not be *NULL*. -.. cfunction:: int PyDelta_Check(PyObject *ob) +.. c:function:: int PyDelta_Check(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_DeltaType` or a subtype of - :cdata:`PyDateTime_DeltaType`. *ob* must not be *NULL*. + Return true if *ob* is of type :c:data:`PyDateTime_DeltaType` or a subtype of + :c:data:`PyDateTime_DeltaType`. *ob* must not be *NULL*. -.. cfunction:: int PyDelta_CheckExact(PyObject *ob) +.. c:function:: int PyDelta_CheckExact(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_DeltaType`. *ob* must not be + Return true if *ob* is of type :c:data:`PyDateTime_DeltaType`. *ob* must not be *NULL*. -.. cfunction:: int PyTZInfo_Check(PyObject *ob) +.. c:function:: int PyTZInfo_Check(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType` or a subtype of - :cdata:`PyDateTime_TZInfoType`. *ob* must not be *NULL*. + Return true if *ob* is of type :c:data:`PyDateTime_TZInfoType` or a subtype of + :c:data:`PyDateTime_TZInfoType`. *ob* must not be *NULL*. -.. cfunction:: int PyTZInfo_CheckExact(PyObject *ob) +.. c:function:: int PyTZInfo_CheckExact(PyObject *ob) - Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType`. *ob* must not be + Return true if *ob* is of type :c:data:`PyDateTime_TZInfoType`. *ob* must not be *NULL*. Macros to create objects: -.. cfunction:: PyObject* PyDate_FromDate(int year, int month, int day) +.. c:function:: PyObject* PyDate_FromDate(int year, int month, int day) Return a ``datetime.date`` object with the specified year, month and day. -.. cfunction:: PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond) +.. c:function:: PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond) Return a ``datetime.datetime`` object with the specified year, month, day, hour, minute, second and microsecond. -.. cfunction:: PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond) +.. c:function:: PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond) Return a ``datetime.time`` object with the specified hour, minute, second and microsecond. -.. cfunction:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds) +.. c:function:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds) Return a ``datetime.timedelta`` object representing the given number of days, seconds and microseconds. Normalization is performed so that the resulting @@ -103,82 +103,82 @@ Macros to create objects: Macros to extract fields from date objects. The argument must be an instance of -:cdata:`PyDateTime_Date`, including subclasses (such as -:cdata:`PyDateTime_DateTime`). The argument must not be *NULL*, and the type is +:c:data:`PyDateTime_Date`, including subclasses (such as +:c:data:`PyDateTime_DateTime`). The argument must not be *NULL*, and the type is not checked: -.. cfunction:: int PyDateTime_GET_YEAR(PyDateTime_Date *o) +.. c:function:: int PyDateTime_GET_YEAR(PyDateTime_Date *o) Return the year, as a positive int. -.. cfunction:: int PyDateTime_GET_MONTH(PyDateTime_Date *o) +.. c:function:: int PyDateTime_GET_MONTH(PyDateTime_Date *o) Return the month, as an int from 1 through 12. -.. cfunction:: int PyDateTime_GET_DAY(PyDateTime_Date *o) +.. c:function:: int PyDateTime_GET_DAY(PyDateTime_Date *o) Return the day, as an int from 1 through 31. Macros to extract fields from datetime objects. The argument must be an -instance of :cdata:`PyDateTime_DateTime`, including subclasses. The argument +instance of :c:data:`PyDateTime_DateTime`, including subclasses. The argument must not be *NULL*, and the type is not checked: -.. cfunction:: int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o) +.. c:function:: int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o) Return the hour, as an int from 0 through 23. -.. cfunction:: int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o) +.. c:function:: int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o) Return the minute, as an int from 0 through 59. -.. cfunction:: int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o) +.. c:function:: int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o) Return the second, as an int from 0 through 59. -.. cfunction:: int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o) +.. c:function:: int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o) Return the microsecond, as an int from 0 through 999999. Macros to extract fields from time objects. The argument must be an instance of -:cdata:`PyDateTime_Time`, including subclasses. The argument must not be *NULL*, +:c:data:`PyDateTime_Time`, including subclasses. The argument must not be *NULL*, and the type is not checked: -.. cfunction:: int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o) +.. c:function:: int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o) Return the hour, as an int from 0 through 23. -.. cfunction:: int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o) +.. c:function:: int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o) Return the minute, as an int from 0 through 59. -.. cfunction:: int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o) +.. c:function:: int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o) Return the second, as an int from 0 through 59. -.. cfunction:: int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o) +.. c:function:: int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o) Return the microsecond, as an int from 0 through 999999. Macros for the convenience of modules implementing the DB API: -.. cfunction:: PyObject* PyDateTime_FromTimestamp(PyObject *args) +.. c:function:: PyObject* PyDateTime_FromTimestamp(PyObject *args) Create and return a new ``datetime.datetime`` object given an argument tuple suitable for passing to ``datetime.datetime.fromtimestamp()``. -.. cfunction:: PyObject* PyDate_FromTimestamp(PyObject *args) +.. c:function:: PyObject* PyDate_FromTimestamp(PyObject *args) Create and return a new ``datetime.date`` object given an argument tuple suitable for passing to ``datetime.date.fromtimestamp()``. diff --git a/Doc/c-api/descriptor.rst b/Doc/c-api/descriptor.rst index 5db2570..c8f6fa5 100644 --- a/Doc/c-api/descriptor.rst +++ b/Doc/c-api/descriptor.rst @@ -10,31 +10,31 @@ found in the dictionary of type objects. .. XXX document these! -.. cvar:: PyTypeObject PyProperty_Type +.. c:var:: PyTypeObject PyProperty_Type The type object for the built-in descriptor types. -.. cfunction:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset) +.. c:function:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset) -.. cfunction:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth) +.. c:function:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth) -.. cfunction:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth) +.. c:function:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth) -.. cfunction:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped) +.. c:function:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped) -.. cfunction:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) +.. c:function:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) -.. cfunction:: int PyDescr_IsData(PyObject *descr) +.. c:function:: int PyDescr_IsData(PyObject *descr) Return true if the descriptor objects *descr* describes a data attribute, or false if it describes a method. *descr* must be a descriptor object; there is no error checking. -.. cfunction:: PyObject* PyWrapper_New(PyObject *, PyObject *) +.. c:function:: PyObject* PyWrapper_New(PyObject *, PyObject *) diff --git a/Doc/c-api/dict.rst b/Doc/c-api/dict.rst index 4b966fb..4ea71bc 100644 --- a/Doc/c-api/dict.rst +++ b/Doc/c-api/dict.rst @@ -8,132 +8,132 @@ Dictionary Objects .. index:: object: dictionary -.. ctype:: PyDictObject +.. c:type:: PyDictObject - This subtype of :ctype:`PyObject` represents a Python dictionary object. + This subtype of :c:type:`PyObject` represents a Python dictionary object. -.. cvar:: PyTypeObject PyDict_Type +.. c:var:: PyTypeObject PyDict_Type .. index:: single: DictType (in module types) single: DictionaryType (in module types) - This instance of :ctype:`PyTypeObject` represents the Python dictionary + This instance of :c:type:`PyTypeObject` represents the Python dictionary type. This is exposed to Python programs as ``dict`` and ``types.DictType``. -.. cfunction:: int PyDict_Check(PyObject *p) +.. c:function:: int PyDict_Check(PyObject *p) Return true if *p* is a dict object or an instance of a subtype of the dict type. -.. cfunction:: int PyDict_CheckExact(PyObject *p) +.. c:function:: int PyDict_CheckExact(PyObject *p) Return true if *p* is a dict object, but not an instance of a subtype of the dict type. -.. cfunction:: PyObject* PyDict_New() +.. c:function:: PyObject* PyDict_New() Return a new empty dictionary, or *NULL* on failure. -.. cfunction:: PyObject* PyDictProxy_New(PyObject *dict) +.. c:function:: PyObject* PyDictProxy_New(PyObject *dict) Return a proxy object for a mapping which enforces read-only behavior. This is normally used to create a proxy to prevent modification of the dictionary for non-dynamic class types. -.. cfunction:: void PyDict_Clear(PyObject *p) +.. c:function:: void PyDict_Clear(PyObject *p) Empty an existing dictionary of all key-value pairs. -.. cfunction:: int PyDict_Contains(PyObject *p, PyObject *key) +.. c:function:: int PyDict_Contains(PyObject *p, PyObject *key) Determine if dictionary *p* contains *key*. If an item in *p* is matches *key*, return ``1``, otherwise return ``0``. On error, return ``-1``. This is equivalent to the Python expression ``key in p``. -.. cfunction:: PyObject* PyDict_Copy(PyObject *p) +.. c:function:: PyObject* PyDict_Copy(PyObject *p) Return a new dictionary that contains the same key-value pairs as *p*. -.. cfunction:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val) +.. c:function:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val) Insert *value* into the dictionary *p* with a key of *key*. *key* must be :term:`hashable`; if it isn't, :exc:`TypeError` will be raised. Return ``0`` on success or ``-1`` on failure. -.. cfunction:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val) +.. c:function:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val) .. index:: single: PyUnicode_FromString() Insert *value* into the dictionary *p* using *key* as a key. *key* should - be a :ctype:`char\*`. The key object is created using + be a :c:type:`char\*`. The key object is created using ``PyUnicode_FromString(key)``. Return ``0`` on success or ``-1`` on failure. -.. cfunction:: int PyDict_DelItem(PyObject *p, PyObject *key) +.. c:function:: int PyDict_DelItem(PyObject *p, PyObject *key) Remove the entry in dictionary *p* with key *key*. *key* must be hashable; if it isn't, :exc:`TypeError` is raised. Return ``0`` on success or ``-1`` on failure. -.. cfunction:: int PyDict_DelItemString(PyObject *p, char *key) +.. c:function:: int PyDict_DelItemString(PyObject *p, char *key) Remove the entry in dictionary *p* which has a key specified by the string *key*. Return ``0`` on success or ``-1`` on failure. -.. cfunction:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key) +.. c:function:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key) Return the object from dictionary *p* which has a key *key*. Return *NULL* if the key *key* is not present, but *without* setting an exception. -.. cfunction:: PyObject* PyDict_GetItemWithError(PyObject *p, PyObject *key) +.. c:function:: PyObject* PyDict_GetItemWithError(PyObject *p, PyObject *key) - Variant of :cfunc:`PyDict_GetItem` that does not suppress + Variant of :c:func:`PyDict_GetItem` that does not suppress exceptions. Return *NULL* **with** an exception set if an exception occurred. Return *NULL* **without** an exception set if the key wasn't present. -.. cfunction:: PyObject* PyDict_GetItemString(PyObject *p, const char *key) +.. c:function:: PyObject* PyDict_GetItemString(PyObject *p, const char *key) - This is the same as :cfunc:`PyDict_GetItem`, but *key* is specified as a - :ctype:`char\*`, rather than a :ctype:`PyObject\*`. + This is the same as :c:func:`PyDict_GetItem`, but *key* is specified as a + :c:type:`char\*`, rather than a :c:type:`PyObject\*`. -.. cfunction:: PyObject* PyDict_Items(PyObject *p) +.. c:function:: PyObject* PyDict_Items(PyObject *p) - Return a :ctype:`PyListObject` containing all the items from the + Return a :c:type:`PyListObject` containing all the items from the dictionary, as in the dictionary method :meth:`dict.items`. -.. cfunction:: PyObject* PyDict_Keys(PyObject *p) +.. c:function:: PyObject* PyDict_Keys(PyObject *p) - Return a :ctype:`PyListObject` containing all the keys from the dictionary, + Return a :c:type:`PyListObject` containing all the keys from the dictionary, as in the dictionary method :meth:`dict.keys`. -.. cfunction:: PyObject* PyDict_Values(PyObject *p) +.. c:function:: PyObject* PyDict_Values(PyObject *p) - Return a :ctype:`PyListObject` containing all the values from the + Return a :c:type:`PyListObject` containing all the values from the dictionary *p*, as in the dictionary method :meth:`dict.values`. -.. cfunction:: Py_ssize_t PyDict_Size(PyObject *p) +.. c:function:: Py_ssize_t PyDict_Size(PyObject *p) .. index:: builtin: len @@ -141,14 +141,14 @@ Dictionary Objects ``len(p)`` on a dictionary. -.. cfunction:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) +.. c:function:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) Iterate over all key-value pairs in the dictionary *p*. The - :ctype:`Py_ssize_t` referred to by *ppos* must be initialized to ``0`` + :c:type:`Py_ssize_t` referred to by *ppos* must be initialized to ``0`` prior to the first call to this function to start the iteration; the function returns true for each pair in the dictionary, and false once all pairs have been reported. The parameters *pkey* and *pvalue* should either - point to :ctype:`PyObject\*` variables that will be filled in with each key + point to :c:type:`PyObject\*` variables that will be filled in with each key and value, respectively, or may be *NULL*. Any references returned through them are borrowed. *ppos* should not be altered during iteration. Its value represents offsets within the internal dictionary structure, and @@ -187,23 +187,23 @@ Dictionary Objects } -.. cfunction:: int PyDict_Merge(PyObject *a, PyObject *b, int override) +.. c:function:: int PyDict_Merge(PyObject *a, PyObject *b, int override) Iterate over mapping object *b* adding key-value pairs to dictionary *a*. - *b* may be a dictionary, or any object supporting :cfunc:`PyMapping_Keys` - and :cfunc:`PyObject_GetItem`. If *override* is true, existing pairs in *a* + *b* may be a dictionary, or any object supporting :c:func:`PyMapping_Keys` + and :c:func:`PyObject_GetItem`. If *override* is true, existing pairs in *a* will be replaced if a matching key is found in *b*, otherwise pairs will only be added if there is not a matching key in *a*. Return ``0`` on success or ``-1`` if an exception was raised. -.. cfunction:: int PyDict_Update(PyObject *a, PyObject *b) +.. c:function:: int PyDict_Update(PyObject *a, PyObject *b) This is the same as ``PyDict_Merge(a, b, 1)`` in C, or ``a.update(b)`` in Python. Return ``0`` on success or ``-1`` if an exception was raised. -.. cfunction:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override) +.. c:function:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override) Update or merge into dictionary *a*, from the key-value pairs in *seq2*. *seq2* must be an iterable object producing iterable objects of length 2, diff --git a/Doc/c-api/exceptions.rst b/Doc/c-api/exceptions.rst index 367ba3e..3fce3b2 100644 --- a/Doc/c-api/exceptions.rst +++ b/Doc/c-api/exceptions.rst @@ -9,12 +9,12 @@ Exception Handling 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 Unix :cdata:`errno` variable: +exception handling. It works somewhat like the Unix :c:data:`errno` variable: there is a global indicator (per thread) of the last error that occurred. Most functions don't clear this on success, but will set it to indicate the cause of the error on failure. Most 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 :cfunc:`PyArg_\*` functions return ``1`` for success and +integer (exception: the :c:func:`PyArg_\*` functions return ``1`` for success and ``0`` for failure). When a function must fail because some function it called failed, it generally @@ -35,7 +35,7 @@ in various ways. There is a separate error indicator for each thread. Either alphabetical or some kind of structure. -.. cfunction:: void PyErr_PrintEx(int set_sys_last_vars) +.. c:function:: void PyErr_PrintEx(int set_sys_last_vars) Print a standard traceback to ``sys.stderr`` and clear the error indicator. Call this function only when the error indicator is set. (Otherwise it will @@ -46,35 +46,35 @@ in various ways. There is a separate error indicator for each thread. type, value and traceback of the printed exception, respectively. -.. cfunction:: void PyErr_Print() +.. c:function:: void PyErr_Print() Alias for ``PyErr_PrintEx(1)``. -.. cfunction:: PyObject* PyErr_Occurred() +.. c:function:: PyObject* PyErr_Occurred() Test whether the error indicator is set. If set, return the exception *type* - (the first argument to the last call to one of the :cfunc:`PyErr_Set\*` - functions or to :cfunc:`PyErr_Restore`). If not set, return *NULL*. You do not - own a reference to the return value, so you do not need to :cfunc:`Py_DECREF` + (the first argument to the last call to one of the :c:func:`PyErr_Set\*` + functions or to :c:func:`PyErr_Restore`). If not set, return *NULL*. You do not + own a reference to the return value, so you do not need to :c:func:`Py_DECREF` it. .. note:: Do not compare the return value to a specific exception; use - :cfunc:`PyErr_ExceptionMatches` instead, shown below. (The comparison could + :c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could easily fail since the exception may be an instance instead of a class, in the case of a class exception, or it may the a subclass of the expected exception.) -.. cfunction:: int PyErr_ExceptionMatches(PyObject *exc) +.. c:function:: int PyErr_ExceptionMatches(PyObject *exc) Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This should only be called when an exception is actually set; a memory access violation will occur if no exception has been raised. -.. cfunction:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc) +.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc) Return true if the *given* exception matches the exception in *exc*. If *exc* is a class object, this also returns true when *given* is an instance @@ -82,22 +82,22 @@ in various ways. There is a separate error indicator for each thread. recursively in subtuples) are searched for a match. -.. cfunction:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb) +.. c:function:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb) - Under certain circumstances, the values returned by :cfunc:`PyErr_Fetch` below + Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is not an instance of the same class. This function can be used to instantiate the class in that case. If the values are already normalized, nothing happens. The delayed normalization is implemented to improve performance. -.. cfunction:: void PyErr_Clear() +.. c:function:: void PyErr_Clear() Clear the error indicator. If the error indicator is not set, there is no effect. -.. cfunction:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback) +.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback) Retrieve the error indicator into three variables whose addresses are passed. If the error indicator is not set, set all three variables to *NULL*. If it is @@ -110,7 +110,7 @@ in various ways. There is a separate error indicator for each thread. by code that needs to save and restore the error indicator temporarily. -.. cfunction:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) +.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) 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 @@ -125,29 +125,29 @@ in various ways. There is a separate error indicator for each thread. .. note:: This function is normally only used by code that needs to save and restore the - error indicator temporarily; use :cfunc:`PyErr_Fetch` to save the current + error indicator temporarily; use :c:func:`PyErr_Fetch` to save the current exception state. -.. cfunction:: void PyErr_SetString(PyObject *type, const char *message) +.. c:function:: void PyErr_SetString(PyObject *type, const char *message) 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. :cdata:`PyExc_RuntimeError`. You need not increment its reference count. + e.g. :c:data:`PyExc_RuntimeError`. You need not increment its reference count. The second argument is an error message; it is converted to a string object. -.. cfunction:: void PyErr_SetObject(PyObject *type, PyObject *value) +.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value) - This function is similar to :cfunc:`PyErr_SetString` but lets you specify an + This function is similar to :c:func:`PyErr_SetString` but lets you specify an arbitrary Python object for the "value" of the exception. -.. cfunction:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...) +.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...) This function sets the error indicator and returns *NULL*. *exception* should be a Python exception (class, not an instance). *format* should be an ASCII-encoded string, - containing format codes, similar to :cfunc:`printf`. The ``width.precision`` + containing format codes, similar to :c:func:`printf`. The ``width.precision`` before a format code is parsed, but the width part is ignored. .. % This should be exactly the same as the table in PyString_FromFormat. @@ -220,81 +220,81 @@ in various ways. There is a separate error indicator for each thread. Support for `"%lld"` and `"%llu"` added. -.. cfunction:: void PyErr_SetNone(PyObject *type) +.. c:function:: void PyErr_SetNone(PyObject *type) This is a shorthand for ``PyErr_SetObject(type, Py_None)``. -.. cfunction:: int PyErr_BadArgument() +.. c:function:: int PyErr_BadArgument() This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where *message* indicates that a built-in operation was invoked with an illegal argument. It is mostly for internal use. -.. cfunction:: PyObject* PyErr_NoMemory() +.. c:function:: PyObject* PyErr_NoMemory() This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns *NULL* so an object allocation function can write ``return PyErr_NoMemory();`` when it runs out of memory. -.. cfunction:: PyObject* PyErr_SetFromErrno(PyObject *type) +.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type) .. index:: single: strerror() This is a convenience function to raise an exception when a C library function - has returned an error and set the C variable :cdata:`errno`. It constructs a - tuple object whose first item is the integer :cdata:`errno` value and whose - second item is the corresponding error message (gotten from :cfunc:`strerror`), + has returned an error and set the C variable :c:data:`errno`. It constructs a + tuple object whose first item is the integer :c:data:`errno` value and whose + second item is the corresponding error message (gotten from :c:func:`strerror`), and then calls ``PyErr_SetObject(type, object)``. On Unix, when the - :cdata:`errno` value is :const:`EINTR`, indicating an interrupted system call, - this calls :cfunc:`PyErr_CheckSignals`, and if that set the error indicator, + :c:data:`errno` value is :const:`EINTR`, indicating an interrupted system call, + this calls :c:func:`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. -.. cfunction:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename) +.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename) - Similar to :cfunc:`PyErr_SetFromErrno`, with the additional behavior that if + Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if *filename* is not *NULL*, it is passed to the constructor of *type* as a third parameter. In the case of exceptions such as :exc:`IOError` and :exc:`OSError`, this is used to define the :attr:`filename` attribute of the exception instance. -.. cfunction:: PyObject* PyErr_SetFromWindowsErr(int ierr) +.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr) This is a convenience function to raise :exc:`WindowsError`. If called with - *ierr* of :cdata:`0`, the error code returned by a call to :cfunc:`GetLastError` - is used instead. It calls the Win32 function :cfunc:`FormatMessage` to retrieve - the Windows description of error code given by *ierr* or :cfunc:`GetLastError`, + *ierr* of :c:data:`0`, the error code returned by a call to :c:func:`GetLastError` + is used instead. It calls the Win32 function :c:func:`FormatMessage` to retrieve + the Windows description of error code given by *ierr* or :c:func:`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 - :cfunc:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError, + :c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError, object)``. This function always returns *NULL*. Availability: Windows. -.. cfunction:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr) +.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr) - Similar to :cfunc:`PyErr_SetFromWindowsErr`, with an additional parameter + Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter specifying the exception type to be raised. Availability: Windows. -.. cfunction:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename) +.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename) - Similar to :cfunc:`PyErr_SetFromWindowsErr`, with the additional behavior that + Similar to :c:func:`PyErr_SetFromWindowsErr`, with the additional behavior that if *filename* is not *NULL*, it is passed to the constructor of :exc:`WindowsError` as a third parameter. Availability: Windows. -.. cfunction:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, char *filename) +.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, char *filename) - Similar to :cfunc:`PyErr_SetFromWindowsErrWithFilename`, with an additional + Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional parameter specifying the exception type to be raised. Availability: Windows. -.. cfunction:: void PyErr_SyntaxLocationEx(char *filename, int lineno, int col_offset) +.. c:function:: void PyErr_SyntaxLocationEx(char *filename, int lineno, int col_offset) Set file, line, and offset information for the current exception. If the current exception is not a :exc:`SyntaxError`, then it sets additional @@ -304,13 +304,13 @@ in various ways. There is a separate error indicator for each thread. .. versionadded:: 3.2 -.. cfunction:: void PyErr_SyntaxLocation(char *filename, int lineno) +.. c:function:: void PyErr_SyntaxLocation(char *filename, int lineno) - Like :cfunc:`PyErr_SyntaxLocationExc`, but the col_offset parameter is + Like :c:func:`PyErr_SyntaxLocationExc`, but the col_offset parameter is omitted. -.. cfunction:: void PyErr_BadInternalCall() +.. c:function:: void PyErr_BadInternalCall() This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``, where *message* indicates that an internal operation (e.g. a Python/C API @@ -318,13 +318,13 @@ in various ways. There is a separate error indicator for each thread. use. -.. cfunction:: int PyErr_WarnEx(PyObject *category, char *message, int stack_level) +.. c:function:: int PyErr_WarnEx(PyObject *category, char *message, int stack_level) Issue a warning message. The *category* argument is a warning category (see below) or *NULL*; the *message* argument is a message string. *stack_level* is a positive number giving a number of stack frames; the warning will be issued from the currently executing line of code in that stack frame. A *stack_level* of 1 - is the function calling :cfunc:`PyErr_WarnEx`, 2 is the function above that, + is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that, and so forth. This function normally prints a warning message to *sys.stderr*; however, it is @@ -336,26 +336,26 @@ in various ways. There is a separate error indicator for each thread. is raised. (It is not possible to determine whether a warning message is actually printed, nor what the reason is for the exception; this is intentional.) If an exception is raised, the caller should do its normal - exception handling (for example, :cfunc:`Py_DECREF` owned references and return + exception handling (for example, :c:func:`Py_DECREF` owned references and return an error value). - Warning categories must be subclasses of :cdata:`Warning`; the default warning - category is :cdata:`RuntimeWarning`. The standard Python warning categories are + Warning categories must be subclasses of :c:data:`Warning`; the default warning + category is :c:data:`RuntimeWarning`. The standard Python warning categories are available as global variables whose names are ``PyExc_`` followed by the Python - exception name. These have the type :ctype:`PyObject\*`; they are all class - objects. Their names are :cdata:`PyExc_Warning`, :cdata:`PyExc_UserWarning`, - :cdata:`PyExc_UnicodeWarning`, :cdata:`PyExc_DeprecationWarning`, - :cdata:`PyExc_SyntaxWarning`, :cdata:`PyExc_RuntimeWarning`, and - :cdata:`PyExc_FutureWarning`. :cdata:`PyExc_Warning` is a subclass of - :cdata:`PyExc_Exception`; the other warning categories are subclasses of - :cdata:`PyExc_Warning`. + exception name. These have the type :c:type:`PyObject\*`; they are all class + objects. Their names are :c:data:`PyExc_Warning`, :c:data:`PyExc_UserWarning`, + :c:data:`PyExc_UnicodeWarning`, :c:data:`PyExc_DeprecationWarning`, + :c:data:`PyExc_SyntaxWarning`, :c:data:`PyExc_RuntimeWarning`, and + :c:data:`PyExc_FutureWarning`. :c:data:`PyExc_Warning` is a subclass of + :c:data:`PyExc_Exception`; the other warning categories are subclasses of + :c:data:`PyExc_Warning`. For information about warning control, see the documentation for the :mod:`warnings` module and the :option:`-W` option in the command line documentation. There is no C API for warning control. -.. cfunction:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry) +.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry) Issue a warning message with explicit control over all warning attributes. This is a straightforward wrapper around the Python function @@ -364,14 +364,14 @@ in various ways. There is a separate error indicator for each thread. described there. -.. cfunction:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...) +.. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...) - Function similar to :cfunc:`PyErr_WarnEx`, but use - :cfunc:`PyUnicode_FromFormatV` to format the warning message. + Function similar to :c:func:`PyErr_WarnEx`, but use + :c:func:`PyUnicode_FromFormatV` to format the warning message. .. versionadded:: 3.2 -.. cfunction:: int PyErr_CheckSignals() +.. c:function:: int PyErr_CheckSignals() .. index:: module: signal @@ -388,21 +388,21 @@ in various ways. There is a separate error indicator for each thread. cleared if it was previously set. -.. cfunction:: void PyErr_SetInterrupt() +.. c:function:: void PyErr_SetInterrupt() .. index:: single: SIGINT single: KeyboardInterrupt (built-in exception) This function simulates the effect of a :const:`SIGINT` signal arriving --- the - next time :cfunc:`PyErr_CheckSignals` is called, :exc:`KeyboardInterrupt` will + next time :c:func:`PyErr_CheckSignals` is called, :exc:`KeyboardInterrupt` will be raised. It may be called without holding the interpreter lock. .. % XXX This was described as obsolete, but is used in .. % _thread.interrupt_main() (used from IDLE), so it's still needed. -.. cfunction:: int PySignal_SetWakeupFd(int fd) +.. c:function:: int PySignal_SetWakeupFd(int fd) This utility function specifies a file descriptor to which a ``'\0'`` byte will be written whenever a signal is received. It returns the previous such file @@ -412,13 +412,13 @@ in various ways. There is a separate error indicator for each thread. only be called from the main thread. -.. cfunction:: PyObject* PyErr_NewException(char *name, PyObject *base, PyObject *dict) +.. c:function:: PyObject* PyErr_NewException(char *name, PyObject *base, PyObject *dict) This utility function creates and returns a new exception object. The *name* argument must be the name of the new exception, a C string of the form ``module.class``. The *base* and *dict* arguments are normally *NULL*. This creates a class object derived from :exc:`Exception` (accessible in C as - :cdata:`PyExc_Exception`). + :c:data:`PyExc_Exception`). The :attr:`__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 @@ -427,16 +427,16 @@ in various ways. There is a separate error indicator for each thread. argument can be used to specify a dictionary of class variables and methods. -.. cfunction:: PyObject* PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict) +.. c:function:: PyObject* PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict) - Same as :cfunc:`PyErr_NewException`, except that the new exception class can + Same as :c:func:`PyErr_NewException`, except that the new exception class can easily be given a docstring: If *doc* is non-*NULL*, it will be used as the docstring for the exception class. .. versionadded:: 3.2 -.. cfunction:: void PyErr_WriteUnraisable(PyObject *obj) +.. c:function:: void PyErr_WriteUnraisable(PyObject *obj) 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 @@ -451,20 +451,20 @@ in various ways. There is a separate error indicator for each thread. Exception Objects ================= -.. cfunction:: PyObject* PyException_GetTraceback(PyObject *ex) +.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex) Return the traceback associated with the exception as a new reference, as accessible from Python through :attr:`__traceback__`. If there is no traceback associated, this returns *NULL*. -.. cfunction:: int PyException_SetTraceback(PyObject *ex, PyObject *tb) +.. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb) Set the traceback associated with the exception to *tb*. Use ``Py_None`` to clear it. -.. cfunction:: PyObject* PyException_GetContext(PyObject *ex) +.. c:function:: PyObject* PyException_GetContext(PyObject *ex) Return the context (another exception instance during whose handling *ex* was raised) associated with the exception as a new reference, as accessible from @@ -472,14 +472,14 @@ Exception Objects returns *NULL*. -.. cfunction:: void PyException_SetContext(PyObject *ex, PyObject *ctx) +.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx) Set the context associated with the exception to *ctx*. Use *NULL* to clear it. There is no type check to make sure that *ctx* is an exception instance. This steals a reference to *ctx*. -.. cfunction:: PyObject* PyException_GetCause(PyObject *ex) +.. c:function:: PyObject* PyException_GetCause(PyObject *ex) Return the cause (another exception instance set by ``raise ... from ...``) associated with the exception as a new reference, as accessible from Python @@ -487,7 +487,7 @@ Exception Objects *NULL*. -.. cfunction:: void PyException_SetCause(PyObject *ex, PyObject *ctx) +.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *ctx) Set the cause associated with the exception to *ctx*. Use *NULL* to clear it. There is no type check to make sure that *ctx* is an exception instance. @@ -502,12 +502,12 @@ 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). -.. cfunction:: int Py_EnterRecursiveCall(char *where) +.. c:function:: int Py_EnterRecursiveCall(char *where) Marks a point where a recursive C-level call is about to be performed. If :const:`USE_STACKCHECK` is defined, this function checks if the the OS - stack overflowed using :cfunc:`PyOS_CheckStack`. In this is the case, it + stack overflowed using :c:func:`PyOS_CheckStack`. In this is the case, it sets a :exc:`MemoryError` and returns a nonzero value. The function then checks if the recursion limit is reached. If this is the @@ -518,10 +518,10 @@ recursion depth automatically). concatenated to the :exc:`RuntimeError` message caused by the recursion depth limit. -.. cfunction:: void Py_LeaveRecursiveCall() +.. c:function:: void Py_LeaveRecursiveCall() - Ends a :cfunc:`Py_EnterRecursiveCall`. Must be called once for each - *successful* invocation of :cfunc:`Py_EnterRecursiveCall`. + Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each + *successful* invocation of :c:func:`Py_EnterRecursiveCall`. .. _standardexceptions: @@ -531,68 +531,68 @@ Standard Exceptions All standard Python exceptions are available as global variables whose names are ``PyExc_`` followed by the Python exception name. These have the type -:ctype:`PyObject\*`; they are all class objects. For completeness, here are all +:c:type:`PyObject\*`; they are all class objects. For completeness, here are all the variables: -+------------------------------------+----------------------------+----------+ -| C Name | Python Name | Notes | -+====================================+============================+==========+ -| :cdata:`PyExc_BaseException` | :exc:`BaseException` | \(1) | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_Exception` | :exc:`Exception` | \(1) | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | \(1) | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_LookupError` | :exc:`LookupError` | \(1) | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_AssertionError` | :exc:`AssertionError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_AttributeError` | :exc:`AttributeError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_EOFError` | :exc:`EOFError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_EnvironmentError` | :exc:`EnvironmentError` | \(1) | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_IOError` | :exc:`IOError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_ImportError` | :exc:`ImportError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_IndexError` | :exc:`IndexError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_KeyError` | :exc:`KeyError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_MemoryError` | :exc:`MemoryError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_NameError` | :exc:`NameError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_OSError` | :exc:`OSError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_OverflowError` | :exc:`OverflowError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_ReferenceError` | :exc:`ReferenceError` | \(2) | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_RuntimeError` | :exc:`RuntimeError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_SyntaxError` | :exc:`SyntaxError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_SystemError` | :exc:`SystemError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_SystemExit` | :exc:`SystemExit` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_TypeError` | :exc:`TypeError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_ValueError` | :exc:`ValueError` | | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_WindowsError` | :exc:`WindowsError` | \(3) | -+------------------------------------+----------------------------+----------+ -| :cdata:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | | -+------------------------------------+----------------------------+----------+ ++-------------------------------------+----------------------------+----------+ +| C Name | Python Name | Notes | ++=====================================+============================+==========+ +| :c:data:`PyExc_BaseException` | :exc:`BaseException` | \(1) | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_Exception` | :exc:`Exception` | \(1) | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | \(1) | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_LookupError` | :exc:`LookupError` | \(1) | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_AssertionError` | :exc:`AssertionError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_AttributeError` | :exc:`AttributeError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_EOFError` | :exc:`EOFError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_EnvironmentError` | :exc:`EnvironmentError` | \(1) | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_IOError` | :exc:`IOError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_ImportError` | :exc:`ImportError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_IndexError` | :exc:`IndexError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_KeyError` | :exc:`KeyError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_MemoryError` | :exc:`MemoryError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_NameError` | :exc:`NameError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_OSError` | :exc:`OSError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_OverflowError` | :exc:`OverflowError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_ReferenceError` | :exc:`ReferenceError` | \(2) | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_RuntimeError` | :exc:`RuntimeError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_SyntaxError` | :exc:`SyntaxError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_SystemError` | :exc:`SystemError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_SystemExit` | :exc:`SystemExit` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_TypeError` | :exc:`TypeError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_ValueError` | :exc:`ValueError` | | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_WindowsError` | :exc:`WindowsError` | \(3) | ++-------------------------------------+----------------------------+----------+ +| :c:data:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | | ++-------------------------------------+----------------------------+----------+ .. index:: single: PyExc_BaseException diff --git a/Doc/c-api/file.rst b/Doc/c-api/file.rst index 0cbe070..c5a4a59 100644 --- a/Doc/c-api/file.rst +++ b/Doc/c-api/file.rst @@ -8,7 +8,7 @@ File Objects .. index:: object: file These APIs are a minimal emulation of the Python 2 C API for built-in file -objects, which used to rely on the buffered I/O (:ctype:`FILE\*`) support +objects, which used to rely on the buffered I/O (:c:type:`FILE\*`) support from the C standard library. In Python 3, files and streams use the new :mod:`io` module, which defines several layers over the low-level unbuffered I/O of the operating system. The functions described below are @@ -17,7 +17,7 @@ error reporting in the interpreter; third-party code is advised to access the :mod:`io` APIs instead. -.. cfunction:: PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *errors, char *newline, int closefd) +.. c:function:: PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *errors, char *newline, int closefd) Create a Python file object from the file descriptor of an already opened file *fd*. The arguments *name*, *encoding*, *errors* and *newline* @@ -36,16 +36,16 @@ the :mod:`io` APIs instead. Ignore *name* attribute. -.. cfunction:: int PyObject_AsFileDescriptor(PyObject *p) +.. c:function:: int PyObject_AsFileDescriptor(PyObject *p) - Return the file descriptor associated with *p* as an :ctype:`int`. If the + Return the file descriptor associated with *p* as an :c:type:`int`. If the object is an integer, its value is returned. If not, the object's :meth:`fileno` method is called if it exists; the method must return an integer, which is returned as the file descriptor value. Sets an exception and returns ``-1`` on failure. -.. cfunction:: PyObject* PyFile_GetLine(PyObject *p, int n) +.. c:function:: PyObject* PyFile_GetLine(PyObject *p, int n) .. index:: single: EOFError (built-in exception) @@ -59,7 +59,7 @@ the :mod:`io` APIs instead. raised if the end of the file is reached immediately. -.. cfunction:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags) +.. c:function:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags) .. index:: single: Py_PRINT_RAW @@ -69,7 +69,7 @@ the :mod:`io` APIs instead. appropriate exception will be set. -.. cfunction:: int PyFile_WriteString(const char *s, PyObject *p) +.. c:function:: int PyFile_WriteString(const char *s, PyObject *p) Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on failure; the appropriate exception will be set. diff --git a/Doc/c-api/float.rst b/Doc/c-api/float.rst index e2e4b73..5fb8a1c 100644 --- a/Doc/c-api/float.rst +++ b/Doc/c-api/float.rst @@ -8,72 +8,72 @@ Floating Point Objects .. index:: object: floating point -.. ctype:: PyFloatObject +.. c:type:: PyFloatObject - This subtype of :ctype:`PyObject` represents a Python floating point object. + This subtype of :c:type:`PyObject` represents a Python floating point object. -.. cvar:: PyTypeObject PyFloat_Type +.. c:var:: PyTypeObject PyFloat_Type .. index:: single: FloatType (in modules types) - This instance of :ctype:`PyTypeObject` represents the Python floating point + This instance of :c:type:`PyTypeObject` represents the Python floating point type. This is the same object as ``float`` and ``types.FloatType``. -.. cfunction:: int PyFloat_Check(PyObject *p) +.. c:function:: int PyFloat_Check(PyObject *p) - Return true if its argument is a :ctype:`PyFloatObject` or a subtype of - :ctype:`PyFloatObject`. + Return true if its argument is a :c:type:`PyFloatObject` or a subtype of + :c:type:`PyFloatObject`. -.. cfunction:: int PyFloat_CheckExact(PyObject *p) +.. c:function:: int PyFloat_CheckExact(PyObject *p) - Return true if its argument is a :ctype:`PyFloatObject`, but not a subtype of - :ctype:`PyFloatObject`. + Return true if its argument is a :c:type:`PyFloatObject`, but not a subtype of + :c:type:`PyFloatObject`. -.. cfunction:: PyObject* PyFloat_FromString(PyObject *str) +.. c:function:: PyObject* PyFloat_FromString(PyObject *str) - Create a :ctype:`PyFloatObject` object based on the string value in *str*, or + Create a :c:type:`PyFloatObject` object based on the string value in *str*, or *NULL* on failure. -.. cfunction:: PyObject* PyFloat_FromDouble(double v) +.. c:function:: PyObject* PyFloat_FromDouble(double v) - Create a :ctype:`PyFloatObject` object from *v*, or *NULL* on failure. + Create a :c:type:`PyFloatObject` object from *v*, or *NULL* on failure. -.. cfunction:: double PyFloat_AsDouble(PyObject *pyfloat) +.. c:function:: double PyFloat_AsDouble(PyObject *pyfloat) - Return a C :ctype:`double` representation of the contents of *pyfloat*. If + Return a C :c:type:`double` representation of the contents of *pyfloat*. If *pyfloat* is not a Python floating point object but has a :meth:`__float__` method, this method will first be called to convert *pyfloat* into a float. -.. cfunction:: double PyFloat_AS_DOUBLE(PyObject *pyfloat) +.. c:function:: double PyFloat_AS_DOUBLE(PyObject *pyfloat) - Return a C :ctype:`double` representation of the contents of *pyfloat*, but + Return a C :c:type:`double` representation of the contents of *pyfloat*, but without error checking. -.. cfunction:: PyObject* PyFloat_GetInfo(void) +.. c:function:: PyObject* PyFloat_GetInfo(void) Return a structseq instance which contains information about the precision, minimum and maximum values of a float. It's a thin wrapper around the header file :file:`float.h`. -.. cfunction:: double PyFloat_GetMax() +.. c:function:: double PyFloat_GetMax() - Return the maximum representable finite float *DBL_MAX* as C :ctype:`double`. + Return the maximum representable finite float *DBL_MAX* as C :c:type:`double`. -.. cfunction:: double PyFloat_GetMin() +.. c:function:: double PyFloat_GetMin() - Return the minimum normalized positive float *DBL_MIN* as C :ctype:`double`. + Return the minimum normalized positive float *DBL_MIN* as C :c:type:`double`. -.. cfunction:: int PyFloat_ClearFreeList() +.. c:function:: int PyFloat_ClearFreeList() Clear the float free list. Return the number of items that could not be freed. diff --git a/Doc/c-api/function.rst b/Doc/c-api/function.rst index 3512fe2..31805fd 100644 --- a/Doc/c-api/function.rst +++ b/Doc/c-api/function.rst @@ -10,26 +10,26 @@ Function Objects There are a few functions specific to Python functions. -.. ctype:: PyFunctionObject +.. c:type:: PyFunctionObject The C structure used for functions. -.. cvar:: PyTypeObject PyFunction_Type +.. c:var:: PyTypeObject PyFunction_Type .. index:: single: MethodType (in module types) - This is an instance of :ctype:`PyTypeObject` and represents the Python function + This is an instance of :c:type:`PyTypeObject` and represents the Python function type. It is exposed to Python programmers as ``types.FunctionType``. -.. cfunction:: int PyFunction_Check(PyObject *o) +.. c:function:: int PyFunction_Check(PyObject *o) - Return true if *o* is a function object (has type :cdata:`PyFunction_Type`). + Return true if *o* is a function object (has type :c:data:`PyFunction_Type`). The parameter must not be *NULL*. -.. cfunction:: PyObject* PyFunction_New(PyObject *code, PyObject *globals) +.. c:function:: PyObject* PyFunction_New(PyObject *code, PyObject *globals) Return a new function object associated with the code object *code*. *globals* must be a dictionary with the global variables accessible to the function. @@ -38,30 +38,30 @@ There are a few functions specific to Python functions. object, the argument defaults and closure are set to *NULL*. -.. cfunction:: PyObject* PyFunction_GetCode(PyObject *op) +.. c:function:: PyObject* PyFunction_GetCode(PyObject *op) Return the code object associated with the function object *op*. -.. cfunction:: PyObject* PyFunction_GetGlobals(PyObject *op) +.. c:function:: PyObject* PyFunction_GetGlobals(PyObject *op) Return the globals dictionary associated with the function object *op*. -.. cfunction:: PyObject* PyFunction_GetModule(PyObject *op) +.. c:function:: PyObject* PyFunction_GetModule(PyObject *op) Return the *__module__* attribute of the function object *op*. This is normally a string containing the module name, but can be set to any other object by Python code. -.. cfunction:: PyObject* PyFunction_GetDefaults(PyObject *op) +.. c:function:: PyObject* PyFunction_GetDefaults(PyObject *op) Return the argument default values of the function object *op*. This can be a tuple of arguments or *NULL*. -.. cfunction:: int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) +.. c:function:: int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) Set the argument default values for the function object *op*. *defaults* must be *Py_None* or a tuple. @@ -69,13 +69,13 @@ There are a few functions specific to Python functions. Raises :exc:`SystemError` and returns ``-1`` on failure. -.. cfunction:: PyObject* PyFunction_GetClosure(PyObject *op) +.. c:function:: PyObject* PyFunction_GetClosure(PyObject *op) Return the closure associated with the function object *op*. This can be *NULL* or a tuple of cell objects. -.. cfunction:: int PyFunction_SetClosure(PyObject *op, PyObject *closure) +.. c:function:: int PyFunction_SetClosure(PyObject *op, PyObject *closure) Set the closure associated with the function object *op*. *closure* must be *Py_None* or a tuple of cell objects. @@ -83,13 +83,13 @@ There are a few functions specific to Python functions. Raises :exc:`SystemError` and returns ``-1`` on failure. -.. cfunction:: PyObject *PyFunction_GetAnnotations(PyObject *op) +.. c:function:: PyObject *PyFunction_GetAnnotations(PyObject *op) Return the annotations of the function object *op*. This can be a mutable dictionary or *NULL*. -.. cfunction:: int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) +.. c:function:: int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) Set the annotations for the function object *op*. *annotations* must be a dictionary or *Py_None*. diff --git a/Doc/c-api/gcsupport.rst b/Doc/c-api/gcsupport.rst index 1a280c8..3875ff2 100644 --- a/Doc/c-api/gcsupport.rst +++ b/Doc/c-api/gcsupport.rst @@ -27,32 +27,32 @@ include the :const:`Py_TPFLAGS_HAVE_GC` and provide an implementation of the Constructors for container types must conform to two rules: -#. The memory for the object must be allocated using :cfunc:`PyObject_GC_New` - or :cfunc:`PyObject_GC_NewVar`. +#. The memory for the object must be allocated using :c:func:`PyObject_GC_New` + or :c:func:`PyObject_GC_NewVar`. #. Once all the fields which may contain references to other containers are - initialized, it must call :cfunc:`PyObject_GC_Track`. + initialized, it must call :c:func:`PyObject_GC_Track`. -.. cfunction:: TYPE* PyObject_GC_New(TYPE, PyTypeObject *type) +.. c:function:: TYPE* PyObject_GC_New(TYPE, PyTypeObject *type) - Analogous to :cfunc:`PyObject_New` but for container objects with the + Analogous to :c:func:`PyObject_New` but for container objects with the :const:`Py_TPFLAGS_HAVE_GC` flag set. -.. cfunction:: TYPE* PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) +.. c:function:: TYPE* PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) - Analogous to :cfunc:`PyObject_NewVar` but for container objects with the + Analogous to :c:func:`PyObject_NewVar` but for container objects with the :const:`Py_TPFLAGS_HAVE_GC` flag set. -.. cfunction:: TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize) +.. c:function:: TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize) - Resize an object allocated by :cfunc:`PyObject_NewVar`. Returns the + Resize an object allocated by :c:func:`PyObject_NewVar`. Returns the resized object or *NULL* on failure. -.. cfunction:: void PyObject_GC_Track(PyObject *op) +.. c:function:: void PyObject_GC_Track(PyObject *op) Adds the object *op* to the set of container objects tracked by the collector. The collector can run at unexpected times so objects must be @@ -61,44 +61,44 @@ Constructors for container types must conform to two rules: end of the constructor. -.. cfunction:: void _PyObject_GC_TRACK(PyObject *op) +.. c:function:: void _PyObject_GC_TRACK(PyObject *op) - A macro version of :cfunc:`PyObject_GC_Track`. It should not be used for + A macro version of :c:func:`PyObject_GC_Track`. It should not be used for extension modules. Similarly, the deallocator for the object must conform to a similar pair of rules: #. Before fields which refer to other containers are invalidated, - :cfunc:`PyObject_GC_UnTrack` must be called. + :c:func:`PyObject_GC_UnTrack` must be called. -#. The object's memory must be deallocated using :cfunc:`PyObject_GC_Del`. +#. The object's memory must be deallocated using :c:func:`PyObject_GC_Del`. -.. cfunction:: void PyObject_GC_Del(void *op) +.. c:function:: void PyObject_GC_Del(void *op) - Releases memory allocated to an object using :cfunc:`PyObject_GC_New` or - :cfunc:`PyObject_GC_NewVar`. + Releases memory allocated to an object using :c:func:`PyObject_GC_New` or + :c:func:`PyObject_GC_NewVar`. -.. cfunction:: void PyObject_GC_UnTrack(void *op) +.. c:function:: void PyObject_GC_UnTrack(void *op) Remove the object *op* from the set of container objects tracked by the - collector. Note that :cfunc:`PyObject_GC_Track` can be called again on + collector. Note that :c:func:`PyObject_GC_Track` can be called again on this object to add it back to the set of tracked objects. The deallocator (:attr:`tp_dealloc` handler) should call this for the object before any of the fields used by the :attr:`tp_traverse` handler become invalid. -.. cfunction:: void _PyObject_GC_UNTRACK(PyObject *op) +.. c:function:: void _PyObject_GC_UNTRACK(PyObject *op) - A macro version of :cfunc:`PyObject_GC_UnTrack`. It should not be used for + A macro version of :c:func:`PyObject_GC_UnTrack`. It should not be used for extension modules. The :attr:`tp_traverse` handler accepts a function parameter of this type: -.. ctype:: int (*visitproc)(PyObject *object, void *arg) +.. c:type:: int (*visitproc)(PyObject *object, void *arg) Type of the visitor function passed to the :attr:`tp_traverse` handler. The function should be called with an object to traverse as *object* and @@ -110,7 +110,7 @@ The :attr:`tp_traverse` handler accepts a function parameter of this type: The :attr:`tp_traverse` handler must have the following type: -.. ctype:: int (*traverseproc)(PyObject *self, visitproc visit, void *arg) +.. c:type:: int (*traverseproc)(PyObject *self, visitproc visit, void *arg) Traversal function for a container object. Implementations must call the *visit* function for each object directly contained by *self*, with the @@ -119,12 +119,12 @@ The :attr:`tp_traverse` handler must have the following type: object argument. If *visit* returns a non-zero value that value should be returned immediately. -To simplify writing :attr:`tp_traverse` handlers, a :cfunc:`Py_VISIT` macro is +To simplify writing :attr:`tp_traverse` handlers, a :c:func:`Py_VISIT` macro is provided. In order to use this macro, the :attr:`tp_traverse` implementation must name its arguments exactly *visit* and *arg*: -.. cfunction:: void Py_VISIT(PyObject *o) +.. c:function:: void Py_VISIT(PyObject *o) Call the *visit* callback, with arguments *o* and *arg*. If *visit* returns a non-zero value, then return it. Using this macro, :attr:`tp_traverse` @@ -138,15 +138,15 @@ must name its arguments exactly *visit* and *arg*: return 0; } -The :attr:`tp_clear` handler must be of the :ctype:`inquiry` type, or *NULL* +The :attr:`tp_clear` handler must be of the :c:type:`inquiry` type, or *NULL* if the object is immutable. -.. ctype:: int (*inquiry)(PyObject *self) +.. c:type:: int (*inquiry)(PyObject *self) Drop references that may have created reference cycles. Immutable objects do not have to define this method since they can never directly create reference cycles. Note that the object must still be valid after calling - this method (don't just call :cfunc:`Py_DECREF` on a reference). The + this method (don't just call :c:func:`Py_DECREF` on a reference). The collector will call this method if it detects that this object is involved in a reference cycle. diff --git a/Doc/c-api/gen.rst b/Doc/c-api/gen.rst index 0d3789a..33cd27a 100644 --- a/Doc/c-api/gen.rst +++ b/Doc/c-api/gen.rst @@ -7,31 +7,31 @@ Generator Objects Generator objects are what Python uses to implement generator iterators. They are normally created by iterating over a function that yields values, rather -than explicitly calling :cfunc:`PyGen_New`. +than explicitly calling :c:func:`PyGen_New`. -.. ctype:: PyGenObject +.. c:type:: PyGenObject The C structure used for generator objects. -.. cvar:: PyTypeObject PyGen_Type +.. c:var:: PyTypeObject PyGen_Type The type object corresponding to generator objects -.. cfunction:: int PyGen_Check(ob) +.. c:function:: int PyGen_Check(ob) Return true if *ob* is a generator object; *ob* must not be *NULL*. -.. cfunction:: int PyGen_CheckExact(ob) +.. c:function:: int PyGen_CheckExact(ob) Return true if *ob*'s type is *PyGen_Type* is a generator object; *ob* must not be *NULL*. -.. cfunction:: PyObject* PyGen_New(PyFrameObject *frame) +.. c:function:: PyObject* PyGen_New(PyFrameObject *frame) Create and return a new generator object based on the *frame* object. A reference to *frame* is stolen by this function. The parameter must not be diff --git a/Doc/c-api/import.rst b/Doc/c-api/import.rst index ffbabbc..15a11fd 100644 --- a/Doc/c-api/import.rst +++ b/Doc/c-api/import.rst @@ -6,14 +6,14 @@ Importing Modules ================= -.. cfunction:: PyObject* PyImport_ImportModule(const char *name) +.. c:function:: PyObject* PyImport_ImportModule(const char *name) .. index:: single: package variable; __all__ single: __all__ (package variable) single: modules (in module sys) - This is a simplified interface to :cfunc:`PyImport_ImportModuleEx` below, + This is a simplified interface to :c:func:`PyImport_ImportModuleEx` below, leaving the *globals* and *locals* arguments set to *NULL* and *level* set to 0. When the *name* argument contains a dot (when it specifies a submodule of a package), the @@ -28,18 +28,18 @@ Importing Modules This function always uses absolute imports. -.. cfunction:: PyObject* PyImport_ImportModuleNoBlock(const char *name) +.. c:function:: PyObject* PyImport_ImportModuleNoBlock(const char *name) - This version of :cfunc:`PyImport_ImportModule` does not block. It's intended + This version of :c:func:`PyImport_ImportModule` does not block. It's intended to be used in C functions that import other modules to execute a function. The import may block if another thread holds the import lock. The function - :cfunc:`PyImport_ImportModuleNoBlock` never blocks. It first tries to fetch - the module from sys.modules and falls back to :cfunc:`PyImport_ImportModule` + :c:func:`PyImport_ImportModuleNoBlock` never blocks. It first tries to fetch + the module from sys.modules and falls back to :c:func:`PyImport_ImportModule` unless the lock is held, in which case the function will raise an :exc:`ImportError`. -.. cfunction:: PyObject* PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist) +.. c:function:: PyObject* PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist) .. index:: builtin: __import__ @@ -54,10 +54,10 @@ Importing Modules was given. Failing imports remove incomplete module objects, like with - :cfunc:`PyImport_ImportModule`. + :c:func:`PyImport_ImportModule`. -.. cfunction:: PyObject* PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) +.. c:function:: PyObject* PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) Import a module. This is best described by referring to the built-in Python function :func:`__import__`, as the standard :func:`__import__` function calls @@ -69,7 +69,7 @@ Importing Modules top-level package, unless a non-empty *fromlist* was given. -.. cfunction:: PyObject* PyImport_Import(PyObject *name) +.. c:function:: PyObject* PyImport_Import(PyObject *name) This is a higher-level interface that calls the current "import hook function" (with an explicit *level* of 0, meaning absolute import). It @@ -80,13 +80,13 @@ Importing Modules This function always uses absolute imports. -.. cfunction:: PyObject* PyImport_ReloadModule(PyObject *m) +.. c:function:: PyObject* PyImport_ReloadModule(PyObject *m) Reload a module. Return a new reference to the reloaded module, or *NULL* with an exception set on failure (the module still exists in this case). -.. cfunction:: PyObject* PyImport_AddModule(const char *name) +.. c:function:: PyObject* PyImport_AddModule(const char *name) Return the module object corresponding to a module name. The *name* argument may be of the form ``package.module``. First check the modules dictionary if @@ -96,12 +96,12 @@ Importing Modules .. note:: This function does not load or import the module; if the module wasn't already - loaded, you will get an empty module object. Use :cfunc:`PyImport_ImportModule` + loaded, you will get an empty module object. Use :c:func:`PyImport_ImportModule` or one of its variants to import a module. Package structures implied by a dotted name for *name* are not created if not already present. -.. cfunction:: PyObject* PyImport_ExecCodeModule(char *name, PyObject *co) +.. c:function:: PyObject* PyImport_ExecCodeModule(char *name, PyObject *co) .. index:: builtin: compile @@ -110,58 +110,58 @@ Importing Modules :func:`compile`, load the module. Return a new reference to the module object, or *NULL* with an exception set if an error occurred. *name* is removed from :attr:`sys.modules` in error cases, even if *name* was already - in :attr:`sys.modules` on entry to :cfunc:`PyImport_ExecCodeModule`. Leaving + in :attr:`sys.modules` on entry to :c:func:`PyImport_ExecCodeModule`. Leaving incompletely initialized modules in :attr:`sys.modules` is dangerous, as imports of such modules have no way to know that the module object is an unknown (and probably damaged with respect to the module author's intents) state. The module's :attr:`__file__` attribute will be set to the code object's - :cmember:`co_filename`. + :c:member:`co_filename`. This function will reload the module if it was already imported. See - :cfunc:`PyImport_ReloadModule` for the intended way to reload a module. + :c:func:`PyImport_ReloadModule` for the intended way to reload a module. If *name* points to a dotted name of the form ``package.module``, any package structures not already created will still not be created. - See also :cfunc:`PyImport_ExecCodeModuleEx` and - :cfunc:`PyImport_ExecCodeModuleWithPathnames`. + See also :c:func:`PyImport_ExecCodeModuleEx` and + :c:func:`PyImport_ExecCodeModuleWithPathnames`. -.. cfunction:: PyObject* PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) +.. c:function:: PyObject* PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) - Like :cfunc:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute of + Like :c:func:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute of the module object is set to *pathname* if it is non-``NULL``. - See also :cfunc:`PyImport_ExecCodeModuleWithPathnames`. + See also :c:func:`PyImport_ExecCodeModuleWithPathnames`. -.. cfunction:: PyObject* PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname, char *cpathname) +.. c:function:: PyObject* PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname, char *cpathname) - Like :cfunc:`PyImport_ExecCodeModuleEx`, but the :attr:`__cached__` + Like :c:func:`PyImport_ExecCodeModuleEx`, but the :attr:`__cached__` attribute of the module object is set to *cpathname* if it is non-``NULL``. Of the three functions, this is the preferred one to use. -.. cfunction:: long PyImport_GetMagicNumber() +.. c:function:: long PyImport_GetMagicNumber() Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` and :file:`.pyo` files). The magic number should be present in the first four bytes of the bytecode file, in little-endian byte order. -.. cfunction:: const char * PyImport_GetMagicTag() +.. c:function:: const char * PyImport_GetMagicTag() Return the magic tag string for :pep:`3147` format Python bytecode file names. -.. cfunction:: PyObject* PyImport_GetModuleDict() +.. c:function:: PyObject* PyImport_GetModuleDict() Return the dictionary used for the module administration (a.k.a. ``sys.modules``). Note that this is a per-interpreter variable. -.. cfunction:: PyObject* PyImport_GetImporter(PyObject *path) +.. c:function:: PyObject* PyImport_GetImporter(PyObject *path) Return an importer object for a :data:`sys.path`/:attr:`pkg.__path__` item *path*, possibly by fetching it from the :data:`sys.path_importer_cache` @@ -172,41 +172,41 @@ Importing Modules to the importer object. -.. cfunction:: void _PyImport_Init() +.. c:function:: void _PyImport_Init() Initialize the import mechanism. For internal use only. -.. cfunction:: void PyImport_Cleanup() +.. c:function:: void PyImport_Cleanup() Empty the module table. For internal use only. -.. cfunction:: void _PyImport_Fini() +.. c:function:: void _PyImport_Fini() Finalize the import mechanism. For internal use only. -.. cfunction:: PyObject* _PyImport_FindExtension(char *, char *) +.. c:function:: PyObject* _PyImport_FindExtension(char *, char *) For internal use only. -.. cfunction:: PyObject* _PyImport_FixupExtension(char *, char *) +.. c:function:: PyObject* _PyImport_FixupExtension(char *, char *) For internal use only. -.. cfunction:: int PyImport_ImportFrozenModule(char *name) +.. c:function:: int PyImport_ImportFrozenModule(char *name) Load a frozen module named *name*. Return ``1`` for success, ``0`` if the module is not found, and ``-1`` with an exception set if the initialization failed. To access the imported module on a successful load, use - :cfunc:`PyImport_ImportModule`. (Note the misnomer --- this function would + :c:func:`PyImport_ImportModule`. (Note the misnomer --- this function would reload the module if it was already imported.) -.. ctype:: struct _frozen +.. c:type:: struct _frozen .. index:: single: freeze utility @@ -222,30 +222,30 @@ Importing Modules }; -.. cvar:: struct _frozen* PyImport_FrozenModules +.. c:var:: struct _frozen* PyImport_FrozenModules - This pointer is initialized to point to an array of :ctype:`struct _frozen` + This pointer is initialized to point to an array of :c:type:`struct _frozen` records, terminated by one whose members are all *NULL* or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules. -.. cfunction:: int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void)) +.. c:function:: int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void)) Add a single module to the existing table of built-in modules. This is a - convenience wrapper around :cfunc:`PyImport_ExtendInittab`, returning ``-1`` if + convenience wrapper around :c:func:`PyImport_ExtendInittab`, returning ``-1`` if the table could not be extended. The new module can be imported by the name *name*, and uses the function *initfunc* as the initialization function called on the first attempted import. This should be called before - :cfunc:`Py_Initialize`. + :c:func:`Py_Initialize`. -.. ctype:: struct _inittab +.. c:type:: struct _inittab Structure describing a single entry in the list of built-in modules. Each of these structures gives the name and initialization function for a module built into the interpreter. Programs which embed Python may use an array of these - structures in conjunction with :cfunc:`PyImport_ExtendInittab` to provide + structures in conjunction with :c:func:`PyImport_ExtendInittab` to provide additional built-in modules. The structure is defined in :file:`Include/import.h` as:: @@ -255,11 +255,11 @@ Importing Modules }; -.. cfunction:: int PyImport_ExtendInittab(struct _inittab *newtab) +.. c:function:: int PyImport_ExtendInittab(struct _inittab *newtab) Add a collection of modules to the table of built-in modules. The *newtab* array must end with a sentinel entry which contains *NULL* for the :attr:`name` field; failure to provide the sentinel value can result in a memory fault. Returns ``0`` on success or ``-1`` if insufficient memory could be allocated to extend the internal table. In the event of failure, no modules are added to the - internal table. This should be called before :cfunc:`Py_Initialize`. + internal table. This should be called before :c:func:`Py_Initialize`. diff --git a/Doc/c-api/init.rst b/Doc/c-api/init.rst index 52797f7..87211dc 100644 --- a/Doc/c-api/init.rst +++ b/Doc/c-api/init.rst @@ -8,7 +8,7 @@ Initialization, Finalization, and Threads ***************************************** -.. cfunction:: void Py_Initialize() +.. c:function:: void Py_Initialize() .. index:: single: Py_SetProgramName() @@ -27,39 +27,39 @@ Initialization, Finalization, and Threads Initialize the Python interpreter. In an application embedding Python, this should be called before using any other Python/C API functions; with the - exception of :cfunc:`Py_SetProgramName`, :cfunc:`Py_SetPath`, - :cfunc:`PyEval_InitThreads`, :cfunc:`PyEval_ReleaseLock`, and - :cfunc:`PyEval_AcquireLock`. This initializes + exception of :c:func:`Py_SetProgramName`, :c:func:`Py_SetPath`, + :c:func:`PyEval_InitThreads`, :c:func:`PyEval_ReleaseLock`, and + :c:func:`PyEval_AcquireLock`. This initializes the table of loaded modules (``sys.modules``), and creates the fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. It also initializes the module search path (``sys.path``). It does not set ``sys.argv``; use - :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time - (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a + :c:func:`PySys_SetArgvEx` for that. This is a no-op when called for a second time + (without calling :c:func:`Py_Finalize` first). There is no return value; it is a fatal error if the initialization fails. -.. cfunction:: void Py_InitializeEx(int initsigs) +.. c:function:: void Py_InitializeEx(int initsigs) - This function works like :cfunc:`Py_Initialize` if *initsigs* is 1. If + This function works like :c:func:`Py_Initialize` if *initsigs* is 1. If *initsigs* is 0, it skips initialization registration of signal handlers, which might be useful when Python is embedded. -.. cfunction:: int Py_IsInitialized() +.. c:function:: int Py_IsInitialized() Return true (nonzero) when the Python interpreter has been initialized, false - (zero) if not. After :cfunc:`Py_Finalize` is called, this returns false until - :cfunc:`Py_Initialize` is called again. + (zero) if not. After :c:func:`Py_Finalize` is called, this returns false until + :c:func:`Py_Initialize` is called again. -.. cfunction:: void Py_Finalize() +.. c:function:: void Py_Finalize() - Undo all initializations made by :cfunc:`Py_Initialize` and subsequent use of + Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of Python/C API functions, and destroy all sub-interpreters (see - :cfunc:`Py_NewInterpreter` below) that were created and not yet destroyed since - the last call to :cfunc:`Py_Initialize`. Ideally, this frees all memory + :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since + the last call to :c:func:`Py_Initialize`. Ideally, this frees all memory allocated by the Python interpreter. This is a no-op when called for a second - time (without calling :cfunc:`Py_Initialize` again first). There is no return + time (without calling :c:func:`Py_Initialize` again first). There is no return value; errors during finalization are ignored. This function is provided for a number of reasons. An embedding application @@ -78,11 +78,11 @@ Initialization, Finalization, and Threads please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more - than once; this can happen if an application calls :cfunc:`Py_Initialize` and - :cfunc:`Py_Finalize` more than once. + than once; this can happen if an application calls :c:func:`Py_Initialize` and + :c:func:`Py_Finalize` more than once. -.. cfunction:: PyThreadState* Py_NewInterpreter() +.. c:function:: PyThreadState* Py_NewInterpreter() .. index:: module: builtins @@ -100,7 +100,7 @@ Initialization, Finalization, and Threads (``sys.path``) are also separate. The new environment has no ``sys.argv`` variable. It has new standard I/O stream file objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying - :ctype:`FILE` structures in the C library). + :c:type:`FILE` structures in the C library). The return value points to the first thread state created in the new sub-interpreter. This thread state is made in the current thread state. @@ -124,7 +124,7 @@ Initialization, Finalization, and Threads and filled with the contents of this copy; the extension's ``init`` function is not called. Note that this is different from what happens when an extension is imported after the interpreter has been completely re-initialized by calling - :cfunc:`Py_Finalize` and :cfunc:`Py_Initialize`; in that case, the extension's + :c:func:`Py_Finalize` and :c:func:`Py_Initialize`; in that case, the extension's ``initmodule`` function *is* called again. .. index:: single: close() (in module os) @@ -145,12 +145,12 @@ Initialization, Finalization, and Threads release.) Also note that the use of this functionality is incompatible with extension - modules such as PyObjC and ctypes that use the :cfunc:`PyGILState_\*` APIs (and - this is inherent in the way the :cfunc:`PyGILState_\*` functions work). Simple + modules such as PyObjC and ctypes that use the :c:func:`PyGILState_\*` APIs (and + this is inherent in the way the :c:func:`PyGILState_\*` functions work). Simple things may work, but confusing behavior will always be near. -.. cfunction:: void Py_EndInterpreter(PyThreadState *tstate) +.. c:function:: void Py_EndInterpreter(PyThreadState *tstate) .. index:: single: Py_Finalize() @@ -159,22 +159,22 @@ Initialization, Finalization, and Threads states below. When the call returns, the current thread state is *NULL*. All thread states associated with this interpreter are destroyed. (The global interpreter lock must be held before calling this function and is still held - when it returns.) :cfunc:`Py_Finalize` will destroy all sub-interpreters that + when it returns.) :c:func:`Py_Finalize` will destroy all sub-interpreters that haven't been explicitly destroyed at that point. -.. cfunction:: void Py_SetProgramName(wchar_t *name) +.. c:function:: void Py_SetProgramName(wchar_t *name) .. index:: single: Py_Initialize() single: main() single: Py_GetPath() - This function should be called before :cfunc:`Py_Initialize` is called for + This function should be called before :c:func:`Py_Initialize` is called for the first time, if it is called at all. It tells the interpreter the value - of the ``argv[0]`` argument to the :cfunc:`main` function of the program + of the ``argv[0]`` argument to the :c:func:`main` function of the program (converted to wide characters). - This is used by :cfunc:`Py_GetPath` and some other functions below to find + This is used by :c:func:`Py_GetPath` and some other functions below to find the Python run-time libraries relative to the interpreter executable. The default value is ``'python'``. The argument should point to a zero-terminated wide character string in static storage whose contents will not @@ -182,20 +182,20 @@ Initialization, Finalization, and Threads interpreter will change the contents of this storage. -.. cfunction:: wchar* Py_GetProgramName() +.. c:function:: wchar* Py_GetProgramName() .. index:: single: Py_SetProgramName() - Return the program name set with :cfunc:`Py_SetProgramName`, or the default. + Return the program name set with :c:func:`Py_SetProgramName`, or the default. The returned string points into static storage; the caller should not modify its value. -.. cfunction:: wchar_t* Py_GetPrefix() +.. c:function:: wchar_t* Py_GetPrefix() Return the *prefix* for installed platform-independent files. This is derived through a number of complicated rules from the program name set with - :cfunc:`Py_SetProgramName` and some environment variables; for example, if the + :c:func:`Py_SetProgramName` and some environment variables; for example, if the program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The returned string points into static storage; the caller should not modify its value. This corresponds to the :makevar:`prefix` variable in the top-level @@ -204,11 +204,11 @@ Initialization, Finalization, and Threads It is only useful on Unix. See also the next function. -.. cfunction:: wchar_t* Py_GetExecPrefix() +.. c:function:: wchar_t* Py_GetExecPrefix() Return the *exec-prefix* for installed platform-*dependent* files. This is derived through a number of complicated rules from the program name set with - :cfunc:`Py_SetProgramName` and some environment variables; for example, if the + :c:func:`Py_SetProgramName` and some environment variables; for example, if the program name is ``'/usr/local/bin/python'``, the exec-prefix is ``'/usr/local'``. The returned string points into static storage; the caller should not modify its value. This corresponds to the :makevar:`exec_prefix` @@ -239,7 +239,7 @@ Initialization, Finalization, and Threads platform. -.. cfunction:: wchar_t* Py_GetProgramFullPath() +.. c:function:: wchar_t* Py_GetProgramFullPath() .. index:: single: Py_SetProgramName() @@ -247,12 +247,12 @@ Initialization, Finalization, and Threads Return the full program name of the Python executable; this is computed as a side-effect of deriving the default module search path from the program name - (set by :cfunc:`Py_SetProgramName` above). The returned string points into + (set by :c:func:`Py_SetProgramName` above). The returned string points into static storage; the caller should not modify its value. The value is available to Python code as ``sys.executable``. -.. cfunction:: wchar_t* Py_GetPath() +.. c:function:: wchar_t* Py_GetPath() .. index:: triple: module; search; path @@ -260,7 +260,7 @@ Initialization, Finalization, and Threads single: Py_SetPath() Return the default module search path; this is computed from the program name - (set by :cfunc:`Py_SetProgramName` above) and some environment variables. + (set by :c:func:`Py_SetProgramName` above) and some environment variables. The returned string consists of a series of directory names separated by a platform dependent delimiter character. The delimiter character is ``':'`` on Unix and Mac OS X, ``';'`` on Windows. The returned string points into @@ -272,7 +272,7 @@ Initialization, Finalization, and Threads .. XXX should give the exact rules -.. cfunction:: void Py_SetPath(const wchar_t *) +.. c:function:: void Py_SetPath(const wchar_t *) .. index:: triple: module; search; path @@ -280,18 +280,18 @@ Initialization, Finalization, and Threads single: Py_GetPath() Set the default module search path. If this function is called before - :cfunc: `Py_Initialize` then :cfunc: Py_GetPath won't attempt to compute + :c:func: `Py_Initialize` then :c:func: Py_GetPath won't attempt to compute a default serarch path but uses the provided one in stead. This is useful if Python is being embedded by an application that has full knowledge of the location of all modules. The path components should be separated by semicolons. This also causes `sys.executable` to be set only to the raw program name - (see :cfunc:`Py_SetProgramName`) and `for sys.prefix` and + (see :c:func:`Py_SetProgramName`) and `for sys.prefix` and `sys.exec_prefix` to be empty. It is up to the caller to modify these if - required after calling :cfunc: `Py_Initialize`. + required after calling :c:func:`Py_Initialize`. -.. cfunction:: const char* Py_GetVersion() +.. c:function:: const char* Py_GetVersion() Return the version of this Python interpreter. This is a string that looks something like :: @@ -306,7 +306,7 @@ Initialization, Finalization, and Threads modify its value. The value is available to Python code as :data:`sys.version`. -.. cfunction:: const char* Py_GetPlatform() +.. c:function:: const char* Py_GetPlatform() .. index:: single: platform (in module sys) @@ -319,7 +319,7 @@ Initialization, Finalization, and Threads to Python code as ``sys.platform``. -.. cfunction:: const char* Py_GetCopyright() +.. c:function:: const char* Py_GetCopyright() Return the official copyright string for the current Python version, for example @@ -331,7 +331,7 @@ Initialization, Finalization, and Threads value. The value is available to Python code as ``sys.copyright``. -.. cfunction:: const char* Py_GetCompiler() +.. c:function:: const char* Py_GetCompiler() Return an indication of the compiler used to build the current Python version, in square brackets, for example:: @@ -345,7 +345,7 @@ Initialization, Finalization, and Threads ``sys.version``. -.. cfunction:: const char* Py_GetBuildInfo() +.. c:function:: const char* Py_GetBuildInfo() Return information about the sequence number and build date and time of the current Python interpreter instance, for example :: @@ -359,7 +359,7 @@ Initialization, Finalization, and Threads ``sys.version``. -.. cfunction:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) +.. c:function:: void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) .. index:: single: main() @@ -367,12 +367,12 @@ Initialization, Finalization, and Threads single: argv (in module sys) Set :data:`sys.argv` based on *argc* and *argv*. These parameters are - similar to those passed to the program's :cfunc:`main` function with the + similar to those passed to the program's :c:func:`main` function with the difference that the first entry should refer to the script file to be executed rather than the executable hosting the Python interpreter. If there isn't a script that will be run, the first entry in *argv* can be an empty string. If this function fails to initialize :data:`sys.argv`, a fatal - condition is signalled using :cfunc:`Py_FatalError`. + condition is signalled using :c:func:`Py_FatalError`. If *updatepath* is zero, this is all the function does. If *updatepath* is non-zero, the function also modifies :data:`sys.path` according to the @@ -394,7 +394,7 @@ Initialization, Finalization, and Threads On versions before 3.1.3, you can achieve the same effect by manually popping the first :data:`sys.path` element after having called - :cfunc:`PySys_SetArgv`, for example using:: + :c:func:`PySys_SetArgv`, for example using:: PyRun_SimpleString("import sys; sys.path.pop(0)\n"); @@ -404,12 +404,12 @@ Initialization, Finalization, and Threads check w/ Guido. -.. cfunction:: void PySys_SetArgv(int argc, wchar_t **argv) +.. c:function:: void PySys_SetArgv(int argc, wchar_t **argv) - This function works like :cfunc:`PySys_SetArgvEx` with *updatepath* set to 1. + This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set to 1. -.. cfunction:: void Py_SetPythonHome(wchar_t *home) +.. c:function:: void Py_SetPythonHome(wchar_t *home) Set the default "home" directory, that is, the location of the standard Python libraries. The libraries are searched in @@ -420,10 +420,10 @@ Initialization, Finalization, and Threads this storage. -.. cfunction:: w_char* Py_GetPythonHome() +.. c:function:: w_char* Py_GetPythonHome() Return the default "home", that is, the value set by a previous call to - :cfunc:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME` + :c:func:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME` environment variable if it is set. @@ -461,9 +461,9 @@ the I/O is waiting for the I/O operation to complete. single: PyThreadState The Python interpreter needs to keep some bookkeeping information separate per -thread --- for this it uses a data structure called :ctype:`PyThreadState`. +thread --- for this it uses a data structure called :c:type:`PyThreadState`. There's one global variable, however: the pointer to the current -:ctype:`PyThreadState` structure. Before the addition of :dfn:`thread-local +:c:type:`PyThreadState` structure. Before the addition of :dfn:`thread-local storage` (:dfn:`TLS`) the current thread state had to be manipulated explicitly. @@ -486,8 +486,8 @@ This is so common that a pair of macros exists to simplify it:: single: Py_BEGIN_ALLOW_THREADS single: Py_END_ALLOW_THREADS -The :cmacro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a -hidden local variable; the :cmacro:`Py_END_ALLOW_THREADS` macro closes the +The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a +hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the block. Another advantage of using these two macros is that when Python is compiled without thread support, they are defined empty, thus saving the thread state and GIL manipulations. @@ -518,12 +518,12 @@ follows:: single: PyEval_ReleaseLock() single: PyEval_AcquireLock() -There are some subtle differences; in particular, :cfunc:`PyEval_RestoreThread` -saves and restores the value of the global variable :cdata:`errno`, since the -lock manipulation does not guarantee that :cdata:`errno` is left alone. Also, -when thread support is disabled, :cfunc:`PyEval_SaveThread` and -:cfunc:`PyEval_RestoreThread` don't manipulate the GIL; in this case, -:cfunc:`PyEval_ReleaseLock` and :cfunc:`PyEval_AcquireLock` are not available. +There are some subtle differences; in particular, :c:func:`PyEval_RestoreThread` +saves and restores the value of the global variable :c:data:`errno`, since the +lock manipulation does not guarantee that :c:data:`errno` is left alone. Also, +when thread support is disabled, :c:func:`PyEval_SaveThread` and +:c:func:`PyEval_RestoreThread` don't manipulate the GIL; in this case, +:c:func:`PyEval_ReleaseLock` and :c:func:`PyEval_AcquireLock` are not available. This is done so that dynamically loaded extensions compiled with thread support enabled can be loaded by an interpreter that was compiled with disabled thread support. @@ -543,7 +543,7 @@ storing their thread state pointer, before they can start using the Python/C API. When they are done, they should reset the thread state pointer, release the lock, and finally free their thread state data structure. -Threads can take advantage of the :cfunc:`PyGILState_\*` functions to do all of +Threads can take advantage of the :c:func:`PyGILState_\*` functions to do all of the above automatically. The typical idiom for calling into Python from a C thread is now:: @@ -557,14 +557,14 @@ thread is now:: /* Release the thread. No Python API allowed beyond this point. */ PyGILState_Release(gstate); -Note that the :cfunc:`PyGILState_\*` functions assume there is only one global -interpreter (created automatically by :cfunc:`Py_Initialize`). Python still +Note that the :c:func:`PyGILState_\*` functions assume there is only one global +interpreter (created automatically by :c:func:`Py_Initialize`). Python still supports the creation of additional interpreters (using -:cfunc:`Py_NewInterpreter`), but mixing multiple interpreters and the -:cfunc:`PyGILState_\*` API is unsupported. +:c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the +:c:func:`PyGILState_\*` API is unsupported. Another important thing to note about threads is their behaviour in the face -of the C :cfunc:`fork` call. On most systems with :cfunc:`fork`, after a +of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a process forks only the thread that issued the fork will exist. That also means any locks held by other threads will never be released. Python solves this for :func:`os.fork` by acquiring the locks it uses internally before @@ -572,15 +572,15 @@ the fork, and releasing them afterwards. In addition, it resets any :ref:`lock-objects` in the child. When extending or embedding Python, there is no way to inform Python of additional (non-Python) locks that need to be acquired before or reset after a fork. OS facilities such as -:cfunc:`posix_atfork` would need to be used to accomplish the same thing. -Additionally, when extending or embedding Python, calling :cfunc:`fork` +:c:func:`posix_atfork` would need to be used to accomplish the same thing. +Additionally, when extending or embedding Python, calling :c:func:`fork` directly rather than through :func:`os.fork` (and returning to or calling into Python) may result in a deadlock by one of Python's internal locks being held by a thread that is defunct after the fork. -:cfunc:`PyOS_AfterFork` tries to reset the necessary locks, but is not +:c:func:`PyOS_AfterFork` tries to reset the necessary locks, but is not always able to. -.. ctype:: PyInterpreterState +.. c:type:: PyInterpreterState This data structure represents the state shared by a number of cooperating threads. Threads belonging to the same interpreter share their module @@ -593,14 +593,14 @@ always able to. interpreter they belong. -.. ctype:: PyThreadState +.. c:type:: PyThreadState This data structure represents the state of a single thread. The only public - data member is :ctype:`PyInterpreterState \*`:attr:`interp`, which points to + data member is :c:type:`PyInterpreterState \*`:attr:`interp`, which points to this thread's interpreter state. -.. cfunction:: void PyEval_InitThreads() +.. c:function:: void PyEval_InitThreads() .. index:: single: PyEval_ReleaseLock() @@ -610,14 +610,14 @@ always able to. Initialize and acquire the global interpreter lock. It should be called in the main thread before creating a second thread or engaging in any other thread - operations such as :cfunc:`PyEval_ReleaseLock` or + operations such as :c:func:`PyEval_ReleaseLock` or ``PyEval_ReleaseThread(tstate)``. It is not needed before calling - :cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_RestoreThread`. + :c:func:`PyEval_SaveThread` or :c:func:`PyEval_RestoreThread`. .. index:: single: Py_Initialize() This is a no-op when called for a second time. It is safe to call this function - before calling :cfunc:`Py_Initialize`. + before calling :c:func:`Py_Initialize`. .. index:: module: _thread @@ -629,7 +629,7 @@ always able to. when this function initializes the global interpreter lock, it also acquires it. Before the Python :mod:`_thread` module creates a new thread, knowing that either it has the lock or the lock hasn't been created yet, it calls - :cfunc:`PyEval_InitThreads`. When this call returns, it is guaranteed that + :c:func:`PyEval_InitThreads`. When this call returns, it is guaranteed that the lock has been created and that the calling thread has acquired it. It is **not** safe to call this function when it is unknown which thread (if @@ -638,28 +638,28 @@ always able to. This function is not available when thread support is disabled at compile time. -.. cfunction:: int PyEval_ThreadsInitialized() +.. c:function:: int PyEval_ThreadsInitialized() - Returns a non-zero value if :cfunc:`PyEval_InitThreads` has been called. This + Returns a non-zero value if :c:func:`PyEval_InitThreads` has been called. This function can be called without holding the GIL, and therefore can be used to avoid calls to the locking API when running single-threaded. This function is not available when thread support is disabled at compile time. -.. cfunction:: void PyEval_AcquireLock() +.. c:function:: void PyEval_AcquireLock() Acquire the global interpreter lock. The lock must have been created earlier. If this thread already has the lock, a deadlock ensues. This function is not available when thread support is disabled at compile time. -.. cfunction:: void PyEval_ReleaseLock() +.. c:function:: void PyEval_ReleaseLock() Release the global interpreter lock. The lock must have been created earlier. This function is not available when thread support is disabled at compile time. -.. cfunction:: void PyEval_AcquireThread(PyThreadState *tstate) +.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate) Acquire the global interpreter lock and set the current thread state to *tstate*, which should not be *NULL*. The lock must have been created earlier. @@ -667,7 +667,7 @@ always able to. available when thread support is disabled at compile time. -.. cfunction:: void PyEval_ReleaseThread(PyThreadState *tstate) +.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate) Reset the current thread state to *NULL* and release the global interpreter lock. The lock must have been created earlier and must be held by the current @@ -677,7 +677,7 @@ always able to. compile time. -.. cfunction:: PyThreadState* PyEval_SaveThread() +.. c:function:: PyThreadState* PyEval_SaveThread() Release the global interpreter lock (if it has been created and thread support is enabled) and reset the thread state to *NULL*, returning the @@ -686,7 +686,7 @@ always able to. when thread support is disabled at compile time.) -.. cfunction:: void PyEval_RestoreThread(PyThreadState *tstate) +.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate) Acquire the global interpreter lock (if it has been created and thread support is enabled) and set the thread state to *tstate*, which must not be @@ -695,9 +695,9 @@ always able to. when thread support is disabled at compile time.) -.. cfunction:: void PyEval_ReInitThreads() +.. c:function:: void PyEval_ReInitThreads() - This function is called from :cfunc:`PyOS_AfterFork` to ensure that newly + This function is called from :c:func:`PyOS_AfterFork` to ensure that newly created child processes don't hold locks referring to threads which are not running in the child process. @@ -706,33 +706,33 @@ The following macros are normally used without a trailing semicolon; look for example usage in the Python source distribution. -.. cmacro:: Py_BEGIN_ALLOW_THREADS +.. c:macro:: Py_BEGIN_ALLOW_THREADS This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``. Note that it contains an opening brace; it must be matched with a following - :cmacro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this + :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this macro. It is a no-op when thread support is disabled at compile time. -.. cmacro:: Py_END_ALLOW_THREADS +.. c:macro:: Py_END_ALLOW_THREADS This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains a closing brace; it must be matched with an earlier - :cmacro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of + :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of this macro. It is a no-op when thread support is disabled at compile time. -.. cmacro:: Py_BLOCK_THREADS +.. c:macro:: Py_BLOCK_THREADS This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to - :cmacro:`Py_END_ALLOW_THREADS` without the closing brace. It is a no-op when + :c:macro:`Py_END_ALLOW_THREADS` without the closing brace. It is a no-op when thread support is disabled at compile time. -.. cmacro:: Py_UNBLOCK_THREADS +.. c:macro:: Py_UNBLOCK_THREADS This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to - :cmacro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable + :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable declaration. It is a no-op when thread support is disabled at compile time. All of the following functions are only available when thread support is enabled @@ -740,60 +740,60 @@ at compile time, and must be called only when the global interpreter lock has been created. -.. cfunction:: PyInterpreterState* PyInterpreterState_New() +.. c:function:: PyInterpreterState* PyInterpreterState_New() Create a new interpreter state object. The global interpreter lock need not be held, but may be held if it is necessary to serialize calls to this function. -.. cfunction:: void PyInterpreterState_Clear(PyInterpreterState *interp) +.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp) Reset all information in an interpreter state object. The global interpreter lock must be held. -.. cfunction:: void PyInterpreterState_Delete(PyInterpreterState *interp) +.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp) Destroy an interpreter state object. The global interpreter lock need not be held. The interpreter state must have been reset with a previous call to - :cfunc:`PyInterpreterState_Clear`. + :c:func:`PyInterpreterState_Clear`. -.. cfunction:: PyThreadState* PyThreadState_New(PyInterpreterState *interp) +.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp) Create a new thread state object belonging to the given interpreter object. The global interpreter lock need not be held, but may be held if it is necessary to serialize calls to this function. -.. cfunction:: void PyThreadState_Clear(PyThreadState *tstate) +.. c:function:: void PyThreadState_Clear(PyThreadState *tstate) Reset all information in a thread state object. The global interpreter lock must be held. -.. cfunction:: void PyThreadState_Delete(PyThreadState *tstate) +.. c:function:: void PyThreadState_Delete(PyThreadState *tstate) Destroy a thread state object. The global interpreter lock need not be held. The thread state must have been reset with a previous call to - :cfunc:`PyThreadState_Clear`. + :c:func:`PyThreadState_Clear`. -.. cfunction:: PyThreadState* PyThreadState_Get() +.. c:function:: PyThreadState* PyThreadState_Get() Return the current thread state. The global interpreter lock must be held. When the current thread state is *NULL*, this issues a fatal error (so that the caller needn't check for *NULL*). -.. cfunction:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate) +.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate) Swap the current thread state with the thread state given by the argument *tstate*, which may be *NULL*. The global interpreter lock must be held. -.. cfunction:: PyObject* PyThreadState_GetDict() +.. c:function:: PyObject* PyThreadState_GetDict() Return a dictionary in which extensions can store thread-specific state information. Each extension should use a unique key to use to store state in @@ -802,7 +802,7 @@ been created. the caller should assume no current thread state is available. -.. cfunction:: int PyThreadState_SetAsyncExc(long id, PyObject *exc) +.. c:function:: int PyThreadState_SetAsyncExc(long id, PyObject *exc) Asynchronously raise an exception in a thread. The *id* argument is the thread id of the target thread; *exc* is the exception object to be raised. This @@ -813,38 +813,38 @@ been created. exception (if any) for the thread is cleared. This raises no exceptions. -.. cfunction:: PyGILState_STATE PyGILState_Ensure() +.. c:function:: PyGILState_STATE PyGILState_Ensure() Ensure that the current thread is ready to call the Python C API regardless of the current state of Python, or of the global interpreter lock. This may be called as many times as desired by a thread as long as each call is - matched with a call to :cfunc:`PyGILState_Release`. In general, other - thread-related APIs may be used between :cfunc:`PyGILState_Ensure` and - :cfunc:`PyGILState_Release` calls as long as the thread state is restored to + matched with a call to :c:func:`PyGILState_Release`. In general, other + thread-related APIs may be used between :c:func:`PyGILState_Ensure` and + :c:func:`PyGILState_Release` calls as long as the thread state is restored to its previous state before the Release(). For example, normal usage of the - :cmacro:`Py_BEGIN_ALLOW_THREADS` and :cmacro:`Py_END_ALLOW_THREADS` macros is + :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is acceptable. The return value is an opaque "handle" to the thread state when - :cfunc:`PyGILState_Ensure` was called, and must be passed to - :cfunc:`PyGILState_Release` to ensure Python is left in the same state. Even + :c:func:`PyGILState_Ensure` was called, and must be passed to + :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even though recursive calls are allowed, these handles *cannot* be shared - each - unique call to :cfunc:`PyGILState_Ensure` must save the handle for its call - to :cfunc:`PyGILState_Release`. + unique call to :c:func:`PyGILState_Ensure` must save the handle for its call + to :c:func:`PyGILState_Release`. When the function returns, the current thread will hold the GIL. Failure is a fatal error. -.. cfunction:: void PyGILState_Release(PyGILState_STATE) +.. c:function:: void PyGILState_Release(PyGILState_STATE) Release any resources previously acquired. After this call, Python's state will - be the same as it was prior to the corresponding :cfunc:`PyGILState_Ensure` call + be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call (but generally this state will be unknown to the caller, hence the use of the GILState API.) - Every call to :cfunc:`PyGILState_Ensure` must be matched by a call to - :cfunc:`PyGILState_Release` on the same thread. + Every call to :c:func:`PyGILState_Ensure` must be matched by a call to + :c:func:`PyGILState_Release` on the same thread. @@ -864,7 +864,7 @@ a worker thread and the actual call than made at the earliest convenience by the main thread where it has possession of the global interpreter lock and can perform any Python API calls. -.. cfunction:: void Py_AddPendingCall( int (*func)(void *, void *arg) ) +.. c:function:: void Py_AddPendingCall( int (*func)(void *, void *arg) ) .. index:: single: Py_AddPendingCall() @@ -909,10 +909,10 @@ events reported to the trace function are the same as had been reported to the Python-level trace functions in previous versions. -.. ctype:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg) +.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg) - The type of the trace function registered using :cfunc:`PyEval_SetProfile` and - :cfunc:`PyEval_SetTrace`. The first parameter is the object passed to the + The type of the trace function registered using :c:func:`PyEval_SetProfile` and + :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the registration function as *obj*, *frame* is the frame object to which the event pertains, *what* is one of the constants :const:`PyTrace_CALL`, :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`, @@ -939,18 +939,18 @@ Python-level trace functions in previous versions. +------------------------------+--------------------------------------+ -.. cvar:: int PyTrace_CALL +.. c:var:: int PyTrace_CALL - The value of the *what* parameter to a :ctype:`Py_tracefunc` function when a new + The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new call to a function or method is being reported, or a new entry into a generator. Note that the creation of the iterator for a generator function is not reported as there is no control transfer to the Python bytecode in the corresponding frame. -.. cvar:: int PyTrace_EXCEPTION +.. c:var:: int PyTrace_EXCEPTION - The value of the *what* parameter to a :ctype:`Py_tracefunc` function when an + The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an exception has been raised. The callback function is called with this value for *what* when after any bytecode is processed after which the exception becomes set within the frame being executed. The effect of this is that as exception @@ -959,37 +959,37 @@ Python-level trace functions in previous versions. these events; they are not needed by the profiler. -.. cvar:: int PyTrace_LINE +.. c:var:: int PyTrace_LINE The value passed as the *what* parameter to a trace function (but not a profiling function) when a line-number event is being reported. -.. cvar:: int PyTrace_RETURN +.. c:var:: int PyTrace_RETURN - The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a + The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a call is returning without propagating an exception. -.. cvar:: int PyTrace_C_CALL +.. c:var:: int PyTrace_C_CALL - The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C + The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C function is about to be called. -.. cvar:: int PyTrace_C_EXCEPTION +.. c:var:: int PyTrace_C_EXCEPTION - The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C + The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C function has raised an exception. -.. cvar:: int PyTrace_C_RETURN +.. c:var:: int PyTrace_C_RETURN - The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C + The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C function has returned. -.. cfunction:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj) +.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj) Set the profiler function to *func*. The *obj* parameter is passed to the function as its first parameter, and may be any Python object, or *NULL*. If @@ -999,13 +999,13 @@ Python-level trace functions in previous versions. events. -.. cfunction:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj) +.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj) Set the tracing function to *func*. This is similar to - :cfunc:`PyEval_SetProfile`, except the tracing function does receive line-number + :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number events. -.. cfunction:: PyObject* PyEval_GetCallStats(PyObject *self) +.. c:function:: PyObject* PyEval_GetCallStats(PyObject *self) Return a tuple of function call counts. There are constants defined for the positions within the tuple: @@ -1057,25 +1057,25 @@ Advanced Debugger Support These functions are only intended to be used by advanced debugging tools. -.. cfunction:: PyInterpreterState* PyInterpreterState_Head() +.. c:function:: PyInterpreterState* PyInterpreterState_Head() Return the interpreter state object at the head of the list of all such objects. -.. cfunction:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp) +.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp) Return the next interpreter state object after *interp* from the list of all such objects. -.. cfunction:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) +.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) - Return the a pointer to the first :ctype:`PyThreadState` object in the list of + Return the a pointer to the first :c:type:`PyThreadState` object in the list of threads associated with the interpreter *interp*. -.. cfunction:: PyThreadState* PyThreadState_Next(PyThreadState *tstate) +.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate) Return the next thread state object after *tstate* from the list of all such - objects belonging to the same :ctype:`PyInterpreterState` object. + objects belonging to the same :c:type:`PyInterpreterState` object. diff --git a/Doc/c-api/intro.rst b/Doc/c-api/intro.rst index 249610b..e2a2f9a 100644 --- a/Doc/c-api/intro.rst +++ b/Doc/c-api/intro.rst @@ -88,15 +88,15 @@ Objects, Types and Reference Counts .. index:: object: type Most Python/C API functions have one or more arguments as well as a return value -of type :ctype:`PyObject\*`. This type is a pointer to an opaque data type +of type :c:type:`PyObject\*`. This type is a pointer to an opaque data type representing an arbitrary Python object. Since all Python object types are treated the same way by the Python language in most situations (e.g., assignments, scope rules, and argument passing), it is only fitting that they should be represented by a single C type. Almost all Python objects live on the heap: you never declare an automatic or static variable of type -:ctype:`PyObject`, only pointer variables of type :ctype:`PyObject\*` can be +:c:type:`PyObject`, only pointer variables of type :c:type:`PyObject\*` can be declared. The sole exception are the type objects; since these must never be -deallocated, they are typically static :ctype:`PyTypeObject` objects. +deallocated, they are typically static :c:type:`PyTypeObject` objects. All Python objects (even Python integers) have a :dfn:`type` and a :dfn:`reference count`. An object's type determines what kind of object it is @@ -127,8 +127,8 @@ that.") single: Py_DECREF() Reference counts are always manipulated explicitly. The normal way is to use -the macro :cfunc:`Py_INCREF` to increment an object's reference count by one, -and :cfunc:`Py_DECREF` to decrement it by one. The :cfunc:`Py_DECREF` macro +the macro :c:func:`Py_INCREF` to increment an object's reference count by one, +and :c:func:`Py_DECREF` to decrement it by one. The :c:func:`Py_DECREF` macro is considerably more complex than the incref one, since it must check whether the reference count becomes zero and then cause the object's deallocator to be called. The deallocator is a function pointer contained in the object's type @@ -159,13 +159,13 @@ for a while without incrementing its reference count. Some other operation might conceivably remove the object from the list, decrementing its reference count and possible deallocating it. The real danger is that innocent-looking operations may invoke arbitrary Python code which could do this; there is a code -path which allows control to flow back to the user from a :cfunc:`Py_DECREF`, so +path which allows control to flow back to the user from a :c:func:`Py_DECREF`, so almost any operation is potentially dangerous. A safe approach is to always use the generic operations (functions whose name begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``). These operations always increment the reference count of the object they return. -This leaves the caller with the responsibility to call :cfunc:`Py_DECREF` when +This leaves the caller with the responsibility to call :c:func:`Py_DECREF` when they are done with the result; this soon becomes second nature. @@ -180,7 +180,7 @@ to objects (objects are not owned: they are always shared). "Owning a reference" means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for -eventually decref'ing it by calling :cfunc:`Py_DECREF` or :cfunc:`Py_XDECREF` +eventually decref'ing it by calling :c:func:`Py_DECREF` or :c:func:`Py_XDECREF` when it's no longer needed---or passing on this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is said to receive a *new* reference. When no ownership is transferred, @@ -198,7 +198,7 @@ responsible for it any longer. single: PyTuple_SetItem() Few functions steal references; the two notable exceptions are -:cfunc:`PyList_SetItem` and :cfunc:`PyTuple_SetItem`, which steal a reference +:c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which steal a reference to the item (but not to the tuple or list into which the item is put!). These functions were designed to steal a reference because of a common idiom for populating a tuple or list with newly created objects; for example, the code to @@ -212,21 +212,21 @@ error handling for the moment; a better way to code this is shown below):: PyTuple_SetItem(t, 1, PyLong_FromLong(2L)); PyTuple_SetItem(t, 2, PyString_FromString("three")); -Here, :cfunc:`PyLong_FromLong` returns a new reference which is immediately -stolen by :cfunc:`PyTuple_SetItem`. When you want to keep using an object -although the reference to it will be stolen, use :cfunc:`Py_INCREF` to grab +Here, :c:func:`PyLong_FromLong` returns a new reference which is immediately +stolen by :c:func:`PyTuple_SetItem`. When you want to keep using an object +although the reference to it will be stolen, use :c:func:`Py_INCREF` to grab another reference before calling the reference-stealing function. -Incidentally, :cfunc:`PyTuple_SetItem` is the *only* way to set tuple items; -:cfunc:`PySequence_SetItem` and :cfunc:`PyObject_SetItem` refuse to do this +Incidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple items; +:c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to do this since tuples are an immutable data type. You should only use -:cfunc:`PyTuple_SetItem` for tuples that you are creating yourself. +:c:func:`PyTuple_SetItem` for tuples that you are creating yourself. -Equivalent code for populating a list can be written using :cfunc:`PyList_New` -and :cfunc:`PyList_SetItem`. +Equivalent code for populating a list can be written using :c:func:`PyList_New` +and :c:func:`PyList_SetItem`. However, in practice, you will rarely use these ways of creating and populating -a tuple or list. There's a generic function, :cfunc:`Py_BuildValue`, that can +a tuple or list. There's a generic function, :c:func:`Py_BuildValue`, that can create most common objects from C values, directed by a :dfn:`format string`. For example, the above two blocks of code could be replaced by the following (which also takes care of the error checking):: @@ -236,7 +236,7 @@ For example, the above two blocks of code could be replaced by the following tuple = Py_BuildValue("(iis)", 1, 2, "three"); list = Py_BuildValue("[iis]", 1, 2, "three"); -It is much more common to use :cfunc:`PyObject_SetItem` and friends with items +It is much more common to use :c:func:`PyObject_SetItem` and friends with items whose references you are only borrowing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding reference counts is much saner, since you don't have to increment a reference count so you @@ -270,15 +270,15 @@ for that reference, many functions that return a reference to an object give you ownership of the reference. The reason is simple: in many cases, the returned object is created on the fly, and the reference you get is the only reference to the object. Therefore, the generic functions that return object -references, like :cfunc:`PyObject_GetItem` and :cfunc:`PySequence_GetItem`, +references, like :c:func:`PyObject_GetItem` and :c:func:`PySequence_GetItem`, always return a new reference (the caller becomes the owner of the reference). It is important to realize that whether you own a reference returned by a function depends on which function you call only --- *the plumage* (the type of the object passed as an argument to the function) *doesn't enter into it!* -Thus, if you extract an item from a list using :cfunc:`PyList_GetItem`, you +Thus, if you extract an item from a list using :c:func:`PyList_GetItem`, you don't own the reference --- but if you obtain the same item from the same list -using :cfunc:`PySequence_GetItem` (which happens to take exactly the same +using :c:func:`PySequence_GetItem` (which happens to take exactly the same arguments), you do own a reference to the returned object. .. index:: @@ -286,8 +286,8 @@ arguments), you do own a reference to the returned object. single: PySequence_GetItem() Here is an example of how you could write a function that computes the sum of -the items in a list of integers; once using :cfunc:`PyList_GetItem`, and once -using :cfunc:`PySequence_GetItem`. :: +the items in a list of integers; once using :c:func:`PyList_GetItem`, and once +using :c:func:`PySequence_GetItem`. :: long sum_list(PyObject *list) @@ -340,8 +340,8 @@ Types ----- There are few other data types that play a significant role in the Python/C -API; most are simple C types such as :ctype:`int`, :ctype:`long`, -:ctype:`double` and :ctype:`char\*`. A few structure types are used to +API; most are simple C types such as :c:type:`int`, :c:type:`long`, +:c:type:`double` and :c:type:`char\*`. A few structure types are used to describe static tables used to list the functions exported by a module or the data attributes of a new object type, and another is used to describe the value of a complex number. These will be discussed together with the functions that @@ -369,7 +369,7 @@ it owns, and returns an error indicator --- usually *NULL* or ``-1``. A few functions return a Boolean true/false result, with false indicating an error. Very few functions return no explicit error indicator or have an ambiguous return value, and require explicit testing for errors with -:cfunc:`PyErr_Occurred`. +:c:func:`PyErr_Occurred`. .. index:: single: PyErr_SetString() @@ -378,11 +378,11 @@ return value, and require explicit testing for errors with Exception state is maintained in per-thread storage (this is equivalent to using global storage in an unthreaded application). A thread can be in one of two states: an exception has occurred, or not. The function -:cfunc:`PyErr_Occurred` can be used to check for this: it returns a borrowed +:c:func:`PyErr_Occurred` can be used to check for this: it returns a borrowed reference to the exception type object when an exception has occurred, and *NULL* otherwise. There are a number of functions to set the exception state: -:cfunc:`PyErr_SetString` is the most common (though not the most general) -function to set the exception state, and :cfunc:`PyErr_Clear` clears the +:c:func:`PyErr_SetString` is the most common (though not the most general) +function to set the exception state, and :c:func:`PyErr_Clear` clears the exception state. The full exception state consists of three objects (all of which can be @@ -418,7 +418,7 @@ and lose important information about the exact cause of the error. .. index:: single: sum_sequence() A simple example of detecting exceptions and passing them on is shown in the -:cfunc:`sum_sequence` example above. It so happens that that example doesn't +:c:func:`sum_sequence` example above. It so happens that that example doesn't need to clean up any owned references when it detects an error. The following example function shows some error cleanup. First, to remind you why you like Python, we show the equivalent Python code:: @@ -485,10 +485,10 @@ Here is the corresponding C code, in all its glory:: single: Py_XDECREF() This example represents an endorsed use of the ``goto`` statement in C! -It illustrates the use of :cfunc:`PyErr_ExceptionMatches` and -:cfunc:`PyErr_Clear` to handle specific exceptions, and the use of -:cfunc:`Py_XDECREF` to dispose of owned references that may be *NULL* (note the -``'X'`` in the name; :cfunc:`Py_DECREF` would crash when confronted with a +It illustrates the use of :c:func:`PyErr_ExceptionMatches` and +:c:func:`PyErr_Clear` to handle specific exceptions, and the use of +:c:func:`Py_XDECREF` to dispose of owned references that may be *NULL* (note the +``'X'`` in the name; :c:func:`Py_DECREF` would crash when confronted with a *NULL* reference). It is important that the variables used to hold owned references are initialized to *NULL* for this to work; likewise, the proposed return value is initialized to ``-1`` (failure) and only set to success after @@ -514,20 +514,20 @@ interpreter can only be used after the interpreter has been initialized. triple: module; search; path single: path (in module sys) -The basic initialization function is :cfunc:`Py_Initialize`. This initializes +The basic initialization function is :c:func:`Py_Initialize`. This initializes the table of loaded modules, and creates the fundamental modules :mod:`builtins`, :mod:`__main__`, :mod:`sys`, and :mod:`exceptions`. It also initializes the module search path (``sys.path``). .. index:: single: PySys_SetArgvEx() -:cfunc:`Py_Initialize` does not set the "script argument list" (``sys.argv``). +:c:func:`Py_Initialize` does not set the "script argument list" (``sys.argv``). If this variable is needed by Python code that will be executed later, it must be set explicitly with a call to ``PySys_SetArgvEx(argc, argv, updatepath)`` -after the call to :cfunc:`Py_Initialize`. +after the call to :c:func:`Py_Initialize`. On most systems (in particular, on Unix and Windows, although the details are -slightly different), :cfunc:`Py_Initialize` calculates the module search path +slightly different), :c:func:`Py_Initialize` calculates the module search path based upon its best guess for the location of the standard Python interpreter executable, assuming that the Python library is found in a fixed location relative to the Python interpreter executable. In particular, it looks for a @@ -551,22 +551,22 @@ front of the standard path by setting :envvar:`PYTHONPATH`. single: Py_GetProgramFullPath() The embedding application can steer the search by calling -``Py_SetProgramName(file)`` *before* calling :cfunc:`Py_Initialize`. Note that +``Py_SetProgramName(file)`` *before* calling :c:func:`Py_Initialize`. Note that :envvar:`PYTHONHOME` still overrides this and :envvar:`PYTHONPATH` is still inserted in front of the standard path. An application that requires total -control has to provide its own implementation of :cfunc:`Py_GetPath`, -:cfunc:`Py_GetPrefix`, :cfunc:`Py_GetExecPrefix`, and -:cfunc:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`). +control has to provide its own implementation of :c:func:`Py_GetPath`, +:c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and +:c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`). .. index:: single: Py_IsInitialized() Sometimes, it is desirable to "uninitialize" Python. For instance, the application may want to start over (make another call to -:cfunc:`Py_Initialize`) or the application is simply done with its use of +:c:func:`Py_Initialize`) or the application is simply done with its use of Python and wants to free memory allocated by Python. This can be accomplished -by calling :cfunc:`Py_Finalize`. The function :cfunc:`Py_IsInitialized` returns +by calling :c:func:`Py_Finalize`. The function :c:func:`Py_IsInitialized` returns true if Python is currently in the initialized state. More information about -these functions is given in a later chapter. Notice that :cfunc:`Py_Finalize` +these functions is given in a later chapter. Notice that :c:func:`Py_Finalize` does *not* free all memory allocated by the Python interpreter, e.g. memory allocated by extension modules currently cannot be released. @@ -586,11 +586,11 @@ available that support tracing of reference counts, debugging the memory allocator, or low-level profiling of the main interpreter loop. Only the most frequently-used builds will be described in the remainder of this section. -Compiling the interpreter with the :cmacro:`Py_DEBUG` macro defined produces -what is generally meant by "a debug build" of Python. :cmacro:`Py_DEBUG` is +Compiling the interpreter with the :c:macro:`Py_DEBUG` macro defined produces +what is generally meant by "a debug build" of Python. :c:macro:`Py_DEBUG` is enabled in the Unix build by adding :option:`--with-pydebug` to the :file:`configure` command. It is also implied by the presence of the -not-Python-specific :cmacro:`_DEBUG` macro. When :cmacro:`Py_DEBUG` is enabled +not-Python-specific :c:macro:`_DEBUG` macro. When :c:macro:`Py_DEBUG` is enabled in the Unix build, compiler optimization is disabled. In addition to the reference count debugging described below, the following @@ -619,11 +619,11 @@ extra checks are performed: There may be additional checks not mentioned here. -Defining :cmacro:`Py_TRACE_REFS` enables reference tracing. When defined, a +Defining :c:macro:`Py_TRACE_REFS` enables reference tracing. When defined, a circular doubly linked list of active objects is maintained by adding two extra -fields to every :ctype:`PyObject`. Total allocations are tracked as well. Upon +fields to every :c:type:`PyObject`. Total allocations are tracked as well. Upon exit, all existing references are printed. (In interactive mode this happens -after every statement run by the interpreter.) Implied by :cmacro:`Py_DEBUG`. +after every statement run by the interpreter.) Implied by :c:macro:`Py_DEBUG`. Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution for more detailed information. diff --git a/Doc/c-api/iter.rst b/Doc/c-api/iter.rst index ba7e9e3..3f0f554 100644 --- a/Doc/c-api/iter.rst +++ b/Doc/c-api/iter.rst @@ -7,12 +7,12 @@ Iterator Protocol There are only a couple of functions specifically for working with iterators. -.. cfunction:: int PyIter_Check(PyObject *o) +.. c:function:: int PyIter_Check(PyObject *o) Return true if the object *o* supports the iterator protocol. -.. cfunction:: PyObject* PyIter_Next(PyObject *o) +.. c:function:: PyObject* PyIter_Next(PyObject *o) Return the next value from the iteration *o*. If the object is an iterator, this retrieves the next value from the iteration, and returns *NULL* with no diff --git a/Doc/c-api/iterator.rst b/Doc/c-api/iterator.rst index 8665080..82cb4eb 100644 --- a/Doc/c-api/iterator.rst +++ b/Doc/c-api/iterator.rst @@ -12,37 +12,37 @@ the callable for each item in the sequence, and ending the iteration when the sentinel value is returned. -.. cvar:: PyTypeObject PySeqIter_Type +.. c:var:: PyTypeObject PySeqIter_Type - Type object for iterator objects returned by :cfunc:`PySeqIter_New` and the + Type object for iterator objects returned by :c:func:`PySeqIter_New` and the one-argument form of the :func:`iter` built-in function for built-in sequence types. -.. cfunction:: int PySeqIter_Check(op) +.. c:function:: int PySeqIter_Check(op) - Return true if the type of *op* is :cdata:`PySeqIter_Type`. + Return true if the type of *op* is :c:data:`PySeqIter_Type`. -.. cfunction:: PyObject* PySeqIter_New(PyObject *seq) +.. c:function:: PyObject* PySeqIter_New(PyObject *seq) Return an iterator that works with a general sequence object, *seq*. The iteration ends when the sequence raises :exc:`IndexError` for the subscripting operation. -.. cvar:: PyTypeObject PyCallIter_Type +.. c:var:: PyTypeObject PyCallIter_Type - Type object for iterator objects returned by :cfunc:`PyCallIter_New` and the + Type object for iterator objects returned by :c:func:`PyCallIter_New` and the two-argument form of the :func:`iter` built-in function. -.. cfunction:: int PyCallIter_Check(op) +.. c:function:: int PyCallIter_Check(op) - Return true if the type of *op* is :cdata:`PyCallIter_Type`. + Return true if the type of *op* is :c:data:`PyCallIter_Type`. -.. cfunction:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel) +.. c:function:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel) Return a new iterator. The first parameter, *callable*, can be any Python callable object that can be called with no parameters; each call to it should diff --git a/Doc/c-api/list.rst b/Doc/c-api/list.rst index 89f0f9d..f7d050a 100644 --- a/Doc/c-api/list.rst +++ b/Doc/c-api/list.rst @@ -8,30 +8,30 @@ List Objects .. index:: object: list -.. ctype:: PyListObject +.. c:type:: PyListObject - This subtype of :ctype:`PyObject` represents a Python list object. + This subtype of :c:type:`PyObject` represents a Python list object. -.. cvar:: PyTypeObject PyList_Type +.. c:var:: PyTypeObject PyList_Type - This instance of :ctype:`PyTypeObject` represents the Python list type. This + This instance of :c:type:`PyTypeObject` represents the Python list type. This is the same object as ``list`` in the Python layer. -.. cfunction:: int PyList_Check(PyObject *p) +.. c:function:: int PyList_Check(PyObject *p) Return true if *p* is a list object or an instance of a subtype of the list type. -.. cfunction:: int PyList_CheckExact(PyObject *p) +.. c:function:: int PyList_CheckExact(PyObject *p) Return true if *p* is a list object, but not an instance of a subtype of the list type. -.. cfunction:: PyObject* PyList_New(Py_ssize_t len) +.. c:function:: PyObject* PyList_New(Py_ssize_t len) Return a new list of length *len* on success, or *NULL* on failure. @@ -39,11 +39,11 @@ List Objects If *length* is greater than zero, the returned list object's items are set to ``NULL``. Thus you cannot use abstract API functions such as - :cfunc:`PySequence_SetItem` or expose the object to Python code before - setting all items to a real object with :cfunc:`PyList_SetItem`. + :c:func:`PySequence_SetItem` or expose the object to Python code before + setting all items to a real object with :c:func:`PyList_SetItem`. -.. cfunction:: Py_ssize_t PyList_Size(PyObject *list) +.. c:function:: Py_ssize_t PyList_Size(PyObject *list) .. index:: builtin: len @@ -51,12 +51,12 @@ List Objects ``len(list)`` on a list object. -.. cfunction:: Py_ssize_t PyList_GET_SIZE(PyObject *list) +.. c:function:: Py_ssize_t PyList_GET_SIZE(PyObject *list) - Macro form of :cfunc:`PyList_Size` without error checking. + Macro form of :c:func:`PyList_Size` without error checking. -.. cfunction:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index) +.. c:function:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index) Return the object at position *pos* in the list pointed to by *p*. The position must be positive, indexing from the end of the list is not @@ -64,12 +64,12 @@ List Objects :exc:`IndexError` exception. -.. cfunction:: PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i) +.. c:function:: PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i) - Macro form of :cfunc:`PyList_GetItem` without error checking. + Macro form of :c:func:`PyList_GetItem` without error checking. -.. cfunction:: int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item) +.. c:function:: int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item) Set the item at index *index* in list to *item*. Return ``0`` on success or ``-1`` on failure. @@ -80,34 +80,34 @@ List Objects an item already in the list at the affected position. -.. cfunction:: void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o) +.. c:function:: void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o) - Macro form of :cfunc:`PyList_SetItem` without error checking. This is + Macro form of :c:func:`PyList_SetItem` without error checking. This is normally only used to fill in new lists where there is no previous content. .. note:: This macro "steals" a reference to *item*, and, unlike - :cfunc:`PyList_SetItem`, does *not* discard a reference to any item that + :c:func:`PyList_SetItem`, does *not* discard a reference to any item that is being replaced; any reference in *list* at position *i* will be leaked. -.. cfunction:: int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item) +.. c:function:: int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item) Insert the item *item* into list *list* in front of index *index*. Return ``0`` if successful; return ``-1`` and set an exception if unsuccessful. Analogous to ``list.insert(index, item)``. -.. cfunction:: int PyList_Append(PyObject *list, PyObject *item) +.. c:function:: int PyList_Append(PyObject *list, PyObject *item) Append the object *item* at the end of list *list*. Return ``0`` if successful; return ``-1`` and set an exception if unsuccessful. Analogous to ``list.append(item)``. -.. cfunction:: PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high) +.. c:function:: PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high) Return a list of the objects in *list* containing the objects *between* *low* and *high*. Return *NULL* and set an exception if unsuccessful. Analogous @@ -115,7 +115,7 @@ List Objects supported. -.. cfunction:: int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist) +.. c:function:: int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist) Set the slice of *list* between *low* and *high* to the contents of *itemlist*. Analogous to ``list[low:high] = itemlist``. The *itemlist* may @@ -124,19 +124,19 @@ List Objects slicing from Python, are not supported. -.. cfunction:: int PyList_Sort(PyObject *list) +.. c:function:: int PyList_Sort(PyObject *list) Sort the items of *list* in place. Return ``0`` on success, ``-1`` on failure. This is equivalent to ``list.sort()``. -.. cfunction:: int PyList_Reverse(PyObject *list) +.. c:function:: int PyList_Reverse(PyObject *list) Reverse the items of *list* in place. Return ``0`` on success, ``-1`` on failure. This is the equivalent of ``list.reverse()``. -.. cfunction:: PyObject* PyList_AsTuple(PyObject *list) +.. c:function:: PyObject* PyList_AsTuple(PyObject *list) .. index:: builtin: tuple diff --git a/Doc/c-api/long.rst b/Doc/c-api/long.rst index 9a7811e..6ae1fb6 100644 --- a/Doc/c-api/long.rst +++ b/Doc/c-api/long.rst @@ -10,32 +10,32 @@ Integer Objects All integers are implemented as "long" integer objects of arbitrary size. -.. ctype:: PyLongObject +.. c:type:: PyLongObject - This subtype of :ctype:`PyObject` represents a Python integer object. + This subtype of :c:type:`PyObject` represents a Python integer object. -.. cvar:: PyTypeObject PyLong_Type +.. c:var:: PyTypeObject PyLong_Type - This instance of :ctype:`PyTypeObject` represents the Python integer type. + This instance of :c:type:`PyTypeObject` represents the Python integer type. This is the same object as ``int``. -.. cfunction:: int PyLong_Check(PyObject *p) +.. c:function:: int PyLong_Check(PyObject *p) - Return true if its argument is a :ctype:`PyLongObject` or a subtype of - :ctype:`PyLongObject`. + Return true if its argument is a :c:type:`PyLongObject` or a subtype of + :c:type:`PyLongObject`. -.. cfunction:: int PyLong_CheckExact(PyObject *p) +.. c:function:: int PyLong_CheckExact(PyObject *p) - Return true if its argument is a :ctype:`PyLongObject`, but not a subtype of - :ctype:`PyLongObject`. + Return true if its argument is a :c:type:`PyLongObject`, but not a subtype of + :c:type:`PyLongObject`. -.. cfunction:: PyObject* PyLong_FromLong(long v) +.. c:function:: PyObject* PyLong_FromLong(long v) - Return a new :ctype:`PyLongObject` object from *v*, or *NULL* on failure. + Return a new :c:type:`PyLongObject` object from *v*, or *NULL* on failure. The current implementation keeps an array of integer objects for all integers between ``-5`` and ``256``, when you create an int in that range you actually @@ -44,45 +44,45 @@ All integers are implemented as "long" integer objects of arbitrary size. undefined. :-) -.. cfunction:: PyObject* PyLong_FromUnsignedLong(unsigned long v) +.. c:function:: PyObject* PyLong_FromUnsignedLong(unsigned long v) - Return a new :ctype:`PyLongObject` object from a C :ctype:`unsigned long`, or + Return a new :c:type:`PyLongObject` object from a C :c:type:`unsigned long`, or *NULL* on failure. -.. cfunction:: PyObject* PyLong_FromSsize_t(Py_ssize_t v) +.. c:function:: PyObject* PyLong_FromSsize_t(Py_ssize_t v) - Return a new :ctype:`PyLongObject` object from a C :ctype:`Py_ssize_t`, or + Return a new :c:type:`PyLongObject` object from a C :c:type:`Py_ssize_t`, or *NULL* on failure. -.. cfunction:: PyObject* PyLong_FromSize_t(size_t v) +.. c:function:: PyObject* PyLong_FromSize_t(size_t v) - Return a new :ctype:`PyLongObject` object from a C :ctype:`size_t`, or + Return a new :c:type:`PyLongObject` object from a C :c:type:`size_t`, or *NULL* on failure. -.. cfunction:: PyObject* PyLong_FromLongLong(PY_LONG_LONG v) +.. c:function:: PyObject* PyLong_FromLongLong(PY_LONG_LONG v) - Return a new :ctype:`PyLongObject` object from a C :ctype:`long long`, or *NULL* + Return a new :c:type:`PyLongObject` object from a C :c:type:`long long`, or *NULL* on failure. -.. cfunction:: PyObject* PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG v) +.. c:function:: PyObject* PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG v) - Return a new :ctype:`PyLongObject` object from a C :ctype:`unsigned long long`, + Return a new :c:type:`PyLongObject` object from a C :c:type:`unsigned long long`, or *NULL* on failure. -.. cfunction:: PyObject* PyLong_FromDouble(double v) +.. c:function:: PyObject* PyLong_FromDouble(double v) - Return a new :ctype:`PyLongObject` object from the integer part of *v*, or + Return a new :c:type:`PyLongObject` object from the integer part of *v*, or *NULL* on failure. -.. cfunction:: PyObject* PyLong_FromString(char *str, char **pend, int base) +.. c:function:: PyObject* PyLong_FromString(char *str, char **pend, int base) - Return a new :ctype:`PyLongObject` based on the string value in *str*, which + Return a new :c:type:`PyLongObject` based on the string value in *str*, which is interpreted according to the radix in *base*. If *pend* is non-*NULL*, *\*pend* will point to the first character in *str* which follows the representation of the number. If *base* is ``0``, the radix will be @@ -94,34 +94,34 @@ All integers are implemented as "long" integer objects of arbitrary size. ignored. If there are no digits, :exc:`ValueError` will be raised. -.. cfunction:: PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) +.. c:function:: PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) Convert a sequence of Unicode digits to a Python integer value. The Unicode - string is first encoded to a byte string using :cfunc:`PyUnicode_EncodeDecimal` - and then converted using :cfunc:`PyLong_FromString`. + string is first encoded to a byte string using :c:func:`PyUnicode_EncodeDecimal` + and then converted using :c:func:`PyLong_FromString`. -.. cfunction:: PyObject* PyLong_FromVoidPtr(void *p) +.. c:function:: PyObject* PyLong_FromVoidPtr(void *p) Create a Python integer from the pointer *p*. The pointer value can be - retrieved from the resulting value using :cfunc:`PyLong_AsVoidPtr`. + retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`. .. XXX alias PyLong_AS_LONG (for now) -.. cfunction:: long PyLong_AsLong(PyObject *pylong) +.. c:function:: long PyLong_AsLong(PyObject *pylong) .. index:: single: LONG_MAX single: OverflowError (built-in exception) - Return a C :ctype:`long` representation of the contents of *pylong*. If + Return a C :c:type:`long` representation of the contents of *pylong*. If *pylong* is greater than :const:`LONG_MAX`, raise an :exc:`OverflowError`, and return -1. Convert non-long objects automatically to long first, and return -1 if that raises exceptions. -.. cfunction:: long PyLong_AsLongAndOverflow(PyObject *pylong, int *overflow) +.. c:function:: long PyLong_AsLongAndOverflow(PyObject *pylong, int *overflow) - Return a C :ctype:`long` representation of the contents of + Return a C :c:type:`long` representation of the contents of *pylong*. If *pylong* is greater than :const:`LONG_MAX` or less than :const:`LONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and return ``-1``; otherwise, set *\*overflow* to @@ -130,9 +130,9 @@ All integers are implemented as "long" integer objects of arbitrary size. be ``0``. -.. cfunction:: PY_LONG_LONG PyLong_AsLongLongAndOverflow(PyObject *pylong, int *overflow) +.. c:function:: PY_LONG_LONG PyLong_AsLongLongAndOverflow(PyObject *pylong, int *overflow) - Return a C :ctype:`long long` representation of the contents of + Return a C :c:type:`long long` representation of the contents of *pylong*. If *pylong* is greater than :const:`PY_LLONG_MAX` or less than :const:`PY_LLONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and return ``-1``; otherwise, set *\*overflow* to @@ -143,52 +143,52 @@ All integers are implemented as "long" integer objects of arbitrary size. .. versionadded:: 3.2 -.. cfunction:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) +.. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) .. index:: single: PY_SSIZE_T_MAX single: OverflowError (built-in exception) - Return a C :ctype:`Py_ssize_t` representation of the contents of *pylong*. + Return a C :c:type:`Py_ssize_t` representation of the contents of *pylong*. If *pylong* is greater than :const:`PY_SSIZE_T_MAX`, an :exc:`OverflowError` is raised and ``-1`` will be returned. -.. cfunction:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong) +.. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong) .. index:: single: ULONG_MAX single: OverflowError (built-in exception) - Return a C :ctype:`unsigned long` representation of the contents of *pylong*. + Return a C :c:type:`unsigned long` representation of the contents of *pylong*. If *pylong* is greater than :const:`ULONG_MAX`, an :exc:`OverflowError` is raised. -.. cfunction:: size_t PyLong_AsSize_t(PyObject *pylong) +.. c:function:: size_t PyLong_AsSize_t(PyObject *pylong) - Return a :ctype:`size_t` representation of the contents of *pylong*. If - *pylong* is greater than the maximum value for a :ctype:`size_t`, an + Return a :c:type:`size_t` representation of the contents of *pylong*. If + *pylong* is greater than the maximum value for a :c:type:`size_t`, an :exc:`OverflowError` is raised. -.. cfunction:: PY_LONG_LONG PyLong_AsLongLong(PyObject *pylong) +.. c:function:: PY_LONG_LONG PyLong_AsLongLong(PyObject *pylong) .. index:: single: OverflowError (built-in exception) - Return a C :ctype:`long long` from a Python integer. If *pylong* - cannot be represented as a :ctype:`long long`, an + Return a C :c:type:`long long` from a Python integer. If *pylong* + cannot be represented as a :c:type:`long long`, an :exc:`OverflowError` is raised and ``-1`` is returned. -.. cfunction:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *pylong) +.. c:function:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *pylong) .. index:: single: OverflowError (built-in exception) - Return a C :ctype:`unsigned long long` from a Python integer. If - *pylong* cannot be represented as an :ctype:`unsigned long long`, + Return a C :c:type:`unsigned long long` from a Python integer. If + *pylong* cannot be represented as an :c:type:`unsigned long long`, an :exc:`OverflowError` is raised and ``(unsigned long long)-1`` is returned. @@ -196,28 +196,28 @@ All integers are implemented as "long" integer objects of arbitrary size. A negative *pylong* now raises :exc:`OverflowError`, not :exc:`TypeError`. -.. cfunction:: unsigned long PyLong_AsUnsignedLongMask(PyObject *io) +.. c:function:: unsigned long PyLong_AsUnsignedLongMask(PyObject *io) - Return a C :ctype:`unsigned long` from a Python integer, without checking for + Return a C :c:type:`unsigned long` from a Python integer, without checking for overflow. -.. cfunction:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(PyObject *io) +.. c:function:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(PyObject *io) - Return a C :ctype:`unsigned long long` from a Python integer, without + Return a C :c:type:`unsigned long long` from a Python integer, without checking for overflow. -.. cfunction:: double PyLong_AsDouble(PyObject *pylong) +.. c:function:: double PyLong_AsDouble(PyObject *pylong) - Return a C :ctype:`double` representation of the contents of *pylong*. If - *pylong* cannot be approximately represented as a :ctype:`double`, an + Return a C :c:type:`double` representation of the contents of *pylong*. If + *pylong* cannot be approximately represented as a :c:type:`double`, an :exc:`OverflowError` exception is raised and ``-1.0`` will be returned. -.. cfunction:: void* PyLong_AsVoidPtr(PyObject *pylong) +.. c:function:: void* PyLong_AsVoidPtr(PyObject *pylong) - Convert a Python integer *pylong* to a C :ctype:`void` pointer. + Convert a Python integer *pylong* to a C :c:type:`void` pointer. If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This - is only assured to produce a usable :ctype:`void` pointer for values created - with :cfunc:`PyLong_FromVoidPtr`. + is only assured to produce a usable :c:type:`void` pointer for values created + with :c:func:`PyLong_FromVoidPtr`. diff --git a/Doc/c-api/mapping.rst b/Doc/c-api/mapping.rst index 5b2de14..0ef2961 100644 --- a/Doc/c-api/mapping.rst +++ b/Doc/c-api/mapping.rst @@ -6,13 +6,13 @@ Mapping Protocol ================ -.. cfunction:: int PyMapping_Check(PyObject *o) +.. c:function:: int PyMapping_Check(PyObject *o) Return ``1`` if the object provides mapping protocol, and ``0`` otherwise. This function always succeeds. -.. cfunction:: Py_ssize_t PyMapping_Size(PyObject *o) +.. c:function:: Py_ssize_t PyMapping_Size(PyObject *o) Py_ssize_t PyMapping_Length(PyObject *o) .. index:: builtin: len @@ -22,58 +22,58 @@ Mapping Protocol expression ``len(o)``. -.. cfunction:: int PyMapping_DelItemString(PyObject *o, char *key) +.. c:function:: int PyMapping_DelItemString(PyObject *o, char *key) Remove the mapping for object *key* from the object *o*. Return ``-1`` on failure. This is equivalent to the Python statement ``del o[key]``. -.. cfunction:: int PyMapping_DelItem(PyObject *o, PyObject *key) +.. c:function:: int PyMapping_DelItem(PyObject *o, PyObject *key) Remove the mapping for object *key* from the object *o*. Return ``-1`` on failure. This is equivalent to the Python statement ``del o[key]``. -.. cfunction:: int PyMapping_HasKeyString(PyObject *o, char *key) +.. c:function:: int PyMapping_HasKeyString(PyObject *o, char *key) On success, return ``1`` if the mapping object has the key *key* and ``0`` otherwise. This is equivalent to the Python expression ``key in o``. This function always succeeds. -.. cfunction:: int PyMapping_HasKey(PyObject *o, PyObject *key) +.. c:function:: int PyMapping_HasKey(PyObject *o, PyObject *key) Return ``1`` if the mapping object has the key *key* and ``0`` otherwise. This is equivalent to the Python expression ``key in o``. This function always succeeds. -.. cfunction:: PyObject* PyMapping_Keys(PyObject *o) +.. c:function:: PyObject* PyMapping_Keys(PyObject *o) On success, return a list of the keys in object *o*. On failure, return *NULL*. This is equivalent to the Python expression ``list(o.keys())``. -.. cfunction:: PyObject* PyMapping_Values(PyObject *o) +.. c:function:: PyObject* PyMapping_Values(PyObject *o) On success, return a list of the values in object *o*. On failure, return *NULL*. This is equivalent to the Python expression ``list(o.values())``. -.. cfunction:: PyObject* PyMapping_Items(PyObject *o) +.. c:function:: PyObject* PyMapping_Items(PyObject *o) On success, return a list of the items in object *o*, where each item is a tuple containing a key-value pair. On failure, return *NULL*. This is equivalent to the Python expression ``list(o.items())``. -.. cfunction:: PyObject* PyMapping_GetItemString(PyObject *o, char *key) +.. c:function:: PyObject* PyMapping_GetItemString(PyObject *o, char *key) Return element of *o* corresponding to the object *key* or *NULL* on failure. This is the equivalent of the Python expression ``o[key]``. -.. cfunction:: int PyMapping_SetItemString(PyObject *o, char *key, PyObject *v) +.. c:function:: int PyMapping_SetItemString(PyObject *o, char *key, PyObject *v) Map the object *key* to the value *v* in object *o*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``o[key] = v``. diff --git a/Doc/c-api/marshal.rst b/Doc/c-api/marshal.rst index 04b0b88..da402a8 100644 --- a/Doc/c-api/marshal.rst +++ b/Doc/c-api/marshal.rst @@ -19,20 +19,20 @@ unmarshalling. Version 2 uses a binary format for floating point numbers. *Py_MARSHAL_VERSION* indicates the current file format (currently 2). -.. cfunction:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version) +.. c:function:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version) - Marshal a :ctype:`long` integer, *value*, to *file*. This will only write + Marshal a :c:type:`long` integer, *value*, to *file*. This will only write the least-significant 32 bits of *value*; regardless of the size of the - native :ctype:`long` type. *version* indicates the file format. + native :c:type:`long` type. *version* indicates the file format. -.. cfunction:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version) +.. c:function:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version) Marshal a Python object, *value*, to *file*. *version* indicates the file format. -.. cfunction:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version) +.. c:function:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version) Return a string object containing the marshalled representation of *value*. *version* indicates the file format. @@ -47,31 +47,31 @@ no error. What's the right way to tell? Should only non-negative values be written using these routines? -.. cfunction:: long PyMarshal_ReadLongFromFile(FILE *file) +.. c:function:: long PyMarshal_ReadLongFromFile(FILE *file) - Return a C :ctype:`long` from the data stream in a :ctype:`FILE\*` opened + Return a C :c:type:`long` from the data stream in a :c:type:`FILE\*` opened for reading. Only a 32-bit value can be read in using this function, - regardless of the native size of :ctype:`long`. + regardless of the native size of :c:type:`long`. -.. cfunction:: int PyMarshal_ReadShortFromFile(FILE *file) +.. c:function:: int PyMarshal_ReadShortFromFile(FILE *file) - Return a C :ctype:`short` from the data stream in a :ctype:`FILE\*` opened + Return a C :c:type:`short` from the data stream in a :c:type:`FILE\*` opened for reading. Only a 16-bit value can be read in using this function, - regardless of the native size of :ctype:`short`. + regardless of the native size of :c:type:`short`. -.. cfunction:: PyObject* PyMarshal_ReadObjectFromFile(FILE *file) +.. c:function:: PyObject* PyMarshal_ReadObjectFromFile(FILE *file) - Return a Python object from the data stream in a :ctype:`FILE\*` opened for + Return a Python object from the data stream in a :c:type:`FILE\*` opened for reading. On error, sets the appropriate exception (:exc:`EOFError` or :exc:`TypeError`) and returns *NULL*. -.. cfunction:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file) +.. c:function:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file) - Return a Python object from the data stream in a :ctype:`FILE\*` opened for - reading. Unlike :cfunc:`PyMarshal_ReadObjectFromFile`, this function + Return a Python object from the data stream in a :c:type:`FILE\*` opened for + reading. Unlike :c:func:`PyMarshal_ReadObjectFromFile`, this function assumes that no further objects will be read from the file, allowing it to aggressively load file data into memory so that the de-serialization can operate from data in memory rather than reading a byte at a time from the @@ -80,7 +80,7 @@ written using these routines? (:exc:`EOFError` or :exc:`TypeError`) and returns *NULL*. -.. cfunction:: PyObject* PyMarshal_ReadObjectFromString(char *string, Py_ssize_t len) +.. c:function:: PyObject* PyMarshal_ReadObjectFromString(char *string, Py_ssize_t len) Return a Python object from the data stream in a character buffer containing *len* bytes pointed to by *string*. On error, sets the diff --git a/Doc/c-api/memory.rst b/Doc/c-api/memory.rst index 81d7cd9..b80b3d5 100644 --- a/Doc/c-api/memory.rst +++ b/Doc/c-api/memory.rst @@ -47,8 +47,8 @@ API functions listed in this document. single: free() To avoid memory corruption, extension writers should never try to operate on -Python objects with the functions exported by the C library: :cfunc:`malloc`, -:cfunc:`calloc`, :cfunc:`realloc` and :cfunc:`free`. This will result in mixed +Python objects with the functions exported by the C library: :c:func:`malloc`, +:c:func:`calloc`, :c:func:`realloc` and :c:func:`free`. This will result in mixed calls between the C allocator and the Python memory manager with fatal consequences, because they implement different algorithms and operate on different heaps. However, one may safely allocate and release memory blocks @@ -94,65 +94,65 @@ behavior when requesting zero bytes, are available for allocating and releasing memory from the Python heap: -.. cfunction:: void* PyMem_Malloc(size_t n) +.. c:function:: void* PyMem_Malloc(size_t n) - Allocates *n* bytes and returns a pointer of type :ctype:`void\*` to the + Allocates *n* bytes and returns a pointer of type :c:type:`void\*` to the allocated memory, or *NULL* if the request fails. Requesting zero bytes returns - a distinct non-*NULL* pointer if possible, as if :cfunc:`PyMem_Malloc(1)` had + a distinct non-*NULL* pointer if possible, as if :c:func:`PyMem_Malloc(1)` had been called instead. The memory will not have been initialized in any way. -.. cfunction:: void* PyMem_Realloc(void *p, size_t n) +.. c:function:: void* PyMem_Realloc(void *p, size_t n) Resizes the memory block pointed to by *p* to *n* bytes. The contents will be unchanged to the minimum of the old and the new sizes. If *p* is *NULL*, the - call is equivalent to :cfunc:`PyMem_Malloc(n)`; else if *n* is equal to zero, + call is equivalent to :c:func:`PyMem_Malloc(n)`; else if *n* is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-*NULL*. Unless *p* is *NULL*, it must have been returned by a previous call - to :cfunc:`PyMem_Malloc` or :cfunc:`PyMem_Realloc`. If the request fails, - :cfunc:`PyMem_Realloc` returns *NULL* and *p* remains a valid pointer to the + to :c:func:`PyMem_Malloc` or :c:func:`PyMem_Realloc`. If the request fails, + :c:func:`PyMem_Realloc` returns *NULL* and *p* remains a valid pointer to the previous memory area. -.. cfunction:: void PyMem_Free(void *p) +.. c:function:: void PyMem_Free(void *p) Frees the memory block pointed to by *p*, which must have been returned by a - previous call to :cfunc:`PyMem_Malloc` or :cfunc:`PyMem_Realloc`. Otherwise, or - if :cfunc:`PyMem_Free(p)` has been called before, undefined behavior occurs. If + previous call to :c:func:`PyMem_Malloc` or :c:func:`PyMem_Realloc`. Otherwise, or + if :c:func:`PyMem_Free(p)` has been called before, undefined behavior occurs. If *p* is *NULL*, no operation is performed. The following type-oriented macros are provided for convenience. Note that *TYPE* refers to any C type. -.. cfunction:: TYPE* PyMem_New(TYPE, size_t n) +.. c:function:: TYPE* PyMem_New(TYPE, size_t n) - Same as :cfunc:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of - memory. Returns a pointer cast to :ctype:`TYPE\*`. The memory will not have + Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of + memory. Returns a pointer cast to :c:type:`TYPE\*`. The memory will not have been initialized in any way. -.. cfunction:: TYPE* PyMem_Resize(void *p, TYPE, size_t n) +.. c:function:: TYPE* PyMem_Resize(void *p, TYPE, size_t n) - Same as :cfunc:`PyMem_Realloc`, but the memory block is resized to ``(n * - sizeof(TYPE))`` bytes. Returns a pointer cast to :ctype:`TYPE\*`. On return, + Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n * + sizeof(TYPE))`` bytes. Returns a pointer cast to :c:type:`TYPE\*`. On return, *p* will be a pointer to the new memory area, or *NULL* in the event of failure. This is a C preprocessor macro; p is always reassigned. Save the original value of p to avoid losing memory when handling errors. -.. cfunction:: void PyMem_Del(void *p) +.. c:function:: void PyMem_Del(void *p) - Same as :cfunc:`PyMem_Free`. + Same as :c:func:`PyMem_Free`. In addition, the following macro sets are provided for calling the Python memory allocator directly, without involving the C API functions listed above. However, note that their use does not preserve binary compatibility across Python versions and is therefore deprecated in extension modules. -:cfunc:`PyMem_MALLOC`, :cfunc:`PyMem_REALLOC`, :cfunc:`PyMem_FREE`. +:c:func:`PyMem_MALLOC`, :c:func:`PyMem_REALLOC`, :c:func:`PyMem_FREE`. -:cfunc:`PyMem_NEW`, :cfunc:`PyMem_RESIZE`, :cfunc:`PyMem_DEL`. +:c:func:`PyMem_NEW`, :c:func:`PyMem_RESIZE`, :c:func:`PyMem_DEL`. .. _memoryexamples: @@ -201,8 +201,8 @@ allocators operating on different heaps. :: free(buf1); /* Fatal -- should be PyMem_Del() */ In addition to the functions aimed at handling raw memory blocks from the Python -heap, objects in Python are allocated and released with :cfunc:`PyObject_New`, -:cfunc:`PyObject_NewVar` and :cfunc:`PyObject_Del`. +heap, objects in Python are allocated and released with :c:func:`PyObject_New`, +:c:func:`PyObject_NewVar` and :c:func:`PyObject_Del`. These will be explained in the next chapter on defining and implementing new object types in C. diff --git a/Doc/c-api/memoryview.rst b/Doc/c-api/memoryview.rst index 9003d3e..34ecd12 100644 --- a/Doc/c-api/memoryview.rst +++ b/Doc/c-api/memoryview.rst @@ -13,22 +13,22 @@ A :class:`memoryview` object exposes the C level :ref:`buffer interface any other object. -.. cfunction:: PyObject *PyMemoryView_FromObject(PyObject *obj) +.. c:function:: PyObject *PyMemoryView_FromObject(PyObject *obj) Create a memoryview object from an object that provides the buffer interface. If *obj* supports writable buffer exports, the memoryview object will be readable and writable, other it will be read-only. -.. cfunction:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view) +.. c:function:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view) Create a memoryview object wrapping the given buffer structure *view*. The memoryview object then owns the buffer represented by *view*, which - means you shouldn't try to call :cfunc:`PyBuffer_Release` yourself: it + means you shouldn't try to call :c:func:`PyBuffer_Release` yourself: it will be done on deallocation of the memoryview object. -.. cfunction:: PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order) +.. c:function:: PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order) Create a memoryview object to a contiguous chunk of memory (in either 'C' or 'F'ortran *order*) from an object that defines the buffer @@ -37,13 +37,13 @@ any other object. new bytes object. -.. cfunction:: int PyMemoryView_Check(PyObject *obj) +.. c:function:: int PyMemoryView_Check(PyObject *obj) Return true if the object *obj* is a memoryview object. It is not currently allowed to create subclasses of :class:`memoryview`. -.. cfunction:: Py_buffer *PyMemoryView_GET_BUFFER(PyObject *obj) +.. c:function:: Py_buffer *PyMemoryView_GET_BUFFER(PyObject *obj) Return a pointer to the buffer structure wrapped by the given memoryview object. The object **must** be a memoryview instance; diff --git a/Doc/c-api/method.rst b/Doc/c-api/method.rst index d8b2ed8..27f9576 100644 --- a/Doc/c-api/method.rst +++ b/Doc/c-api/method.rst @@ -7,38 +7,38 @@ Instance Method Objects .. index:: object: instancemethod -An instance method is a wrapper for a :cdata:`PyCFunction` and the new way -to bind a :cdata:`PyCFunction` to a class object. It replaces the former call +An instance method is a wrapper for a :c:data:`PyCFunction` and the new way +to bind a :c:data:`PyCFunction` to a class object. It replaces the former call ``PyMethod_New(func, NULL, class)``. -.. cvar:: PyTypeObject PyInstanceMethod_Type +.. c:var:: PyTypeObject PyInstanceMethod_Type - This instance of :ctype:`PyTypeObject` represents the Python instance + This instance of :c:type:`PyTypeObject` represents the Python instance method type. It is not exposed to Python programs. -.. cfunction:: int PyInstanceMethod_Check(PyObject *o) +.. c:function:: int PyInstanceMethod_Check(PyObject *o) Return true if *o* is an instance method object (has type - :cdata:`PyInstanceMethod_Type`). The parameter must not be *NULL*. + :c:data:`PyInstanceMethod_Type`). The parameter must not be *NULL*. -.. cfunction:: PyObject* PyInstanceMethod_New(PyObject *func) +.. c:function:: PyObject* PyInstanceMethod_New(PyObject *func) Return a new instance method object, with *func* being any callable object *func* is is the function that will be called when the instance method is called. -.. cfunction:: PyObject* PyInstanceMethod_Function(PyObject *im) +.. c:function:: PyObject* PyInstanceMethod_Function(PyObject *im) Return the function object associated with the instance method *im*. -.. cfunction:: PyObject* PyInstanceMethod_GET_FUNCTION(PyObject *im) +.. c:function:: PyObject* PyInstanceMethod_GET_FUNCTION(PyObject *im) - Macro version of :cfunc:`PyInstanceMethod_Function` which avoids error checking. + Macro version of :c:func:`PyInstanceMethod_Function` which avoids error checking. .. _method-objects: @@ -53,48 +53,48 @@ an user-defined class. Unbound methods (methods bound to a class object) are no longer available. -.. cvar:: PyTypeObject PyMethod_Type +.. c:var:: PyTypeObject PyMethod_Type .. index:: single: MethodType (in module types) - This instance of :ctype:`PyTypeObject` represents the Python method type. This + This instance of :c:type:`PyTypeObject` represents the Python method type. This is exposed to Python programs as ``types.MethodType``. -.. cfunction:: int PyMethod_Check(PyObject *o) +.. c:function:: int PyMethod_Check(PyObject *o) - Return true if *o* is a method object (has type :cdata:`PyMethod_Type`). The + Return true if *o* is a method object (has type :c:data:`PyMethod_Type`). The parameter must not be *NULL*. -.. cfunction:: PyObject* PyMethod_New(PyObject *func, PyObject *self) +.. c:function:: PyObject* PyMethod_New(PyObject *func, PyObject *self) Return a new method object, with *func* being any callable object and *self* the instance the method should be bound. *func* is is the function that will be called when the method is called. *self* must not be *NULL*. -.. cfunction:: PyObject* PyMethod_Function(PyObject *meth) +.. c:function:: PyObject* PyMethod_Function(PyObject *meth) Return the function object associated with the method *meth*. -.. cfunction:: PyObject* PyMethod_GET_FUNCTION(PyObject *meth) +.. c:function:: PyObject* PyMethod_GET_FUNCTION(PyObject *meth) - Macro version of :cfunc:`PyMethod_Function` which avoids error checking. + Macro version of :c:func:`PyMethod_Function` which avoids error checking. -.. cfunction:: PyObject* PyMethod_Self(PyObject *meth) +.. c:function:: PyObject* PyMethod_Self(PyObject *meth) Return the instance associated with the method *meth*. -.. cfunction:: PyObject* PyMethod_GET_SELF(PyObject *meth) +.. c:function:: PyObject* PyMethod_GET_SELF(PyObject *meth) - Macro version of :cfunc:`PyMethod_Self` which avoids error checking. + Macro version of :c:func:`PyMethod_Self` which avoids error checking. -.. cfunction:: int PyMethod_ClearFreeList() +.. c:function:: int PyMethod_ClearFreeList() Clear the free list. Return the total number of freed items. diff --git a/Doc/c-api/module.rst b/Doc/c-api/module.rst index 9e1af09..1a64947 100644 --- a/Doc/c-api/module.rst +++ b/Doc/c-api/module.rst @@ -10,26 +10,26 @@ Module Objects There are only a few functions special to module objects. -.. cvar:: PyTypeObject PyModule_Type +.. c:var:: PyTypeObject PyModule_Type .. index:: single: ModuleType (in module types) - This instance of :ctype:`PyTypeObject` represents the Python module type. This + This instance of :c:type:`PyTypeObject` represents the Python module type. This is exposed to Python programs as ``types.ModuleType``. -.. cfunction:: int PyModule_Check(PyObject *p) +.. c:function:: int PyModule_Check(PyObject *p) Return true if *p* is a module object, or a subtype of a module object. -.. cfunction:: int PyModule_CheckExact(PyObject *p) +.. c:function:: int PyModule_CheckExact(PyObject *p) Return true if *p* is a module object, but not a subtype of - :cdata:`PyModule_Type`. + :c:data:`PyModule_Type`. -.. cfunction:: PyObject* PyModule_New(const char *name) +.. c:function:: PyObject* PyModule_New(const char *name) .. index:: single: __name__ (module attribute) @@ -41,18 +41,18 @@ There are only a few functions special to module objects. the caller is responsible for providing a :attr:`__file__` attribute. -.. cfunction:: PyObject* PyModule_GetDict(PyObject *module) +.. c:function:: PyObject* PyModule_GetDict(PyObject *module) .. index:: single: __dict__ (module attribute) Return the dictionary object that implements *module*'s namespace; this object is the same as the :attr:`__dict__` attribute of the module object. This function never fails. It is recommended extensions use other - :cfunc:`PyModule_\*` and :cfunc:`PyObject_\*` functions rather than directly + :c:func:`PyModule_\*` and :c:func:`PyObject_\*` functions rather than directly manipulate a module's :attr:`__dict__`. -.. cfunction:: char* PyModule_GetName(PyObject *module) +.. c:function:: char* PyModule_GetName(PyObject *module) .. index:: single: __name__ (module attribute) @@ -62,17 +62,17 @@ There are only a few functions special to module objects. or if it is not a string, :exc:`SystemError` is raised and *NULL* is returned. -.. cfunction:: char* PyModule_GetFilename(PyObject *module) +.. c:function:: char* PyModule_GetFilename(PyObject *module) - Similar to :cfunc:`PyModule_GetFilenameObject` but return the filename + Similar to :c:func:`PyModule_GetFilenameObject` but return the filename encoded to 'utf-8'. .. deprecated:: 3.2 - :cfunc:`PyModule_GetFilename` raises :ctype:`UnicodeEncodeError` on - unencodable filenames, use :cfunc:`PyModule_GetFilenameObject` instead. + :c:func:`PyModule_GetFilename` raises :c:type:`UnicodeEncodeError` on + unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead. -.. cfunction:: PyObject* PyModule_GetFilenameObject(PyObject *module) +.. c:function:: PyObject* PyModule_GetFilenameObject(PyObject *module) .. index:: single: __file__ (module attribute) @@ -81,23 +81,23 @@ There are only a few functions special to module objects. Return the name of the file from which *module* was loaded using *module*'s :attr:`__file__` attribute. If this is not defined, or if it is not a unicode string, raise :exc:`SystemError` and return *NULL*; otherwise return - a reference to a :ctype:`PyUnicodeObject`. + a reference to a :c:type:`PyUnicodeObject`. .. versionadded:: 3.2 -.. cfunction:: void* PyModule_GetState(PyObject *module) +.. c:function:: void* PyModule_GetState(PyObject *module) Return the "state" of the module, that is, a pointer to the block of memory allocated at module creation time, or *NULL*. See - :cmember:`PyModuleDef.m_size`. + :c:member:`PyModuleDef.m_size`. -.. cfunction:: PyModuleDef* PyModule_GetDef(PyObject *module) +.. c:function:: PyModuleDef* PyModule_GetDef(PyObject *module) - Return a pointer to the :ctype:`PyModuleDef` struct from which the module was + Return a pointer to the :c:type:`PyModuleDef` struct from which the module was created, or *NULL* if the module wasn't created with - :cfunc:`PyModule_Create`. + :c:func:`PyModule_Create`. Initializing C modules @@ -105,14 +105,14 @@ Initializing C modules These functions are usually used in the module initialization function. -.. cfunction:: PyObject* PyModule_Create(PyModuleDef *module) +.. c:function:: PyObject* PyModule_Create(PyModuleDef *module) Create a new module object, given the definition in *module*. This behaves - like :cfunc:`PyModule_Create2` with *module_api_version* set to + like :c:func:`PyModule_Create2` with *module_api_version* set to :const:`PYTHON_API_VERSION`. -.. cfunction:: PyObject* PyModule_Create2(PyModuleDef *module, int module_api_version) +.. c:function:: PyObject* PyModule_Create2(PyModuleDef *module, int module_api_version) Create a new module object, given the definition in *module*, assuming the API version *module_api_version*. If that version does not match the version @@ -120,89 +120,89 @@ These functions are usually used in the module initialization function. .. note:: - Most uses of this function should be using :cfunc:`PyModule_Create` + Most uses of this function should be using :c:func:`PyModule_Create` instead; only use this if you are sure you need it. -.. ctype:: PyModuleDef +.. c:type:: PyModuleDef This struct holds all information that is needed to create a module object. There is usually only one static variable of that type for each module, which - is statically initialized and then passed to :cfunc:`PyModule_Create` in the + is statically initialized and then passed to :c:func:`PyModule_Create` in the module initialization function. - .. cmember:: PyModuleDef_Base m_base + .. c:member:: PyModuleDef_Base m_base Always initialize this member to :const:`PyModuleDef_HEAD_INIT`. - .. cmember:: char* m_name + .. c:member:: char* m_name Name for the new module. - .. cmember:: char* m_doc + .. c:member:: char* m_doc Docstring for the module; usually a docstring variable created with - :cfunc:`PyDoc_STRVAR` is used. + :c:func:`PyDoc_STRVAR` is used. - .. cmember:: Py_ssize_t m_size + .. c:member:: Py_ssize_t m_size If the module object needs additional memory, this should be set to the number of bytes to allocate; a pointer to the block of memory can be - retrieved with :cfunc:`PyModule_GetState`. If no memory is needed, set + retrieved with :c:func:`PyModule_GetState`. If no memory is needed, set this to ``-1``. This memory should be used, rather than static globals, to hold per-module state, since it is then safe for use in multiple sub-interpreters. It is - freed when the module object is deallocated, after the :cmember:`m_free` + freed when the module object is deallocated, after the :c:member:`m_free` function has been called, if present. - .. cmember:: PyMethodDef* m_methods + .. c:member:: PyMethodDef* m_methods A pointer to a table of module-level functions, described by - :ctype:`PyMethodDef` values. Can be *NULL* if no functions are present. + :c:type:`PyMethodDef` values. Can be *NULL* if no functions are present. - .. cmember:: inquiry m_reload + .. c:member:: inquiry m_reload Currently unused, should be *NULL*. - .. cmember:: traverseproc m_traverse + .. c:member:: traverseproc m_traverse A traversal function to call during GC traversal of the module object, or *NULL* if not needed. - .. cmember:: inquiry m_clear + .. c:member:: inquiry m_clear A clear function to call during GC clearing of the module object, or *NULL* if not needed. - .. cmember:: freefunc m_free + .. c:member:: freefunc m_free A function to call during deallocation of the module object, or *NULL* if not needed. -.. cfunction:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value) +.. c:function:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value) Add an object to *module* as *name*. This is a convenience function which can be used from the module's initialization function. This steals a reference to *value*. Return ``-1`` on error, ``0`` on success. -.. cfunction:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value) +.. c:function:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value) Add an integer constant to *module* as *name*. This convenience function can be used from the module's initialization function. Return ``-1`` on error, ``0`` on success. -.. cfunction:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value) +.. c:function:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value) Add a string constant to *module* as *name*. This convenience function can be used from the module's initialization function. The string *value* must be null-terminated. Return ``-1`` on error, ``0`` on success. -.. cfunction:: int PyModule_AddIntMacro(PyObject *module, macro) +.. c:function:: int PyModule_AddIntMacro(PyObject *module, macro) Add an int constant to *module*. The name and the value are taken from *macro*. For example ``PyModule_AddConstant(module, AF_INET)`` adds the int @@ -210,6 +210,6 @@ These functions are usually used in the module initialization function. Return ``-1`` on error, ``0`` on success. -.. cfunction:: int PyModule_AddStringMacro(PyObject *module, macro) +.. c:function:: int PyModule_AddStringMacro(PyObject *module, macro) Add a string constant to *module*. diff --git a/Doc/c-api/none.rst b/Doc/c-api/none.rst index 70e2c04..b9ac269 100644 --- a/Doc/c-api/none.rst +++ b/Doc/c-api/none.rst @@ -7,20 +7,20 @@ The None Object .. index:: object: None -Note that the :ctype:`PyTypeObject` for ``None`` is not directly exposed in the +Note that the :c:type:`PyTypeObject` for ``None`` is not directly exposed in the Python/C API. Since ``None`` is a singleton, testing for object identity (using -``==`` in C) is sufficient. There is no :cfunc:`PyNone_Check` function for the +``==`` in C) is sufficient. There is no :c:func:`PyNone_Check` function for the same reason. -.. cvar:: PyObject* Py_None +.. c:var:: PyObject* Py_None The Python ``None`` object, denoting lack of value. This object has no methods. It needs to be treated just like any other object with respect to reference counts. -.. cmacro:: Py_RETURN_NONE +.. c:macro:: Py_RETURN_NONE - Properly handle returning :cdata:`Py_None` from within a C function (that is, + Properly handle returning :c:data:`Py_None` from within a C function (that is, increment the reference count of None and return it.) diff --git a/Doc/c-api/number.rst b/Doc/c-api/number.rst index d79b9fb..eda722d 100644 --- a/Doc/c-api/number.rst +++ b/Doc/c-api/number.rst @@ -6,37 +6,37 @@ Number Protocol =============== -.. cfunction:: int PyNumber_Check(PyObject *o) +.. c:function:: int PyNumber_Check(PyObject *o) Returns ``1`` if the object *o* provides numeric protocols, and false otherwise. This function always succeeds. -.. cfunction:: PyObject* PyNumber_Add(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_Add(PyObject *o1, PyObject *o2) Returns the result of adding *o1* and *o2*, or *NULL* on failure. This is the equivalent of the Python expression ``o1 + o2``. -.. cfunction:: PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2) Returns the result of subtracting *o2* from *o1*, or *NULL* on failure. This is the equivalent of the Python expression ``o1 - o2``. -.. cfunction:: PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2) Returns the result of multiplying *o1* and *o2*, or *NULL* on failure. This is the equivalent of the Python expression ``o1 * o2``. -.. cfunction:: PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2) Return the floor of *o1* divided by *o2*, or *NULL* on failure. This is equivalent to the "classic" division of integers. -.. cfunction:: PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2) Return a reasonable approximation for the mathematical value of *o1* divided by *o2*, or *NULL* on failure. The return value is "approximate" because binary @@ -45,13 +45,13 @@ Number Protocol passed two integers. -.. cfunction:: PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2) Returns the remainder of dividing *o1* by *o2*, or *NULL* on failure. This is the equivalent of the Python expression ``o1 % o2``. -.. cfunction:: PyObject* PyNumber_Divmod(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_Divmod(PyObject *o1, PyObject *o2) .. index:: builtin: divmod @@ -59,29 +59,29 @@ Number Protocol the equivalent of the Python expression ``divmod(o1, o2)``. -.. cfunction:: PyObject* PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3) +.. c:function:: PyObject* PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3) .. index:: builtin: pow See the built-in function :func:`pow`. Returns *NULL* on failure. This is the equivalent of the Python expression ``pow(o1, o2, o3)``, where *o3* is optional. - If *o3* is to be ignored, pass :cdata:`Py_None` in its place (passing *NULL* for + If *o3* is to be ignored, pass :c:data:`Py_None` in its place (passing *NULL* for *o3* would cause an illegal memory access). -.. cfunction:: PyObject* PyNumber_Negative(PyObject *o) +.. c:function:: PyObject* PyNumber_Negative(PyObject *o) Returns the negation of *o* on success, or *NULL* on failure. This is the equivalent of the Python expression ``-o``. -.. cfunction:: PyObject* PyNumber_Positive(PyObject *o) +.. c:function:: PyObject* PyNumber_Positive(PyObject *o) Returns *o* on success, or *NULL* on failure. This is the equivalent of the Python expression ``+o``. -.. cfunction:: PyObject* PyNumber_Absolute(PyObject *o) +.. c:function:: PyObject* PyNumber_Absolute(PyObject *o) .. index:: builtin: abs @@ -89,71 +89,71 @@ Number Protocol of the Python expression ``abs(o)``. -.. cfunction:: PyObject* PyNumber_Invert(PyObject *o) +.. c:function:: PyObject* PyNumber_Invert(PyObject *o) Returns the bitwise negation of *o* on success, or *NULL* on failure. This is the equivalent of the Python expression ``~o``. -.. cfunction:: PyObject* PyNumber_Lshift(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_Lshift(PyObject *o1, PyObject *o2) Returns the result of left shifting *o1* by *o2* on success, or *NULL* on failure. This is the equivalent of the Python expression ``o1 << o2``. -.. cfunction:: PyObject* PyNumber_Rshift(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_Rshift(PyObject *o1, PyObject *o2) Returns the result of right shifting *o1* by *o2* on success, or *NULL* on failure. This is the equivalent of the Python expression ``o1 >> o2``. -.. cfunction:: PyObject* PyNumber_And(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_And(PyObject *o1, PyObject *o2) Returns the "bitwise and" of *o1* and *o2* on success and *NULL* on failure. This is the equivalent of the Python expression ``o1 & o2``. -.. cfunction:: PyObject* PyNumber_Xor(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_Xor(PyObject *o1, PyObject *o2) Returns the "bitwise exclusive or" of *o1* by *o2* on success, or *NULL* on failure. This is the equivalent of the Python expression ``o1 ^ o2``. -.. cfunction:: PyObject* PyNumber_Or(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_Or(PyObject *o1, PyObject *o2) Returns the "bitwise or" of *o1* and *o2* on success, or *NULL* on failure. This is the equivalent of the Python expression ``o1 | o2``. -.. cfunction:: PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2) Returns the result of adding *o1* and *o2*, or *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 += o2``. -.. cfunction:: PyObject* PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2) Returns the result of subtracting *o2* from *o1*, or *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 -= o2``. -.. cfunction:: PyObject* PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2) Returns the result of multiplying *o1* and *o2*, or *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 *= o2``. -.. cfunction:: PyObject* PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2) Returns the mathematical floor of dividing *o1* by *o2*, or *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 //= o2``. -.. cfunction:: PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2) Return a reasonable approximation for the mathematical value of *o1* divided by *o2*, or *NULL* on failure. The return value is "approximate" because binary @@ -162,60 +162,60 @@ Number Protocol passed two integers. The operation is done *in-place* when *o1* supports it. -.. cfunction:: PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2) Returns the remainder of dividing *o1* by *o2*, or *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 %= o2``. -.. cfunction:: PyObject* PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3) +.. c:function:: PyObject* PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3) .. index:: builtin: pow See the built-in function :func:`pow`. Returns *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python - statement ``o1 **= o2`` when o3 is :cdata:`Py_None`, or an in-place variant of - ``pow(o1, o2, o3)`` otherwise. If *o3* is to be ignored, pass :cdata:`Py_None` + statement ``o1 **= o2`` when o3 is :c:data:`Py_None`, or an in-place variant of + ``pow(o1, o2, o3)`` otherwise. If *o3* is to be ignored, pass :c:data:`Py_None` in its place (passing *NULL* for *o3* would cause an illegal memory access). -.. cfunction:: PyObject* PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2) Returns the result of left shifting *o1* by *o2* on success, or *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 <<= o2``. -.. cfunction:: PyObject* PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2) Returns the result of right shifting *o1* by *o2* on success, or *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 >>= o2``. -.. cfunction:: PyObject* PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2) Returns the "bitwise and" of *o1* and *o2* on success and *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 &= o2``. -.. cfunction:: PyObject* PyNumber_InPlaceXor(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceXor(PyObject *o1, PyObject *o2) Returns the "bitwise exclusive or" of *o1* by *o2* on success, or *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 ^= o2``. -.. cfunction:: PyObject* PyNumber_InPlaceOr(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PyNumber_InPlaceOr(PyObject *o1, PyObject *o2) Returns the "bitwise or" of *o1* and *o2* on success, or *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 |= o2``. -.. cfunction:: PyObject* PyNumber_Long(PyObject *o) +.. c:function:: PyObject* PyNumber_Long(PyObject *o) .. index:: builtin: int @@ -223,7 +223,7 @@ Number Protocol failure. This is the equivalent of the Python expression ``int(o)``. -.. cfunction:: PyObject* PyNumber_Float(PyObject *o) +.. c:function:: PyObject* PyNumber_Float(PyObject *o) .. index:: builtin: float @@ -231,22 +231,22 @@ Number Protocol This is the equivalent of the Python expression ``float(o)``. -.. cfunction:: PyObject* PyNumber_Index(PyObject *o) +.. c:function:: PyObject* PyNumber_Index(PyObject *o) Returns the *o* converted to a Python int on success or *NULL* with a :exc:`TypeError` exception raised on failure. -.. cfunction:: PyObject* PyNumber_ToBase(PyObject *n, int base) +.. c:function:: PyObject* PyNumber_ToBase(PyObject *n, int base) Returns the integer *n* converted to *base* as a string with a base marker of ``'0b'``, ``'0o'``, or ``'0x'`` if applicable. When *base* is not 2, 8, 10, or 16, the format is ``'x#num'`` where x is the base. If *n* is not an int object, it is converted with - :cfunc:`PyNumber_Index` first. + :c:func:`PyNumber_Index` first. -.. cfunction:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc) +.. c:function:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc) Returns *o* converted to a Py_ssize_t value if *o* can be interpreted as an integer. If *o* can be converted to a Python int but the attempt to @@ -257,7 +257,7 @@ Number Protocol integer or *PY_SSIZE_T_MAX* for a positive integer. -.. cfunction:: int PyIndex_Check(PyObject *o) +.. c:function:: int PyIndex_Check(PyObject *o) Returns True if *o* is an index integer (has the nb_index slot of the tp_as_number structure filled in). diff --git a/Doc/c-api/objbuffer.rst b/Doc/c-api/objbuffer.rst index 728d383..e7f4fde 100644 --- a/Doc/c-api/objbuffer.rst +++ b/Doc/c-api/objbuffer.rst @@ -12,13 +12,13 @@ around the :ref:`new buffer protocol <bufferobjects>`, but they don't give you control over the lifetime of the resources acquired when a buffer is exported. -Therefore, it is recommended that you call :cfunc:`PyObject_GetBuffer` +Therefore, it is recommended that you call :c:func:`PyObject_GetBuffer` (or the ``y*`` or ``w*`` :ref:`format codes <arg-parsing>` with the -:cfunc:`PyArg_ParseTuple` family of functions) to get a buffer view over -an object, and :cfunc:`PyBuffer_Release` when the buffer view can be released. +:c:func:`PyArg_ParseTuple` family of functions) to get a buffer view over +an object, and :c:func:`PyBuffer_Release` when the buffer view can be released. -.. cfunction:: int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len) +.. c:function:: int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len) Returns a pointer to a read-only memory location usable as character-based input. The *obj* argument must support the single-segment character buffer @@ -27,7 +27,7 @@ an object, and :cfunc:`PyBuffer_Release` when the buffer view can be released. :exc:`TypeError` on error. -.. cfunction:: int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) +.. c:function:: int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) Returns a pointer to a read-only memory location containing arbitrary data. The *obj* argument must support the single-segment readable buffer @@ -36,13 +36,13 @@ an object, and :cfunc:`PyBuffer_Release` when the buffer view can be released. :exc:`TypeError` on error. -.. cfunction:: int PyObject_CheckReadBuffer(PyObject *o) +.. c:function:: int PyObject_CheckReadBuffer(PyObject *o) Returns ``1`` if *o* supports the single-segment readable buffer interface. Otherwise returns ``0``. -.. cfunction:: int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len) +.. c:function:: int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len) Returns a pointer to a writable memory location. The *obj* argument must support the single-segment, character buffer interface. On success, diff --git a/Doc/c-api/object.rst b/Doc/c-api/object.rst index a7be156..7efc0d2 100644 --- a/Doc/c-api/object.rst +++ b/Doc/c-api/object.rst @@ -6,7 +6,7 @@ Object Protocol =============== -.. cfunction:: int PyObject_Print(PyObject *o, FILE *fp, int flags) +.. c:function:: int PyObject_Print(PyObject *o, FILE *fp, int flags) Print an object *o*, on file *fp*. Returns ``-1`` on error. The flags argument is used to enable certain printing options. The only option currently supported @@ -14,35 +14,35 @@ Object Protocol instead of the :func:`repr`. -.. cfunction:: int PyObject_HasAttr(PyObject *o, PyObject *attr_name) +.. c:function:: int PyObject_HasAttr(PyObject *o, PyObject *attr_name) Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise. This is equivalent to the Python expression ``hasattr(o, attr_name)``. This function always succeeds. -.. cfunction:: int PyObject_HasAttrString(PyObject *o, const char *attr_name) +.. c:function:: int PyObject_HasAttrString(PyObject *o, const char *attr_name) Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise. This is equivalent to the Python expression ``hasattr(o, attr_name)``. This function always succeeds. -.. cfunction:: PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name) +.. c:function:: PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name) Retrieve an attribute named *attr_name* from object *o*. Returns the attribute value on success, or *NULL* on failure. This is the equivalent of the Python expression ``o.attr_name``. -.. cfunction:: PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name) +.. c:function:: PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name) Retrieve an attribute named *attr_name* from object *o*. Returns the attribute value on success, or *NULL* on failure. This is the equivalent of the Python expression ``o.attr_name``. -.. cfunction:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) +.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) Generic attribute getter function that is meant to be put into a type object's ``tp_getattro`` slot. It looks for a descriptor in the dictionary @@ -52,21 +52,21 @@ Object Protocol descriptors don't. Otherwise, an :exc:`AttributeError` is raised. -.. cfunction:: int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v) +.. c:function:: int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v) Set the value of the attribute named *attr_name*, for object *o*, to the value *v*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``o.attr_name = v``. -.. cfunction:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v) +.. c:function:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v) Set the value of the attribute named *attr_name*, for object *o*, to the value *v*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``o.attr_name = v``. -.. cfunction:: int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value) +.. c:function:: int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value) Generic attribute setter function that is meant to be put into a type object's ``tp_setattro`` slot. It looks for a data descriptor in the @@ -76,19 +76,19 @@ Object Protocol an :exc:`AttributeError` is raised and ``-1`` is returned. -.. cfunction:: int PyObject_DelAttr(PyObject *o, PyObject *attr_name) +.. c:function:: int PyObject_DelAttr(PyObject *o, PyObject *attr_name) Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``del o.attr_name``. -.. cfunction:: int PyObject_DelAttrString(PyObject *o, const char *attr_name) +.. c:function:: int PyObject_DelAttrString(PyObject *o, const char *attr_name) Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``del o.attr_name``. -.. cfunction:: PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid) +.. c:function:: PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid) Compare the values of *o1* and *o2* using the operation specified by *opid*, which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`, @@ -98,7 +98,7 @@ Object Protocol to *opid*. Returns the value of the comparison on success, or *NULL* on failure. -.. cfunction:: int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid) +.. c:function:: int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid) Compare the values of *o1* and *o2* using the operation specified by *opid*, which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`, @@ -109,7 +109,7 @@ Object Protocol *opid*. -.. cfunction:: PyObject* PyObject_Repr(PyObject *o) +.. c:function:: PyObject* PyObject_Repr(PyObject *o) .. index:: builtin: repr @@ -118,18 +118,18 @@ Object Protocol Python expression ``repr(o)``. Called by the :func:`repr` built-in function. -.. cfunction:: PyObject* PyObject_ASCII(PyObject *o) +.. c:function:: PyObject* PyObject_ASCII(PyObject *o) .. index:: builtin: ascii - As :cfunc:`PyObject_Repr`, compute a string representation of object *o*, but + As :c:func:`PyObject_Repr`, compute a string representation of object *o*, but escape the non-ASCII characters in the string returned by - :cfunc:`PyObject_Repr` with ``\x``, ``\u`` or ``\U`` escapes. This generates - a string similar to that returned by :cfunc:`PyObject_Repr` in Python 2. + :c:func:`PyObject_Repr` with ``\x``, ``\u`` or ``\U`` escapes. This generates + a string similar to that returned by :c:func:`PyObject_Repr` in Python 2. Called by the :func:`ascii` built-in function. -.. cfunction:: PyObject* PyObject_Str(PyObject *o) +.. c:function:: PyObject* PyObject_Str(PyObject *o) .. index:: builtin: str @@ -138,7 +138,7 @@ Object Protocol Python expression ``str(o)``. Called by the :func:`str` built-in function and, therefore, by the :func:`print` function. -.. cfunction:: PyObject* PyObject_Bytes(PyObject *o) +.. c:function:: PyObject* PyObject_Bytes(PyObject *o) .. index:: builtin: bytes @@ -148,11 +148,11 @@ Object Protocol a TypeError is raised when *o* is an integer instead of a zero-initialized bytes object. -.. cfunction:: int PyObject_IsInstance(PyObject *inst, PyObject *cls) +.. c:function:: int PyObject_IsInstance(PyObject *inst, PyObject *cls) Returns ``1`` if *inst* is an instance of the class *cls* or a subclass of *cls*, or ``0`` if not. On error, returns ``-1`` and sets an exception. If - *cls* is a type object rather than a class object, :cfunc:`PyObject_IsInstance` + *cls* is a type object rather than a class object, :c:func:`PyObject_IsInstance` returns ``1`` if *inst* is of type *cls*. If *cls* is a tuple, the check will be done against every entry in *cls*. The result will be ``1`` when at least one of the checks returns ``1``, otherwise it will be ``0``. If *inst* is not a @@ -168,13 +168,13 @@ of. If :class:`A` and :class:`B` are class objects, :class:`B` is a subclass of :class:`A` if it inherits from :class:`A` either directly or indirectly. If either is not a class object, a more general mechanism is used to determine the class relationship of the two objects. When testing if *B* is a subclass of -*A*, if *A* is *B*, :cfunc:`PyObject_IsSubclass` returns true. If *A* and *B* +*A*, if *A* is *B*, :c:func:`PyObject_IsSubclass` returns true. If *A* and *B* are different objects, *B*'s :attr:`__bases__` attribute is searched in a depth-first fashion for *A* --- the presence of the :attr:`__bases__` attribute is considered sufficient for this determination. -.. cfunction:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls) +.. c:function:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls) Returns ``1`` if the class *derived* is identical to or derived from the class *cls*, otherwise returns ``0``. In case of an error, returns ``-1``. If *cls* @@ -184,13 +184,13 @@ is considered sufficient for this determination. this function uses the generic algorithm described above. -.. cfunction:: int PyCallable_Check(PyObject *o) +.. c:function:: int PyCallable_Check(PyObject *o) Determine if the object *o* is callable. Return ``1`` if the object is callable and ``0`` otherwise. This function always succeeds. -.. cfunction:: PyObject* PyObject_Call(PyObject *callable_object, PyObject *args, PyObject *kw) +.. c:function:: PyObject* PyObject_Call(PyObject *callable_object, PyObject *args, PyObject *kw) Call a callable Python object *callable_object*, with arguments given by the tuple *args*, and named arguments given by the dictionary *kw*. If no named @@ -200,7 +200,7 @@ is considered sufficient for this determination. ``callable_object(*args, **kw)``. -.. cfunction:: PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args) +.. c:function:: PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args) Call a callable Python object *callable_object*, with arguments given by the tuple *args*. If no arguments are needed, then *args* may be *NULL*. Returns @@ -208,46 +208,46 @@ is considered sufficient for this determination. of the Python expression ``callable_object(*args)``. -.. cfunction:: PyObject* PyObject_CallFunction(PyObject *callable, char *format, ...) +.. c:function:: PyObject* PyObject_CallFunction(PyObject *callable, char *format, ...) Call a callable Python object *callable*, with a variable number of C arguments. - The C arguments are described using a :cfunc:`Py_BuildValue` style format + The C arguments are described using a :c:func:`Py_BuildValue` style format string. The format may be *NULL*, indicating that no arguments are provided. Returns the result of the call on success, or *NULL* on failure. This is the equivalent of the Python expression ``callable(*args)``. Note that if you only - pass :ctype:`PyObject \*` args, :cfunc:`PyObject_CallFunctionObjArgs` is a + pass :c:type:`PyObject \*` args, :c:func:`PyObject_CallFunctionObjArgs` is a faster alternative. -.. cfunction:: PyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...) +.. c:function:: PyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...) Call the method named *method* of object *o* with a variable number of C - arguments. The C arguments are described by a :cfunc:`Py_BuildValue` format + arguments. The C arguments are described by a :c:func:`Py_BuildValue` format string that should produce a tuple. The format may be *NULL*, indicating that no arguments are provided. Returns the result of the call on success, or *NULL* on failure. This is the equivalent of the Python expression ``o.method(args)``. - Note that if you only pass :ctype:`PyObject \*` args, - :cfunc:`PyObject_CallMethodObjArgs` is a faster alternative. + Note that if you only pass :c:type:`PyObject \*` args, + :c:func:`PyObject_CallMethodObjArgs` is a faster alternative. -.. cfunction:: PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL) +.. c:function:: PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL) Call a callable Python object *callable*, with a variable number of - :ctype:`PyObject\*` arguments. The arguments are provided as a variable number + :c:type:`PyObject\*` arguments. The arguments are provided as a variable number of parameters followed by *NULL*. Returns the result of the call on success, or *NULL* on failure. -.. cfunction:: PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL) +.. c:function:: PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL) Calls a method of the object *o*, where the name of the method is given as a Python string object in *name*. It is called with a variable number of - :ctype:`PyObject\*` arguments. The arguments are provided as a variable number + :c:type:`PyObject\*` arguments. The arguments are provided as a variable number of parameters followed by *NULL*. Returns the result of the call on success, or *NULL* on failure. -.. cfunction:: long PyObject_Hash(PyObject *o) +.. c:function:: long PyObject_Hash(PyObject *o) .. index:: builtin: hash @@ -255,7 +255,7 @@ is considered sufficient for this determination. This is the equivalent of the Python expression ``hash(o)``. -.. cfunction:: long PyObject_HashNotImplemented(PyObject *o) +.. c:function:: long PyObject_HashNotImplemented(PyObject *o) Set a :exc:`TypeError` indicating that ``type(o)`` is not hashable and return ``-1``. This function receives special treatment when stored in a ``tp_hash`` slot, @@ -263,21 +263,21 @@ is considered sufficient for this determination. hashable. -.. cfunction:: int PyObject_IsTrue(PyObject *o) +.. c:function:: int PyObject_IsTrue(PyObject *o) Returns ``1`` if the object *o* is considered to be true, and ``0`` otherwise. This is equivalent to the Python expression ``not not o``. On failure, return ``-1``. -.. cfunction:: int PyObject_Not(PyObject *o) +.. c:function:: int PyObject_Not(PyObject *o) Returns ``0`` if the object *o* is considered to be true, and ``1`` otherwise. This is equivalent to the Python expression ``not o``. On failure, return ``-1``. -.. cfunction:: PyObject* PyObject_Type(PyObject *o) +.. c:function:: PyObject* PyObject_Type(PyObject *o) .. index:: builtin: type @@ -286,17 +286,17 @@ is considered sufficient for this determination. is equivalent to the Python expression ``type(o)``. This function increments the reference count of the return value. There's really no reason to use this function instead of the common expression ``o->ob_type``, which returns a - pointer of type :ctype:`PyTypeObject\*`, except when the incremented reference + pointer of type :c:type:`PyTypeObject\*`, except when the incremented reference count is needed. -.. cfunction:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type) +.. c:function:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type) Return true if the object *o* is of type *type* or a subtype of *type*. Both parameters must be non-*NULL*. -.. cfunction:: Py_ssize_t PyObject_Length(PyObject *o) +.. c:function:: Py_ssize_t PyObject_Length(PyObject *o) Py_ssize_t PyObject_Size(PyObject *o) .. index:: builtin: len @@ -306,34 +306,34 @@ is considered sufficient for this determination. returned. This is the equivalent to the Python expression ``len(o)``. -.. cfunction:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key) +.. c:function:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key) Return element of *o* corresponding to the object *key* or *NULL* on failure. This is the equivalent of the Python expression ``o[key]``. -.. cfunction:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v) +.. c:function:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v) Map the object *key* to the value *v*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``o[key] = v``. -.. cfunction:: int PyObject_DelItem(PyObject *o, PyObject *key) +.. c:function:: int PyObject_DelItem(PyObject *o, PyObject *key) Delete the mapping for *key* from *o*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``del o[key]``. -.. cfunction:: PyObject* PyObject_Dir(PyObject *o) +.. c:function:: PyObject* PyObject_Dir(PyObject *o) This is equivalent to the Python expression ``dir(o)``, returning a (possibly empty) list of strings appropriate for the object argument, or *NULL* if there was an error. If the argument is *NULL*, this is like the Python ``dir()``, returning the names of the current locals; in this case, if no execution frame - is active then *NULL* is returned but :cfunc:`PyErr_Occurred` will return false. + is active then *NULL* is returned but :c:func:`PyErr_Occurred` will return false. -.. cfunction:: PyObject* PyObject_GetIter(PyObject *o) +.. c:function:: PyObject* PyObject_GetIter(PyObject *o) This is equivalent to the Python expression ``iter(o)``. It returns a new iterator for the object argument, or the object itself if the object is already diff --git a/Doc/c-api/refcounting.rst b/Doc/c-api/refcounting.rst index c0f4ca1..4f512ec 100644 --- a/Doc/c-api/refcounting.rst +++ b/Doc/c-api/refcounting.rst @@ -11,22 +11,22 @@ The macros in this section are used for managing reference counts of Python objects. -.. cfunction:: void Py_INCREF(PyObject *o) +.. c:function:: void Py_INCREF(PyObject *o) Increment the reference count for object *o*. The object must not be *NULL*; if - you aren't sure that it isn't *NULL*, use :cfunc:`Py_XINCREF`. + you aren't sure that it isn't *NULL*, use :c:func:`Py_XINCREF`. -.. cfunction:: void Py_XINCREF(PyObject *o) +.. c:function:: void Py_XINCREF(PyObject *o) Increment the reference count for object *o*. The object may be *NULL*, in which case the macro has no effect. -.. cfunction:: void Py_DECREF(PyObject *o) +.. c:function:: void Py_DECREF(PyObject *o) Decrement the reference count for object *o*. The object must not be *NULL*; if - you aren't sure that it isn't *NULL*, use :cfunc:`Py_XDECREF`. If the reference + you aren't sure that it isn't *NULL*, use :c:func:`Py_XDECREF`. If the reference count reaches zero, the object's type's deallocation function (which must not be *NULL*) is invoked. @@ -36,25 +36,25 @@ objects. when a class instance with a :meth:`__del__` method is deallocated). While exceptions in such code are not propagated, the executed code has free access to all Python global variables. This means that any object that is reachable from - a global variable should be in a consistent state before :cfunc:`Py_DECREF` is + a global variable should be in a consistent state before :c:func:`Py_DECREF` is invoked. For example, code to delete an object from a list should copy a reference to the deleted object in a temporary variable, update the list data - structure, and then call :cfunc:`Py_DECREF` for the temporary variable. + structure, and then call :c:func:`Py_DECREF` for the temporary variable. -.. cfunction:: void Py_XDECREF(PyObject *o) +.. c:function:: void Py_XDECREF(PyObject *o) Decrement the reference count for object *o*. The object may be *NULL*, in which case the macro has no effect; otherwise the effect is the same as for - :cfunc:`Py_DECREF`, and the same warning applies. + :c:func:`Py_DECREF`, and the same warning applies. -.. cfunction:: void Py_CLEAR(PyObject *o) +.. c:function:: void Py_CLEAR(PyObject *o) Decrement the reference count for object *o*. The object may be *NULL*, in which case the macro has no effect; otherwise the effect is the same as for - :cfunc:`Py_DECREF`, except that the argument is also set to *NULL*. The warning - for :cfunc:`Py_DECREF` does not apply with respect to the object passed because + :c:func:`Py_DECREF`, except that the argument is also set to *NULL*. The warning + for :c:func:`Py_DECREF` does not apply with respect to the object passed because the macro carefully uses a temporary variable and sets the argument to *NULL* before decrementing its reference count. @@ -64,10 +64,10 @@ objects. The following functions are for runtime dynamic embedding of Python: ``Py_IncRef(PyObject *o)``, ``Py_DecRef(PyObject *o)``. They are -simply exported function versions of :cfunc:`Py_XINCREF` and -:cfunc:`Py_XDECREF`, respectively. +simply exported function versions of :c:func:`Py_XINCREF` and +:c:func:`Py_XDECREF`, respectively. The following functions or macros are only for use within the interpreter core: -:cfunc:`_Py_Dealloc`, :cfunc:`_Py_ForgetReference`, :cfunc:`_Py_NewReference`, -as well as the global variable :cdata:`_Py_RefTotal`. +:c:func:`_Py_Dealloc`, :c:func:`_Py_ForgetReference`, :c:func:`_Py_NewReference`, +as well as the global variable :c:data:`_Py_RefTotal`. diff --git a/Doc/c-api/reflection.rst b/Doc/c-api/reflection.rst index 234d66b..9689365 100644 --- a/Doc/c-api/reflection.rst +++ b/Doc/c-api/reflection.rst @@ -5,45 +5,45 @@ Reflection ========== -.. cfunction:: PyObject* PyEval_GetBuiltins() +.. c:function:: PyObject* PyEval_GetBuiltins() Return a dictionary of the builtins in the current execution frame, or the interpreter of the thread state if no frame is currently executing. -.. cfunction:: PyObject* PyEval_GetLocals() +.. c:function:: PyObject* PyEval_GetLocals() Return a dictionary of the local variables in the current execution frame, or *NULL* if no frame is currently executing. -.. cfunction:: PyObject* PyEval_GetGlobals() +.. c:function:: PyObject* PyEval_GetGlobals() Return a dictionary of the global variables in the current execution frame, or *NULL* if no frame is currently executing. -.. cfunction:: PyFrameObject* PyEval_GetFrame() +.. c:function:: PyFrameObject* PyEval_GetFrame() Return the current thread state's frame, which is *NULL* if no frame is currently executing. -.. cfunction:: int PyFrame_GetLineNumber(PyFrameObject *frame) +.. c:function:: int PyFrame_GetLineNumber(PyFrameObject *frame) Return the line number that *frame* is currently executing. -.. cfunction:: const char* PyEval_GetFuncName(PyObject *func) +.. c:function:: const char* PyEval_GetFuncName(PyObject *func) Return the name of *func* if it is a function, class or instance object, else the name of *func*\s type. -.. cfunction:: const char* PyEval_GetFuncDesc(PyObject *func) +.. c:function:: const char* PyEval_GetFuncDesc(PyObject *func) Return a description string, depending on the type of *func*. Return values include "()" for functions and methods, " constructor", " instance", and " object". Concatenated with the result of - :cfunc:`PyEval_GetFuncName`, the result will be a description of + :c:func:`PyEval_GetFuncName`, the result will be a description of *func*. diff --git a/Doc/c-api/sequence.rst b/Doc/c-api/sequence.rst index d863177..599074c 100644 --- a/Doc/c-api/sequence.rst +++ b/Doc/c-api/sequence.rst @@ -6,13 +6,13 @@ Sequence Protocol ================= -.. cfunction:: int PySequence_Check(PyObject *o) +.. c:function:: int PySequence_Check(PyObject *o) Return ``1`` if the object provides sequence protocol, and ``0`` otherwise. This function always succeeds. -.. cfunction:: Py_ssize_t PySequence_Size(PyObject *o) +.. c:function:: Py_ssize_t PySequence_Size(PyObject *o) Py_ssize_t PySequence_Length(PyObject *o) .. index:: builtin: len @@ -22,96 +22,96 @@ Sequence Protocol Python expression ``len(o)``. -.. cfunction:: PyObject* PySequence_Concat(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PySequence_Concat(PyObject *o1, PyObject *o2) Return the concatenation of *o1* and *o2* on success, and *NULL* on failure. This is the equivalent of the Python expression ``o1 + o2``. -.. cfunction:: PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count) +.. c:function:: PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count) Return the result of repeating sequence object *o* *count* times, or *NULL* on failure. This is the equivalent of the Python expression ``o * count``. -.. cfunction:: PyObject* PySequence_InPlaceConcat(PyObject *o1, PyObject *o2) +.. c:function:: PyObject* PySequence_InPlaceConcat(PyObject *o1, PyObject *o2) Return the concatenation of *o1* and *o2* on success, and *NULL* on failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python expression ``o1 += o2``. -.. cfunction:: PyObject* PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) +.. c:function:: PyObject* PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) Return the result of repeating sequence object *o* *count* times, or *NULL* on failure. The operation is done *in-place* when *o* supports it. This is the equivalent of the Python expression ``o *= count``. -.. cfunction:: PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i) +.. c:function:: PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i) Return the *i*\ th element of *o*, or *NULL* on failure. This is the equivalent of the Python expression ``o[i]``. -.. cfunction:: PyObject* PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) +.. c:function:: PyObject* PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) Return the slice of sequence object *o* between *i1* and *i2*, or *NULL* on failure. This is the equivalent of the Python expression ``o[i1:i2]``. -.. cfunction:: int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v) +.. c:function:: int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v) Assign object *v* to the *i*\ th element of *o*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``o[i] = v``. This function *does not* steal a reference to *v*. -.. cfunction:: int PySequence_DelItem(PyObject *o, Py_ssize_t i) +.. c:function:: int PySequence_DelItem(PyObject *o, Py_ssize_t i) Delete the *i*\ th element of object *o*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``del o[i]``. -.. cfunction:: int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v) +.. c:function:: int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v) Assign the sequence object *v* to the slice in sequence object *o* from *i1* to *i2*. This is the equivalent of the Python statement ``o[i1:i2] = v``. -.. cfunction:: int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) +.. c:function:: int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) Delete the slice in sequence object *o* from *i1* to *i2*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``del o[i1:i2]``. -.. cfunction:: Py_ssize_t PySequence_Count(PyObject *o, PyObject *value) +.. c:function:: Py_ssize_t PySequence_Count(PyObject *o, PyObject *value) Return the number of occurrences of *value* in *o*, that is, return the number of keys for which ``o[key] == value``. On failure, return ``-1``. This is equivalent to the Python expression ``o.count(value)``. -.. cfunction:: int PySequence_Contains(PyObject *o, PyObject *value) +.. c:function:: int PySequence_Contains(PyObject *o, PyObject *value) Determine if *o* contains *value*. If an item in *o* is equal to *value*, return ``1``, otherwise return ``0``. On error, return ``-1``. This is equivalent to the Python expression ``value in o``. -.. cfunction:: Py_ssize_t PySequence_Index(PyObject *o, PyObject *value) +.. c:function:: Py_ssize_t PySequence_Index(PyObject *o, PyObject *value) Return the first index *i* for which ``o[i] == value``. On error, return ``-1``. This is equivalent to the Python expression ``o.index(value)``. -.. cfunction:: PyObject* PySequence_List(PyObject *o) +.. c:function:: PyObject* PySequence_List(PyObject *o) Return a list object with the same contents as the arbitrary sequence *o*. The returned list is guaranteed to be new. -.. cfunction:: PyObject* PySequence_Tuple(PyObject *o) +.. c:function:: PyObject* PySequence_Tuple(PyObject *o) .. index:: builtin: tuple @@ -121,42 +121,42 @@ Sequence Protocol equivalent to the Python expression ``tuple(o)``. -.. cfunction:: PyObject* PySequence_Fast(PyObject *o, const char *m) +.. c:function:: PyObject* PySequence_Fast(PyObject *o, const char *m) Returns the sequence *o* as a tuple, unless it is already a tuple or list, in - which case *o* is returned. Use :cfunc:`PySequence_Fast_GET_ITEM` to access the + which case *o* is returned. Use :c:func:`PySequence_Fast_GET_ITEM` to access the members of the result. Returns *NULL* on failure. If the object is not a sequence, raises :exc:`TypeError` with *m* as the message text. -.. cfunction:: PyObject* PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i) +.. c:function:: PyObject* PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i) Return the *i*\ th element of *o*, assuming that *o* was returned by - :cfunc:`PySequence_Fast`, *o* is not *NULL*, and that *i* is within bounds. + :c:func:`PySequence_Fast`, *o* is not *NULL*, and that *i* is within bounds. -.. cfunction:: PyObject** PySequence_Fast_ITEMS(PyObject *o) +.. c:function:: PyObject** PySequence_Fast_ITEMS(PyObject *o) Return the underlying array of PyObject pointers. Assumes that *o* was returned - by :cfunc:`PySequence_Fast` and *o* is not *NULL*. + by :c:func:`PySequence_Fast` and *o* is not *NULL*. Note, if a list gets resized, the reallocation may relocate the items array. So, only use the underlying array pointer in contexts where the sequence cannot change. -.. cfunction:: PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i) +.. c:function:: PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i) Return the *i*\ th element of *o* or *NULL* on failure. Macro form of - :cfunc:`PySequence_GetItem` but without checking that - :cfunc:`PySequence_Check(o)` is true and without adjustment for negative + :c:func:`PySequence_GetItem` but without checking that + :c:func:`PySequence_Check(o)` is true and without adjustment for negative indices. -.. cfunction:: Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o) +.. c:function:: Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o) Returns the length of *o*, assuming that *o* was returned by - :cfunc:`PySequence_Fast` and that *o* is not *NULL*. The size can also be - gotten by calling :cfunc:`PySequence_Size` on *o*, but - :cfunc:`PySequence_Fast_GET_SIZE` is faster because it can assume *o* is a list + :c:func:`PySequence_Fast` and that *o* is not *NULL*. The size can also be + gotten by calling :c:func:`PySequence_Size` on *o*, but + :c:func:`PySequence_Fast_GET_SIZE` is faster because it can assume *o* is a list or tuple. diff --git a/Doc/c-api/set.rst b/Doc/c-api/set.rst index 4348108..66b47c4 100644 --- a/Doc/c-api/set.rst +++ b/Doc/c-api/set.rst @@ -14,20 +14,20 @@ Set Objects This section details the public API for :class:`set` and :class:`frozenset` objects. Any functionality not listed below is best accessed using the either -the abstract object protocol (including :cfunc:`PyObject_CallMethod`, -:cfunc:`PyObject_RichCompareBool`, :cfunc:`PyObject_Hash`, -:cfunc:`PyObject_Repr`, :cfunc:`PyObject_IsTrue`, :cfunc:`PyObject_Print`, and -:cfunc:`PyObject_GetIter`) or the abstract number protocol (including -:cfunc:`PyNumber_And`, :cfunc:`PyNumber_Subtract`, :cfunc:`PyNumber_Or`, -:cfunc:`PyNumber_Xor`, :cfunc:`PyNumber_InPlaceAnd`, -:cfunc:`PyNumber_InPlaceSubtract`, :cfunc:`PyNumber_InPlaceOr`, and -:cfunc:`PyNumber_InPlaceXor`). +the abstract object protocol (including :c:func:`PyObject_CallMethod`, +:c:func:`PyObject_RichCompareBool`, :c:func:`PyObject_Hash`, +:c:func:`PyObject_Repr`, :c:func:`PyObject_IsTrue`, :c:func:`PyObject_Print`, and +:c:func:`PyObject_GetIter`) or the abstract number protocol (including +:c:func:`PyNumber_And`, :c:func:`PyNumber_Subtract`, :c:func:`PyNumber_Or`, +:c:func:`PyNumber_Xor`, :c:func:`PyNumber_InPlaceAnd`, +:c:func:`PyNumber_InPlaceSubtract`, :c:func:`PyNumber_InPlaceOr`, and +:c:func:`PyNumber_InPlaceXor`). -.. ctype:: PySetObject +.. c:type:: PySetObject - This subtype of :ctype:`PyObject` is used to hold the internal data for both - :class:`set` and :class:`frozenset` objects. It is like a :ctype:`PyDictObject` + This subtype of :c:type:`PyObject` is used to hold the internal data for both + :class:`set` and :class:`frozenset` objects. It is like a :c:type:`PyDictObject` in that it is a fixed size for small sets (much like tuple storage) and will point to a separate, variable sized block of memory for medium and large sized sets (much like list storage). None of the fields of this structure should be @@ -35,49 +35,49 @@ the abstract object protocol (including :cfunc:`PyObject_CallMethod`, the documented API rather than by manipulating the values in the structure. -.. cvar:: PyTypeObject PySet_Type +.. c:var:: PyTypeObject PySet_Type - This is an instance of :ctype:`PyTypeObject` representing the Python + This is an instance of :c:type:`PyTypeObject` representing the Python :class:`set` type. -.. cvar:: PyTypeObject PyFrozenSet_Type +.. c:var:: PyTypeObject PyFrozenSet_Type - This is an instance of :ctype:`PyTypeObject` representing the Python + This is an instance of :c:type:`PyTypeObject` representing the Python :class:`frozenset` type. The following type check macros work on pointers to any Python object. Likewise, the constructor functions work with any iterable Python object. -.. cfunction:: int PySet_Check(PyObject *p) +.. c:function:: int PySet_Check(PyObject *p) Return true if *p* is a :class:`set` object or an instance of a subtype. -.. cfunction:: int PyFrozenSet_Check(PyObject *p) +.. c:function:: int PyFrozenSet_Check(PyObject *p) Return true if *p* is a :class:`frozenset` object or an instance of a subtype. -.. cfunction:: int PyAnySet_Check(PyObject *p) +.. c:function:: int PyAnySet_Check(PyObject *p) Return true if *p* is a :class:`set` object, a :class:`frozenset` object, or an instance of a subtype. -.. cfunction:: int PyAnySet_CheckExact(PyObject *p) +.. c:function:: int PyAnySet_CheckExact(PyObject *p) Return true if *p* is a :class:`set` object or a :class:`frozenset` object but not an instance of a subtype. -.. cfunction:: int PyFrozenSet_CheckExact(PyObject *p) +.. c:function:: int PyFrozenSet_CheckExact(PyObject *p) Return true if *p* is a :class:`frozenset` object but not an instance of a subtype. -.. cfunction:: PyObject* PySet_New(PyObject *iterable) +.. c:function:: PyObject* PySet_New(PyObject *iterable) Return a new :class:`set` containing objects returned by the *iterable*. The *iterable* may be *NULL* to create a new empty set. Return the new set on @@ -86,7 +86,7 @@ the constructor functions work with any iterable Python object. (``c=set(s)``). -.. cfunction:: PyObject* PyFrozenSet_New(PyObject *iterable) +.. c:function:: PyObject* PyFrozenSet_New(PyObject *iterable) Return a new :class:`frozenset` containing objects returned by the *iterable*. The *iterable* may be *NULL* to create a new empty frozenset. Return the new @@ -98,7 +98,7 @@ The following functions and macros are available for instances of :class:`set` or :class:`frozenset` or instances of their subtypes. -.. cfunction:: Py_ssize_t PySet_Size(PyObject *anyset) +.. c:function:: Py_ssize_t PySet_Size(PyObject *anyset) .. index:: builtin: len @@ -107,12 +107,12 @@ or :class:`frozenset` or instances of their subtypes. :class:`set`, :class:`frozenset`, or an instance of a subtype. -.. cfunction:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset) +.. c:function:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset) - Macro form of :cfunc:`PySet_Size` without error checking. + Macro form of :c:func:`PySet_Size` without error checking. -.. cfunction:: int PySet_Contains(PyObject *anyset, PyObject *key) +.. c:function:: int PySet_Contains(PyObject *anyset, PyObject *key) Return 1 if found, 0 if not found, and -1 if an error is encountered. Unlike the Python :meth:`__contains__` method, this function does not automatically @@ -121,10 +121,10 @@ or :class:`frozenset` or instances of their subtypes. :class:`set`, :class:`frozenset`, or an instance of a subtype. -.. cfunction:: int PySet_Add(PyObject *set, PyObject *key) +.. c:function:: int PySet_Add(PyObject *set, PyObject *key) Add *key* to a :class:`set` instance. Also works with :class:`frozenset` - instances (like :cfunc:`PyTuple_SetItem` it can be used to fill-in the values + instances (like :c:func:`PyTuple_SetItem` it can be used to fill-in the values of brand new frozensets before they are exposed to other code). Return 0 on success or -1 on failure. Raise a :exc:`TypeError` if the *key* is unhashable. Raise a :exc:`MemoryError` if there is no room to grow. Raise a @@ -136,7 +136,7 @@ The following functions are available for instances of :class:`set` or its subtypes but not for instances of :class:`frozenset` or its subtypes. -.. cfunction:: int PySet_Discard(PyObject *set, PyObject *key) +.. c:function:: int PySet_Discard(PyObject *set, PyObject *key) Return 1 if found and removed, 0 if not found (no action taken), and -1 if an error is encountered. Does not raise :exc:`KeyError` for missing keys. Raise a @@ -146,7 +146,7 @@ subtypes but not for instances of :class:`frozenset` or its subtypes. instance of :class:`set` or its subtype. -.. cfunction:: PyObject* PySet_Pop(PyObject *set) +.. c:function:: PyObject* PySet_Pop(PyObject *set) Return a new reference to an arbitrary object in the *set*, and removes the object from the *set*. Return *NULL* on failure. Raise :exc:`KeyError` if the @@ -154,6 +154,6 @@ subtypes but not for instances of :class:`frozenset` or its subtypes. :class:`set` or its subtype. -.. cfunction:: int PySet_Clear(PyObject *set) +.. c:function:: int PySet_Clear(PyObject *set) Empty an existing set of all elements. diff --git a/Doc/c-api/slice.rst b/Doc/c-api/slice.rst index f8f2a44..5f2a05a 100644 --- a/Doc/c-api/slice.rst +++ b/Doc/c-api/slice.rst @@ -6,7 +6,7 @@ Slice Objects ------------- -.. cvar:: PyTypeObject PySlice_Type +.. c:var:: PyTypeObject PySlice_Type .. index:: single: SliceType (in module types) @@ -14,12 +14,12 @@ Slice Objects ``types.SliceType``. -.. cfunction:: int PySlice_Check(PyObject *ob) +.. c:function:: int PySlice_Check(PyObject *ob) Return true if *ob* is a slice object; *ob* must not be *NULL*. -.. cfunction:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step) +.. c:function:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step) Return a new slice object with the given values. The *start*, *stop*, and *step* parameters are used as the values of the slice object attributes of @@ -28,7 +28,7 @@ Slice Objects the new object could not be allocated. -.. cfunction:: int PySlice_GetIndices(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) +.. c:function:: int PySlice_GetIndices(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) Retrieve the start, stop and step indices from the slice object *slice*, assuming a sequence of length *length*. Treats indices greater than @@ -41,9 +41,9 @@ Slice Objects You probably do not want to use this function. -.. cfunction:: int PySlice_GetIndicesEx(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) +.. c:function:: int PySlice_GetIndicesEx(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) - Usable replacement for :cfunc:`PySlice_GetIndices`. Retrieve the start, + Usable replacement for :c:func:`PySlice_GetIndices`. Retrieve the start, stop, and step indices from the slice object *slice* assuming a sequence of length *length*, and store the length of the slice in *slicelength*. Out of bounds indices are clipped in a manner consistent with the handling of diff --git a/Doc/c-api/structures.rst b/Doc/c-api/structures.rst index dbacedf..bb741fb 100644 --- a/Doc/c-api/structures.rst +++ b/Doc/c-api/structures.rst @@ -11,12 +11,12 @@ are used. All Python objects ultimately share a small number of fields at the beginning of the object's representation in memory. These are represented by the -:ctype:`PyObject` and :ctype:`PyVarObject` types, which are defined, in turn, +:c:type:`PyObject` and :c:type:`PyVarObject` types, which are defined, in turn, by the expansions of some macros also used, whether directly or indirectly, in the definition of all other Python objects. -.. ctype:: PyObject +.. c:type:: PyObject All object types are extensions of this type. This is a type which contains the information Python needs to treat a pointer to an object as an @@ -26,88 +26,88 @@ the definition of all other Python objects. macro. -.. ctype:: PyVarObject +.. c:type:: PyVarObject - This is an extension of :ctype:`PyObject` that adds the :attr:`ob_size` + This is an extension of :c:type:`PyObject` that adds the :attr:`ob_size` field. This is only used for objects that have some notion of *length*. This type does not often appear in the Python/C API. It corresponds to the fields defined by the expansion of the ``PyObject_VAR_HEAD`` macro. -These macros are used in the definition of :ctype:`PyObject` and -:ctype:`PyVarObject`: +These macros are used in the definition of :c:type:`PyObject` and +:c:type:`PyVarObject`: .. XXX need to document PEP 3123 changes here -.. cmacro:: PyObject_HEAD +.. c:macro:: PyObject_HEAD This is a macro which expands to the declarations of the fields of the - :ctype:`PyObject` type; it is used when declaring new types which represent + :c:type:`PyObject` type; it is used when declaring new types which represent objects without a varying length. The specific fields it expands to depend - on the definition of :cmacro:`Py_TRACE_REFS`. By default, that macro is - not defined, and :cmacro:`PyObject_HEAD` expands to:: + on the definition of :c:macro:`Py_TRACE_REFS`. By default, that macro is + not defined, and :c:macro:`PyObject_HEAD` expands to:: Py_ssize_t ob_refcnt; PyTypeObject *ob_type; - When :cmacro:`Py_TRACE_REFS` is defined, it expands to:: + When :c:macro:`Py_TRACE_REFS` is defined, it expands to:: PyObject *_ob_next, *_ob_prev; Py_ssize_t ob_refcnt; PyTypeObject *ob_type; -.. cmacro:: PyObject_VAR_HEAD +.. c:macro:: PyObject_VAR_HEAD This is a macro which expands to the declarations of the fields of the - :ctype:`PyVarObject` type; it is used when declaring new types which + :c:type:`PyVarObject` type; it is used when declaring new types which represent objects with a length that varies from instance to instance. This macro always expands to:: PyObject_HEAD Py_ssize_t ob_size; - Note that :cmacro:`PyObject_HEAD` is part of the expansion, and that its own - expansion varies depending on the definition of :cmacro:`Py_TRACE_REFS`. + Note that :c:macro:`PyObject_HEAD` is part of the expansion, and that its own + expansion varies depending on the definition of :c:macro:`Py_TRACE_REFS`. -.. cmacro:: PyObject_HEAD_INIT(type) +.. c:macro:: PyObject_HEAD_INIT(type) This is a macro which expands to initialization values for a new - :ctype:`PyObject` type. This macro expands to:: + :c:type:`PyObject` type. This macro expands to:: _PyObject_EXTRA_INIT 1, type, -.. cmacro:: PyVarObject_HEAD_INIT(type, size) +.. c:macro:: PyVarObject_HEAD_INIT(type, size) This is a macro which expands to initialization values for a new - :ctype:`PyVarObject` type, including the :attr:`ob_size` field. + :c:type:`PyVarObject` type, including the :attr:`ob_size` field. This macro expands to:: _PyObject_EXTRA_INIT 1, type, size, -.. ctype:: PyCFunction +.. c:type:: PyCFunction Type of the functions used to implement most Python callables in C. - Functions of this type take two :ctype:`PyObject\*` parameters and return + Functions of this type take two :c:type:`PyObject\*` parameters and return one such value. If the return value is *NULL*, an exception shall have been set. If not *NULL*, the return value is interpreted as the return value of the function as exposed in Python. The function must return a new reference. -.. ctype:: PyCFunctionWithKeywords +.. c:type:: PyCFunctionWithKeywords Type of the functions used to implement Python callables in C that take - keyword arguments: they take three :ctype:`PyObject\*` parameters and return - one such value. See :ctype:`PyCFunction` above for the meaning of the return + keyword arguments: they take three :c:type:`PyObject\*` parameters and return + one such value. See :c:type:`PyCFunction` above for the meaning of the return value. -.. ctype:: PyMethodDef +.. c:type:: PyMethodDef Structure used to describe a method of an extension type. This structure has four fields: @@ -128,10 +128,10 @@ These macros are used in the definition of :ctype:`PyObject` and +------------------+-------------+-------------------------------+ The :attr:`ml_meth` is a C function pointer. The functions may be of different -types, but they always return :ctype:`PyObject\*`. If the function is not of -the :ctype:`PyCFunction`, the compiler will require a cast in the method table. -Even though :ctype:`PyCFunction` defines the first parameter as -:ctype:`PyObject\*`, it is common that the method implementation uses a the +types, but they always return :c:type:`PyObject\*`. If the function is not of +the :c:type:`PyCFunction`, the compiler will require a cast in the method table. +Even though :c:type:`PyCFunction` defines the first parameter as +:c:type:`PyObject\*`, it is common that the method implementation uses a the specific C type of the *self* object. The :attr:`ml_flags` field is a bitfield which can include the following flags. @@ -145,27 +145,27 @@ convention flags can be combined with a binding flag. .. data:: METH_VARARGS This is the typical calling convention, where the methods have the type - :ctype:`PyCFunction`. The function expects two :ctype:`PyObject\*` values. + :c:type:`PyCFunction`. The function expects two :c:type:`PyObject\*` values. The first one is the *self* object for methods; for module functions, it is the module object. The second parameter (often called *args*) is a tuple object representing all arguments. This parameter is typically processed - using :cfunc:`PyArg_ParseTuple` or :cfunc:`PyArg_UnpackTuple`. + using :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_UnpackTuple`. .. data:: METH_KEYWORDS - Methods with these flags must be of type :ctype:`PyCFunctionWithKeywords`. + Methods with these flags must be of type :c:type:`PyCFunctionWithKeywords`. The function expects three parameters: *self*, *args*, and a dictionary of all the keyword arguments. The flag is typically combined with :const:`METH_VARARGS`, and the parameters are typically processed using - :cfunc:`PyArg_ParseTupleAndKeywords`. + :c:func:`PyArg_ParseTupleAndKeywords`. .. data:: METH_NOARGS Methods without parameters don't need to check whether arguments are given if they are listed with the :const:`METH_NOARGS` flag. They need to be of type - :ctype:`PyCFunction`. The first parameter is typically named *self* and will + :c:type:`PyCFunction`. The first parameter is typically named *self* and will hold a reference to the module or object instance. In all cases the second parameter will be *NULL*. @@ -173,9 +173,9 @@ convention flags can be combined with a binding flag. .. data:: METH_O Methods with a single object argument can be listed with the :const:`METH_O` - flag, instead of invoking :cfunc:`PyArg_ParseTuple` with a ``"O"`` argument. - They have the type :ctype:`PyCFunction`, with the *self* parameter, and a - :ctype:`PyObject\*` parameter representing the single argument. + flag, instead of invoking :c:func:`PyArg_ParseTuple` with a ``"O"`` argument. + They have the type :c:type:`PyCFunction`, with the *self* parameter, and a + :c:type:`PyObject\*` parameter representing the single argument. These two constants are not used to indicate the calling convention but the @@ -219,7 +219,7 @@ definition with the same method name. than wrapper object calls. -.. ctype:: PyMemberDef +.. c:type:: PyMemberDef Structure which describes an attribute of a type which corresponds to a C struct member. Its fields are: @@ -271,14 +271,14 @@ definition with the same method name. T_PYSSIZET Py_ssize_t =============== ================== - :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` differ in that - :cmacro:`T_OBJECT` returns ``None`` if the member is *NULL* and - :cmacro:`T_OBJECT_EX` raises an :exc:`AttributeError`. Try to use - :cmacro:`T_OBJECT_EX` over :cmacro:`T_OBJECT` because :cmacro:`T_OBJECT_EX` + :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX` differ in that + :c:macro:`T_OBJECT` returns ``None`` if the member is *NULL* and + :c:macro:`T_OBJECT_EX` raises an :exc:`AttributeError`. Try to use + :c:macro:`T_OBJECT_EX` over :c:macro:`T_OBJECT` because :c:macro:`T_OBJECT_EX` handles use of the :keyword:`del` statement on that attribute more correctly - than :cmacro:`T_OBJECT`. + than :c:macro:`T_OBJECT`. - :attr:`flags` can be 0 for write and read access or :cmacro:`READONLY` for - read-only access. Using :cmacro:`T_STRING` for :attr:`type` implies - :cmacro:`READONLY`. Only :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` + :attr:`flags` can be 0 for write and read access or :c:macro:`READONLY` for + read-only access. Using :c:macro:`T_STRING` for :attr:`type` implies + :c:macro:`READONLY`. Only :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX` members can be deleted. (They are set to *NULL*). diff --git a/Doc/c-api/sys.rst b/Doc/c-api/sys.rst index 00ddf00..232cec0 100644 --- a/Doc/c-api/sys.rst +++ b/Doc/c-api/sys.rst @@ -6,16 +6,16 @@ Operating System Utilities ========================== -.. cfunction:: int Py_FdIsInteractive(FILE *fp, const char *filename) +.. c:function:: int Py_FdIsInteractive(FILE *fp, const char *filename) Return true (nonzero) if the standard I/O file *fp* with name *filename* is deemed interactive. This is the case for files for which ``isatty(fileno(fp))`` - is true. If the global flag :cdata:`Py_InteractiveFlag` is true, this function + is true. If the global flag :c:data:`Py_InteractiveFlag` is true, this function also returns true if the *filename* pointer is *NULL* or if the name is equal to one of the strings ``'<stdin>'`` or ``'???'``. -.. cfunction:: void PyOS_AfterFork() +.. c:function:: void PyOS_AfterFork() Function to update some internal state after a process fork; this should be called in the new process if the Python interpreter will continue to be used. @@ -23,7 +23,7 @@ Operating System Utilities to be called. -.. cfunction:: int PyOS_CheckStack() +.. c:function:: int PyOS_CheckStack() Return true when the interpreter runs out of stack space. This is a reliable check, but is only available when :const:`USE_STACKCHECK` is defined (currently @@ -32,20 +32,20 @@ Operating System Utilities own code. -.. cfunction:: PyOS_sighandler_t PyOS_getsig(int i) +.. c:function:: PyOS_sighandler_t PyOS_getsig(int i) Return the current signal handler for signal *i*. This is a thin wrapper around - either :cfunc:`sigaction` or :cfunc:`signal`. Do not call those functions - directly! :ctype:`PyOS_sighandler_t` is a typedef alias for :ctype:`void + either :c:func:`sigaction` or :c:func:`signal`. Do not call those functions + directly! :c:type:`PyOS_sighandler_t` is a typedef alias for :c:type:`void (\*)(int)`. -.. cfunction:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h) +.. c:function:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h) Set the signal handler for signal *i* to be *h*; return the old signal handler. - This is a thin wrapper around either :cfunc:`sigaction` or :cfunc:`signal`. Do - not call those functions directly! :ctype:`PyOS_sighandler_t` is a typedef - alias for :ctype:`void (\*)(int)`. + This is a thin wrapper around either :c:func:`sigaction` or :c:func:`signal`. Do + not call those functions directly! :c:type:`PyOS_sighandler_t` is a typedef + alias for :c:type:`void (\*)(int)`. .. _systemfunctions: @@ -56,42 +56,42 @@ These are utility functions that make functionality from the :mod:`sys` module accessible to C code. They all work with the current interpreter thread's :mod:`sys` module's dict, which is contained in the internal thread state structure. -.. cfunction:: PyObject *PySys_GetObject(char *name) +.. c:function:: PyObject *PySys_GetObject(char *name) Return the object *name* from the :mod:`sys` module or *NULL* if it does not exist, without setting an exception. -.. cfunction:: FILE *PySys_GetFile(char *name, FILE *def) +.. c:function:: FILE *PySys_GetFile(char *name, FILE *def) - Return the :ctype:`FILE*` associated with the object *name* in the + Return the :c:type:`FILE*` associated with the object *name* in the :mod:`sys` module, or *def* if *name* is not in the module or is not associated - with a :ctype:`FILE*`. + with a :c:type:`FILE*`. -.. cfunction:: int PySys_SetObject(char *name, PyObject *v) +.. c:function:: int PySys_SetObject(char *name, PyObject *v) Set *name* in the :mod:`sys` module to *v* unless *v* is *NULL*, in which case *name* is deleted from the sys module. Returns ``0`` on success, ``-1`` on error. -.. cfunction:: void PySys_ResetWarnOptions() +.. c:function:: void PySys_ResetWarnOptions() Reset :data:`sys.warnoptions` to an empty list. -.. cfunction:: void PySys_AddWarnOption(wchar_t *s) +.. c:function:: void PySys_AddWarnOption(wchar_t *s) Append *s* to :data:`sys.warnoptions`. -.. cfunction:: void PySys_AddWarnOptionUnicode(PyObject *unicode) +.. c:function:: void PySys_AddWarnOptionUnicode(PyObject *unicode) Append *unicode* to :data:`sys.warnoptions`. -.. cfunction:: void PySys_SetPath(wchar_t *path) +.. c:function:: void PySys_SetPath(wchar_t *path) Set :data:`sys.path` to a list object of paths found in *path* which should be a list of paths separated with the platform's search path delimiter (``:`` on Unix, ``;`` on Windows). -.. cfunction:: void PySys_WriteStdout(const char *format, ...) +.. c:function:: void PySys_WriteStdout(const char *format, ...) Write the output string described by *format* to :data:`sys.stdout`. No exceptions are raised, even if truncation occurs (see below). @@ -107,22 +107,22 @@ accessible to C code. They all work with the current interpreter thread's If a problem occurs, or :data:`sys.stdout` is unset, the formatted message is written to the real (C level) *stdout*. -.. cfunction:: void PySys_WriteStderr(const char *format, ...) +.. c:function:: void PySys_WriteStderr(const char *format, ...) - As :cfunc:`PySys_WriteStdout`, but write to :data:`sys.stderr` or *stderr* + As :c:func:`PySys_WriteStdout`, but write to :data:`sys.stderr` or *stderr* instead. -.. cfunction:: void PySys_FormatStdout(const char *format, ...) +.. c:function:: void PySys_FormatStdout(const char *format, ...) Function similar to PySys_WriteStdout() but format the message using - :cfunc:`PyUnicode_FromFormatV` and don't truncate the message to an + :c:func:`PyUnicode_FromFormatV` and don't truncate the message to an arbitrary length. .. versionadded:: 3.2 -.. cfunction:: void PySys_FormatStderr(const char *format, ...) +.. c:function:: void PySys_FormatStderr(const char *format, ...) - As :cfunc:`PySys_FormatStdout`, but write to :data:`sys.stderr` or *stderr* + As :c:func:`PySys_FormatStdout`, but write to :data:`sys.stderr` or *stderr* instead. .. versionadded:: 3.2 @@ -134,7 +134,7 @@ Process Control =============== -.. cfunction:: void Py_FatalError(const char *message) +.. c:function:: void Py_FatalError(const char *message) .. index:: single: abort() @@ -142,30 +142,30 @@ Process Control This function should only be invoked when a condition is detected that would make it dangerous to continue using the Python interpreter; e.g., when the object administration appears to be corrupted. On Unix, the standard C library - function :cfunc:`abort` is called which will attempt to produce a :file:`core` + function :c:func:`abort` is called which will attempt to produce a :file:`core` file. -.. cfunction:: void Py_Exit(int status) +.. c:function:: void Py_Exit(int status) .. index:: single: Py_Finalize() single: exit() - Exit the current process. This calls :cfunc:`Py_Finalize` and then calls the + Exit the current process. This calls :c:func:`Py_Finalize` and then calls the standard C library function ``exit(status)``. -.. cfunction:: int Py_AtExit(void (*func) ()) +.. c:function:: int Py_AtExit(void (*func) ()) .. index:: single: Py_Finalize() single: cleanup functions - Register a cleanup function to be called by :cfunc:`Py_Finalize`. The cleanup + Register a cleanup function to be called by :c:func:`Py_Finalize`. The cleanup function will be called with no arguments and should return no value. At most 32 cleanup functions can be registered. When the registration is successful, - :cfunc:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup + :c:func:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup function registered last is called first. Each cleanup function will be called at most once. Since Python's internal finalization will have completed before the cleanup function, no Python APIs should be called by *func*. diff --git a/Doc/c-api/tuple.rst b/Doc/c-api/tuple.rst index c1f8e12..7f6a79c 100644 --- a/Doc/c-api/tuple.rst +++ b/Doc/c-api/tuple.rst @@ -8,72 +8,72 @@ Tuple Objects .. index:: object: tuple -.. ctype:: PyTupleObject +.. c:type:: PyTupleObject - This subtype of :ctype:`PyObject` represents a Python tuple object. + This subtype of :c:type:`PyObject` represents a Python tuple object. -.. cvar:: PyTypeObject PyTuple_Type +.. c:var:: PyTypeObject PyTuple_Type .. index:: single: TupleType (in module types) - This instance of :ctype:`PyTypeObject` represents the Python tuple type; it is + This instance of :c:type:`PyTypeObject` represents the Python tuple type; it is the same object as ``tuple`` and ``types.TupleType`` in the Python layer.. -.. cfunction:: int PyTuple_Check(PyObject *p) +.. c:function:: int PyTuple_Check(PyObject *p) Return true if *p* is a tuple object or an instance of a subtype of the tuple type. -.. cfunction:: int PyTuple_CheckExact(PyObject *p) +.. c:function:: int PyTuple_CheckExact(PyObject *p) Return true if *p* is a tuple object, but not an instance of a subtype of the tuple type. -.. cfunction:: PyObject* PyTuple_New(Py_ssize_t len) +.. c:function:: PyObject* PyTuple_New(Py_ssize_t len) Return a new tuple object of size *len*, or *NULL* on failure. -.. cfunction:: PyObject* PyTuple_Pack(Py_ssize_t n, ...) +.. c:function:: PyObject* PyTuple_Pack(Py_ssize_t n, ...) Return a new tuple object of size *n*, or *NULL* on failure. The tuple values are initialized to the subsequent *n* C arguments pointing to Python objects. ``PyTuple_Pack(2, a, b)`` is equivalent to ``Py_BuildValue("(OO)", a, b)``. -.. cfunction:: Py_ssize_t PyTuple_Size(PyObject *p) +.. c:function:: Py_ssize_t PyTuple_Size(PyObject *p) Take a pointer to a tuple object, and return the size of that tuple. -.. cfunction:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p) +.. c:function:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p) Return the size of the tuple *p*, which must be non-*NULL* and point to a tuple; no error checking is performed. -.. cfunction:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos) +.. c:function:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos) Return the object at position *pos* in the tuple pointed to by *p*. If *pos* is out of bounds, return *NULL* and sets an :exc:`IndexError` exception. -.. cfunction:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos) +.. c:function:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos) - Like :cfunc:`PyTuple_GetItem`, but does no checking of its arguments. + Like :c:func:`PyTuple_GetItem`, but does no checking of its arguments. -.. cfunction:: PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high) +.. c:function:: PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high) Take a slice of the tuple pointed to by *p* from *low* to *high* and return it as a new tuple. -.. cfunction:: int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o) +.. c:function:: int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o) Insert a reference to object *o* at position *pos* of the tuple pointed to by *p*. Return ``0`` on success. @@ -83,9 +83,9 @@ Tuple Objects This function "steals" a reference to *o*. -.. cfunction:: void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o) +.. c:function:: void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o) - Like :cfunc:`PyTuple_SetItem`, but does no error checking, and should *only* be + Like :c:func:`PyTuple_SetItem`, but does no error checking, and should *only* be used to fill in brand new tuples. .. note:: @@ -93,7 +93,7 @@ Tuple Objects This function "steals" a reference to *o*. -.. cfunction:: int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize) +.. c:function:: int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize) Can be used to resize a tuple. *newsize* will be the new length of the tuple. Because tuples are *supposed* to be immutable, this should only be used if there @@ -107,6 +107,6 @@ Tuple Objects raises :exc:`MemoryError` or :exc:`SystemError`. -.. cfunction:: int PyTuple_ClearFreeList() +.. c:function:: int PyTuple_ClearFreeList() Clear the free list. Return the total number of freed items. diff --git a/Doc/c-api/type.rst b/Doc/c-api/type.rst index d0edd55..431d79e 100644 --- a/Doc/c-api/type.rst +++ b/Doc/c-api/type.rst @@ -8,12 +8,12 @@ Type Objects .. index:: object: type -.. ctype:: PyTypeObject +.. c:type:: PyTypeObject The C structure of the objects used to describe built-in types. -.. cvar:: PyObject* PyType_Type +.. c:var:: PyObject* PyType_Type .. index:: single: TypeType (in module types) @@ -21,58 +21,58 @@ Type Objects ``types.TypeType`` in the Python layer. -.. cfunction:: int PyType_Check(PyObject *o) +.. c:function:: int PyType_Check(PyObject *o) Return true if the object *o* is a type object, including instances of types derived from the standard type object. Return false in all other cases. -.. cfunction:: int PyType_CheckExact(PyObject *o) +.. c:function:: int PyType_CheckExact(PyObject *o) Return true if the object *o* is a type object, but not a subtype of the standard type object. Return false in all other cases. -.. cfunction:: unsigned int PyType_ClearCache() +.. c:function:: unsigned int PyType_ClearCache() Clear the internal lookup cache. Return the current version tag. -.. cfunction:: void PyType_Modified(PyTypeObject *type) +.. c:function:: void PyType_Modified(PyTypeObject *type) Invalidate the internal lookup cache for the type and all of its subtypes. This function must be called after any manual modification of the attributes or base classes of the type. -.. cfunction:: int PyType_HasFeature(PyObject *o, int feature) +.. c:function:: int PyType_HasFeature(PyObject *o, int feature) Return true if the type object *o* sets the feature *feature*. Type features are denoted by single bit flags. -.. cfunction:: int PyType_IS_GC(PyObject *o) +.. c:function:: int PyType_IS_GC(PyObject *o) Return true if the type object includes support for the cycle detector; this tests the type flag :const:`Py_TPFLAGS_HAVE_GC`. -.. cfunction:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) +.. c:function:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) Return true if *a* is a subtype of *b*. -.. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) +.. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) XXX: Document. -.. cfunction:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) +.. c:function:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) XXX: Document. -.. cfunction:: int PyType_Ready(PyTypeObject *type) +.. c:function:: int PyType_Ready(PyTypeObject *type) Finalize a type object. This should be called on all type objects to finish their initialization. This function is responsible for adding inherited slots diff --git a/Doc/c-api/typeobj.rst b/Doc/c-api/typeobj.rst index eb8a83e..a25ca41 100644 --- a/Doc/c-api/typeobj.rst +++ b/Doc/c-api/typeobj.rst @@ -6,9 +6,9 @@ Type Objects ============ Perhaps one of the most important structures of the Python object system is the -structure that defines a new type: the :ctype:`PyTypeObject` structure. Type -objects can be handled using any of the :cfunc:`PyObject_\*` or -:cfunc:`PyType_\*` functions, but do not offer much that's interesting to most +structure that defines a new type: the :c:type:`PyTypeObject` structure. Type +objects can be handled using any of the :c:func:`PyObject_\*` or +:c:func:`PyType_\*` functions, but do not offer much that's interesting to most Python applications. These objects are fundamental to how objects behave, so they are very important to the interpreter itself and to any extension module that implements new types. @@ -25,21 +25,21 @@ intintargfunc, intobjargproc, intintobjargproc, objobjargproc, destructor, freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc, reprfunc, hashfunc -The structure definition for :ctype:`PyTypeObject` can be found in +The structure definition for :c:type:`PyTypeObject` can be found in :file:`Include/object.h`. For convenience of reference, this repeats the definition found there: .. literalinclude:: ../includes/typestruct.h -The type object structure extends the :ctype:`PyVarObject` structure. The +The type object structure extends the :c:type:`PyVarObject` structure. The :attr:`ob_size` field is used for dynamic types (created by :func:`type_new`, -usually called from a class statement). Note that :cdata:`PyType_Type` (the +usually called from a class statement). Note that :c:data:`PyType_Type` (the metatype) initializes :attr:`tp_itemsize`, which means that its instances (i.e. type objects) *must* have the :attr:`ob_size` field. -.. cmember:: PyObject* PyObject._ob_next +.. c:member:: PyObject* PyObject._ob_next PyObject* PyObject._ob_prev These fields are only present when the macro ``Py_TRACE_REFS`` is defined. @@ -54,7 +54,7 @@ type objects) *must* have the :attr:`ob_size` field. These fields are not inherited by subtypes. -.. cmember:: Py_ssize_t PyObject.ob_refcnt +.. c:member:: Py_ssize_t PyObject.ob_refcnt This is the type object's reference count, initialized to ``1`` by the ``PyObject_HEAD_INIT`` macro. Note that for statically allocated type objects, @@ -65,7 +65,7 @@ type objects) *must* have the :attr:`ob_size` field. This field is not inherited by subtypes. -.. cmember:: PyTypeObject* PyObject.ob_type +.. c:member:: PyTypeObject* PyObject.ob_type This is the type's type, in other words its metatype. It is initialized by the argument to the ``PyObject_HEAD_INIT`` macro, and its value should normally be @@ -79,14 +79,14 @@ type objects) *must* have the :attr:`ob_size` field. Foo_Type.ob_type = &PyType_Type; This should be done before any instances of the type are created. - :cfunc:`PyType_Ready` checks if :attr:`ob_type` is *NULL*, and if so, + :c:func:`PyType_Ready` checks if :attr:`ob_type` is *NULL*, and if so, initializes it to the :attr:`ob_type` field of the base class. - :cfunc:`PyType_Ready` will not change this field if it is non-zero. + :c:func:`PyType_Ready` will not change this field if it is non-zero. This field is inherited by subtypes. -.. cmember:: Py_ssize_t PyVarObject.ob_size +.. c:member:: Py_ssize_t PyVarObject.ob_size For statically allocated type objects, this should be initialized to zero. For dynamically allocated type objects, this field has a special internal meaning. @@ -94,7 +94,7 @@ type objects) *must* have the :attr:`ob_size` field. This field is not inherited by subtypes. -.. cmember:: char* PyTypeObject.tp_name +.. c:member:: char* PyTypeObject.tp_name Pointer to a NUL-terminated string containing the name of the type. For types that are accessible as module globals, the string should be the full module @@ -121,7 +121,7 @@ type objects) *must* have the :attr:`ob_size` field. This field is not inherited by subtypes. -.. cmember:: Py_ssize_t PyTypeObject.tp_basicsize +.. c:member:: Py_ssize_t PyTypeObject.tp_basicsize Py_ssize_t PyTypeObject.tp_itemsize These fields allow calculating the size in bytes of instances of the type. @@ -143,7 +143,7 @@ type objects) *must* have the :attr:`ob_size` field. field). The basic size includes the fields in the instance declared by the macro - :cmacro:`PyObject_HEAD` or :cmacro:`PyObject_VAR_HEAD` (whichever is used to + :c:macro:`PyObject_HEAD` or :c:macro:`PyObject_VAR_HEAD` (whichever is used to declare the instance struct) and this in turn includes the :attr:`_ob_prev` and :attr:`_ob_next` fields if they are present. This means that the only correct way to get an initializer for the :attr:`tp_basicsize` is to use the @@ -163,14 +163,14 @@ type objects) *must* have the :attr:`ob_size` field. alignment requirement for ``double``). -.. cmember:: destructor PyTypeObject.tp_dealloc +.. c:member:: destructor PyTypeObject.tp_dealloc A pointer to the instance destructor function. This function must be defined unless the type guarantees that its instances will never be deallocated (as is the case for the singletons ``None`` and ``Ellipsis``). - The destructor function is called by the :cfunc:`Py_DECREF` and - :cfunc:`Py_XDECREF` macros when the new reference count is zero. At this point, + The destructor function is called by the :c:func:`Py_DECREF` and + :c:func:`Py_XDECREF` macros when the new reference count is zero. At this point, the instance is still in existence, but there are no references to it. The destructor function should free all references which the instance owns, free all memory buffers owned by the instance (using the freeing function corresponding @@ -179,15 +179,15 @@ type objects) *must* have the :attr:`ob_size` field. subtypable (doesn't have the :const:`Py_TPFLAGS_BASETYPE` flag bit set), it is permissible to call the object deallocator directly instead of via :attr:`tp_free`. The object deallocator should be the one used to allocate the - instance; this is normally :cfunc:`PyObject_Del` if the instance was allocated - using :cfunc:`PyObject_New` or :cfunc:`PyObject_VarNew`, or - :cfunc:`PyObject_GC_Del` if the instance was allocated using - :cfunc:`PyObject_GC_New` or :cfunc:`PyObject_GC_NewVar`. + instance; this is normally :c:func:`PyObject_Del` if the instance was allocated + using :c:func:`PyObject_New` or :c:func:`PyObject_VarNew`, or + :c:func:`PyObject_GC_Del` if the instance was allocated using + :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`. This field is inherited by subtypes. -.. cmember:: printfunc PyTypeObject.tp_print +.. c:member:: printfunc PyTypeObject.tp_print An optional pointer to the instance print function. @@ -198,7 +198,7 @@ type objects) *must* have the :attr:`ob_size` field. *NULL*. A type should never implement :attr:`tp_print` in a way that produces different output than :attr:`tp_repr` or :attr:`tp_str` would. - The print function is called with the same signature as :cfunc:`PyObject_Print`: + The print function is called with the same signature as :c:func:`PyObject_Print`: ``int tp_print(PyObject *self, FILE *file, int flags)``. The *self* argument is the instance to be printed. The *file* argument is the stdio file to which it is to be printed. The *flags* argument is composed of flag bits. The only flag @@ -216,47 +216,47 @@ type objects) *must* have the :attr:`ob_size` field. This field is inherited by subtypes. -.. cmember:: getattrfunc PyTypeObject.tp_getattr +.. c:member:: getattrfunc PyTypeObject.tp_getattr An optional pointer to the get-attribute-string function. This field is deprecated. When it is defined, it should point to a function that acts the same as the :attr:`tp_getattro` function, but taking a C string instead of a Python string object to give the attribute name. The signature is - the same as for :cfunc:`PyObject_GetAttrString`. + the same as for :c:func:`PyObject_GetAttrString`. This field is inherited by subtypes together with :attr:`tp_getattro`: a subtype inherits both :attr:`tp_getattr` and :attr:`tp_getattro` from its base type when the subtype's :attr:`tp_getattr` and :attr:`tp_getattro` are both *NULL*. -.. cmember:: setattrfunc PyTypeObject.tp_setattr +.. c:member:: setattrfunc PyTypeObject.tp_setattr An optional pointer to the set-attribute-string function. This field is deprecated. When it is defined, it should point to a function that acts the same as the :attr:`tp_setattro` function, but taking a C string instead of a Python string object to give the attribute name. The signature is - the same as for :cfunc:`PyObject_SetAttrString`. + the same as for :c:func:`PyObject_SetAttrString`. This field is inherited by subtypes together with :attr:`tp_setattro`: a subtype inherits both :attr:`tp_setattr` and :attr:`tp_setattro` from its base type when the subtype's :attr:`tp_setattr` and :attr:`tp_setattro` are both *NULL*. -.. cmember:: void* PyTypeObject.tp_reserved +.. c:member:: void* PyTypeObject.tp_reserved Reserved slot, formerly known as tp_compare. -.. cmember:: reprfunc PyTypeObject.tp_repr +.. c:member:: reprfunc PyTypeObject.tp_repr .. index:: builtin: repr An optional pointer to a function that implements the built-in function :func:`repr`. - The signature is the same as for :cfunc:`PyObject_Repr`; it must return a string + The signature is the same as for :c:func:`PyObject_Repr`; it must return a string or a Unicode object. Ideally, this function should return a string that, when passed to :func:`eval`, given a suitable environment, returns an object with the same value. If this is not feasible, it should return a string starting with @@ -269,7 +269,7 @@ type objects) *must* have the :attr:`ob_size` field. This field is inherited by subtypes. -.. cmember:: PyNumberMethods* tp_as_number +.. c:member:: PyNumberMethods* tp_as_number Pointer to an additional structure that contains fields relevant only to objects which implement the number protocol. These fields are documented in @@ -279,7 +279,7 @@ type objects) *must* have the :attr:`ob_size` field. inherited individually. -.. cmember:: PySequenceMethods* tp_as_sequence +.. c:member:: PySequenceMethods* tp_as_sequence Pointer to an additional structure that contains fields relevant only to objects which implement the sequence protocol. These fields are documented @@ -289,7 +289,7 @@ type objects) *must* have the :attr:`ob_size` field. are inherited individually. -.. cmember:: PyMappingMethods* tp_as_mapping +.. c:member:: PyMappingMethods* tp_as_mapping Pointer to an additional structure that contains fields relevant only to objects which implement the mapping protocol. These fields are documented in @@ -299,25 +299,25 @@ type objects) *must* have the :attr:`ob_size` field. are inherited individually. -.. cmember:: hashfunc PyTypeObject.tp_hash +.. c:member:: hashfunc PyTypeObject.tp_hash .. index:: builtin: hash An optional pointer to a function that implements the built-in function :func:`hash`. - The signature is the same as for :cfunc:`PyObject_Hash`; it must return a C + The signature is the same as for :c:func:`PyObject_Hash`; it must return a C long. The value ``-1`` should not be returned as a normal return value; when an error occurs during the computation of the hash value, the function should set an exception and return ``-1``. - This field can be set explicitly to :cfunc:`PyObject_HashNotImplemented` to + This field can be set explicitly to :c:func:`PyObject_HashNotImplemented` to block inheritance of the hash method from a parent type. This is interpreted as the equivalent of ``__hash__ = None`` at the Python level, causing ``isinstance(o, collections.Hashable)`` to correctly return ``False``. Note that the converse is also true - setting ``__hash__ = None`` on a class at the Python level will result in the ``tp_hash`` slot being set to - :cfunc:`PyObject_HashNotImplemented`. + :c:func:`PyObject_HashNotImplemented`. When this field is not set, an attempt to take the hash of the object raises :exc:`TypeError`. @@ -328,39 +328,39 @@ type objects) *must* have the :attr:`ob_size` field. :attr:`tp_richcompare` and :attr:`tp_hash` are both *NULL*. -.. cmember:: ternaryfunc PyTypeObject.tp_call +.. c:member:: ternaryfunc PyTypeObject.tp_call An optional pointer to a function that implements calling the object. This should be *NULL* if the object is not callable. The signature is the same as - for :cfunc:`PyObject_Call`. + for :c:func:`PyObject_Call`. This field is inherited by subtypes. -.. cmember:: reprfunc PyTypeObject.tp_str +.. c:member:: reprfunc PyTypeObject.tp_str An optional pointer to a function that implements the built-in operation :func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls the - constructor for that type. This constructor calls :cfunc:`PyObject_Str` to do - the actual work, and :cfunc:`PyObject_Str` will call this handler.) + constructor for that type. This constructor calls :c:func:`PyObject_Str` to do + the actual work, and :c:func:`PyObject_Str` will call this handler.) - The signature is the same as for :cfunc:`PyObject_Str`; it must return a string + The signature is the same as for :c:func:`PyObject_Str`; it must return a string or a Unicode object. This function should return a "friendly" string representation of the object, as this is the representation that will be used, among other things, by the :func:`print` function. - When this field is not set, :cfunc:`PyObject_Repr` is called to return a string + When this field is not set, :c:func:`PyObject_Repr` is called to return a string representation. This field is inherited by subtypes. -.. cmember:: getattrofunc PyTypeObject.tp_getattro +.. c:member:: getattrofunc PyTypeObject.tp_getattro An optional pointer to the get-attribute function. - The signature is the same as for :cfunc:`PyObject_GetAttr`. It is usually - convenient to set this field to :cfunc:`PyObject_GenericGetAttr`, which + The signature is the same as for :c:func:`PyObject_GetAttr`. It is usually + convenient to set this field to :c:func:`PyObject_GenericGetAttr`, which implements the normal way of looking for object attributes. This field is inherited by subtypes together with :attr:`tp_getattr`: a subtype @@ -368,12 +368,12 @@ type objects) *must* have the :attr:`ob_size` field. the subtype's :attr:`tp_getattr` and :attr:`tp_getattro` are both *NULL*. -.. cmember:: setattrofunc PyTypeObject.tp_setattro +.. c:member:: setattrofunc PyTypeObject.tp_setattro An optional pointer to the set-attribute function. - The signature is the same as for :cfunc:`PyObject_SetAttr`. It is usually - convenient to set this field to :cfunc:`PyObject_GenericSetAttr`, which + The signature is the same as for :c:func:`PyObject_SetAttr`. It is usually + convenient to set this field to :c:func:`PyObject_GenericSetAttr`, which implements the normal way of setting object attributes. This field is inherited by subtypes together with :attr:`tp_setattr`: a subtype @@ -381,7 +381,7 @@ type objects) *must* have the :attr:`ob_size` field. the subtype's :attr:`tp_setattr` and :attr:`tp_setattro` are both *NULL*. -.. cmember:: PyBufferProcs* PyTypeObject.tp_as_buffer +.. c:member:: PyBufferProcs* PyTypeObject.tp_as_buffer Pointer to an additional structure that contains fields relevant only to objects which implement the buffer interface. These fields are documented in @@ -391,7 +391,7 @@ type objects) *must* have the :attr:`ob_size` field. inherited individually. -.. cmember:: long PyTypeObject.tp_flags +.. c:member:: long PyTypeObject.tp_flags This field is a bit mask of various flags. Some flags indicate variant semantics for certain situations; others are used to indicate that certain @@ -414,7 +414,7 @@ type objects) *must* have the :attr:`ob_size` field. The following bit masks are currently defined; these can be ORed together using the ``|`` operator to form the value of the :attr:`tp_flags` field. The macro - :cfunc:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and + :c:func:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and checks whether ``tp->tp_flags & f`` is non-zero. @@ -438,20 +438,20 @@ type objects) *must* have the :attr:`ob_size` field. .. data:: Py_TPFLAGS_READY This bit is set when the type object has been fully initialized by - :cfunc:`PyType_Ready`. + :c:func:`PyType_Ready`. .. data:: Py_TPFLAGS_READYING - This bit is set while :cfunc:`PyType_Ready` is in the process of initializing + This bit is set while :c:func:`PyType_Ready` is in the process of initializing the type object. .. data:: Py_TPFLAGS_HAVE_GC This bit is set when the object supports garbage collection. If this bit - is set, instances must be created using :cfunc:`PyObject_GC_New` and - destroyed using :cfunc:`PyObject_GC_Del`. More information in section + is set, instances must be created using :c:func:`PyObject_GC_New` and + destroyed using :c:func:`PyObject_GC_Del`. More information in section :ref:`supporting-cycle-detection`. This bit also implies that the GC-related fields :attr:`tp_traverse` and :attr:`tp_clear` are present in the type object. @@ -465,7 +465,7 @@ type objects) *must* have the :attr:`ob_size` field. :const:`Py_TPFLAGS_HAVE_VERSION_TAG`. -.. cmember:: char* PyTypeObject.tp_doc +.. c:member:: char* PyTypeObject.tp_doc An optional pointer to a NUL-terminated C string giving the docstring for this type object. This is exposed as the :attr:`__doc__` attribute on the type and @@ -474,7 +474,7 @@ type objects) *must* have the :attr:`ob_size` field. This field is *not* inherited by subtypes. -.. cmember:: traverseproc PyTypeObject.tp_traverse +.. c:member:: traverseproc PyTypeObject.tp_traverse An optional pointer to a traversal function for the garbage collector. This is only used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set. More information @@ -483,8 +483,8 @@ type objects) *must* have the :attr:`ob_size` field. The :attr:`tp_traverse` pointer is used by the garbage collector to detect reference cycles. A typical implementation of a :attr:`tp_traverse` function - simply calls :cfunc:`Py_VISIT` on each of the instance's members that are Python - objects. For example, this is function :cfunc:`local_traverse` from the + simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python + objects. For example, this is function :c:func:`local_traverse` from the :mod:`_thread` extension module:: static int @@ -496,7 +496,7 @@ type objects) *must* have the :attr:`ob_size` field. return 0; } - Note that :cfunc:`Py_VISIT` is called only on those members that can participate + Note that :c:func:`Py_VISIT` is called only on those members that can participate in reference cycles. Although there is also a ``self->key`` member, it can only be *NULL* or a Python string and therefore cannot be part of a reference cycle. @@ -504,8 +504,8 @@ type objects) *must* have the :attr:`ob_size` field. debugging aid you may want to visit it anyway just so the :mod:`gc` module's :func:`get_referents` function will include it. - Note that :cfunc:`Py_VISIT` requires the *visit* and *arg* parameters to - :cfunc:`local_traverse` to have these specific names; don't name them just + Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to + :c:func:`local_traverse` to have these specific names; don't name them just anything. This field is inherited by subtypes together with :attr:`tp_clear` and the @@ -514,7 +514,7 @@ type objects) *must* have the :attr:`ob_size` field. the subtype. -.. cmember:: inquiry PyTypeObject.tp_clear +.. c:member:: inquiry PyTypeObject.tp_clear An optional pointer to a clear function for the garbage collector. This is only used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set. @@ -543,7 +543,7 @@ type objects) *must* have the :attr:`ob_size` field. return 0; } - The :cfunc:`Py_CLEAR` macro should be used, because clearing references is + The :c:func:`Py_CLEAR` macro should be used, because clearing references is delicate: the reference to the contained object must not be decremented until after the pointer to the contained object is set to *NULL*. This is because decrementing the reference count may cause the contained object to become trash, @@ -552,7 +552,7 @@ type objects) *must* have the :attr:`ob_size` field. contained object). If it's possible for such code to reference *self* again, it's important that the pointer to the contained object be *NULL* at that time, so that *self* knows the contained object can no longer be used. The - :cfunc:`Py_CLEAR` macro performs the operations in a safe order. + :c:func:`Py_CLEAR` macro performs the operations in a safe order. Because the goal of :attr:`tp_clear` functions is to break reference cycles, it's not necessary to clear contained objects like Python strings or Python @@ -569,7 +569,7 @@ type objects) *must* have the :attr:`ob_size` field. the subtype. -.. cmember:: richcmpfunc PyTypeObject.tp_richcompare +.. c:member:: richcmpfunc PyTypeObject.tp_richcompare An optional pointer to the rich comparison function, whose signature is ``PyObject *tp_richcompare(PyObject *a, PyObject *b, int op)``. @@ -591,7 +591,7 @@ type objects) *must* have the :attr:`ob_size` field. *NULL*. The following constants are defined to be used as the third argument for - :attr:`tp_richcompare` and for :cfunc:`PyObject_RichCompare`: + :attr:`tp_richcompare` and for :c:func:`PyObject_RichCompare`: +----------------+------------+ | Constant | Comparison | @@ -610,13 +610,13 @@ type objects) *must* have the :attr:`ob_size` field. +----------------+------------+ -.. cmember:: long PyTypeObject.tp_weaklistoffset +.. c:member:: long PyTypeObject.tp_weaklistoffset If the instances of this type are weakly referenceable, this field is greater than zero and contains the offset in the instance structure of the weak reference list head (ignoring the GC header, if present); this offset is used by - :cfunc:`PyObject_ClearWeakRefs` and the :cfunc:`PyWeakref_\*` functions. The - instance structure needs to include a field of type :ctype:`PyObject\*` which is + :c:func:`PyObject_ClearWeakRefs` and the :c:func:`PyWeakref_\*` functions. The + instance structure needs to include a field of type :c:type:`PyObject\*` which is initialized to *NULL*. Do not confuse this field with :attr:`tp_weaklist`; that is the list head for @@ -641,18 +641,18 @@ type objects) *must* have the :attr:`ob_size` field. :attr:`__weakref__`, the type inherits its :attr:`tp_weaklistoffset` from its base type. -.. cmember:: getiterfunc PyTypeObject.tp_iter +.. c:member:: getiterfunc PyTypeObject.tp_iter An optional pointer to a function that returns an iterator for the object. Its presence normally signals that the instances of this type are iterable (although sequences may be iterable without this function). - This function has the same signature as :cfunc:`PyObject_GetIter`. + This function has the same signature as :c:func:`PyObject_GetIter`. This field is inherited by subtypes. -.. cmember:: iternextfunc PyTypeObject.tp_iternext +.. c:member:: iternextfunc PyTypeObject.tp_iternext An optional pointer to a function that returns the next item in an iterator. When the iterator is exhausted, it must return *NULL*; a :exc:`StopIteration` @@ -664,14 +664,14 @@ type objects) *must* have the :attr:`ob_size` field. function should return the iterator instance itself (not a new iterator instance). - This function has the same signature as :cfunc:`PyIter_Next`. + This function has the same signature as :c:func:`PyIter_Next`. This field is inherited by subtypes. -.. cmember:: struct PyMethodDef* PyTypeObject.tp_methods +.. c:member:: struct PyMethodDef* PyTypeObject.tp_methods - An optional pointer to a static *NULL*-terminated array of :ctype:`PyMethodDef` + An optional pointer to a static *NULL*-terminated array of :c:type:`PyMethodDef` structures, declaring regular methods of this type. For each entry in the array, an entry is added to the type's dictionary (see @@ -681,9 +681,9 @@ type objects) *must* have the :attr:`ob_size` field. different mechanism). -.. cmember:: struct PyMemberDef* PyTypeObject.tp_members +.. c:member:: struct PyMemberDef* PyTypeObject.tp_members - An optional pointer to a static *NULL*-terminated array of :ctype:`PyMemberDef` + An optional pointer to a static *NULL*-terminated array of :c:type:`PyMemberDef` structures, declaring regular data members (fields or slots) of instances of this type. @@ -694,9 +694,9 @@ type objects) *must* have the :attr:`ob_size` field. different mechanism). -.. cmember:: struct PyGetSetDef* PyTypeObject.tp_getset +.. c:member:: struct PyGetSetDef* PyTypeObject.tp_getset - An optional pointer to a static *NULL*-terminated array of :ctype:`PyGetSetDef` + An optional pointer to a static *NULL*-terminated array of :c:type:`PyGetSetDef` structures, declaring computed attributes of instances of this type. For each entry in the array, an entry is added to the type's dictionary (see @@ -719,7 +719,7 @@ type objects) *must* have the :attr:`ob_size` field. } PyGetSetDef; -.. cmember:: PyTypeObject* PyTypeObject.tp_base +.. c:member:: PyTypeObject* PyTypeObject.tp_base An optional pointer to a base type from which type properties are inherited. At this level, only single inheritance is supported; multiple inheritance require @@ -730,13 +730,13 @@ type objects) *must* have the :attr:`ob_size` field. :class:`object`). -.. cmember:: PyObject* PyTypeObject.tp_dict +.. c:member:: PyObject* PyTypeObject.tp_dict - The type's dictionary is stored here by :cfunc:`PyType_Ready`. + The type's dictionary is stored here by :c:func:`PyType_Ready`. This field should normally be initialized to *NULL* before PyType_Ready is called; it may also be initialized to a dictionary containing initial attributes - for the type. Once :cfunc:`PyType_Ready` has initialized the type, extra + for the type. Once :c:func:`PyType_Ready` has initialized the type, extra attributes for the type may be added to this dictionary only if they don't correspond to overloaded operations (like :meth:`__add__`). @@ -744,7 +744,7 @@ type objects) *must* have the :attr:`ob_size` field. are inherited through a different mechanism). -.. cmember:: descrgetfunc PyTypeObject.tp_descr_get +.. c:member:: descrgetfunc PyTypeObject.tp_descr_get An optional pointer to a "descriptor get" function. @@ -757,7 +757,7 @@ type objects) *must* have the :attr:`ob_size` field. This field is inherited by subtypes. -.. cmember:: descrsetfunc PyTypeObject.tp_descr_set +.. c:member:: descrsetfunc PyTypeObject.tp_descr_set An optional pointer to a "descriptor set" function. @@ -770,12 +770,12 @@ type objects) *must* have the :attr:`ob_size` field. XXX explain. -.. cmember:: long PyTypeObject.tp_dictoffset +.. c:member:: long PyTypeObject.tp_dictoffset If the instances of this type have a dictionary containing instance variables, this field is non-zero and contains the offset in the instances of the type of the instance variable dictionary; this offset is used by - :cfunc:`PyObject_GenericGetAttr`. + :c:func:`PyObject_GenericGetAttr`. Do not confuse this field with :attr:`tp_dict`; that is the dictionary for attributes of the type object itself. @@ -803,7 +803,7 @@ type objects) *must* have the :attr:`ob_size` field. taken from the type object, and :attr:`ob_size` is taken from the instance. The absolute value is taken because ints use the sign of :attr:`ob_size` to store the sign of the number. (There's never a need to do this calculation - yourself; it is done for you by :cfunc:`_PyObject_GetDictPtr`.) + yourself; it is done for you by :c:func:`_PyObject_GetDictPtr`.) This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means that the subtype instances store the @@ -823,7 +823,7 @@ type objects) *must* have the :attr:`ob_size` field. added as a feature just like :attr:`__weakref__` though.) -.. cmember:: initproc PyTypeObject.tp_init +.. c:member:: initproc PyTypeObject.tp_init An optional pointer to an instance initialization function. @@ -850,7 +850,7 @@ type objects) *must* have the :attr:`ob_size` field. This field is inherited by subtypes. -.. cmember:: allocfunc PyTypeObject.tp_alloc +.. c:member:: allocfunc PyTypeObject.tp_alloc An optional pointer to an instance allocation function. @@ -873,11 +873,11 @@ type objects) *must* have the :attr:`ob_size` field. This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement); in the latter, this field is always set - to :cfunc:`PyType_GenericAlloc`, to force a standard heap allocation strategy. + to :c:func:`PyType_GenericAlloc`, to force a standard heap allocation strategy. That is also the recommended value for statically defined types. -.. cmember:: newfunc PyTypeObject.tp_new +.. c:member:: newfunc PyTypeObject.tp_new An optional pointer to an instance creation function. @@ -907,22 +907,22 @@ type objects) *must* have the :attr:`ob_size` field. whose :attr:`tp_base` is *NULL* or ``&PyBaseObject_Type``. -.. cmember:: destructor PyTypeObject.tp_free +.. c:member:: destructor PyTypeObject.tp_free An optional pointer to an instance deallocation function. Its signature is - :ctype:`freefunc`:: + :c:type:`freefunc`:: void tp_free(void *) - An initializer that is compatible with this signature is :cfunc:`PyObject_Free`. + An initializer that is compatible with this signature is :c:func:`PyObject_Free`. This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement); in the latter, this field is set to a - deallocator suitable to match :cfunc:`PyType_GenericAlloc` and the value of the + deallocator suitable to match :c:func:`PyType_GenericAlloc` and the value of the :const:`Py_TPFLAGS_HAVE_GC` flag bit. -.. cmember:: inquiry PyTypeObject.tp_is_gc +.. c:member:: inquiry PyTypeObject.tp_is_gc An optional pointer to a function called by the garbage collector. @@ -937,13 +937,13 @@ type objects) *must* have the :attr:`ob_size` field. int tp_is_gc(PyObject *self) (The only example of this are types themselves. The metatype, - :cdata:`PyType_Type`, defines this function to distinguish between statically + :c:data:`PyType_Type`, defines this function to distinguish between statically and dynamically allocated types.) This field is inherited by subtypes. -.. cmember:: PyObject* PyTypeObject.tp_bases +.. c:member:: PyObject* PyTypeObject.tp_bases Tuple of base types. @@ -953,25 +953,25 @@ type objects) *must* have the :attr:`ob_size` field. This field is not inherited. -.. cmember:: PyObject* PyTypeObject.tp_mro +.. c:member:: PyObject* PyTypeObject.tp_mro Tuple containing the expanded set of base types, starting with the type itself and ending with :class:`object`, in Method Resolution Order. - This field is not inherited; it is calculated fresh by :cfunc:`PyType_Ready`. + This field is not inherited; it is calculated fresh by :c:func:`PyType_Ready`. -.. cmember:: PyObject* PyTypeObject.tp_cache +.. c:member:: PyObject* PyTypeObject.tp_cache Unused. Not inherited. Internal use only. -.. cmember:: PyObject* PyTypeObject.tp_subclasses +.. c:member:: PyObject* PyTypeObject.tp_subclasses List of weak references to subclasses. Not inherited. Internal use only. -.. cmember:: PyObject* PyTypeObject.tp_weaklist +.. c:member:: PyObject* PyTypeObject.tp_weaklist Weak reference list head, for weak references to this type object. Not inherited. Internal use only. @@ -982,22 +982,22 @@ documented here for completeness. None of these fields are inherited by subtypes. -.. cmember:: Py_ssize_t PyTypeObject.tp_allocs +.. c:member:: Py_ssize_t PyTypeObject.tp_allocs Number of allocations. -.. cmember:: Py_ssize_t PyTypeObject.tp_frees +.. c:member:: Py_ssize_t PyTypeObject.tp_frees Number of frees. -.. cmember:: Py_ssize_t PyTypeObject.tp_maxalloc +.. c:member:: Py_ssize_t PyTypeObject.tp_maxalloc Maximum simultaneously allocated objects. -.. cmember:: PyTypeObject* PyTypeObject.tp_next +.. c:member:: PyTypeObject* PyTypeObject.tp_next Pointer to the next type object with a non-zero :attr:`tp_allocs` field. @@ -1020,7 +1020,7 @@ Number Object Structures .. sectionauthor:: Amaury Forgeot d'Arc -.. ctype:: PyNumberMethods +.. c:type:: PyNumberMethods This structure holds pointers to the functions which an object uses to implement the number protocol. Each function is used by the function of @@ -1079,8 +1079,8 @@ Number Object Structures .. note:: - The :cdata:`nb_reserved` field should always be ``NULL``. It - was previously called :cdata:`nb_long`, and was renamed in + The :c:data:`nb_reserved` field should always be ``NULL``. It + was previously called :c:data:`nb_long`, and was renamed in Python 3.0.1. @@ -1092,26 +1092,26 @@ Mapping Object Structures .. sectionauthor:: Amaury Forgeot d'Arc -.. ctype:: PyMappingMethods +.. c:type:: PyMappingMethods This structure holds pointers to the functions which an object uses to implement the mapping protocol. It has three members: -.. cmember:: lenfunc PyMappingMethods.mp_length +.. c:member:: lenfunc PyMappingMethods.mp_length - This function is used by :cfunc:`PyMapping_Length` and - :cfunc:`PyObject_Size`, and has the same signature. This slot may be set to + This function is used by :c:func:`PyMapping_Length` and + :c:func:`PyObject_Size`, and has the same signature. This slot may be set to *NULL* if the object has no defined length. -.. cmember:: binaryfunc PyMappingMethods.mp_subscript +.. c:member:: binaryfunc PyMappingMethods.mp_subscript - This function is used by :cfunc:`PyObject_GetItem` and has the same - signature. This slot must be filled for the :cfunc:`PyMapping_Check` + This function is used by :c:func:`PyObject_GetItem` and has the same + signature. This slot must be filled for the :c:func:`PyMapping_Check` function to return ``1``, it can be *NULL* otherwise. -.. cmember:: objobjargproc PyMappingMethods.mp_ass_subscript +.. c:member:: objobjargproc PyMappingMethods.mp_ass_subscript - This function is used by :cfunc:`PyObject_SetItem` and has the same + This function is used by :c:func:`PyObject_SetItem` and has the same signature. If this slot is *NULL*, the object does not support item assignment. @@ -1124,32 +1124,32 @@ Sequence Object Structures .. sectionauthor:: Amaury Forgeot d'Arc -.. ctype:: PySequenceMethods +.. c:type:: PySequenceMethods This structure holds pointers to the functions which an object uses to implement the sequence protocol. -.. cmember:: lenfunc PySequenceMethods.sq_length +.. c:member:: lenfunc PySequenceMethods.sq_length - This function is used by :cfunc:`PySequence_Size` and :cfunc:`PyObject_Size`, + This function is used by :c:func:`PySequence_Size` and :c:func:`PyObject_Size`, and has the same signature. -.. cmember:: binaryfunc PySequenceMethods.sq_concat +.. c:member:: binaryfunc PySequenceMethods.sq_concat - This function is used by :cfunc:`PySequence_Concat` and has the same + This function is used by :c:func:`PySequence_Concat` and has the same signature. It is also used by the ``+`` operator, after trying the numeric addition via the :attr:`tp_as_number.nb_add` slot. -.. cmember:: ssizeargfunc PySequenceMethods.sq_repeat +.. c:member:: ssizeargfunc PySequenceMethods.sq_repeat - This function is used by :cfunc:`PySequence_Repeat` and has the same + This function is used by :c:func:`PySequence_Repeat` and has the same signature. It is also used by the ``*`` operator, after trying numeric multiplication via the :attr:`tp_as_number.nb_mul` slot. -.. cmember:: ssizeargfunc PySequenceMethods.sq_item +.. c:member:: ssizeargfunc PySequenceMethods.sq_item - This function is used by :cfunc:`PySequence_GetItem` and has the same - signature. This slot must be filled for the :cfunc:`PySequence_Check` + This function is used by :c:func:`PySequence_GetItem` and has the same + signature. This slot must be filled for the :c:func:`PySequence_Check` function to return ``1``, it can be *NULL* otherwise. Negative indexes are handled as follows: if the :attr:`sq_length` slot is @@ -1157,27 +1157,27 @@ Sequence Object Structures index which is passed to :attr:`sq_item`. If :attr:`sq_length` is *NULL*, the index is passed as is to the function. -.. cmember:: ssizeobjargproc PySequenceMethods.sq_ass_item +.. c:member:: ssizeobjargproc PySequenceMethods.sq_ass_item - This function is used by :cfunc:`PySequence_SetItem` and has the same + This function is used by :c:func:`PySequence_SetItem` and has the same signature. This slot may be left to *NULL* if the object does not support item assignment. -.. cmember:: objobjproc PySequenceMethods.sq_contains +.. c:member:: objobjproc PySequenceMethods.sq_contains - This function may be used by :cfunc:`PySequence_Contains` and has the same + This function may be used by :c:func:`PySequence_Contains` and has the same signature. This slot may be left to *NULL*, in this case - :cfunc:`PySequence_Contains` simply traverses the sequence until it finds a + :c:func:`PySequence_Contains` simply traverses the sequence until it finds a match. -.. cmember:: binaryfunc PySequenceMethods.sq_inplace_concat +.. c:member:: binaryfunc PySequenceMethods.sq_inplace_concat - This function is used by :cfunc:`PySequence_InPlaceConcat` and has the same + This function is used by :c:func:`PySequence_InPlaceConcat` and has the same signature. It should modify its first operand, and return it. -.. cmember:: ssizeargfunc PySequenceMethods.sq_inplace_repeat +.. c:member:: ssizeargfunc PySequenceMethods.sq_inplace_repeat - This function is used by :cfunc:`PySequence_InPlaceRepeat` and has the same + This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same signature. It should modify its first operand, and return it. .. XXX need to explain precedence between mapping and sequence @@ -1197,40 +1197,40 @@ The buffer interface exports a model where an object can expose its internal data. If an object does not export the buffer interface, then its :attr:`tp_as_buffer` -member in the :ctype:`PyTypeObject` structure should be *NULL*. Otherwise, the -:attr:`tp_as_buffer` will point to a :ctype:`PyBufferProcs` structure. +member in the :c:type:`PyTypeObject` structure should be *NULL*. Otherwise, the +:attr:`tp_as_buffer` will point to a :c:type:`PyBufferProcs` structure. -.. ctype:: PyBufferProcs +.. c:type:: PyBufferProcs Structure used to hold the function pointers which define an implementation of the buffer protocol. - .. cmember:: getbufferproc bf_getbuffer + .. c:member:: getbufferproc bf_getbuffer - This should fill a :ctype:`Py_buffer` with the necessary data for + This should fill a :c:type:`Py_buffer` with the necessary data for exporting the type. The signature of :data:`getbufferproc` is ``int (PyObject *obj, Py_buffer *view, int flags)``. *obj* is the object to - export, *view* is the :ctype:`Py_buffer` struct to fill, and *flags* gives + export, *view* is the :c:type:`Py_buffer` struct to fill, and *flags* gives the conditions the caller wants the memory under. (See - :cfunc:`PyObject_GetBuffer` for all flags.) :cmember:`bf_getbuffer` is + :c:func:`PyObject_GetBuffer` for all flags.) :c:member:`bf_getbuffer` is responsible for filling *view* with the appropriate information. - (:cfunc:`PyBuffer_FillView` can be used in simple cases.) See - :ctype:`Py_buffer`\s docs for what needs to be filled in. + (:c:func:`PyBuffer_FillView` can be used in simple cases.) See + :c:type:`Py_buffer`\s docs for what needs to be filled in. - .. cmember:: releasebufferproc bf_releasebuffer + .. c:member:: releasebufferproc bf_releasebuffer This should release the resources of the buffer. The signature of - :cdata:`releasebufferproc` is ``void (PyObject *obj, Py_buffer *view)``. - If the :cdata:`bf_releasebuffer` function is not provided (i.e. it is + :c:data:`releasebufferproc` is ``void (PyObject *obj, Py_buffer *view)``. + If the :c:data:`bf_releasebuffer` function is not provided (i.e. it is *NULL*), then it does not ever need to be called. The exporter of the buffer interface must make sure that any memory - pointed to in the :ctype:`Py_buffer` structure remains valid until + pointed to in the :c:type:`Py_buffer` structure remains valid until releasebuffer is called. Exporters will need to define a - :cdata:`bf_releasebuffer` function if they can re-allocate their memory, + :c:data:`bf_releasebuffer` function if they can re-allocate their memory, strides, shape, suboffsets, or format variables which they might share through the struct bufferinfo. - See :cfunc:`PyBuffer_Release`. + See :c:func:`PyBuffer_Release`. diff --git a/Doc/c-api/unicode.rst b/Doc/c-api/unicode.rst index 45c46aa..aae2b4a 100644 --- a/Doc/c-api/unicode.rst +++ b/Doc/c-api/unicode.rst @@ -17,75 +17,75 @@ These are the basic Unicode object types used for the Unicode implementation in Python: -.. ctype:: Py_UNICODE +.. c:type:: Py_UNICODE This type represents the storage type which is used by Python internally as basis for holding Unicode ordinals. Python's default builds use a 16-bit type - for :ctype:`Py_UNICODE` and store Unicode values internally as UCS2. It is also + for :c:type:`Py_UNICODE` and store Unicode values internally as UCS2. It is also possible to build a UCS4 version of Python (most recent Linux distributions come with UCS4 builds of Python). These builds then use a 32-bit type for - :ctype:`Py_UNICODE` and store Unicode data internally as UCS4. On platforms - where :ctype:`wchar_t` is available and compatible with the chosen Python - Unicode build variant, :ctype:`Py_UNICODE` is a typedef alias for - :ctype:`wchar_t` to enhance native platform compatibility. On all other - platforms, :ctype:`Py_UNICODE` is a typedef alias for either :ctype:`unsigned - short` (UCS2) or :ctype:`unsigned long` (UCS4). + :c:type:`Py_UNICODE` and store Unicode data internally as UCS4. On platforms + where :c:type:`wchar_t` is available and compatible with the chosen Python + Unicode build variant, :c:type:`Py_UNICODE` is a typedef alias for + :c:type:`wchar_t` to enhance native platform compatibility. On all other + platforms, :c:type:`Py_UNICODE` is a typedef alias for either :c:type:`unsigned + short` (UCS2) or :c:type:`unsigned long` (UCS4). Note that UCS2 and UCS4 Python builds are not binary compatible. Please keep this in mind when writing extensions or interfaces. -.. ctype:: PyUnicodeObject +.. c:type:: PyUnicodeObject - This subtype of :ctype:`PyObject` represents a Python Unicode object. + This subtype of :c:type:`PyObject` represents a Python Unicode object. -.. cvar:: PyTypeObject PyUnicode_Type +.. c:var:: PyTypeObject PyUnicode_Type - This instance of :ctype:`PyTypeObject` represents the Python Unicode type. It + This instance of :c:type:`PyTypeObject` represents the Python Unicode type. It is exposed to Python code as ``str``. The following APIs are really C macros and can be used to do fast checks and to access internal read-only data of Unicode objects: -.. cfunction:: int PyUnicode_Check(PyObject *o) +.. c:function:: int PyUnicode_Check(PyObject *o) Return true if the object *o* is a Unicode object or an instance of a Unicode subtype. -.. cfunction:: int PyUnicode_CheckExact(PyObject *o) +.. c:function:: int PyUnicode_CheckExact(PyObject *o) Return true if the object *o* is a Unicode object, but not an instance of a subtype. -.. cfunction:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o) +.. c:function:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o) - Return the size of the object. *o* has to be a :ctype:`PyUnicodeObject` (not + Return the size of the object. *o* has to be a :c:type:`PyUnicodeObject` (not checked). -.. cfunction:: Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o) +.. c:function:: Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o) Return the size of the object's internal buffer in bytes. *o* has to be a - :ctype:`PyUnicodeObject` (not checked). + :c:type:`PyUnicodeObject` (not checked). -.. cfunction:: Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o) +.. c:function:: Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o) - Return a pointer to the internal :ctype:`Py_UNICODE` buffer of the object. *o* - has to be a :ctype:`PyUnicodeObject` (not checked). + Return a pointer to the internal :c:type:`Py_UNICODE` buffer of the object. *o* + has to be a :c:type:`PyUnicodeObject` (not checked). -.. cfunction:: const char* PyUnicode_AS_DATA(PyObject *o) +.. c:function:: const char* PyUnicode_AS_DATA(PyObject *o) Return a pointer to the internal buffer of the object. *o* has to be a - :ctype:`PyUnicodeObject` (not checked). + :c:type:`PyUnicodeObject` (not checked). -.. cfunction:: int PyUnicode_ClearFreeList() +.. c:function:: int PyUnicode_ClearFreeList() Clear the free list. Return the total number of freed items. @@ -98,57 +98,57 @@ are available through these macros which are mapped to C functions depending on the Python configuration. -.. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is a whitespace character. -.. cfunction:: int Py_UNICODE_ISLOWER(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISLOWER(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is a lowercase character. -.. cfunction:: int Py_UNICODE_ISUPPER(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISUPPER(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is an uppercase character. -.. cfunction:: int Py_UNICODE_ISTITLE(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISTITLE(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is a titlecase character. -.. cfunction:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is a linebreak character. -.. cfunction:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is a decimal character. -.. cfunction:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is a digit character. -.. cfunction:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is a numeric character. -.. cfunction:: int Py_UNICODE_ISALPHA(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISALPHA(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is an alphabetic character. -.. cfunction:: int Py_UNICODE_ISALNUM(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISALNUM(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is an alphanumeric character. -.. cfunction:: int Py_UNICODE_ISPRINTABLE(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_ISPRINTABLE(Py_UNICODE ch) Return 1 or 0 depending on whether *ch* is a printable character. Nonprintable characters are those characters defined in the Unicode character @@ -162,34 +162,34 @@ the Python configuration. These APIs can be used for fast direct character conversions: -.. cfunction:: Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch) +.. c:function:: Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch) Return the character *ch* converted to lower case. -.. cfunction:: Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch) +.. c:function:: Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch) Return the character *ch* converted to upper case. -.. cfunction:: Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch) +.. c:function:: Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch) Return the character *ch* converted to title case. -.. cfunction:: int Py_UNICODE_TODECIMAL(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_TODECIMAL(Py_UNICODE ch) Return the character *ch* converted to a decimal positive integer. Return ``-1`` if this is not possible. This macro does not raise exceptions. -.. cfunction:: int Py_UNICODE_TODIGIT(Py_UNICODE ch) +.. c:function:: int Py_UNICODE_TODIGIT(Py_UNICODE ch) Return the character *ch* converted to a single digit integer. Return ``-1`` if this is not possible. This macro does not raise exceptions. -.. cfunction:: double Py_UNICODE_TONUMERIC(Py_UNICODE ch) +.. c:function:: double Py_UNICODE_TONUMERIC(Py_UNICODE ch) Return the character *ch* converted to a double. Return ``-1.0`` if this is not possible. This macro does not raise exceptions. @@ -202,7 +202,7 @@ To create Unicode objects and access their basic sequence properties, use these APIs: -.. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) +.. c:function:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) Create a Unicode Object from the Py_UNICODE buffer *u* of the given size. *u* may be *NULL* which causes the contents to be undefined. It is the user's @@ -212,7 +212,7 @@ APIs: is *NULL*. -.. cfunction:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) +.. c:function:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) Create a Unicode Object from the char buffer *u*. The bytes will be interpreted as being UTF-8 encoded. *u* may also be *NULL* which @@ -222,15 +222,15 @@ APIs: the resulting Unicode object is only allowed when *u* is *NULL*. -.. cfunction:: PyObject *PyUnicode_FromString(const char *u) +.. c:function:: PyObject *PyUnicode_FromString(const char *u) Create a Unicode object from an UTF-8 encoded null-terminated char buffer *u*. -.. cfunction:: PyObject* PyUnicode_FromFormat(const char *format, ...) +.. c:function:: PyObject* PyUnicode_FromFormat(const char *format, ...) - Take a C :cfunc:`printf`\ -style *format* string and a variable number of + Take a C :c:func:`printf`\ -style *format* string and a variable number of arguments, calculate the size of the resulting Python unicode string and return a string with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the *format* @@ -305,10 +305,10 @@ APIs: | | | *NULL*). | +-------------------+---------------------+--------------------------------+ | :attr:`%S` | PyObject\* | The result of calling | - | | | :cfunc:`PyObject_Str`. | + | | | :c:func:`PyObject_Str`. | +-------------------+---------------------+--------------------------------+ | :attr:`%R` | PyObject\* | The result of calling | - | | | :cfunc:`PyObject_Repr`. | + | | | :c:func:`PyObject_Repr`. | +-------------------+---------------------+--------------------------------+ An unrecognized format character causes all the rest of the format string to be @@ -323,34 +323,34 @@ APIs: Support for ``"%lld"`` and ``"%llu"`` added. -.. cfunction:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs) +.. c:function:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs) - Identical to :cfunc:`PyUnicode_FromFormat` except that it takes exactly two + Identical to :c:func:`PyUnicode_FromFormat` except that it takes exactly two arguments. -.. cfunction:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode) +.. c:function:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode) - Return a read-only pointer to the Unicode object's internal :ctype:`Py_UNICODE` + Return a read-only pointer to the Unicode object's internal :c:type:`Py_UNICODE` buffer, *NULL* if *unicode* is not a Unicode object. -.. cfunction:: Py_UNICODE* PyUnicode_AsUnicodeCopy(PyObject *unicode) +.. c:function:: Py_UNICODE* PyUnicode_AsUnicodeCopy(PyObject *unicode) Create a copy of a unicode string ending with a nul character. Return *NULL* and raise a :exc:`MemoryError` exception on memory allocation failure, - otherwise return a new allocated buffer (use :cfunc:`PyMem_Free` to free the + otherwise return a new allocated buffer (use :c:func:`PyMem_Free` to free the buffer). .. versionadded:: 3.2 -.. cfunction:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode) +.. c:function:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode) Return the length of the Unicode object. -.. cfunction:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors) +.. c:function:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors) Coerce an encoded object *obj* to an Unicode object and return a reference with incremented refcount. @@ -367,73 +367,73 @@ APIs: decref'ing the returned objects. -.. cfunction:: PyObject* PyUnicode_FromObject(PyObject *obj) +.. c:function:: PyObject* PyUnicode_FromObject(PyObject *obj) Shortcut for ``PyUnicode_FromEncodedObject(obj, NULL, "strict")`` which is used throughout the interpreter whenever coercion to Unicode is needed. -If the platform supports :ctype:`wchar_t` and provides a header file wchar.h, +If the platform supports :c:type:`wchar_t` and provides a header file wchar.h, Python can interface directly to this type using the following functions. -Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to -the system's :ctype:`wchar_t`. +Support is optimized if Python's own :c:type:`Py_UNICODE` type is identical to +the system's :c:type:`wchar_t`. File System Encoding """""""""""""""""""" To encode and decode file names and other environment strings, -:cdata:`Py_FileSystemEncoding` should be used as the encoding, and +:c:data:`Py_FileSystemEncoding` should be used as the encoding, and ``"surrogateescape"`` should be used as the error handler (:pep:`383`). To encode file names during argument parsing, the ``"O&"`` converter should be -used, passing :cfunc:`PyUnicode_FSConverter` as the conversion function: +used, passing :c:func:`PyUnicode_FSConverter` as the conversion function: -.. cfunction:: int PyUnicode_FSConverter(PyObject* obj, void* result) +.. c:function:: int PyUnicode_FSConverter(PyObject* obj, void* result) ParseTuple converter: encode :class:`str` objects to :class:`bytes` using - :cfunc:`PyUnicode_EncodeFSDefault`; :class:`bytes` objects are output as-is. - *result* must be a :ctype:`PyBytesObject*` which must be released when it is + :c:func:`PyUnicode_EncodeFSDefault`; :class:`bytes` objects are output as-is. + *result* must be a :c:type:`PyBytesObject*` which must be released when it is no longer used. .. versionadded:: 3.1 To decode file names during argument parsing, the ``"O&"`` converter should be -used, passing :cfunc:`PyUnicode_FSDecoder` as the conversion function: +used, passing :c:func:`PyUnicode_FSDecoder` as the conversion function: -.. cfunction:: int PyUnicode_FSDecoder(PyObject* obj, void* result) +.. c:function:: int PyUnicode_FSDecoder(PyObject* obj, void* result) ParseTuple converter: decode :class:`bytes` objects to :class:`str` using - :cfunc:`PyUnicode_DecodeFSDefaultAndSize`; :class:`str` objects are output - as-is. *result* must be a :ctype:`PyUnicodeObject*` which must be released + :c:func:`PyUnicode_DecodeFSDefaultAndSize`; :class:`str` objects are output + as-is. *result* must be a :c:type:`PyUnicodeObject*` which must be released when it is no longer used. .. versionadded:: 3.2 -.. cfunction:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size) +.. c:function:: PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size) - Decode a null-terminated string using :cdata:`Py_FileSystemDefaultEncoding` + Decode a null-terminated string using :c:data:`Py_FileSystemDefaultEncoding` and the ``"surrogateescape"`` error handler. - If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + If :c:data:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. - Use :cfunc:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length. + Use :c:func:`PyUnicode_DecodeFSDefaultAndSize` if you know the string length. -.. cfunction:: PyObject* PyUnicode_DecodeFSDefault(const char *s) +.. c:function:: PyObject* PyUnicode_DecodeFSDefault(const char *s) - Decode a string using :cdata:`Py_FileSystemDefaultEncoding` and + Decode a string using :c:data:`Py_FileSystemDefaultEncoding` and the ``"surrogateescape"`` error handler. - If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + If :c:data:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. -.. cfunction:: PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode) +.. c:function:: PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode) - Encode a Unicode object to :cdata:`Py_FileSystemDefaultEncoding` with the + Encode a Unicode object to :c:data:`Py_FileSystemDefaultEncoding` with the ``'surrogateescape'`` error handler, and return :class:`bytes`. - If :cdata:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. + If :c:data:`Py_FileSystemDefaultEncoding` is not set, fall back to UTF-8. .. versionadded:: 3.2 @@ -443,33 +443,33 @@ wchar_t Support wchar_t support for platforms which support it: -.. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) +.. c:function:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) - Create a Unicode object from the :ctype:`wchar_t` buffer *w* of the given size. + Create a Unicode object from the :c:type:`wchar_t` buffer *w* of the given size. Passing -1 as the size indicates that the function must itself compute the length, using wcslen. Return *NULL* on failure. -.. cfunction:: Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode, wchar_t *w, Py_ssize_t size) +.. c:function:: Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode, wchar_t *w, Py_ssize_t size) - Copy the Unicode object contents into the :ctype:`wchar_t` buffer *w*. At most - *size* :ctype:`wchar_t` characters are copied (excluding a possibly trailing - 0-termination character). Return the number of :ctype:`wchar_t` characters - copied or -1 in case of an error. Note that the resulting :ctype:`wchar_t` + Copy the Unicode object contents into the :c:type:`wchar_t` buffer *w*. At most + *size* :c:type:`wchar_t` characters are copied (excluding a possibly trailing + 0-termination character). Return the number of :c:type:`wchar_t` characters + copied or -1 in case of an error. Note that the resulting :c:type:`wchar_t` string may or may not be 0-terminated. It is the responsibility of the caller - to make sure that the :ctype:`wchar_t` string is 0-terminated in case this is + to make sure that the :c:type:`wchar_t` string is 0-terminated in case this is required by the application. -.. cfunction:: wchar_t* PyUnicode_AsWideCharString(PyUnicodeObject *unicode, Py_ssize_t *size) +.. c:function:: wchar_t* PyUnicode_AsWideCharString(PyUnicodeObject *unicode, Py_ssize_t *size) Convert the Unicode object to a wide character string. The output string always ends with a nul character. If *size* is not *NULL*, write the number of wide characters (excluding the trailing 0-termination character) into *\*size*. - Returns a buffer allocated by :cfunc:`PyMem_Alloc` (use :cfunc:`PyMem_Free` + Returns a buffer allocated by :c:func:`PyMem_Alloc` (use :c:func:`PyMem_Free` to free it) on success. On error, returns *NULL*, *\*size* is undefined and raises a :exc:`MemoryError`. @@ -490,8 +490,8 @@ built-in :func:`str` string object constructor. Setting encoding to *NULL* causes the default encoding to be used which is ASCII. The file system calls should use -:cfunc:`PyUnicode_FSConverter` for encoding file names. This uses the -variable :cdata:`Py_FileSystemDefaultEncoding` internally. This +:c:func:`PyUnicode_FSConverter` for encoding file names. This uses the +variable :c:data:`Py_FileSystemDefaultEncoding` internally. This variable should be treated as read-only: On some systems, it will be a pointer to a static string, on others, it will change at run-time (such as when the application invokes setlocale). @@ -510,7 +510,7 @@ Generic Codecs These are the generic codec APIs: -.. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) +.. c:function:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) Create a Unicode object by decoding *size* bytes of the encoded string *s*. *encoding* and *errors* have the same meaning as the parameters of the same name @@ -519,16 +519,16 @@ These are the generic codec APIs: the codec. -.. cfunction:: PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors) +.. c:function:: PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors) - Encode the :ctype:`Py_UNICODE` buffer of the given size and return a Python + Encode the :c:type:`Py_UNICODE` buffer of the given size and return a Python bytes object. *encoding* and *errors* have the same meaning as the parameters of the same name in the Unicode :meth:`encode` method. The codec to be used is looked up using the Python codec registry. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors) +.. c:function:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors) Encode a Unicode object and return the result as Python bytes object. *encoding* and *errors* have the same meaning as the parameters of the same @@ -543,28 +543,28 @@ UTF-8 Codecs These are the UTF-8 codec APIs: -.. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string *s*. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) +.. c:function:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) - If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF8`. If + If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF8`. If *consumed* is not *NULL*, trailing incomplete UTF-8 byte sequences will not be treated as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. -.. cfunction:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors) - Encode the :ctype:`Py_UNICODE` buffer of the given size using UTF-8 and + Encode the :c:type:`Py_UNICODE` buffer of the given size using UTF-8 and return a Python bytes object. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode) +.. c:function:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode) Encode a Unicode object using UTF-8 and return the result as Python bytes object. Error handling is "strict". Return *NULL* if an exception was @@ -577,7 +577,7 @@ UTF-32 Codecs These are the UTF-32 codec APIs: -.. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) +.. c:function:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) Decode *length* bytes from a UTF-32 encoded buffer string and return the corresponding Unicode object. *errors* (if non-*NULL*) defines the error @@ -605,16 +605,16 @@ These are the UTF-32 codec APIs: Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) +.. c:function:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) - If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF32`. If - *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF32Stateful` will not treat + If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF32`. If + *consumed* is not *NULL*, :c:func:`PyUnicode_DecodeUTF32Stateful` will not treat trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible by four) as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. -.. cfunction:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) +.. c:function:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) Return a Python bytes object holding the UTF-32 encoded value of the Unicode data in *s*. Output is written according to the following byte order:: @@ -632,7 +632,7 @@ These are the UTF-32 codec APIs: Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode) +.. c:function:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode) Return a Python byte string using the UTF-32 encoding in native byte order. The string always starts with a BOM mark. Error handling is "strict". @@ -645,7 +645,7 @@ UTF-16 Codecs These are the UTF-16 codec APIs: -.. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) +.. c:function:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) Decode *length* bytes from a UTF-16 encoded buffer string and return the corresponding Unicode object. *errors* (if non-*NULL*) defines the error @@ -672,16 +672,16 @@ These are the UTF-16 codec APIs: Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) +.. c:function:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) - If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF16`. If - *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF16Stateful` will not treat + If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF16`. If + *consumed* is not *NULL*, :c:func:`PyUnicode_DecodeUTF16Stateful` will not treat trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a split surrogate pair) as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. -.. cfunction:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) +.. c:function:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) Return a Python bytes object holding the UTF-16 encoded value of the Unicode data in *s*. Output is written according to the following byte order:: @@ -693,14 +693,14 @@ These are the UTF-16 codec APIs: If byteorder is ``0``, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended. - If *Py_UNICODE_WIDE* is defined, a single :ctype:`Py_UNICODE` value may get - represented as a surrogate pair. If it is not defined, each :ctype:`Py_UNICODE` + If *Py_UNICODE_WIDE* is defined, a single :c:type:`Py_UNICODE` value may get + represented as a surrogate pair. If it is not defined, each :c:type:`Py_UNICODE` values is interpreted as an UCS-2 character. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode) +.. c:function:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode) Return a Python byte string using the UTF-16 encoding in native byte order. The string always starts with a BOM mark. Error handling is "strict". @@ -713,23 +713,23 @@ UTF-7 Codecs These are the UTF-7 codec APIs: -.. cfunction:: PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string *s*. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) +.. c:function:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) - If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF7`. If + If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF7`. If *consumed* is not *NULL*, trailing incomplete UTF-7 base-64 sections will not be treated as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. -.. cfunction:: PyObject* PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors) +.. c:function:: PyObject* PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors) - Encode the :ctype:`Py_UNICODE` buffer of the given size using UTF-7 and + Encode the :c:type:`Py_UNICODE` buffer of the given size using UTF-7 and return a Python bytes object. Return *NULL* if an exception was raised by the codec. @@ -745,20 +745,20 @@ Unicode-Escape Codecs These are the "Unicode Escape" codec APIs: -.. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded string *s*. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size) +.. c:function:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size) - Encode the :ctype:`Py_UNICODE` buffer of the given size using Unicode-Escape and + Encode the :c:type:`Py_UNICODE` buffer of the given size using Unicode-Escape and return a Python string object. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode) +.. c:function:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode) Encode a Unicode object using Unicode-Escape and return the result as Python string object. Error handling is "strict". Return *NULL* if an exception was @@ -771,20 +771,20 @@ Raw-Unicode-Escape Codecs These are the "Raw Unicode Escape" codec APIs: -.. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape encoded string *s*. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size, const char *errors) - Encode the :ctype:`Py_UNICODE` buffer of the given size using Raw-Unicode-Escape + Encode the :c:type:`Py_UNICODE` buffer of the given size using Raw-Unicode-Escape and return a Python string object. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode) +.. c:function:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode) Encode a Unicode object using Raw-Unicode-Escape and return the result as Python string object. Error handling is "strict". Return *NULL* if an exception @@ -798,20 +798,20 @@ These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding. -.. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string *s*. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors) - Encode the :ctype:`Py_UNICODE` buffer of the given size using Latin-1 and + Encode the :c:type:`Py_UNICODE` buffer of the given size using Latin-1 and return a Python bytes object. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode) +.. c:function:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode) Encode a Unicode object using Latin-1 and return the result as Python bytes object. Error handling is "strict". Return *NULL* if an exception was @@ -825,20 +825,20 @@ These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors. -.. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the ASCII encoded string *s*. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors) - Encode the :ctype:`Py_UNICODE` buffer of the given size using ASCII and + Encode the :c:type:`Py_UNICODE` buffer of the given size using ASCII and return a Python bytes object. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode) +.. c:function:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode) Encode a Unicode object using ASCII and return the result as Python bytes object. Error handling is "strict". Return *NULL* if an exception was @@ -872,7 +872,7 @@ resp. Because of this, mappings only need to contain those mappings which map characters to different code points. -.. cfunction:: PyObject* PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors) +.. c:function:: PyObject* PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors) Create a Unicode object by decoding *size* bytes of the encoded string *s* using the given *mapping* object. Return *NULL* if an exception was raised by the @@ -882,14 +882,14 @@ characters to different code points. treated as "undefined mapping". -.. cfunction:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors) +.. c:function:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors) - Encode the :ctype:`Py_UNICODE` buffer of the given size using the given + Encode the :c:type:`Py_UNICODE` buffer of the given size using the given *mapping* object and return a Python string object. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping) +.. c:function:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping) Encode a Unicode object using the given *mapping* object and return the result as Python string object. Error handling is "strict". Return *NULL* if an @@ -898,9 +898,9 @@ characters to different code points. The following codec API is special in that maps Unicode to Unicode. -.. cfunction:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *table, const char *errors) +.. c:function:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *table, const char *errors) - Translate a :ctype:`Py_UNICODE` buffer of the given length by applying a + Translate a :c:type:`Py_UNICODE` buffer of the given length by applying a character mapping *table* to it and return the resulting Unicode object. Return *NULL* when an exception was raised by the codec. @@ -922,28 +922,28 @@ MBCS codecs for Windows """"""""""""""""""""""" -.. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, int size, const char *errors, int *consumed) +.. c:function:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, int size, const char *errors, int *consumed) - If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeMBCS`. If - *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeMBCSStateful` will not decode + If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeMBCS`. If + *consumed* is not *NULL*, :c:func:`PyUnicode_DecodeMBCSStateful` will not decode trailing lead byte and the number of bytes that have been decoded will be stored in *consumed*. -.. cfunction:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors) +.. c:function:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors) - Encode the :ctype:`Py_UNICODE` buffer of the given size using MBCS and return + Encode the :c:type:`Py_UNICODE` buffer of the given size using MBCS and return a Python bytes object. Return *NULL* if an exception was raised by the codec. -.. cfunction:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode) +.. c:function:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode) Encode a Unicode object using MBCS and return the result as Python bytes object. Error handling is "strict". Return *NULL* if an exception was @@ -966,12 +966,12 @@ integers as appropriate. They all return *NULL* or ``-1`` if an exception occurs. -.. cfunction:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right) +.. c:function:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right) Concat two strings giving a new Unicode string. -.. cfunction:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit) +.. c:function:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit) Split a string giving a list of Unicode strings. If sep is *NULL*, splitting will be done at all whitespace substrings. Otherwise, splits occur at the given @@ -979,14 +979,14 @@ They all return *NULL* or ``-1`` if an exception occurs. set. Separators are not included in the resulting list. -.. cfunction:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend) +.. c:function:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend) Split a Unicode string at line breaks, returning a list of Unicode strings. CRLF is considered to be one line break. If *keepend* is 0, the Line break characters are not included in the resulting strings. -.. cfunction:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors) +.. c:function:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors) Translate a string by applying a character mapping table to it and return the resulting Unicode object. @@ -1002,20 +1002,20 @@ They all return *NULL* or ``-1`` if an exception occurs. use the default error handling. -.. cfunction:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq) +.. c:function:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq) Join a sequence of strings using the given separator and return the resulting Unicode string. -.. cfunction:: int PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) +.. c:function:: int PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) Return 1 if *substr* matches *str*[*start*:*end*] at the given tail end (*direction* == -1 means to do a prefix match, *direction* == 1 a suffix match), 0 otherwise. Return ``-1`` if an error occurred. -.. cfunction:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) +.. c:function:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) Return the first position of *substr* in *str*[*start*:*end*] using the given *direction* (*direction* == 1 means to do a forward search, *direction* == -1 a @@ -1024,32 +1024,32 @@ They all return *NULL* or ``-1`` if an exception occurs. occurred and an exception has been set. -.. cfunction:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end) +.. c:function:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end) Return the number of non-overlapping occurrences of *substr* in ``str[start:end]``. Return ``-1`` if an error occurred. -.. cfunction:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount) +.. c:function:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount) Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and return the resulting Unicode object. *maxcount* == -1 means replace all occurrences. -.. cfunction:: int PyUnicode_Compare(PyObject *left, PyObject *right) +.. c:function:: int PyUnicode_Compare(PyObject *left, PyObject *right) Compare two strings and return -1, 0, 1 for less than, equal, and greater than, respectively. -.. cfunction:: int PyUnicode_CompareWithASCIIString(PyObject *uni, char *string) +.. c:function:: int PyUnicode_CompareWithASCIIString(PyObject *uni, char *string) Compare a unicode object, *uni*, with *string* and return -1, 0, 1 for less than, equal, and greater than, respectively. -.. cfunction:: int PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) +.. c:function:: int PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) Rich compare two unicode strings and return one of the following: @@ -1065,13 +1065,13 @@ They all return *NULL* or ``-1`` if an exception occurs. :const:`Py_NE`, :const:`Py_LT`, and :const:`Py_LE`. -.. cfunction:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args) +.. c:function:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args) Return a new string object from *format* and *args*; this is analogous to ``format % args``. The *args* argument must be a tuple. -.. cfunction:: int PyUnicode_Contains(PyObject *container, PyObject *element) +.. c:function:: int PyUnicode_Contains(PyObject *container, PyObject *element) Check whether *element* is contained in *container* and return true or false accordingly. @@ -1080,7 +1080,7 @@ They all return *NULL* or ``-1`` if an exception occurs. there was an error. -.. cfunction:: void PyUnicode_InternInPlace(PyObject **string) +.. c:function:: void PyUnicode_InternInPlace(PyObject **string) Intern the argument *\*string* in place. The argument must be the address of a pointer variable pointing to a Python unicode string object. If there is an @@ -1093,10 +1093,10 @@ They all return *NULL* or ``-1`` if an exception occurs. if and only if you owned it before the call.) -.. cfunction:: PyObject* PyUnicode_InternFromString(const char *v) +.. c:function:: PyObject* PyUnicode_InternFromString(const char *v) - A combination of :cfunc:`PyUnicode_FromString` and - :cfunc:`PyUnicode_InternInPlace`, returning either a new unicode string object + A combination of :c:func:`PyUnicode_FromString` and + :c:func:`PyUnicode_InternInPlace`, returning either a new unicode string object that has been interned, or a new ("owned") reference to an earlier interned string object with the same value. diff --git a/Doc/c-api/veryhigh.rst b/Doc/c-api/veryhigh.rst index d716a46..2adcd1d 100644 --- a/Doc/c-api/veryhigh.rst +++ b/Doc/c-api/veryhigh.rst @@ -16,21 +16,21 @@ parameter. The available start symbols are :const:`Py_eval_input`, :const:`Py_file_input`, and :const:`Py_single_input`. These are described following the functions which accept them as parameters. -Note also that several of these functions take :ctype:`FILE\*` parameters. One -particular issue which needs to be handled carefully is that the :ctype:`FILE` +Note also that several of these functions take :c:type:`FILE\*` parameters. One +particular issue which needs to be handled carefully is that the :c:type:`FILE` structure for different C libraries can be different and incompatible. Under Windows (at least), it is possible for dynamically linked extensions to actually -use different libraries, so care should be taken that :ctype:`FILE\*` parameters +use different libraries, so care should be taken that :c:type:`FILE\*` parameters are only passed to these functions if it is certain that they were created by the same library that the Python runtime is using. -.. cfunction:: int Py_Main(int argc, wchar_t **argv) +.. c:function:: int Py_Main(int argc, wchar_t **argv) The main program for the standard interpreter. This is made available for programs which embed Python. The *argc* and *argv* parameters should be prepared exactly as those which are passed to - a C program's :cfunc:`main` function (converted to wchar_t + a C program's :c:func:`main` function (converted to wchar_t according to the user's locale). It is important to note that the argument list may be modified (but the contents of the strings pointed to by the argument list are not). The return value will be @@ -43,40 +43,40 @@ the same library that the Python runtime is using. ``Py_InspectFlag`` is not set. -.. cfunction:: int PyRun_AnyFile(FILE *fp, const char *filename) +.. c:function:: int PyRun_AnyFile(FILE *fp, const char *filename) - This is a simplified interface to :cfunc:`PyRun_AnyFileExFlags` below, leaving + This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving *closeit* set to ``0`` and *flags* set to *NULL*. -.. cfunction:: int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) +.. c:function:: int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) - This is a simplified interface to :cfunc:`PyRun_AnyFileExFlags` below, leaving + This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving the *closeit* argument set to ``0``. -.. cfunction:: int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit) +.. c:function:: int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit) - This is a simplified interface to :cfunc:`PyRun_AnyFileExFlags` below, leaving + This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving the *flags* argument set to *NULL*. -.. cfunction:: int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) +.. c:function:: int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) If *fp* refers to a file associated with an interactive device (console or terminal input or Unix pseudo-terminal), return the value of - :cfunc:`PyRun_InteractiveLoop`, otherwise return the result of - :cfunc:`PyRun_SimpleFile`. If *filename* is *NULL*, this function uses + :c:func:`PyRun_InteractiveLoop`, otherwise return the result of + :c:func:`PyRun_SimpleFile`. If *filename* is *NULL*, this function uses ``"???"`` as the filename. -.. cfunction:: int PyRun_SimpleString(const char *command) +.. c:function:: int PyRun_SimpleString(const char *command) - This is a simplified interface to :cfunc:`PyRun_SimpleStringFlags` below, + This is a simplified interface to :c:func:`PyRun_SimpleStringFlags` below, leaving the *PyCompilerFlags\** argument set to NULL. -.. cfunction:: int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) +.. c:function:: int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) Executes the Python source code from *command* in the :mod:`__main__` module according to the *flags* argument. If :mod:`__main__` does not already exist, it @@ -89,39 +89,39 @@ the same library that the Python runtime is using. ``Py_InspectFlag`` is not set. -.. cfunction:: int PyRun_SimpleFile(FILE *fp, const char *filename) +.. c:function:: int PyRun_SimpleFile(FILE *fp, const char *filename) - This is a simplified interface to :cfunc:`PyRun_SimpleFileExFlags` below, + This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, leaving *closeit* set to ``0`` and *flags* set to *NULL*. -.. cfunction:: int PyRun_SimpleFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) +.. c:function:: int PyRun_SimpleFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) - This is a simplified interface to :cfunc:`PyRun_SimpleFileExFlags` below, + This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, leaving *closeit* set to ``0``. -.. cfunction:: int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit) +.. c:function:: int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit) - This is a simplified interface to :cfunc:`PyRun_SimpleFileExFlags` below, + This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, leaving *flags* set to *NULL*. -.. cfunction:: int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) +.. c:function:: int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) - Similar to :cfunc:`PyRun_SimpleStringFlags`, but the Python source code is read + Similar to :c:func:`PyRun_SimpleStringFlags`, but the Python source code is read from *fp* instead of an in-memory string. *filename* should be the name of the file. If *closeit* is true, the file is closed before PyRun_SimpleFileExFlags returns. -.. cfunction:: int PyRun_InteractiveOne(FILE *fp, const char *filename) +.. c:function:: int PyRun_InteractiveOne(FILE *fp, const char *filename) - This is a simplified interface to :cfunc:`PyRun_InteractiveOneFlags` below, + This is a simplified interface to :c:func:`PyRun_InteractiveOneFlags` below, leaving *flags* set to *NULL*. -.. cfunction:: int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) +.. c:function:: int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) Read and execute a single statement from a file associated with an interactive device according to the *flags* argument. If *filename* is *NULL*, ``"???"`` is @@ -132,34 +132,34 @@ the same library that the Python runtime is using. not included by :file:`Python.h`, so must be included specifically if needed.) -.. cfunction:: int PyRun_InteractiveLoop(FILE *fp, const char *filename) +.. c:function:: int PyRun_InteractiveLoop(FILE *fp, const char *filename) - This is a simplified interface to :cfunc:`PyRun_InteractiveLoopFlags` below, + This is a simplified interface to :c:func:`PyRun_InteractiveLoopFlags` below, leaving *flags* set to *NULL*. -.. cfunction:: int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) +.. c:function:: int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) Read and execute statements from a file associated with an interactive device until EOF is reached. If *filename* is *NULL*, ``"???"`` is used instead. The user will be prompted using ``sys.ps1`` and ``sys.ps2``. Returns ``0`` at EOF. -.. cfunction:: struct _node* PyParser_SimpleParseString(const char *str, int start) +.. c:function:: struct _node* PyParser_SimpleParseString(const char *str, int start) This is a simplified interface to - :cfunc:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set + :c:func:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set to *NULL* and *flags* set to ``0``. -.. cfunction:: struct _node* PyParser_SimpleParseStringFlags( const char *str, int start, int flags) +.. c:function:: struct _node* PyParser_SimpleParseStringFlags( const char *str, int start, int flags) This is a simplified interface to - :cfunc:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set + :c:func:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set to *NULL*. -.. cfunction:: struct _node* PyParser_SimpleParseStringFlagsFilename( const char *str, const char *filename, int start, int flags) +.. c:function:: struct _node* PyParser_SimpleParseStringFlagsFilename( const char *str, const char *filename, int start, int flags) Parse Python source code from *str* using the start token *start* according to the *flags* argument. The result can be used to create a code object which can @@ -167,25 +167,25 @@ the same library that the Python runtime is using. many times. -.. cfunction:: struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) +.. c:function:: struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) - This is a simplified interface to :cfunc:`PyParser_SimpleParseFileFlags` below, + This is a simplified interface to :c:func:`PyParser_SimpleParseFileFlags` below, leaving *flags* set to ``0`` -.. cfunction:: struct _node* PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) +.. c:function:: struct _node* PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) - Similar to :cfunc:`PyParser_SimpleParseStringFlagsFilename`, but the Python + Similar to :c:func:`PyParser_SimpleParseStringFlagsFilename`, but the Python source code is read from *fp* instead of an in-memory string. -.. cfunction:: PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals) +.. c:function:: PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals) - This is a simplified interface to :cfunc:`PyRun_StringFlags` below, leaving + This is a simplified interface to :c:func:`PyRun_StringFlags` below, leaving *flags* set to *NULL*. -.. cfunction:: PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) +.. c:function:: PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) Execute Python source code from *str* in the context specified by the dictionaries *globals* and *locals* with the compiler flags specified by @@ -196,39 +196,39 @@ the same library that the Python runtime is using. exception was raised. -.. cfunction:: PyObject* PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals) +.. c:function:: PyObject* PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals) - This is a simplified interface to :cfunc:`PyRun_FileExFlags` below, leaving + This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving *closeit* set to ``0`` and *flags* set to *NULL*. -.. cfunction:: PyObject* PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit) +.. c:function:: PyObject* PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit) - This is a simplified interface to :cfunc:`PyRun_FileExFlags` below, leaving + This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving *flags* set to *NULL*. -.. cfunction:: PyObject* PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) +.. c:function:: PyObject* PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) - This is a simplified interface to :cfunc:`PyRun_FileExFlags` below, leaving + This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving *closeit* set to ``0``. -.. cfunction:: PyObject* PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) +.. c:function:: PyObject* PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) - Similar to :cfunc:`PyRun_StringFlags`, but the Python source code is read from + Similar to :c:func:`PyRun_StringFlags`, but the Python source code is read from *fp* instead of an in-memory string. *filename* should be the name of the file. - If *closeit* is true, the file is closed before :cfunc:`PyRun_FileExFlags` + If *closeit* is true, the file is closed before :c:func:`PyRun_FileExFlags` returns. -.. cfunction:: PyObject* Py_CompileString(const char *str, const char *filename, int start) +.. c:function:: PyObject* Py_CompileString(const char *str, const char *filename, int start) - This is a simplified interface to :cfunc:`Py_CompileStringFlags` below, leaving + This is a simplified interface to :c:func:`Py_CompileStringFlags` below, leaving *flags* set to *NULL*. -.. cfunction:: PyObject* Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags) +.. c:function:: PyObject* Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags) Parse and compile the Python source code in *str*, returning the resulting code object. The start token is given by *start*; this can be used to constrain the @@ -239,14 +239,14 @@ the same library that the Python runtime is using. be parsed or compiled. -.. cfunction:: PyObject* PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) +.. c:function:: PyObject* PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) - This is a simplified interface to :cfunc:`PyEval_EvalCodeEx`, with just + This is a simplified interface to :c:func:`PyEval_EvalCodeEx`, with just the code object, and the dictionaries of global and local variables. The other arguments are set to *NULL*. -.. cfunction:: PyObject* PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, PyObject **args, int argcount, PyObject **kws, int kwcount, PyObject **defs, int defcount, PyObject *closure) +.. c:function:: PyObject* PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, PyObject **args, int argcount, PyObject **kws, int kwcount, PyObject **defs, int defcount, PyObject *closure) Evaluate a precompiled code object, given a particular environment for its evaluation. This environment consists of dictionaries of global and local @@ -254,13 +254,13 @@ the same library that the Python runtime is using. cells. -.. cfunction:: PyObject* PyEval_EvalFrame(PyFrameObject *f) +.. c:function:: PyObject* PyEval_EvalFrame(PyFrameObject *f) Evaluate an execution frame. This is a simplified interface to PyEval_EvalFrameEx, for backward compatibility. -.. cfunction:: PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) +.. c:function:: PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) This is the main, unvarnished function of Python interpretation. It is literally 2000 lines long. The code object associated with the execution @@ -270,39 +270,39 @@ the same library that the Python runtime is using. :meth:`throw` methods of generator objects. -.. cfunction:: int PyEval_MergeCompilerFlags(PyCompilerFlags *cf) +.. c:function:: int PyEval_MergeCompilerFlags(PyCompilerFlags *cf) This function changes the flags of the current evaluation frame, and returns true on success, false on failure. -.. cvar:: int Py_eval_input +.. c:var:: int Py_eval_input .. index:: single: Py_CompileString() The start symbol from the Python grammar for isolated expressions; for use with - :cfunc:`Py_CompileString`. + :c:func:`Py_CompileString`. -.. cvar:: int Py_file_input +.. c:var:: int Py_file_input .. index:: single: Py_CompileString() The start symbol from the Python grammar for sequences of statements as read - from a file or other source; for use with :cfunc:`Py_CompileString`. This is + from a file or other source; for use with :c:func:`Py_CompileString`. This is the symbol to use when compiling arbitrarily long Python source code. -.. cvar:: int Py_single_input +.. c:var:: int Py_single_input .. index:: single: Py_CompileString() The start symbol from the Python grammar for a single statement; for use with - :cfunc:`Py_CompileString`. This is the symbol used for the interactive + :c:func:`Py_CompileString`. This is the symbol used for the interactive interpreter loop. -.. ctype:: struct PyCompilerFlags +.. c:type:: struct PyCompilerFlags This is the structure used to hold compiler flags. In cases where code is only being compiled, it is passed as ``int flags``, and in cases where code is being @@ -318,7 +318,7 @@ the same library that the Python runtime is using. } -.. cvar:: int CO_FUTURE_DIVISION +.. c:var:: int CO_FUTURE_DIVISION This bit can be set in *flags* to cause division operator ``/`` to be interpreted as "true division" according to :pep:`238`. diff --git a/Doc/c-api/weakref.rst b/Doc/c-api/weakref.rst index 8a36110..6b053c8 100644 --- a/Doc/c-api/weakref.rst +++ b/Doc/c-api/weakref.rst @@ -11,22 +11,22 @@ simple reference object, and the second acts as a proxy for the original object as much as it can. -.. cfunction:: int PyWeakref_Check(ob) +.. c:function:: int PyWeakref_Check(ob) Return true if *ob* is either a reference or proxy object. -.. cfunction:: int PyWeakref_CheckRef(ob) +.. c:function:: int PyWeakref_CheckRef(ob) Return true if *ob* is a reference object. -.. cfunction:: int PyWeakref_CheckProxy(ob) +.. c:function:: int PyWeakref_CheckProxy(ob) Return true if *ob* is a proxy object. -.. cfunction:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback) +.. c:function:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback) Return a weak reference object for the object *ob*. This will always return a new reference, but is not guaranteed to create a new object; an existing @@ -38,7 +38,7 @@ as much as it can. *NULL*, this will return *NULL* and raise :exc:`TypeError`. -.. cfunction:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback) +.. c:function:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback) Return a weak reference proxy object for the object *ob*. This will always return a new reference, but is not guaranteed to create a new object; an @@ -50,7 +50,7 @@ as much as it can. ``None``, or *NULL*, this will return *NULL* and raise :exc:`TypeError`. -.. cfunction:: PyObject* PyWeakref_GetObject(PyObject *ref) +.. c:function:: PyObject* PyWeakref_GetObject(PyObject *ref) Return the referenced object from a weak reference, *ref*. If the referent is no longer live, returns :const:`Py_None`. @@ -58,12 +58,12 @@ as much as it can. .. warning:: This function returns a **borrowed reference** to the referenced object. - This means that you should always call :cfunc:`Py_INCREF` on the object + This means that you should always call :c:func:`Py_INCREF` on the object except if you know that it cannot be destroyed while you are still using it. -.. cfunction:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref) +.. c:function:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref) - Similar to :cfunc:`PyWeakref_GetObject`, but implemented as a macro that does no + Similar to :c:func:`PyWeakref_GetObject`, but implemented as a macro that does no error checking. diff --git a/Doc/distutils/builtdist.rst b/Doc/distutils/builtdist.rst index d646328..8c4fe82 100644 --- a/Doc/distutils/builtdist.rst +++ b/Doc/distutils/builtdist.rst @@ -427,7 +427,7 @@ built-in functions in the installation script. Which folders are available depends on the exact Windows version, and probably also the configuration. For details refer to Microsoft's documentation of the - :cfunc:`SHGetSpecialFolderPath` function. + :c:func:`SHGetSpecialFolderPath` function. .. function:: create_shortcut(target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]]) diff --git a/Doc/documenting/markup.rst b/Doc/documenting/markup.rst index b4421cb..33653a8 100644 --- a/Doc/documenting/markup.rst +++ b/Doc/documenting/markup.rst @@ -107,11 +107,11 @@ index entries more informative. The directives are: -.. describe:: cfunction +.. describe:: c:function Describes a C function. The signature should be given as in C, e.g.:: - .. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) + .. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) This is also used to describe function-like preprocessor macros. The names of the arguments should be given so they may be used in the description. @@ -119,29 +119,29 @@ The directives are: Note that you don't have to backslash-escape asterisks in the signature, as it is not parsed by the reST inliner. -.. describe:: cmember +.. describe:: c:member Describes a C struct member. Example signature:: - .. cmember:: PyObject* PyTypeObject.tp_bases + .. c:member:: PyObject* PyTypeObject.tp_bases The text of the description should include the range of values allowed, how the value should be interpreted, and whether the value can be changed. References to structure members in text should use the ``member`` role. -.. describe:: cmacro +.. describe:: c:macro Describes a "simple" C macro. Simple macros are macros which are used for code expansion, but which do not take arguments so cannot be described as functions. This is not to be used for simple constant definitions. Examples - of its use in the Python documentation include :cmacro:`PyObject_HEAD` and - :cmacro:`Py_BEGIN_ALLOW_THREADS`. + of its use in the Python documentation include :c:macro:`PyObject_HEAD` and + :c:macro:`Py_BEGIN_ALLOW_THREADS`. -.. describe:: ctype +.. describe:: c:type Describes a C type. The signature should just be the type name. -.. describe:: cvar +.. describe:: c:var Describes a global C variable. The signature should include the type, such as:: @@ -403,22 +403,26 @@ the currently documented class. The following roles create cross-references to C-language constructs if they are defined in the API documentation: -.. describe:: cdata +.. describe:: c:data The name of a C-language variable. -.. describe:: cfunc +.. describe:: c:func The name of a C-language function. Should include trailing parentheses. -.. describe:: cmacro +.. describe:: c:macro The name of a "simple" C macro, as defined above. -.. describe:: ctype +.. describe:: c:type The name of a C-language type. +.. describe:: c:member + + The name of a C type member, as defined above. + The following role does possibly create a cross-reference, but does not refer to objects: diff --git a/Doc/extending/embedding.rst b/Doc/extending/embedding.rst index 5c4fde8..c64e0a9 100644 --- a/Doc/extending/embedding.rst +++ b/Doc/extending/embedding.rst @@ -25,14 +25,14 @@ the Python interpreter to run some Python code. So if you are embedding Python, you are providing your own main program. One of the things this main program has to do is initialize the Python interpreter. At -the very least, you have to call the function :cfunc:`Py_Initialize`. There are +the very least, you have to call the function :c:func:`Py_Initialize`. There are optional calls to pass command line arguments to Python. Then later you can call the interpreter from any part of the application. There are several different ways to call the interpreter: you can pass a string -containing Python statements to :cfunc:`PyRun_SimpleString`, or you can pass a +containing Python statements to :c:func:`PyRun_SimpleString`, or you can pass a stdio file pointer and a file name (for identification in error messages only) -to :cfunc:`PyRun_SimpleFile`. You can also call the lower-level operations +to :c:func:`PyRun_SimpleFile`. You can also call the lower-level operations described in the previous chapters to construct and use Python objects. A simple demo of embedding Python can be found in the directory @@ -69,12 +69,12 @@ perform some operation on a file. :: } The above code first initializes the Python interpreter with -:cfunc:`Py_Initialize`, followed by the execution of a hard-coded Python script -that print the date and time. Afterwards, the :cfunc:`Py_Finalize` call shuts +:c:func:`Py_Initialize`, followed by the execution of a hard-coded Python script +that print the date and time. Afterwards, the :c:func:`Py_Finalize` call shuts the interpreter down, followed by the end of the program. In a real program, you may want to get the Python script from another source, perhaps a text-editor routine, a file, or a database. Getting the Python code from a file can better -be done by using the :cfunc:`PyRun_SimpleFile` function, which saves you the +be done by using the :c:func:`PyRun_SimpleFile` function, which saves you the trouble of allocating memory space and loading the file contents. @@ -162,8 +162,8 @@ interesting part with respect to embedding Python starts with :: pModule = PyImport_Import(pName); After initializing the interpreter, the script is loaded using -:cfunc:`PyImport_Import`. This routine needs a Python string as its argument, -which is constructed using the :cfunc:`PyString_FromString` data conversion +:c:func:`PyImport_Import`. This routine needs a Python string as its argument, +which is constructed using the :c:func:`PyString_FromString` data conversion routine. :: pFunc = PyObject_GetAttrString(pModule, argv[2]); @@ -175,7 +175,7 @@ routine. :: Py_XDECREF(pFunc); Once the script is loaded, the name we're looking for is retrieved using -:cfunc:`PyObject_GetAttrString`. If the name exists, and the object returned is +:c:func:`PyObject_GetAttrString`. If the name exists, and the object returned is callable, you can safely assume that it is a function. The program then proceeds by constructing a tuple of arguments as normal. The call to the Python function is then made with:: @@ -229,8 +229,8 @@ Python extension. For example:: return PyModule_Create(&EmbModule); } -Insert the above code just above the :cfunc:`main` function. Also, insert the -following two statements before the call to :cfunc:`Py_Initialize`:: +Insert the above code just above the :c:func:`main` function. Also, insert the +following two statements before the call to :c:func:`Py_Initialize`:: numargs = argc; PyImport_AppendInittab("emb", &PyInit_emb); diff --git a/Doc/extending/extending.rst b/Doc/extending/extending.rst index 567fcf8..dcef3f8 100644 --- a/Doc/extending/extending.rst +++ b/Doc/extending/extending.rst @@ -35,7 +35,7 @@ A Simple Example Let's create an extension module called ``spam`` (the favorite food of Monty Python fans...) and let's say we want to create a Python interface to the C -library function :cfunc:`system`. [#]_ This function takes a null-terminated +library function :c:func:`system`. [#]_ This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows:: @@ -65,8 +65,8 @@ All user-visible symbols defined by :file:`Python.h` have a prefix of ``Py`` or since they are used extensively by the Python interpreter, ``"Python.h"`` includes a few standard header files: ``<stdio.h>``, ``<string.h>``, ``<errno.h>``, and ``<stdlib.h>``. If the latter header file does not exist on -your system, it declares the functions :cfunc:`malloc`, :cfunc:`free` and -:cfunc:`realloc` directly. +your system, it declares the functions :c:func:`malloc`, :c:func:`free` and +:c:func:`realloc` directly. The next thing we add to our module file is the C function that will be called when the Python expression ``spam.system(string)`` is evaluated (we'll see @@ -96,12 +96,12 @@ The *args* argument will be a pointer to a Python tuple object containing the arguments. Each item of the tuple corresponds to an argument in the call's argument list. The arguments are Python objects --- in order to do anything with them in our C function we have to convert them to C values. The function -:cfunc:`PyArg_ParseTuple` in the Python API checks the argument types and +:c:func:`PyArg_ParseTuple` in the Python API checks the argument types and converts them to C values. It uses a template string to determine the required types of the arguments as well as the types of the C variables into which to store the converted values. More about this later. -:cfunc:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right +:c:func:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right type and its components have been stored in the variables whose addresses are passed. It returns false (zero) if an invalid argument list was passed. In the latter case it also raises an appropriate exception so the calling function can @@ -126,77 +126,77 @@ to know about them to understand how errors are passed around. The Python API defines a number of functions to set various types of exceptions. -The most common one is :cfunc:`PyErr_SetString`. Its arguments are an exception +The most common one is :c:func:`PyErr_SetString`. Its arguments are an exception object and a C string. The exception object is usually a predefined object like -:cdata:`PyExc_ZeroDivisionError`. The C string indicates the cause of the error +:c:data:`PyExc_ZeroDivisionError`. The C string indicates the cause of the error and is converted to a Python string object and stored as the "associated value" of the exception. -Another useful function is :cfunc:`PyErr_SetFromErrno`, which only takes an +Another useful function is :c:func:`PyErr_SetFromErrno`, which only takes an exception argument and constructs the associated value by inspection of the -global variable :cdata:`errno`. The most general function is -:cfunc:`PyErr_SetObject`, which takes two object arguments, the exception and -its associated value. You don't need to :cfunc:`Py_INCREF` the objects passed +global variable :c:data:`errno`. The most general function is +:c:func:`PyErr_SetObject`, which takes two object arguments, the exception and +its associated value. You don't need to :c:func:`Py_INCREF` the objects passed to any of these functions. You can test non-destructively whether an exception has been set with -:cfunc:`PyErr_Occurred`. This returns the current exception object, or *NULL* +:c:func:`PyErr_Occurred`. This returns the current exception object, or *NULL* if no exception has occurred. You normally don't need to call -:cfunc:`PyErr_Occurred` to see whether an error occurred in a function call, +:c:func:`PyErr_Occurred` to see whether an error occurred in a function call, since you should be able to tell from the return value. When a function *f* that calls another function *g* detects that the latter fails, *f* should itself return an error value (usually *NULL* or ``-1``). It -should *not* call one of the :cfunc:`PyErr_\*` functions --- one has already +should *not* call one of the :c:func:`PyErr_\*` functions --- one has already been called by *g*. *f*'s caller is then supposed to also return an error -indication to *its* caller, again *without* calling :cfunc:`PyErr_\*`, and so on +indication to *its* caller, again *without* calling :c:func:`PyErr_\*`, and so on --- the most detailed cause of the error was already reported by the function that first detected it. Once the error reaches the Python interpreter's main loop, this aborts the currently executing Python code and tries to find an exception handler specified by the Python programmer. (There are situations where a module can actually give a more detailed error -message by calling another :cfunc:`PyErr_\*` function, and in such cases it is +message by calling another :c:func:`PyErr_\*` function, and in such cases it is fine to do so. As a general rule, however, this is not necessary, and can cause information about the cause of the error to be lost: most operations can fail for a variety of reasons.) To ignore an exception set by a function call that failed, the exception -condition must be cleared explicitly by calling :cfunc:`PyErr_Clear`. The only -time C code should call :cfunc:`PyErr_Clear` is if it doesn't want to pass the +c:ondition must be cleared explicitly by calling :c:func:`PyErr_Clear`. The only +time C code should call :c:func:`PyErr_Clear` is if it doesn't want to pass the error on to the interpreter but wants to handle it completely by itself (possibly by trying something else, or pretending nothing went wrong). -Every failing :cfunc:`malloc` call must be turned into an exception --- the -direct caller of :cfunc:`malloc` (or :cfunc:`realloc`) must call -:cfunc:`PyErr_NoMemory` and return a failure indicator itself. All the -object-creating functions (for example, :cfunc:`PyLong_FromLong`) already do -this, so this note is only relevant to those who call :cfunc:`malloc` directly. +Every failing :c:func:`malloc` call must be turned into an exception --- the +direct caller of :c:func:`malloc` (or :c:func:`realloc`) must call +:c:func:`PyErr_NoMemory` and return a failure indicator itself. All the +object-creating functions (for example, :c:func:`PyLong_FromLong`) already do +this, so this note is only relevant to those who call :c:func:`malloc` directly. -Also note that, with the important exception of :cfunc:`PyArg_ParseTuple` and +Also note that, with the important exception of :c:func:`PyArg_ParseTuple` and friends, functions that return an integer status usually return a positive value or zero for success and ``-1`` for failure, like Unix system calls. -Finally, be careful to clean up garbage (by making :cfunc:`Py_XDECREF` or -:cfunc:`Py_DECREF` calls for objects you have already created) when you return +Finally, be careful to clean up garbage (by making :c:func:`Py_XDECREF` or +:c:func:`Py_DECREF` calls for objects you have already created) when you return an error indicator! The choice of which exception to raise is entirely yours. There are predeclared C objects corresponding to all built-in Python exceptions, such as -:cdata:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you -should choose exceptions wisely --- don't use :cdata:`PyExc_TypeError` to mean -that a file couldn't be opened (that should probably be :cdata:`PyExc_IOError`). -If something's wrong with the argument list, the :cfunc:`PyArg_ParseTuple` -function usually raises :cdata:`PyExc_TypeError`. If you have an argument whose +:c:data:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you +should choose exceptions wisely --- don't use :c:data:`PyExc_TypeError` to mean +that a file couldn't be opened (that should probably be :c:data:`PyExc_IOError`). +If something's wrong with the argument list, the :c:func:`PyArg_ParseTuple` +function usually raises :c:data:`PyExc_TypeError`. If you have an argument whose value must be in a particular range or must satisfy other conditions, -:cdata:`PyExc_ValueError` is appropriate. +:c:data:`PyExc_ValueError` is appropriate. You can also define a new exception that is unique to your module. For this, you usually declare a static object variable at the beginning of your file:: static PyObject *SpamError; -and initialize it in your module's initialization function (:cfunc:`PyInit_spam`) +and initialize it in your module's initialization function (:c:func:`PyInit_spam`) with an exception object (leaving out the error checking for now):: PyMODINIT_FUNC @@ -215,14 +215,14 @@ with an exception object (leaving out the error checking for now):: } Note that the Python name for the exception object is :exc:`spam.error`. The -:cfunc:`PyErr_NewException` function may create a class with the base class +:c:func:`PyErr_NewException` function may create a class with the base class being :exc:`Exception` (unless another class is passed in instead of *NULL*), described in :ref:`bltin-exceptions`. -Note also that the :cdata:`SpamError` variable retains a reference to the newly +Note also that the :c:data:`SpamError` variable retains a reference to the newly created exception class; this is intentional! Since the exception could be removed from the module by external code, an owned reference to the class is -needed to ensure that it will not be discarded, causing :cdata:`SpamError` to +needed to ensure that it will not be discarded, causing :c:data:`SpamError` to become a dangling pointer. Should it become a dangling pointer, C code which raises the exception could cause a core dump or other unintended side effects. @@ -230,7 +230,7 @@ We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this sample. The :exc:`spam.error` exception can be raised in your extension module using a -call to :cfunc:`PyErr_SetString` as shown below:: +call to :c:func:`PyErr_SetString` as shown below:: static PyObject * spam_system(PyObject *self, PyObject *args) @@ -262,22 +262,22 @@ statement:: It returns *NULL* (the error indicator for functions returning object pointers) if an error is detected in the argument list, relying on the exception set by -:cfunc:`PyArg_ParseTuple`. Otherwise the string value of the argument has been -copied to the local variable :cdata:`command`. This is a pointer assignment and +:c:func:`PyArg_ParseTuple`. Otherwise the string value of the argument has been +copied to the local variable :c:data:`command`. This is a pointer assignment and you are not supposed to modify the string to which it points (so in Standard C, -the variable :cdata:`command` should properly be declared as ``const char +the variable :c:data:`command` should properly be declared as ``const char *command``). -The next statement is a call to the Unix function :cfunc:`system`, passing it -the string we just got from :cfunc:`PyArg_ParseTuple`:: +The next statement is a call to the Unix function :c:func:`system`, passing it +the string we just got from :c:func:`PyArg_ParseTuple`:: sts = system(command); -Our :func:`spam.system` function must return the value of :cdata:`sts` as a -Python object. This is done using the function :cfunc:`Py_BuildValue`, which is -something like the inverse of :cfunc:`PyArg_ParseTuple`: it takes a format +Our :func:`spam.system` function must return the value of :c:data:`sts` as a +Python object. This is done using the function :c:func:`Py_BuildValue`, which is +something like the inverse of :c:func:`PyArg_ParseTuple`: it takes a format string and an arbitrary number of C values, and returns a new Python object. -More info on :cfunc:`Py_BuildValue` is given later. :: +More info on :c:func:`Py_BuildValue` is given later. :: return Py_BuildValue("i", sts); @@ -285,14 +285,14 @@ In this case, it will return an integer object. (Yes, even integers are objects on the heap in Python!) If you have a C function that returns no useful argument (a function returning -:ctype:`void`), the corresponding Python function must return ``None``. You -need this idiom to do so (which is implemented by the :cmacro:`Py_RETURN_NONE` +:c:type:`void`), the corresponding Python function must return ``None``. You +need this idiom to do so (which is implemented by the :c:macro:`Py_RETURN_NONE` macro):: Py_INCREF(Py_None); return Py_None; -:cdata:`Py_None` is the C name for the special Python object ``None``. It is a +:c:data:`Py_None` is the C name for the special Python object ``None``. It is a genuine Python object rather than a *NULL* pointer, which means "error" in most contexts, as we have seen. @@ -302,7 +302,7 @@ contexts, as we have seen. The Module's Method Table and Initialization Function ===================================================== -I promised to show how :cfunc:`spam_system` is called from Python programs. +I promised to show how :c:func:`spam_system` is called from Python programs. First, we need to list its name and address in a "method table":: static PyMethodDef SpamMethods[] = { @@ -316,16 +316,16 @@ First, we need to list its name and address in a "method table":: Note the third entry (``METH_VARARGS``). This is a flag telling the interpreter the calling convention to be used for the C function. It should normally always be ``METH_VARARGS`` or ``METH_VARARGS | METH_KEYWORDS``; a value of ``0`` means -that an obsolete variant of :cfunc:`PyArg_ParseTuple` is used. +that an obsolete variant of :c:func:`PyArg_ParseTuple` is used. When using only ``METH_VARARGS``, the function should expect the Python-level parameters to be passed in as a tuple acceptable for parsing via -:cfunc:`PyArg_ParseTuple`; more information on this function is provided below. +:c:func:`PyArg_ParseTuple`; more information on this function is provided below. The :const:`METH_KEYWORDS` bit may be set in the third field if keyword arguments should be passed to the function. In this case, the C function should accept a third ``PyObject \*`` parameter which will be a dictionary of keywords. -Use :cfunc:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a +Use :c:func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a function. The method table must be referenced in the module definition structure:: @@ -341,7 +341,7 @@ The method table must be referenced in the module definition structure:: This structure, in turn, must be passed to the interpreter in the module's initialization function. The initialization function must be named -:cfunc:`PyInit_name`, where *name* is the name of the module, and should be the +:c:func:`PyInit_name`, where *name* is the name of the module, and should be the only non-\ ``static`` item defined in the module file:: PyMODINIT_FUNC @@ -355,19 +355,19 @@ declares any special linkage declarations required by the platform, and for C++ declares the function as ``extern "C"``. When the Python program imports module :mod:`spam` for the first time, -:cfunc:`PyInit_spam` is called. (See below for comments about embedding Python.) -It calls :cfunc:`PyModule_Create`, which returns a module object, and +:c:func:`PyInit_spam` is called. (See below for comments about embedding Python.) +It calls :c:func:`PyModule_Create`, which returns a module object, and inserts built-in function objects into the newly created module based upon the -table (an array of :ctype:`PyMethodDef` structures) found in the module definition. -:cfunc:`PyModule_Create` returns a pointer to the module object +table (an array of :c:type:`PyMethodDef` structures) found in the module definition. +:c:func:`PyModule_Create` returns a pointer to the module object that it creates. It may abort with a fatal error for certain errors, or return *NULL* if the module could not be initialized satisfactorily. The init function must return the module object to its caller, so that it then gets inserted into ``sys.modules``. -When embedding Python, the :cfunc:`PyInit_spam` function is not called -automatically unless there's an entry in the :cdata:`PyImport_Inittab` table. -To add the module to the initialization table, use :cfunc:`PyImport_AppendInittab`, +When embedding Python, the :c:func:`PyInit_spam` function is not called +automatically unless there's an entry in the :c:data:`PyImport_Inittab` table. +To add the module to the initialization table, use :c:func:`PyImport_AppendInittab`, optionally followed by an import of the module:: int @@ -393,8 +393,8 @@ source distribution. .. note:: Removing entries from ``sys.modules`` or importing compiled modules into - multiple interpreters within a process (or following a :cfunc:`fork` without an - intervening :cfunc:`exec`) can create problems for some extension modules. + multiple interpreters within a process (or following a :c:func:`fork` without an + intervening :c:func:`exec`) can create problems for some extension modules. Extension module authors should exercise caution when initializing internal data structures. @@ -458,7 +458,7 @@ look at the implementation of the :option:`-c` command line option in Calling a Python function is easy. First, the Python program must somehow pass you the Python function object. You should provide a function (or some other interface) to do this. When this function is called, save a pointer to the -Python function object (be careful to :cfunc:`Py_INCREF` it!) in a global +Python function object (be careful to :c:func:`Py_INCREF` it!) in a global variable --- or wherever you see fit. For example, the following function might be part of a module definition:: @@ -487,10 +487,10 @@ be part of a module definition:: This function must be registered with the interpreter using the :const:`METH_VARARGS` flag; this is described in section :ref:`methodtable`. The -:cfunc:`PyArg_ParseTuple` function and its arguments are documented in section +:c:func:`PyArg_ParseTuple` function and its arguments are documented in section :ref:`parsetuple`. -The macros :cfunc:`Py_XINCREF` and :cfunc:`Py_XDECREF` increment/decrement the +The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement the reference count of an object and are safe in the presence of *NULL* pointers (but note that *temp* will not be *NULL* in this context). More info on them in section :ref:`refcounts`. @@ -498,12 +498,12 @@ in section :ref:`refcounts`. .. index:: single: PyObject_CallObject() Later, when it is time to call the function, you call the C function -:cfunc:`PyObject_CallObject`. This function has two arguments, both pointers to +:c:func:`PyObject_CallObject`. This function has two arguments, both pointers to arbitrary Python objects: the Python function, and the argument list. The argument list must always be a tuple object, whose length is the number of arguments. To call the Python function with no arguments, pass in NULL, or an empty tuple; to call it with one argument, pass a singleton tuple. -:cfunc:`Py_BuildValue` returns a tuple when its format string consists of zero +:c:func:`Py_BuildValue` returns a tuple when its format string consists of zero or more format codes between parentheses. For example:: int arg; @@ -517,25 +517,25 @@ or more format codes between parentheses. For example:: result = PyObject_CallObject(my_callback, arglist); Py_DECREF(arglist); -:cfunc:`PyObject_CallObject` returns a Python object pointer: this is the return -value of the Python function. :cfunc:`PyObject_CallObject` is +:c:func:`PyObject_CallObject` returns a Python object pointer: this is the return +value of the Python function. :c:func:`PyObject_CallObject` is "reference-count-neutral" with respect to its arguments. In the example a new -tuple was created to serve as the argument list, which is :cfunc:`Py_DECREF`\ +tuple was created to serve as the argument list, which is :c:func:`Py_DECREF`\ -ed immediately after the call. -The return value of :cfunc:`PyObject_CallObject` is "new": either it is a brand +The return value of :c:func:`PyObject_CallObject` is "new": either it is a brand new object, or it is an existing object whose reference count has been incremented. So, unless you want to save it in a global variable, you should -somehow :cfunc:`Py_DECREF` the result, even (especially!) if you are not +somehow :c:func:`Py_DECREF` the result, even (especially!) if you are not interested in its value. Before you do this, however, it is important to check that the return value isn't *NULL*. If it is, the Python function terminated by raising an exception. -If the C code that called :cfunc:`PyObject_CallObject` is called from Python, it +If the C code that called :c:func:`PyObject_CallObject` is called from Python, it should now return an error indication to its Python caller, so the interpreter can print a stack trace, or the calling Python code can handle the exception. If this is not possible or desirable, the exception should be cleared by calling -:cfunc:`PyErr_Clear`. For example:: +:c:func:`PyErr_Clear`. For example:: if (result == NULL) return NULL; /* Pass error back */ @@ -543,12 +543,12 @@ If this is not possible or desirable, the exception should be cleared by calling Py_DECREF(result); Depending on the desired interface to the Python callback function, you may also -have to provide an argument list to :cfunc:`PyObject_CallObject`. In some cases +have to provide an argument list to :c:func:`PyObject_CallObject`. In some cases the argument list is also provided by the Python program, through the same interface that specified the callback function. It can then be saved and used in the same manner as the function object. In other cases, you may have to construct a new tuple to pass as the argument list. The simplest way to do this -is to call :cfunc:`Py_BuildValue`. For example, if you want to pass an integral +is to call :c:func:`Py_BuildValue`. For example, if you want to pass an integral event code, you might use the following code:: PyObject *arglist; @@ -563,11 +563,11 @@ event code, you might use the following code:: Note the placement of ``Py_DECREF(arglist)`` immediately after the call, before the error check! Also note that strictly speaking this code is not complete: -:cfunc:`Py_BuildValue` may run out of memory, and this should be checked. +:c:func:`Py_BuildValue` may run out of memory, and this should be checked. You may also call a function with keyword arguments by using -:cfunc:`PyObject_Call`, which supports arguments and keyword arguments. As in -the above example, we use :cfunc:`Py_BuildValue` to construct the dictionary. :: +:c:func:`PyObject_Call`, which supports arguments and keyword arguments. As in +the above example, we use :c:func:`Py_BuildValue` to construct the dictionary. :: PyObject *dict; ... @@ -587,7 +587,7 @@ Extracting Parameters in Extension Functions .. index:: single: PyArg_ParseTuple() -The :cfunc:`PyArg_ParseTuple` function is declared as follows:: +The :c:func:`PyArg_ParseTuple` function is declared as follows:: int PyArg_ParseTuple(PyObject *arg, char *format, ...); @@ -597,7 +597,7 @@ whose syntax is explained in :ref:`arg-parsing` in the Python/C API Reference Manual. The remaining arguments must be addresses of variables whose type is determined by the format string. -Note that while :cfunc:`PyArg_ParseTuple` checks that the Python arguments have +Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments have the required types, it cannot check the validity of the addresses of C variables passed to the call: if you make mistakes there, your code will probably crash or at least overwrite random bits in memory. So be careful! @@ -679,17 +679,17 @@ Keyword Parameters for Extension Functions .. index:: single: PyArg_ParseTupleAndKeywords() -The :cfunc:`PyArg_ParseTupleAndKeywords` function is declared as follows:: +The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows:: int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict, char *format, char *kwlist[], ...); The *arg* and *format* parameters are identical to those of the -:cfunc:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of +:c:func:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of keywords received as the third parameter from the Python runtime. The *kwlist* parameter is a *NULL*-terminated list of strings which identify the parameters; the names are matched with the type information from *format* from left to -right. On success, :cfunc:`PyArg_ParseTupleAndKeywords` returns true, otherwise +right. On success, :c:func:`PyArg_ParseTupleAndKeywords` returns true, otherwise it returns false and raises an appropriate exception. .. note:: @@ -753,19 +753,19 @@ Philbrick (philbrick@hks.com):: Building Arbitrary Values ========================= -This function is the counterpart to :cfunc:`PyArg_ParseTuple`. It is declared +This function is the counterpart to :c:func:`PyArg_ParseTuple`. It is declared as follows:: PyObject *Py_BuildValue(char *format, ...); It recognizes a set of format units similar to the ones recognized by -:cfunc:`PyArg_ParseTuple`, but the arguments (which are input to the function, +:c:func:`PyArg_ParseTuple`, but the arguments (which are input to the function, not output) must not be pointers, just values. It returns a new Python object, suitable for returning from a C function called from Python. -One difference with :cfunc:`PyArg_ParseTuple`: while the latter requires its +One difference with :c:func:`PyArg_ParseTuple`: while the latter requires its first argument to be a tuple (since Python argument lists are always represented -as tuples internally), :cfunc:`Py_BuildValue` does not always build a tuple. It +as tuples internally), :c:func:`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 @@ -799,18 +799,18 @@ Reference Counts In languages like C or C++, the programmer is responsible for dynamic allocation and deallocation of memory on the heap. In C, this is done using the functions -:cfunc:`malloc` and :cfunc:`free`. In C++, the operators ``new`` and +:c:func:`malloc` and :c:func:`free`. In C++, the operators ``new`` and ``delete`` are used with essentially the same meaning and we'll restrict the following discussion to the C case. -Every block of memory allocated with :cfunc:`malloc` should eventually be -returned to the pool of available memory by exactly one call to :cfunc:`free`. -It is important to call :cfunc:`free` at the right time. If a block's address -is forgotten but :cfunc:`free` is not called for it, the memory it occupies +Every block of memory allocated with :c:func:`malloc` should eventually be +returned to the pool of available memory by exactly one call to :c:func:`free`. +It is important to call :c:func:`free` at the right time. If a block's address +is forgotten but :c:func:`free` is not called for it, the memory it occupies cannot be reused until the program terminates. This is called a :dfn:`memory -leak`. On the other hand, if a program calls :cfunc:`free` for a block and then +leak`. On the other hand, if a program calls :c:func:`free` for a block and then continues to use the block, it creates a conflict with re-use of the block -through another :cfunc:`malloc` call. This is called :dfn:`using freed memory`. +through another :c:func:`malloc` call. This is called :dfn:`using freed memory`. It has the same bad consequences as referencing uninitialized data --- core dumps, wrong results, mysterious crashes. @@ -827,7 +827,7 @@ long-running process that uses the leaking function frequently. Therefore, it's important to prevent leaks from happening by having a coding convention or strategy that minimizes this kind of errors. -Since Python makes heavy use of :cfunc:`malloc` and :cfunc:`free`, it needs a +Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it needs a strategy to avoid memory leaks as well as the use of freed memory. The chosen method is called :dfn:`reference counting`. The principle is simple: every object contains a counter, which is incremented when a reference to the object @@ -839,11 +839,11 @@ An alternative strategy is called :dfn:`automatic garbage collection`. (Sometimes, reference counting is also referred to as a garbage collection strategy, hence my use of "automatic" to distinguish the two.) The big advantage of automatic garbage collection is that the user doesn't need to call -:cfunc:`free` explicitly. (Another claimed advantage is an improvement in speed +:c:func:`free` explicitly. (Another claimed advantage is an improvement in speed or memory usage --- this is no hard fact however.) The disadvantage is that for C, there is no truly portable automatic garbage collector, while reference -counting can be implemented portably (as long as the functions :cfunc:`malloc` -and :cfunc:`free` are available --- which the C Standard guarantees). Maybe some +counting can be implemented portably (as long as the functions :c:func:`malloc` +and :c:func:`free` are available --- which the C Standard guarantees). Maybe some day a sufficiently portable automatic garbage collector will be available for C. Until then, we'll have to live with reference counts. @@ -878,9 +878,9 @@ Reference Counting in Python ---------------------------- There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle the -incrementing and decrementing of the reference count. :cfunc:`Py_DECREF` also +incrementing and decrementing of the reference count. :c:func:`Py_DECREF` also frees the object when the count reaches zero. For flexibility, it doesn't call -:cfunc:`free` directly --- rather, it makes a call through a function pointer in +:c:func:`free` directly --- rather, it makes a call through a function pointer in the object's :dfn:`type object`. For this purpose (and others), every object also contains a pointer to its type object. @@ -888,13 +888,13 @@ The big question now remains: when to use ``Py_INCREF(x)`` and ``Py_DECREF(x)``? Let's first introduce some terms. Nobody "owns" an object; however, you can :dfn:`own a reference` to an object. An object's reference count is now defined as the number of owned references to it. The owner of a reference is -responsible for calling :cfunc:`Py_DECREF` when the reference is no longer +responsible for calling :c:func:`Py_DECREF` when the reference is no longer needed. Ownership of a reference can be transferred. There are three ways to -dispose of an owned reference: pass it on, store it, or call :cfunc:`Py_DECREF`. +dispose of an owned reference: pass it on, store it, or call :c:func:`Py_DECREF`. Forgetting to dispose of an owned reference creates a memory leak. It is also possible to :dfn:`borrow` [#]_ a reference to an object. The -borrower of a reference should not call :cfunc:`Py_DECREF`. The borrower must +borrower of a reference should not call :c:func:`Py_DECREF`. The borrower must not hold on to the object longer than the owner from which it was borrowed. Using a borrowed reference after the owner has disposed of it risks using freed memory and should be avoided completely. [#]_ @@ -908,7 +908,7 @@ reference can be used after the owner from which it was borrowed has in fact disposed of it. A borrowed reference can be changed into an owned reference by calling -:cfunc:`Py_INCREF`. This does not affect the status of the owner from which the +:c:func:`Py_INCREF`. This does not affect the status of the owner from which the reference was borrowed --- it creates a new owned reference, and gives full owner responsibilities (the new owner must dispose of the reference properly, as well as the previous owner). @@ -925,36 +925,36 @@ reference or not. Most functions that return a reference to an object pass on ownership with the reference. In particular, all functions whose function it is to create a new -object, such as :cfunc:`PyLong_FromLong` and :cfunc:`Py_BuildValue`, pass +object, such as :c:func:`PyLong_FromLong` and :c:func:`Py_BuildValue`, pass ownership to the receiver. Even if the object is not actually new, you still receive ownership of a new reference to that object. For instance, -:cfunc:`PyLong_FromLong` maintains a cache of popular values and can return a +:c:func:`PyLong_FromLong` maintains a cache of popular values and can return a reference to a cached item. Many functions that extract objects from other objects also transfer ownership -with the reference, for instance :cfunc:`PyObject_GetAttrString`. The picture +with the reference, for instance :c:func:`PyObject_GetAttrString`. The picture is less clear, here, however, since a few common routines are exceptions: -:cfunc:`PyTuple_GetItem`, :cfunc:`PyList_GetItem`, :cfunc:`PyDict_GetItem`, and -:cfunc:`PyDict_GetItemString` all return references that you borrow from the +:c:func:`PyTuple_GetItem`, :c:func:`PyList_GetItem`, :c:func:`PyDict_GetItem`, and +:c:func:`PyDict_GetItemString` all return references that you borrow from the tuple, list or dictionary. -The function :cfunc:`PyImport_AddModule` also returns a borrowed reference, even +The function :c:func:`PyImport_AddModule` also returns a borrowed reference, even though it may actually create the object it returns: this is possible because an owned reference to the object is stored in ``sys.modules``. When you pass an object reference into another function, in general, the function borrows the reference from you --- if it needs to store it, it will use -:cfunc:`Py_INCREF` to become an independent owner. There are exactly two -important exceptions to this rule: :cfunc:`PyTuple_SetItem` and -:cfunc:`PyList_SetItem`. These functions take over ownership of the item passed -to them --- even if they fail! (Note that :cfunc:`PyDict_SetItem` and friends +:c:func:`Py_INCREF` to become an independent owner. There are exactly two +important exceptions to this rule: :c:func:`PyTuple_SetItem` and +:c:func:`PyList_SetItem`. These functions take over ownership of the item passed +to them --- even if they fail! (Note that :c:func:`PyDict_SetItem` and friends don't take over ownership --- they are "normal.") When a C function is called from Python, it borrows references to its arguments from the caller. The caller owns a reference to the object, so the borrowed reference's lifetime is guaranteed until the function returns. Only when such a borrowed reference must be stored or passed on, it must be turned into an owned -reference by calling :cfunc:`Py_INCREF`. +reference by calling :c:func:`Py_INCREF`. The object reference returned from a C function that is called from Python must be an owned reference --- ownership is transferred from the function to its @@ -970,7 +970,7 @@ There are a few situations where seemingly harmless use of a borrowed reference can lead to problems. These all have to do with implicit invocations of the interpreter, which can cause the owner of a reference to dispose of it. -The first and most important case to know about is using :cfunc:`Py_DECREF` on +The first and most important case to know about is using :c:func:`Py_DECREF` on an unrelated object while borrowing a reference to a list item. For instance:: void @@ -986,7 +986,7 @@ This function first borrows a reference to ``list[0]``, then replaces ``list[1]`` with the value ``0``, and finally prints the borrowed reference. Looks harmless, right? But it's not! -Let's follow the control flow into :cfunc:`PyList_SetItem`. The list owns +Let's follow the control flow into :c:func:`PyList_SetItem`. The list owns references to all its items, so when item 1 is replaced, it has to dispose of the original item 1. Now let's suppose the original item 1 was an instance of a user-defined class, and let's further suppose that the class defined a @@ -995,8 +995,8 @@ disposing of it will call its :meth:`__del__` method. Since it is written in Python, the :meth:`__del__` method can execute arbitrary Python code. Could it perhaps do something to invalidate the reference to -``item`` in :cfunc:`bug`? You bet! Assuming that the list passed into -:cfunc:`bug` is accessible to the :meth:`__del__` method, it could execute a +``item`` in :c:func:`bug`? You bet! Assuming that the list passed into +:c:func:`bug` is accessible to the :meth:`__del__` method, it could execute a statement to the effect of ``del list[0]``, and assuming this was the last reference to that object, it would free the memory associated with it, thereby invalidating ``item``. @@ -1023,8 +1023,8 @@ The second case of problems with a borrowed reference is a variant involving threads. Normally, multiple threads in the Python interpreter can't get in each other's way, because there is a global lock protecting Python's entire object space. However, it is possible to temporarily release this lock using the macro -:cmacro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using -:cmacro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to +:c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using +:c:macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to let other threads use the processor while waiting for the I/O to complete. Obviously, the following function has the same problem as the previous one:: @@ -1053,11 +1053,11 @@ function --- if each function were to test for *NULL*, there would be a lot of redundant tests and the code would run more slowly. It is better to test for *NULL* only at the "source:" when a pointer that may be -*NULL* is received, for example, from :cfunc:`malloc` or from a function that +*NULL* is received, for example, from :c:func:`malloc` or from a function that may raise an exception. -The macros :cfunc:`Py_INCREF` and :cfunc:`Py_DECREF` do not check for *NULL* -pointers --- however, their variants :cfunc:`Py_XINCREF` and :cfunc:`Py_XDECREF` +The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for *NULL* +pointers --- however, their variants :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` do. The macros for checking for a particular object type (``Pytype_Check()``) don't @@ -1131,7 +1131,7 @@ other extension modules must be exported in a different way. Python provides a special mechanism to pass C-level information (pointers) from one extension module to another one: Capsules. A Capsule is a Python data type -which stores a pointer (:ctype:`void \*`). Capsules can only be created and +which stores a pointer (:c:type:`void \*`). Capsules can only be created and accessed via their C API, but they can be passed around like any other Python object. In particular, they can be assigned to a name in an extension module's namespace. Other extension modules can then import this module, retrieve the @@ -1144,8 +1144,8 @@ various tasks of storing and retrieving the pointers can be distributed in different ways between the module providing the code and the client modules. Whichever method you choose, it's important to name your Capsules properly. -The function :cfunc:`PyCapsule_New` takes a name parameter -(:ctype:`const char \*`); you're permitted to pass in a *NULL* name, but +The function :c:func:`PyCapsule_New` takes a name parameter +(:c:type:`const char \*`); you're permitted to pass in a *NULL* name, but we strongly encourage you to specify a name. Properly named Capsules provide a degree of runtime type-safety; there is no feasible way to tell one unnamed Capsule from another. @@ -1155,7 +1155,7 @@ this convention:: modulename.attributename -The convenience function :cfunc:`PyCapsule_Import` makes it easy to +The convenience function :c:func:`PyCapsule_Import` makes it easy to load a C API provided via a Capsule, but only if the Capsule's name matches this convention. This behavior gives C API users a high degree of certainty that the Capsule they load contains the correct C API. @@ -1163,19 +1163,19 @@ of certainty that the Capsule they load contains the correct C API. The following example demonstrates an approach that puts most of the burden on the writer of the exporting module, which is appropriate for commonly used library modules. It stores all C API pointers (just one in the example!) in an -array of :ctype:`void` pointers which becomes the value of a Capsule. The header +array of :c:type:`void` pointers which becomes the value of a Capsule. The header file corresponding to the module provides a macro that takes care of importing the module and retrieving its C API pointers; client modules only have to call this macro before accessing the C API. The exporting module is a modification of the :mod:`spam` module from section :ref:`extending-simpleexample`. The function :func:`spam.system` does not call -the C library function :cfunc:`system` directly, but a function -:cfunc:`PySpam_System`, which would of course do something more complicated in +the C library function :c:func:`system` directly, but a function +:c:func:`PySpam_System`, which would of course do something more complicated in reality (such as adding "spam" to every command). This function -:cfunc:`PySpam_System` is also exported to other extension modules. +:c:func:`PySpam_System` is also exported to other extension modules. -The function :cfunc:`PySpam_System` is a plain C function, declared +The function :c:func:`PySpam_System` is a plain C function, declared ``static`` like everything else:: static int @@ -1184,7 +1184,7 @@ The function :cfunc:`PySpam_System` is a plain C function, declared return system(command); } -The function :cfunc:`spam_system` is modified in a trivial way:: +The function :c:func:`spam_system` is modified in a trivial way:: static PyObject * spam_system(PyObject *self, PyObject *args) @@ -1288,8 +1288,8 @@ like this:: #endif /* !defined(Py_SPAMMODULE_H) */ All that a client module must do in order to have access to the function -:cfunc:`PySpam_System` is to call the function (or rather macro) -:cfunc:`import_spam` in its initialization function:: +:c:func:`PySpam_System` is to call the function (or rather macro) +:c:func:`import_spam` in its initialization function:: PyMODINIT_FUNC PyInit_client(void) diff --git a/Doc/extending/newtypes.rst b/Doc/extending/newtypes.rst index d48efc9..75836c7 100644 --- a/Doc/extending/newtypes.rst +++ b/Doc/extending/newtypes.rst @@ -26,7 +26,7 @@ The Basics ========== The Python runtime sees all Python objects as variables of type -:ctype:`PyObject\*`. A :ctype:`PyObject` is not a very magnificent object - it +:c:type:`PyObject\*`. A :c:type:`PyObject` is not a very magnificent object - it just contains the refcount and a pointer to the object's "type object". This is where the action is; the type object determines which (C) functions get called when, for instance, an attribute gets looked up on an object or it is multiplied @@ -95,7 +95,7 @@ Moving on, we come to the crunch --- the type object. :: "Noddy objects", /* tp_doc */ }; -Now if you go and look up the definition of :ctype:`PyTypeObject` in +Now if you go and look up the definition of :c:type:`PyTypeObject` in :file:`object.h` you'll see that it has many more fields that the definition above. The remaining fields will be filled with zeros by the C compiler, and it's common practice to not specify them explicitly unless you need them. @@ -111,7 +111,7 @@ This line is a bit of a wart; what we'd like to write is:: as the type of a type object is "type", but this isn't strictly conforming C and some compilers complain. Fortunately, this member will be filled in for us by -:cfunc:`PyType_Ready`. :: +:c:func:`PyType_Ready`. :: "noddy.Noddy", /* tp_name */ @@ -130,7 +130,7 @@ the type is :class:`Noddy`, so we set the type name to :class:`noddy.Noddy`. :: sizeof(noddy_NoddyObject), /* tp_basicsize */ This is so that Python knows how much memory to allocate when you call -:cfunc:`PyObject_New`. +:c:func:`PyObject_New`. .. note:: @@ -170,12 +170,12 @@ the module. We'll expand this example later to have more interesting behavior. For now, all we want to be able to do is to create new :class:`Noddy` objects. To enable object creation, we have to provide a :attr:`tp_new` implementation. In this case, we can just use the default implementation provided by the API -function :cfunc:`PyType_GenericNew`. We'd like to just assign this to the +function :c:func:`PyType_GenericNew`. We'd like to just assign this to the :attr:`tp_new` slot, but we can't, for portability sake, On some platforms or compilers, we can't statically initialize a structure member with a function defined in another C module, so, instead, we'll assign the :attr:`tp_new` slot in the module initialization function just before calling -:cfunc:`PyType_Ready`:: +:c:func:`PyType_Ready`:: noddy_NoddyType.tp_new = PyType_GenericNew; if (PyType_Ready(&noddy_NoddyType) < 0) @@ -185,7 +185,7 @@ All the other type methods are *NULL*, so we'll go over them later --- that's for a later section! Everything else in the file should be familiar, except for some code in -:cfunc:`PyInit_noddy`:: +:c:func:`PyInit_noddy`:: if (PyType_Ready(&noddy_NoddyType) < 0) return; @@ -273,7 +273,7 @@ which is assigned to the :attr:`tp_dealloc` member:: (destructor)Noddy_dealloc, /*tp_dealloc*/ This method decrements the reference counts of the two Python attributes. We use -:cfunc:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members +:c:func:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members could be *NULL*. It then calls the :attr:`tp_free` member of the object's type to free the object's memory. Note that the object's type might not be :class:`NoddyType`, because the object may be an instance of a subclass. @@ -319,8 +319,8 @@ the :meth:`__new__` method. One reason to implement a new method is to assure the initial values of instance variables. In this case, we use the new method to make sure that the initial values of the members :attr:`first` and :attr:`last` are not *NULL*. If we didn't care whether the initial values were -*NULL*, we could have used :cfunc:`PyType_GenericNew` as our new method, as we -did before. :cfunc:`PyType_GenericNew` initializes all of the instance variable +*NULL*, we could have used :c:func:`PyType_GenericNew` as our new method, as we +did before. :c:func:`PyType_GenericNew` initializes all of the instance variable members to *NULL*. The new method is a static method that is passed the type being instantiated and @@ -330,7 +330,7 @@ often ignore the arguments, leaving the argument handling to initializer methods. Note that if the type supports subclassing, the type passed may not be the type being defined. The new method calls the tp_alloc slot to allocate memory. We don't fill the :attr:`tp_alloc` slot ourselves. Rather -:cfunc:`PyType_Ready` fills it for us by inheriting it from our base class, +:c:func:`PyType_Ready` fills it for us by inheriting it from our base class, which is :class:`object` by default. Most types use the default allocation. .. note:: @@ -515,8 +515,8 @@ object being created or used, so all we need to do is to add the Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ -We rename :cfunc:`PyInit_noddy` to :cfunc:`PyInit_noddy2` and update the module -name in the :ctype:`PyModuleDef` struct. +We rename :c:func:`PyInit_noddy` to :c:func:`PyInit_noddy2` and update the module +name in the :c:type:`PyModuleDef` struct. Finally, we update our :file:`setup.py` file to build the new module:: @@ -582,7 +582,7 @@ closure. The new value may be *NULL*, in which case the attribute is being deleted. In our setter, we raise an error if the attribute is deleted or if the attribute value is not a string. -We create an array of :ctype:`PyGetSetDef` structures:: +We create an array of :c:type:`PyGetSetDef` structures:: static PyGetSetDef Noddy_getseters[] = { {"first", @@ -602,7 +602,7 @@ and register it in the :attr:`tp_getset` slot:: to register our attribute getters and setters. -The last item in a :ctype:`PyGetSetDef` structure is the closure mentioned +The last item in a :c:type:`PyGetSetDef` structure is the closure mentioned above. In this case, we aren't using the closure, so we just pass *NULL*. We also remove the member definitions for these attributes:: @@ -647,8 +647,8 @@ be passed:: With these changes, we can assure that the :attr:`first` and :attr:`last` members are never *NULL* so we can remove checks for *NULL* values in almost all -cases. This means that most of the :cfunc:`Py_XDECREF` calls can be converted to -:cfunc:`Py_DECREF` calls. The only place we can't change these calls is in the +cases. This means that most of the :c:func:`Py_XDECREF` calls can be converted to +:c:func:`Py_DECREF` calls. The only place we can't change these calls is in the deallocator, where there is the possibility that the initialization of these members failed in the constructor. @@ -713,13 +713,13 @@ cycles:: } For each subobject that can participate in cycles, we need to call the -:cfunc:`visit` function, which is passed to the traversal method. The -:cfunc:`visit` function takes as arguments the subobject and the extra argument +:c:func:`visit` function, which is passed to the traversal method. The +:c:func:`visit` function takes as arguments the subobject and the extra argument *arg* passed to the traversal method. It returns an integer value that must be returned if it is non-zero. -Python provides a :cfunc:`Py_VISIT` macro that automates calling visit -functions. With :cfunc:`Py_VISIT`, :cfunc:`Noddy_traverse` can be simplified:: +Python provides a :c:func:`Py_VISIT` macro that automates calling visit +functions. With :c:func:`Py_VISIT`, :c:func:`Noddy_traverse` can be simplified:: static int Noddy_traverse(Noddy *self, visitproc visit, void *arg) @@ -732,7 +732,7 @@ functions. With :cfunc:`Py_VISIT`, :cfunc:`Noddy_traverse` can be simplified:: .. note:: Note that the :attr:`tp_traverse` implementation must name its arguments exactly - *visit* and *arg* in order to use :cfunc:`Py_VISIT`. This is to encourage + *visit* and *arg* in order to use :c:func:`Py_VISIT`. This is to encourage uniformity across these boring implementations. We also need to provide a method for clearing any subobjects that can @@ -762,18 +762,18 @@ to use it:: Py_TYPE(self)->tp_free((PyObject*)self); } -Notice the use of a temporary variable in :cfunc:`Noddy_clear`. We use the +Notice the use of a temporary variable in :c:func:`Noddy_clear`. We use the temporary variable so that we can set each member to *NULL* before decrementing its reference count. We do this because, as was discussed earlier, if the reference count drops to zero, we might cause code to run that calls back into the object. In addition, because we now support garbage collection, we also have to worry about code being run that triggers garbage collection. If garbage collection is run, our :attr:`tp_traverse` handler could get called. We can't -take a chance of having :cfunc:`Noddy_traverse` called when a member's reference +take a chance of having :c:func:`Noddy_traverse` called when a member's reference count has dropped to zero and its value hasn't been set to *NULL*. -Python provides a :cfunc:`Py_CLEAR` that automates the careful decrementing of -reference counts. With :cfunc:`Py_CLEAR`, the :cfunc:`Noddy_clear` function can +Python provides a :c:func:`Py_CLEAR` that automates the careful decrementing of +reference counts. With :c:func:`Py_CLEAR`, the :c:func:`Noddy_clear` function can be simplified:: static int @@ -829,7 +829,7 @@ previous sections. We will break down the main differences between them. :: The primary difference for derived type objects is that the base type's object structure must be the first value. The base type will already include the -:cfunc:`PyObject_HEAD` at the beginning of its structure. +:c:func:`PyObject_HEAD` at the beginning of its structure. When a Python object is a :class:`Shoddy` instance, its *PyObject\** pointer can be safely cast to both *PyListObject\** and *Shoddy\**. :: @@ -851,10 +851,10 @@ This pattern is important when writing a type with custom :attr:`new` and memory for the object with :attr:`tp_alloc`, that will be handled by the base class when calling its :attr:`tp_new`. -When filling out the :cfunc:`PyTypeObject` for the :class:`Shoddy` type, you see -a slot for :cfunc:`tp_base`. Due to cross platform compiler issues, you can't -fill that field directly with the :cfunc:`PyList_Type`; it can be done later in -the module's :cfunc:`init` function. :: +When filling out the :c:func:`PyTypeObject` for the :class:`Shoddy` type, you see +a slot for :c:func:`tp_base`. Due to cross platform compiler issues, you can't +fill that field directly with the :c:func:`PyList_Type`; it can be done later in +the module's :c:func:`init` function. :: PyMODINIT_FUNC PyInit_shoddy(void) @@ -874,12 +874,12 @@ the module's :cfunc:`init` function. :: return m; } -Before calling :cfunc:`PyType_Ready`, the type structure must have the +Before calling :c:func:`PyType_Ready`, the type structure must have the :attr:`tp_base` slot filled in. When we are deriving a new type, it is not -necessary to fill out the :attr:`tp_alloc` slot with :cfunc:`PyType_GenericNew` +necessary to fill out the :attr:`tp_alloc` slot with :c:func:`PyType_GenericNew` -- the allocate function from the base type will be inherited. -After that, calling :cfunc:`PyType_Ready` and adding the type object to the +After that, calling :c:func:`PyType_Ready` and adding the type object to the module is the same as with the basic :class:`Noddy` examples. @@ -891,7 +891,7 @@ Type Methods This section aims to give a quick fly-by on the various type methods you can implement and what they do. -Here is the definition of :ctype:`PyTypeObject`, with some fields only used in +Here is the definition of :c:type:`PyTypeObject`, with some fields only used in debug builds omitted: .. literalinclude:: ../includes/typestruct.h @@ -969,8 +969,8 @@ which a deallocator performs which may cause additional Python code to be executed may detect that an exception has been set. This can lead to misleading errors from the interpreter. The proper way to protect against this is to save a pending exception before performing the unsafe action, and restoring it when -done. This can be done using the :cfunc:`PyErr_Fetch` and -:cfunc:`PyErr_Restore` functions:: +done. This can be done using the :c:func:`PyErr_Fetch` and +:c:func:`PyErr_Restore` functions:: static void my_dealloc(PyObject *obj) @@ -1060,8 +1060,8 @@ a special case, for which the new value passed to the handler is *NULL*. Python supports two pairs of attribute handlers; a type that supports attributes only needs to implement the functions for one pair. The difference is that one -pair takes the name of the attribute as a :ctype:`char\*`, while the other -accepts a :ctype:`PyObject\*`. Each type can use whichever pair makes more +pair takes the name of the attribute as a :c:type:`char\*`, while the other +accepts a :c:type:`PyObject\*`. Each type can use whichever pair makes more sense for the implementation's convenience. :: getattrfunc tp_getattr; /* char * version */ @@ -1072,7 +1072,7 @@ sense for the implementation's convenience. :: If accessing attributes of an object is always a simple operation (this will be explained shortly), there are generic implementations which can be used to -provide the :ctype:`PyObject\*` version of the attribute management functions. +provide the :c:type:`PyObject\*` version of the attribute management functions. The actual need for type-specific attribute handlers almost completely disappeared starting with Python 2.2, though there are many examples which have not been updated to use some of the new generic mechanism that is available. @@ -1086,7 +1086,7 @@ Generic Attribute Management Most extension types only use *simple* attributes. So, what makes the attributes simple? There are only a couple of conditions that must be met: -#. The name of the attributes must be known when :cfunc:`PyType_Ready` is +#. The name of the attributes must be known when :c:func:`PyType_Ready` is called. #. No special processing is needed to record that an attribute was looked up or @@ -1095,7 +1095,7 @@ attributes simple? There are only a couple of conditions that must be met: Note that this list does not place any restrictions on the values of the attributes, when the values are computed, or how relevant data is stored. -When :cfunc:`PyType_Ready` is called, it uses three tables referenced by the +When :c:func:`PyType_Ready` is called, it uses three tables referenced by the type object to create :term:`descriptor`\s which are placed in the dictionary of the type object. Each descriptor controls access to one attribute of the instance object. Each of the tables is optional; if all three are *NULL*, instances of @@ -1110,7 +1110,7 @@ The tables are declared as three fields of the type object:: struct PyGetSetDef *tp_getset; If :attr:`tp_methods` is not *NULL*, it must refer to an array of -:ctype:`PyMethodDef` structures. Each entry in the table is an instance of this +:c:type:`PyMethodDef` structures. Each entry in the table is an instance of this structure:: typedef struct PyMethodDef { @@ -1192,9 +1192,9 @@ of *NULL* is required. Type-specific Attribute Management ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -For simplicity, only the :ctype:`char\*` version will be demonstrated here; the -type of the name parameter is the only difference between the :ctype:`char\*` -and :ctype:`PyObject\*` flavors of the interface. This example effectively does +For simplicity, only the :c:type:`char\*` version will be demonstrated here; the +type of the name parameter is the only difference between the :c:type:`char\*` +and :c:type:`PyObject\*` flavors of the interface. This example effectively does the same thing as the generic example above, but does not use the generic support added in Python 2.2. It explains how the handler functions are called, so that if you do need to extend their functionality, you'll understand @@ -1242,8 +1242,8 @@ Object Comparison The :attr:`tp_richcompare` handler is called when comparisons are needed. It is analogous to the :ref:`rich comparison methods <richcmpfuncs>`, like -:meth:`__lt__`, and also called by :cfunc:`PyObject_RichCompare` and -:cfunc:`PyObject_RichCompareBool`. +:meth:`__lt__`, and also called by :c:func:`PyObject_RichCompare` and +:c:func:`PyObject_RichCompareBool`. This function is called with two Python objects and the operator as arguments, where the operator is one of ``Py_EQ``, ``Py_NE``, ``Py_LE``, ``Py_GT``, @@ -1306,8 +1306,8 @@ to indicate the presence of a slot, but a slot may still be unfilled.) :: If you wish your object to be able to act like a number, a sequence, or a mapping object, then you place the address of a structure that implements the C -type :ctype:`PyNumberMethods`, :ctype:`PySequenceMethods`, or -:ctype:`PyMappingMethods`, respectively. It is up to you to fill in this +type :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, or +:c:type:`PyMappingMethods`, respectively. It is up to you to fill in this structure with appropriate values. You can find examples of the use of each of these in the :file:`Objects` directory of the Python source distribution. :: @@ -1339,11 +1339,11 @@ This function takes three arguments: the call is ``obj1('hello')``, then *arg1* is ``obj1``. #. *arg2* is a tuple containing the arguments to the call. You can use - :cfunc:`PyArg_ParseTuple` to extract the arguments. + :c:func:`PyArg_ParseTuple` to extract the arguments. #. *arg3* is a dictionary of keyword arguments that were passed. If this is non-*NULL* and you support keyword arguments, use - :cfunc:`PyArg_ParseTupleAndKeywords` to extract the arguments. If you do not + :c:func:`PyArg_ParseTupleAndKeywords` to extract the arguments. If you do not want to support keyword arguments and this is non-*NULL*, raise a :exc:`TypeError` with a message saying that keyword arguments are not supported. @@ -1417,7 +1417,7 @@ to participate in the weak reference mechanism without incurring the overhead on those objects which do not benefit by weak referencing (such as numbers). For an object to be weakly referencable, the extension must include a -:ctype:`PyObject\*` field in the instance structure for the use of the weak +:c:type:`PyObject\*` field in the instance structure for the use of the weak reference mechanism; it must be initialized to *NULL* by the object's constructor. It must also set the :attr:`tp_weaklistoffset` field of the corresponding type object to the offset of the field. For example, the instance @@ -1493,7 +1493,7 @@ the function you want (for example, ``tp_richcompare``). You will find examples of the function you want to implement. When you need to verify that an object is an instance of the type you are -implementing, use the :cfunc:`PyObject_TypeCheck` function. A sample of its use +implementing, use the :c:func:`PyObject_TypeCheck` function. A sample of its use might be something like the following:: if (! PyObject_TypeCheck(some_object, &MyType)) { diff --git a/Doc/extending/windows.rst b/Doc/extending/windows.rst index 6733666..66912af 100644 --- a/Doc/extending/windows.rst +++ b/Doc/extending/windows.rst @@ -98,8 +98,8 @@ described here are distributed with the Python sources in the it. Copy your C sources into it. Note that the module source file name does not necessarily have to match the module name, but the name of the initialization function should match the module name --- you can only import a - module :mod:`spam` if its initialization function is called :cfunc:`initspam`, - and it should call :cfunc:`Py_InitModule` with the string ``"spam"`` as its + module :mod:`spam` if its initialization function is called :c:func:`initspam`, + and it should call :c:func:`Py_InitModule` with the string ``"spam"`` as its first argument (use the minimal :file:`example.c` in this directory as a guide). By convention, it lives in a file called :file:`spam.c` or :file:`spammodule.c`. The output file should be called :file:`spam.pyd` (in Release mode) or @@ -259,7 +259,7 @@ use these commands:: The first command created three files: :file:`spam.obj`, :file:`spam.dll` and :file:`spam.lib`. :file:`Spam.dll` does not contain any Python functions (such -as :cfunc:`PyArg_ParseTuple`), but it does know how to find the Python code +as :c:func:`PyArg_ParseTuple`), but it does know how to find the Python code thanks to :file:`pythonXY.lib`. The second command created :file:`ni.dll` (and :file:`.obj` and :file:`.lib`), diff --git a/Doc/faq/extending.rst b/Doc/faq/extending.rst index 737ef7c..59e5422 100644 --- a/Doc/faq/extending.rst +++ b/Doc/faq/extending.rst @@ -63,41 +63,41 @@ C++ libraries. How can I execute arbitrary Python statements from C? ----------------------------------------------------- -The highest-level function to do this is :cfunc:`PyRun_SimpleString` which takes +The highest-level function to do this is :c:func:`PyRun_SimpleString` which takes a single string argument to be executed in the context of the module ``__main__`` and returns 0 for success and -1 when an exception occurred (including ``SyntaxError``). If you want more control, use -:cfunc:`PyRun_String`; see the source for :cfunc:`PyRun_SimpleString` in +:c:func:`PyRun_String`; see the source for :c:func:`PyRun_SimpleString` in ``Python/pythonrun.c``. How can I evaluate an arbitrary Python expression from C? --------------------------------------------------------- -Call the function :cfunc:`PyRun_String` from the previous question with the -start symbol :cdata:`Py_eval_input`; it parses an expression, evaluates it and +Call the function :c:func:`PyRun_String` from the previous question with the +start symbol :c:data:`Py_eval_input`; it parses an expression, evaluates it and returns its value. How do I extract C values from a Python object? ----------------------------------------------- -That depends on the object's type. If it's a tuple, :cfunc:`PyTuple_Size` -returns its length and :cfunc:`PyTuple_GetItem` returns the item at a specified -index. Lists have similar functions, :cfunc:`PyListSize` and -:cfunc:`PyList_GetItem`. +That depends on the object's type. If it's a tuple, :c:func:`PyTuple_Size` +returns its length and :c:func:`PyTuple_GetItem` returns the item at a specified +index. Lists have similar functions, :c:func:`PyListSize` and +:c:func:`PyList_GetItem`. -For strings, :cfunc:`PyString_Size` returns its length and -:cfunc:`PyString_AsString` a pointer to its value. Note that Python strings may -contain null bytes so C's :cfunc:`strlen` should not be used. +For strings, :c:func:`PyString_Size` returns its length and +:c:func:`PyString_AsString` a pointer to its value. Note that Python strings may +contain null bytes so C's :c:func:`strlen` should not be used. To test the type of an object, first make sure it isn't *NULL*, and then use -:cfunc:`PyString_Check`, :cfunc:`PyTuple_Check`, :cfunc:`PyList_Check`, etc. +:c:func:`PyString_Check`, :c:func:`PyTuple_Check`, :c:func:`PyList_Check`, etc. There is also a high-level API to Python objects which is provided by the so-called 'abstract' interface -- read ``Include/abstract.h`` for further details. It allows interfacing with any kind of Python sequence using calls -like :cfunc:`PySequence_Length`, :cfunc:`PySequence_GetItem`, etc.) as well as +like :c:func:`PySequence_Length`, :c:func:`PySequence_GetItem`, etc.) as well as many other useful protocols. @@ -106,7 +106,7 @@ How do I use Py_BuildValue() to create a tuple of arbitrary length? You can't. Use ``t = PyTuple_New(n)`` instead, and fill it with objects using ``PyTuple_SetItem(t, i, o)`` -- note that this "eats" a reference count of -``o``, so you have to :cfunc:`Py_INCREF` it. Lists have similar functions +``o``, so you have to :c:func:`Py_INCREF` it. Lists have similar functions ``PyList_New(n)`` and ``PyList_SetItem(l, i, o)``. Note that you *must* set all the tuple items to some value before you pass the tuple to Python code -- ``PyTuple_New(n)`` initializes them to NULL, which isn't a valid Python value. @@ -115,9 +115,9 @@ the tuple items to some value before you pass the tuple to Python code -- How do I call an object's method from C? ---------------------------------------- -The :cfunc:`PyObject_CallMethod` function can be used to call an arbitrary +The :c:func:`PyObject_CallMethod` function can be used to call an arbitrary method of an object. The parameters are the object, the name of the method to -call, a format string like that used with :cfunc:`Py_BuildValue`, and the +call, a format string like that used with :c:func:`Py_BuildValue`, and the argument values:: PyObject * @@ -125,7 +125,7 @@ argument values:: char *arg_format, ...); This works for any object that has methods -- whether built-in or user-defined. -You are responsible for eventually :cfunc:`Py_DECREF`\ 'ing the return value. +You are responsible for eventually :c:func:`Py_DECREF`\ 'ing the return value. To call, e.g., a file object's "seek" method with arguments 10, 0 (assuming the file object pointer is "f"):: @@ -138,7 +138,7 @@ file object pointer is "f"):: Py_DECREF(res); } -Note that since :cfunc:`PyObject_CallObject` *always* wants a tuple for the +Note that since :c:func:`PyObject_CallObject` *always* wants a tuple for the argument list, to call a function without arguments, pass "()" for the format, and to call a function with one argument, surround the argument in parentheses, e.g. "(i)". @@ -189,7 +189,7 @@ module) as follows:: attr = PyObject_GetAttrString(module, "<attrname>"); -Calling :cfunc:`PyObject_SetAttrString` to assign to variables in the module +Calling :c:func:`PyObject_SetAttrString` to assign to variables in the module also works. @@ -270,16 +270,16 @@ the input is invalid. In Python you can use the :mod:`codeop` module, which approximates the parser's behavior sufficiently. IDLE uses this, for example. -The easiest way to do it in C is to call :cfunc:`PyRun_InteractiveLoop` (perhaps +The easiest way to do it in C is to call :c:func:`PyRun_InteractiveLoop` (perhaps in a separate thread) and let the Python interpreter handle the input for -you. You can also set the :cfunc:`PyOS_ReadlineFunctionPointer` to point at your +you. You can also set the :c:func:`PyOS_ReadlineFunctionPointer` to point at your custom input function. See ``Modules/readline.c`` and ``Parser/myreadline.c`` for more hints. However sometimes you have to run the embedded Python interpreter in the same thread as your rest application and you can't allow the -:cfunc:`PyRun_InteractiveLoop` to stop while waiting for user input. The one -solution then is to call :cfunc:`PyParser_ParseString` and test for ``e.error`` +:c:func:`PyRun_InteractiveLoop` to stop while waiting for user input. The one +solution then is to call :c:func:`PyParser_ParseString` and test for ``e.error`` equal to ``E_EOF``, which means the input is incomplete). Here's a sample code fragment, untested, inspired by code from Alex Farber:: @@ -310,8 +310,8 @@ fragment, untested, inspired by code from Alex Farber:: } Another solution is trying to compile the received string with -:cfunc:`Py_CompileString`. If it compiles without errors, try to execute the -returned code object by calling :cfunc:`PyEval_EvalCode`. Otherwise save the +:c:func:`Py_CompileString`. If it compiles without errors, try to execute the +returned code object by calling :c:func:`PyEval_EvalCode`. Otherwise save the input for later. If the compilation fails, find out if it's an error or just more input is required - by extracting the message string from the exception tuple and comparing it to the string "unexpected EOF while parsing". Here is a @@ -463,8 +463,8 @@ This can easily occur when using pre-built extension packages. RedHat Linux 7.x, in particular, provided a "python2" binary that is compiled with 4-byte Unicode. This only causes the link failure if the extension uses any of the ``PyUnicode_*()`` functions. It is also a problem if an extension uses any of -the Unicode-related format specifiers for :cfunc:`Py_BuildValue` (or similar) or -parameter specifications for :cfunc:`PyArg_ParseTuple`. +the Unicode-related format specifiers for :c:func:`Py_BuildValue` (or similar) or +parameter specifications for :c:func:`PyArg_ParseTuple`. You can check the size of the Unicode character a Python interpreter is using by checking the value of sys.maxunicode: diff --git a/Doc/faq/gui.rst b/Doc/faq/gui.rst index fd6ca0c..dbb3f02 100644 --- a/Doc/faq/gui.rst +++ b/Doc/faq/gui.rst @@ -123,7 +123,7 @@ SAM (stand-alone modules), which is part of the Tix distribution (http://tix.sourceforge.net/). Build Tix with SAM enabled, perform the appropriate call to -:cfunc:`Tclsam_init`, etc. inside Python's +:c:func:`Tclsam_init`, etc. inside Python's :file:`Modules/tkappinit.c`, and link with libtclsam and libtksam (you might include the Tix libraries as well). @@ -132,7 +132,7 @@ Can I have Tk events handled while waiting for I/O? --------------------------------------------------- Yes, and you don't even need threads! But you'll have to restructure your I/O -code a bit. Tk has the equivalent of Xt's :cfunc:`XtAddInput()` call, which allows you +code a bit. Tk has the equivalent of Xt's :c:func:`XtAddInput()` call, which allows you to register a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. Here's what you need:: diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst index dff6074..fdfd9ec 100644 --- a/Doc/faq/programming.rst +++ b/Doc/faq/programming.rst @@ -989,7 +989,7 @@ and then convert decimal strings to numeric values using :func:`int` or if the line uses something other than whitespace as a separator. For more complicated input parsing, regular expressions are more powerful -than C's :cfunc:`sscanf` and better suited for the task. +than C's :c:func:`sscanf` and better suited for the task. What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean? diff --git a/Doc/faq/windows.rst b/Doc/faq/windows.rst index bfd03f7..6266d10 100644 --- a/Doc/faq/windows.rst +++ b/Doc/faq/windows.rst @@ -541,7 +541,7 @@ assumed by the Python interpreter it won't work. The Python 1.5.* DLLs (``python15.dll``) are all compiled with MS VC++ 5.0 and with multithreading-DLL options (``/MD``). -If you can't change compilers or flags, try using :cfunc:`Py_RunSimpleString`. +If you can't change compilers or flags, try using :c:func:`Py_RunSimpleString`. A trick to get it to run an arbitrary file is to construct a call to :func:`execfile` with the name of your file as argument. diff --git a/Doc/howto/cporting.rst b/Doc/howto/cporting.rst index 9f22bd1e..06b9189 100644 --- a/Doc/howto/cporting.rst +++ b/Doc/howto/cporting.rst @@ -22,7 +22,7 @@ Conditional compilation ======================= The easiest way to compile only some code for 3.0 is to check if -:cmacro:`PY_MAJOR_VERSION` is greater than or equal to 3. :: +:c:macro:`PY_MAJOR_VERSION` is greater than or equal to 3. :: #if PY_MAJOR_VERSION >= 3 #define IS_PY3K @@ -47,12 +47,12 @@ Python 3.0's :func:`str` (``PyString_*`` functions in C) type is equivalent to 2.x's :func:`unicode` (``PyUnicode_*``). The old 8-bit string type has become :func:`bytes`. Python 2.6 and later provide a compatibility header, :file:`bytesobject.h`, mapping ``PyBytes`` names to ``PyString`` ones. For best -compatibility with 3.0, :ctype:`PyUnicode` should be used for textual data and -:ctype:`PyBytes` for binary data. It's also important to remember that -:ctype:`PyBytes` and :ctype:`PyUnicode` in 3.0 are not interchangeable like -:ctype:`PyString` and :ctype:`PyString` are in 2.x. The following example shows -best practices with regards to :ctype:`PyUnicode`, :ctype:`PyString`, and -:ctype:`PyBytes`. :: +c:ompatibility with 3.0, :c:type:`PyUnicode` should be used for textual data and +:c:type:`PyBytes` for binary data. It's also important to remember that +:c:type:`PyBytes` and :c:type:`PyUnicode` in 3.0 are not interchangeable like +:c:type:`PyString` and :c:type:`PyString` are in 2.x. The following example shows +best practices with regards to :c:type:`PyUnicode`, :c:type:`PyString`, and +:c:type:`PyBytes`. :: #include "stdlib.h" #include "Python.h" diff --git a/Doc/howto/descriptor.rst b/Doc/howto/descriptor.rst index cdb6a8e..81bb8ca 100644 --- a/Doc/howto/descriptor.rst +++ b/Doc/howto/descriptor.rst @@ -97,7 +97,7 @@ transforms ``b.x`` into ``type(b).__dict__['x'].__get__(b, type(b))``. The implementation works through a precedence chain that gives data descriptors priority over instance variables, instance variables priority over non-data descriptors, and assigns lowest priority to :meth:`__getattr__` if provided. The -full C implementation can be found in :cfunc:`PyObject_GenericGetAttr()` in +full C implementation can be found in :c:func:`PyObject_GenericGetAttr()` in `Objects/object.c <http://svn.python.org/view/python/trunk/Objects/object.c?view=markup>`_\. For classes, the machinery is in :meth:`type.__getattribute__` which transforms @@ -131,7 +131,7 @@ search using :meth:`object.__getattribute__`. Note, in Python 2.2, ``super(B, obj).m()`` would only invoke :meth:`__get__` if ``m`` was a data descriptor. In Python 2.3, non-data descriptors also get invoked unless an old-style class is involved. The implementation details are -in :cfunc:`super_getattro()` in +in :c:func:`super_getattro()` in `Objects/typeobject.c <http://svn.python.org/view/python/trunk/Objects/typeobject.c?view=markup>`_ and a pure Python equivalent can be found in `Guido's Tutorial`_. @@ -297,7 +297,7 @@ Running the interpreter shows how the function descriptor works in practice:: The output suggests that bound and unbound methods are two different types. While they could have been implemented that way, the actual C implementation of -:ctype:`PyMethod_Type` in +:c:type:`PyMethod_Type` in `Objects/classobject.c <http://svn.python.org/view/python/trunk/Objects/classobject.c?view=markup>`_ is a single object with two different representations depending on whether the :attr:`im_self` field is set or is *NULL* (the C equivalent of *None*). diff --git a/Doc/library/array.rst b/Doc/library/array.rst index e4975c8..40655a5 100644 --- a/Doc/library/array.rst +++ b/Doc/library/array.rst @@ -103,7 +103,7 @@ The following data items and methods are also supported: memory buffer in bytes can be computed as ``array.buffer_info()[1] * array.itemsize``. This is occasionally useful when working with low-level (and inherently unsafe) I/O interfaces that require memory addresses, such as certain - :cfunc:`ioctl` operations. The returned numbers are valid as long as the array + :c:func:`ioctl` operations. The returned numbers are valid as long as the array exists and no length-changing operations are applied to it. .. note:: diff --git a/Doc/library/asynchat.rst b/Doc/library/asynchat.rst index 3b8eb12..26d3290 100644 --- a/Doc/library/asynchat.rst +++ b/Doc/library/asynchat.rst @@ -31,7 +31,7 @@ connection requests. Like :class:`asyncore.dispatcher`, :class:`async_chat` defines a set of events that are generated by an analysis of socket conditions after a - :cfunc:`select` call. Once the polling loop has been started the + :c:func:`select` call. Once the polling loop has been started the :class:`async_chat` object's methods are called by the event-processing framework with no action on the part of the programmer. diff --git a/Doc/library/asyncore.rst b/Doc/library/asyncore.rst index cdfdb7a..8e6c243 100644 --- a/Doc/library/asyncore.rst +++ b/Doc/library/asyncore.rst @@ -22,7 +22,7 @@ bound. If your program is processor bound, then pre-emptive scheduled threads are probably what you really need. Network servers are rarely processor bound, however. -If your operating system supports the :cfunc:`select` system call in its I/O +If your operating system supports the :c:func:`select` system call in its I/O library (and nearly all do), then you can use it to juggle multiple communication channels at once; doing other work while your I/O is taking place in the "background." Although this strategy can seem strange and @@ -92,8 +92,8 @@ any that have been added to the map during asynchronous service) is closed. During asynchronous processing, each mapped channel's :meth:`readable` and :meth:`writable` methods are used to determine whether the channel's socket - should be added to the list of channels :cfunc:`select`\ ed or - :cfunc:`poll`\ ed for read and write events. + should be added to the list of channels :c:func:`select`\ ed or + :c:func:`poll`\ ed for read and write events. Thus, the set of channel events is larger than the basic socket events. The full set of methods that can be overridden in your subclass follows: @@ -250,9 +250,9 @@ any that have been added to the map during asynchronous service) is closed. .. class:: file_dispatcher() A file_dispatcher takes a file descriptor or :term:`file object` along - with an optional map argument and wraps it for use with the :cfunc:`poll` - or :cfunc:`loop` functions. If provided a file object or anything with a - :cfunc:`fileno` method, that method will be called and passed to the + with an optional map argument and wraps it for use with the :c:func:`poll` + or :c:func:`loop` functions. If provided a file object or anything with a + :c:func:`fileno` method, that method will be called and passed to the :class:`file_wrapper` constructor. Availability: UNIX. .. class:: file_wrapper() diff --git a/Doc/library/codecs.rst b/Doc/library/codecs.rst index e734fee..1971136 100644 --- a/Doc/library/codecs.rst +++ b/Doc/library/codecs.rst @@ -787,9 +787,9 @@ Encodings and Unicode --------------------- Strings are stored internally as sequences of codepoints (to be precise -as :ctype:`Py_UNICODE` arrays). Depending on the way Python is compiled (either +as :c:type:`Py_UNICODE` arrays). Depending on the way Python is compiled (either via :option:`--without-wide-unicode` or :option:`--with-wide-unicode`, with the -former being the default) :ctype:`Py_UNICODE` is either a 16-bit or 32-bit data +former being the default) :c:type:`Py_UNICODE` is either a 16-bit or 32-bit data type. Once a string object is used outside of CPU and memory, CPU endianness and how these arrays are stored as bytes become an issue. Transforming a string object into a sequence of bytes is called encoding and recreating the diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst index 32499d5..a8977f8 100644 --- a/Doc/library/ctypes.rst +++ b/Doc/library/ctypes.rst @@ -38,7 +38,7 @@ You load libraries by accessing them as attributes of these objects. *cdll* loads libraries which export functions using the standard ``cdecl`` calling convention, while *windll* libraries call functions using the ``stdcall`` calling convention. *oledll* also uses the ``stdcall`` calling convention, and -assumes the functions return a Windows :ctype:`HRESULT` error code. The error +assumes the functions return a Windows :c:type:`HRESULT` error code. The error code is used to automatically raise a :class:`WindowsError` exception when the function call fails. @@ -198,9 +198,9 @@ should be careful anyway. ``None``, integers, bytes objects and (unicode) strings are the only native Python objects that can directly be used as parameters in these function calls. ``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed -as pointer to the memory block that contains their data (:ctype:`char *` or -:ctype:`wchar_t *`). Python integers are passed as the platforms default C -:ctype:`int` type, their value is masked to fit into the C type. +as pointer to the memory block that contains their data (:c:type:`char *` or +:c:type:`wchar_t *`). Python integers are passed as the platforms default C +:c:type:`int` type, their value is masked to fit into the C type. Before we move on calling functions with other parameter types, we have to learn more about :mod:`ctypes` data types. @@ -213,46 +213,46 @@ Fundamental data types :mod:`ctypes` defines a number of primitive C compatible data types : -+----------------------+----------------------------------------+----------------------------+ -| ctypes type | C type | Python type | -+======================+========================================+============================+ -| :class:`c_char` | :ctype:`char` | 1-character bytes object | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_wchar` | :ctype:`wchar_t` | 1-character string | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_byte` | :ctype:`char` | int | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_ubyte` | :ctype:`unsigned char` | int | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_short` | :ctype:`short` | int | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_ushort` | :ctype:`unsigned short` | int | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_int` | :ctype:`int` | int | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_uint` | :ctype:`unsigned int` | int | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_long` | :ctype:`long` | int | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_ulong` | :ctype:`unsigned long` | int | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_longlong` | :ctype:`__int64` or :ctype:`long long` | int | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_ulonglong` | :ctype:`unsigned __int64` or | int | -| | :ctype:`unsigned long long` | | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_float` | :ctype:`float` | float | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_double` | :ctype:`double` | float | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_longdouble`| :ctype:`long double` | float | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_char_p` | :ctype:`char *` (NUL terminated) | bytes object or ``None`` | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_wchar_p` | :ctype:`wchar_t *` (NUL terminated) | string or ``None`` | -+----------------------+----------------------------------------+----------------------------+ -| :class:`c_void_p` | :ctype:`void *` | int or ``None`` | -+----------------------+----------------------------------------+----------------------------+ ++----------------------+------------------------------------------+----------------------------+ +| ctypes type | C type | Python type | ++======================+==========================================+============================+ +| :class:`c_char` | :c:type:`char` | 1-character bytes object | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_wchar` | :c:type:`wchar_t` | 1-character string | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_byte` | :c:type:`char` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_ubyte` | :c:type:`unsigned char` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_short` | :c:type:`short` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_ushort` | :c:type:`unsigned short` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_int` | :c:type:`int` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_uint` | :c:type:`unsigned int` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_long` | :c:type:`long` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_ulong` | :c:type:`unsigned long` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int | +| | :c:type:`unsigned long long` | | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_float` | :c:type:`float` | float | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_double` | :c:type:`double` | float | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_longdouble`| :c:type:`long double` | float | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_char_p` | :c:type:`char *` (NUL terminated) | bytes object or ``None`` | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | string or ``None`` | ++----------------------+------------------------------------------+----------------------------+ +| :class:`c_void_p` | :c:type:`void *` | int or ``None`` | ++----------------------+------------------------------------------+----------------------------+ All these types can be created by calling them with an optional initializer of the correct type and value:: @@ -320,7 +320,7 @@ property:: The :func:`create_string_buffer` function replaces the :func:`c_buffer` function (which is still available as an alias), as well as the :func:`c_string` function from earlier ctypes releases. To create a mutable memory block containing -unicode characters of the C type :ctype:`wchar_t` use the +unicode characters of the C type :c:type:`wchar_t` use the :func:`create_unicode_buffer` function. @@ -431,7 +431,7 @@ integer, string, bytes, a :mod:`ctypes` instance, or an object with an Return types ^^^^^^^^^^^^ -By default functions are assumed to return the C :ctype:`int` type. Other +By default functions are assumed to return the C :c:type:`int` type. Other return types can be specified by setting the :attr:`restype` attribute of the function object. @@ -930,8 +930,8 @@ argument, and the callback functions expected argument types as the remaining arguments. I will present an example here which uses the standard C library's -:cfunc:`qsort` function, this is used to sort items with the help of a callback -function. :cfunc:`qsort` will be used to sort an array of integers:: +:c:func:`qsort` function, this is used to sort items with the help of a callback +function. :c:func:`qsort` will be used to sort an array of integers:: >>> IntArray5 = c_int * 5 >>> ia = IntArray5(5, 1, 7, 33, 99) @@ -1072,7 +1072,7 @@ Accessing values exported from dlls ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Some shared libraries not only export functions, they also export variables. An -example in the Python library itself is the :cdata:`Py_OptimizeFlag`, an integer +example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on startup. @@ -1090,11 +1090,11 @@ have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been specified. An extended example which also demonstrates the use of pointers accesses the -:cdata:`PyImport_FrozenModules` pointer exported by Python. +:c:data:`PyImport_FrozenModules` pointer exported by Python. Quoting the docs for that value: - This pointer is initialized to point to an array of :ctype:`struct _frozen` + This pointer is initialized to point to an array of :c:type:`struct _frozen` records, terminated by one whose members are all *NULL* or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules. @@ -1111,7 +1111,7 @@ size, we show only how this table can be read with :mod:`ctypes`:: ... >>> -We have defined the :ctype:`struct _frozen` data type, so we can get the pointer +We have defined the :c:type:`struct _frozen` data type, so we can get the pointer to the table:: >>> FrozenTable = POINTER(struct_frozen) @@ -1330,7 +1330,7 @@ way is to instantiate one of the following classes: Instances of this class represent loaded shared libraries. Functions in these libraries use the standard C calling convention, and are assumed to return - :ctype:`int`. + :c:type:`int`. .. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False) @@ -1347,7 +1347,7 @@ way is to instantiate one of the following classes: Windows only: Instances of this class represent loaded shared libraries, functions in these libraries use the ``stdcall`` calling convention, and are - assumed to return :ctype:`int` by default. + assumed to return :c:type:`int` by default. On Windows CE only the standard calling convention is used, for convenience the :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this @@ -1488,7 +1488,7 @@ object is available: An instance of :class:`PyDLL` that exposes Python C API functions as attributes. Note that all these functions are assumed to return C - :ctype:`int`, which is of course not always the truth, so you have to assign + :c:type:`int`, which is of course not always the truth, so you have to assign the correct :attr:`restype` attribute to use these functions. @@ -1517,10 +1517,10 @@ They are instances of a private class: .. attribute:: restype Assign a ctypes type to specify the result type of the foreign function. - Use ``None`` for :ctype:`void`, a function not returning anything. + Use ``None`` for :c:type:`void`, a function not returning anything. It is possible to assign a callable Python object that is not a ctypes - type, in this case the function is assumed to return a C :ctype:`int`, and + type, in this case the function is assumed to return a C :c:type:`int`, and the callable will be called with this integer, allowing to do further processing or error checking. Using this is deprecated, for more flexible post processing or error checking use a ctypes data type as @@ -2115,21 +2115,21 @@ These are the fundamental ctypes data types: .. class:: c_byte - Represents the C :ctype:`signed char` datatype, and interprets the value as + Represents the C :c:type:`signed char` datatype, and interprets the value as small integer. The constructor accepts an optional integer initializer; no overflow checking is done. .. class:: c_char - Represents the C :ctype:`char` datatype, and interprets the value as a single + Represents the C :c:type:`char` datatype, and interprets the value as a single character. The constructor accepts an optional string initializer, the length of the string must be exactly one character. .. class:: c_char_p - Represents the C :ctype:`char *` datatype when it points to a zero-terminated + Represents the C :c:type:`char *` datatype when it points to a zero-terminated string. For a general character pointer that may also point to binary data, ``POINTER(c_char)`` must be used. The constructor accepts an integer address, or a bytes object. @@ -2137,180 +2137,180 @@ These are the fundamental ctypes data types: .. class:: c_double - Represents the C :ctype:`double` datatype. The constructor accepts an + Represents the C :c:type:`double` datatype. The constructor accepts an optional float initializer. .. class:: c_longdouble - Represents the C :ctype:`long double` datatype. The constructor accepts an + Represents the C :c:type:`long double` datatype. The constructor accepts an optional float initializer. On platforms where ``sizeof(long double) == sizeof(double)`` it is an alias to :class:`c_double`. .. class:: c_float - Represents the C :ctype:`float` datatype. The constructor accepts an + Represents the C :c:type:`float` datatype. The constructor accepts an optional float initializer. .. class:: c_int - Represents the C :ctype:`signed int` datatype. The constructor accepts an + Represents the C :c:type:`signed int` datatype. The constructor accepts an optional integer initializer; no overflow checking is done. On platforms where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`. .. class:: c_int8 - Represents the C 8-bit :ctype:`signed int` datatype. Usually an alias for + Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for :class:`c_byte`. .. class:: c_int16 - Represents the C 16-bit :ctype:`signed int` datatype. Usually an alias for + Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for :class:`c_short`. .. class:: c_int32 - Represents the C 32-bit :ctype:`signed int` datatype. Usually an alias for + Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for :class:`c_int`. .. class:: c_int64 - Represents the C 64-bit :ctype:`signed int` datatype. Usually an alias for + Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for :class:`c_longlong`. .. class:: c_long - Represents the C :ctype:`signed long` datatype. The constructor accepts an + Represents the C :c:type:`signed long` datatype. The constructor accepts an optional integer initializer; no overflow checking is done. .. class:: c_longlong - Represents the C :ctype:`signed long long` datatype. The constructor accepts + Represents the C :c:type:`signed long long` datatype. The constructor accepts an optional integer initializer; no overflow checking is done. .. class:: c_short - Represents the C :ctype:`signed short` datatype. The constructor accepts an + Represents the C :c:type:`signed short` datatype. The constructor accepts an optional integer initializer; no overflow checking is done. .. class:: c_size_t - Represents the C :ctype:`size_t` datatype. + Represents the C :c:type:`size_t` datatype. .. class:: c_ssize_t - Represents the C :ctype:`ssize_t` datatype. + Represents the C :c:type:`ssize_t` datatype. .. versionadded:: 3.2 .. class:: c_ubyte - Represents the C :ctype:`unsigned char` datatype, it interprets the value as + Represents the C :c:type:`unsigned char` datatype, it interprets the value as small integer. The constructor accepts an optional integer initializer; no overflow checking is done. .. class:: c_uint - Represents the C :ctype:`unsigned int` datatype. The constructor accepts an + Represents the C :c:type:`unsigned int` datatype. The constructor accepts an optional integer initializer; no overflow checking is done. On platforms where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`. .. class:: c_uint8 - Represents the C 8-bit :ctype:`unsigned int` datatype. Usually an alias for + Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for :class:`c_ubyte`. .. class:: c_uint16 - Represents the C 16-bit :ctype:`unsigned int` datatype. Usually an alias for + Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for :class:`c_ushort`. .. class:: c_uint32 - Represents the C 32-bit :ctype:`unsigned int` datatype. Usually an alias for + Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for :class:`c_uint`. .. class:: c_uint64 - Represents the C 64-bit :ctype:`unsigned int` datatype. Usually an alias for + Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for :class:`c_ulonglong`. .. class:: c_ulong - Represents the C :ctype:`unsigned long` datatype. The constructor accepts an + Represents the C :c:type:`unsigned long` datatype. The constructor accepts an optional integer initializer; no overflow checking is done. .. class:: c_ulonglong - Represents the C :ctype:`unsigned long long` datatype. The constructor + Represents the C :c:type:`unsigned long long` datatype. The constructor accepts an optional integer initializer; no overflow checking is done. .. class:: c_ushort - Represents the C :ctype:`unsigned short` datatype. The constructor accepts + Represents the C :c:type:`unsigned short` datatype. The constructor accepts an optional integer initializer; no overflow checking is done. .. class:: c_void_p - Represents the C :ctype:`void *` type. The value is represented as integer. + Represents the C :c:type:`void *` type. The value is represented as integer. The constructor accepts an optional integer initializer. .. class:: c_wchar - Represents the C :ctype:`wchar_t` datatype, and interprets the value as a + Represents the C :c:type:`wchar_t` datatype, and interprets the value as a single character unicode string. The constructor accepts an optional string initializer, the length of the string must be exactly one character. .. class:: c_wchar_p - Represents the C :ctype:`wchar_t *` datatype, which must be a pointer to a + Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a zero-terminated wide character string. The constructor accepts an integer address, or a string. .. class:: c_bool - Represent the C :ctype:`bool` datatype (more accurately, :ctype:`_Bool` from + Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from C99). Its value can be True or False, and the constructor accepts any object that has a truth value. .. class:: HRESULT - Windows only: Represents a :ctype:`HRESULT` value, which contains success or + Windows only: Represents a :c:type:`HRESULT` value, which contains success or error information for a function or method call. .. class:: py_object - Represents the C :ctype:`PyObject *` datatype. Calling this without an - argument creates a ``NULL`` :ctype:`PyObject *` pointer. + Represents the C :c:type:`PyObject *` datatype. Calling this without an + argument creates a ``NULL`` :c:type:`PyObject *` pointer. The :mod:`ctypes.wintypes` module provides quite some other Windows specific -data types, for example :ctype:`HWND`, :ctype:`WPARAM`, or :ctype:`DWORD`. Some -useful structures like :ctype:`MSG` or :ctype:`RECT` are also defined. +data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some +useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined. .. _ctypes-structured-data-types: diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst index 197aad2..714286f 100644 --- a/Doc/library/datetime.rst +++ b/Doc/library/datetime.rst @@ -396,7 +396,7 @@ Other constructors, all class methods: Return the local date corresponding to the POSIX timestamp, such as is returned by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out - of the range of values supported by the platform C :cfunc:`localtime` function. + of the range of values supported by the platform C :c:func:`localtime` function. It's common for this to be restricted to years from 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`. @@ -570,7 +570,7 @@ Instance methods: Return a string representing the date, for example ``date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C - :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which + :c:func:`ctime` function (which :func:`time.ctime` invokes, but which :meth:`date.ctime` does not invoke) conforms to the C standard. @@ -677,7 +677,7 @@ Other constructors, all class methods: or not specified, this is like :meth:`today`, but, if possible, supplies more precision than can be gotten from going through a :func:`time.time` timestamp (for example, this may be possible on platforms supplying the C - :cfunc:`gettimeofday` function). + :c:func:`gettimeofday` function). Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the current date and time are converted to *tz*'s time zone. In this case the @@ -705,8 +705,8 @@ Other constructors, all class methods: ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``. :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of - the range of values supported by the platform C :cfunc:`localtime` or - :cfunc:`gmtime` functions. It's common for this to be restricted to years in + the range of values supported by the platform C :c:func:`localtime` or + :c:func:`gmtime` functions. It's common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`, and then it's possible to have two timestamps differing by a second that yield @@ -717,7 +717,7 @@ Other constructors, all class methods: Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is - out of the range of values supported by the platform C :cfunc:`gmtime` function. + out of the range of values supported by the platform C :c:func:`gmtime` function. It's common for this to be restricted to years in 1970 through 2038. See also :meth:`fromtimestamp`. @@ -1056,7 +1056,7 @@ Instance methods: Return a string representing the date and time, for example ``datetime(2002, 12, 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the - native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which + native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which :meth:`datetime.ctime` does not invoke) conforms to the C standard. diff --git a/Doc/library/exceptions.rst b/Doc/library/exceptions.rst index a4e2e0e..49b5b93 100644 --- a/Doc/library/exceptions.rst +++ b/Doc/library/exceptions.rst @@ -177,7 +177,7 @@ The following exceptions are the exceptions that are usually raised. Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the - underlying memory management architecture (C's :cfunc:`malloc` function), the + underlying memory management architecture (C's :c:func:`malloc` function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause. @@ -204,8 +204,8 @@ The following exceptions are the exceptions that are usually raised. This exception is derived from :exc:`EnvironmentError`. It is raised when a function returns a system-related error (not for illegal argument types or other incidental errors). The :attr:`errno` attribute is a numeric error - code from :cdata:`errno`, and the :attr:`strerror` attribute is the - corresponding string, as would be printed by the C function :cfunc:`perror`. + code from :c:data:`errno`, and the :attr:`strerror` attribute is the + corresponding string, as would be printed by the C function :c:func:`perror`. See the module :mod:`errno`, which contains names for the error codes defined by the underlying operating system. @@ -275,7 +275,7 @@ The following exceptions are the exceptions that are usually raised. This exception is raised by the :func:`sys.exit` function. When it is not handled, the Python interpreter exits; no stack traceback is printed. If the associated value is an integer, it specifies the system exit status (passed - to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; + to C's :c:func:`exit` function); if it is ``None``, the exit status is zero; if it has another type (such as a string), the object's value is printed and the exit status is one. @@ -348,9 +348,9 @@ The following exceptions are the exceptions that are usually raised. .. exception:: WindowsError Raised when a Windows-specific error occurs or when the error number does not - correspond to an :cdata:`errno` value. The :attr:`winerror` and + correspond to an :c:data:`errno` value. The :attr:`winerror` and :attr:`strerror` values are created from the return values of the - :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows + :c:func:`GetLastError` and :c:func:`FormatMessage` functions from the Windows Platform API. The :attr:`errno` value maps the :attr:`winerror` value to corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`. diff --git a/Doc/library/fcntl.rst b/Doc/library/fcntl.rst index dd76d65..6192400 100644 --- a/Doc/library/fcntl.rst +++ b/Doc/library/fcntl.rst @@ -12,7 +12,7 @@ pair: UNIX; I/O control This module performs file control and I/O control on file descriptors. It is an -interface to the :cfunc:`fcntl` and :cfunc:`ioctl` Unix routines. +interface to the :c:func:`fcntl` and :c:func:`ioctl` Unix routines. All functions in this module take a file descriptor *fd* as their first argument. This can be an integer file descriptor, such as returned by @@ -30,17 +30,17 @@ The module defines the following functions: :mod:`fcntl` module. The argument *arg* is optional, and defaults to the integer value ``0``. When present, it can either be an integer value, or a string. With the argument missing or an integer value, the return value of this function - is the integer return value of the C :cfunc:`fcntl` call. When the argument is + is the integer return value of the C :c:func:`fcntl` call. When the argument is a string it represents a binary structure, e.g. created by :func:`struct.pack`. The binary data is copied to a buffer whose address is passed to the C - :cfunc:`fcntl` call. The return value after a successful call is the contents + :c:func:`fcntl` call. The return value after a successful call is the contents of the buffer, converted to a string object. The length of the returned string will be the same as the length of the *arg* argument. This is limited to 1024 bytes. If the information returned in the buffer by the operating system is larger than 1024 bytes, this is most likely to result in a segmentation violation or a more subtle data corruption. - If the :cfunc:`fcntl` fails, an :exc:`IOError` is raised. + If the :c:func:`fcntl` fails, an :exc:`IOError` is raised. .. function:: ioctl(fd, op[, arg[, mutate_flag]]) @@ -91,7 +91,7 @@ The module defines the following functions: Perform the lock operation *op* on file descriptor *fd* (file objects providing a :meth:`fileno` method are accepted as well). See the Unix manual :manpage:`flock(2)` for details. (On some systems, this function is emulated - using :cfunc:`fcntl`.) + using :c:func:`fcntl`.) .. function:: lockf(fd, operation, [length, [start, [whence]]]) diff --git a/Doc/library/getopt.rst b/Doc/library/getopt.rst index f969d7e..b80af01 100644 --- a/Doc/library/getopt.rst +++ b/Doc/library/getopt.rst @@ -7,13 +7,13 @@ .. note:: The :mod:`getopt` module is a parser for command line options whose API is - designed to be familiar to users of the C :cfunc:`getopt` function. Users who - are unfamiliar with the C :cfunc:`getopt` function or who would like to write + designed to be familiar to users of the C :c:func:`getopt` function. Users who + are unfamiliar with the C :c:func:`getopt` function or who would like to write less code and get better help and error messages should consider using the :mod:`argparse` module instead. This module helps scripts to parse the command line arguments in ``sys.argv``. -It supports the same conventions as the Unix :cfunc:`getopt` function (including +It supports the same conventions as the Unix :c:func:`getopt` function (including the special meanings of arguments of the form '``-``' and '``--``'). Long options similar to those supported by GNU software may be used as well via an optional third argument. @@ -31,11 +31,11 @@ exception: be parsed, without the leading reference to the running program. Typically, this means ``sys.argv[1:]``. *shortopts* is the string of option letters that the script wants to recognize, with options that require an argument followed by a - colon (``':'``; i.e., the same format that Unix :cfunc:`getopt` uses). + colon (``':'``; i.e., the same format that Unix :c:func:`getopt` uses). .. note:: - Unlike GNU :cfunc:`getopt`, after a non-option argument, all further + Unlike GNU :c:func:`getopt`, after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work. diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst index 572a401..fe2bc29 100644 --- a/Doc/library/inspect.rst +++ b/Doc/library/inspect.rst @@ -293,7 +293,7 @@ attributes: .. impl-detail:: getsets are attributes defined in extension modules via - :ctype:`PyGetSetDef` structures. For Python implementations without such + :c:type:`PyGetSetDef` structures. For Python implementations without such types, this method will always return ``False``. @@ -304,7 +304,7 @@ attributes: .. impl-detail:: Member descriptors are attributes defined in extension modules via - :ctype:`PyMemberDef` structures. For Python implementations without such + :c:type:`PyMemberDef` structures. For Python implementations without such types, this method will always return ``False``. diff --git a/Doc/library/locale.rst b/Doc/library/locale.rst index b9c001f..c15f7e3 100644 --- a/Doc/library/locale.rst +++ b/Doc/library/locale.rst @@ -215,7 +215,7 @@ The :mod:`locale` module defines the following exception and functions: .. note:: - The expression is in the syntax suitable for the :cfunc:`regex` function + The expression is in the syntax suitable for the :c:func:`regex` function from the C library, which might differ from the syntax used in :mod:`re`. .. data:: NOEXPR @@ -530,7 +530,7 @@ catalogs, and the C library's search algorithms for locating message catalogs. Python applications should normally find no need to invoke these functions, and should use :mod:`gettext` instead. A known exception to this rule are applications that link use additional C libraries which internally invoke -:cfunc:`gettext` or :func:`dcgettext`. For these applications, it may be +:c:func:`gettext` or :func:`dcgettext`. For these applications, it may be necessary to bind the text domain, so that the libraries can properly locate their message catalogs. diff --git a/Doc/library/mailbox.rst b/Doc/library/mailbox.rst index 7409af5..b041d94 100644 --- a/Doc/library/mailbox.rst +++ b/Doc/library/mailbox.rst @@ -452,7 +452,7 @@ Maildir, mbox, MH, Babyl, and MMDF. unlock() Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + :c:func:`flock` and :c:func:`lockf` system calls. .. seealso:: @@ -566,7 +566,7 @@ Maildir, mbox, MH, Babyl, and MMDF. unlock() Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking + :c:func:`flock` and :c:func:`lockf` system calls. For MH mailboxes, locking the mailbox means locking the :file:`.mh_sequences` file and, only for the duration of any operations that affect them, locking individual message files. @@ -664,7 +664,7 @@ Maildir, mbox, MH, Babyl, and MMDF. unlock() Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + :c:func:`flock` and :c:func:`lockf` system calls. .. seealso:: @@ -715,7 +715,7 @@ Maildir, mbox, MH, Babyl, and MMDF. unlock() Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + :c:func:`flock` and :c:func:`lockf` system calls. .. seealso:: diff --git a/Doc/library/msilib.rst b/Doc/library/msilib.rst index 1e6946d..138060d 100644 --- a/Doc/library/msilib.rst +++ b/Doc/library/msilib.rst @@ -42,7 +42,7 @@ structures. .. function:: UuidCreate() Return the string representation of a new unique identifier. This wraps the - Windows API functions :cfunc:`UuidCreate` and :cfunc:`UuidToString`. + Windows API functions :c:func:`UuidCreate` and :c:func:`UuidToString`. .. function:: OpenDatabase(path, persist) @@ -58,7 +58,7 @@ structures. .. function:: CreateRecord(count) - Return a new record object by calling :cfunc:`MSICreateRecord`. *count* is the + Return a new record object by calling :c:func:`MSICreateRecord`. *count* is the number of fields of the record. @@ -133,20 +133,20 @@ Database Objects .. method:: Database.OpenView(sql) - Return a view object, by calling :cfunc:`MSIDatabaseOpenView`. *sql* is the SQL + Return a view object, by calling :c:func:`MSIDatabaseOpenView`. *sql* is the SQL statement to execute. .. method:: Database.Commit() Commit the changes pending in the current transaction, by calling - :cfunc:`MSIDatabaseCommit`. + :c:func:`MSIDatabaseCommit`. .. method:: Database.GetSummaryInformation(count) Return a new summary information object, by calling - :cfunc:`MsiGetSummaryInformation`. *count* is the maximum number of updated + :c:func:`MsiGetSummaryInformation`. *count* is the maximum number of updated values. @@ -164,7 +164,7 @@ View Objects .. method:: View.Execute(params) - Execute the SQL query of the view, through :cfunc:`MSIViewExecute`. If + Execute the SQL query of the view, through :c:func:`MSIViewExecute`. If *params* is not ``None``, it is a record describing actual values of the parameter tokens in the query. @@ -172,18 +172,18 @@ View Objects .. method:: View.GetColumnInfo(kind) Return a record describing the columns of the view, through calling - :cfunc:`MsiViewGetColumnInfo`. *kind* can be either ``MSICOLINFO_NAMES`` or + :c:func:`MsiViewGetColumnInfo`. *kind* can be either ``MSICOLINFO_NAMES`` or ``MSICOLINFO_TYPES``. .. method:: View.Fetch() - Return a result record of the query, through calling :cfunc:`MsiViewFetch`. + Return a result record of the query, through calling :c:func:`MsiViewFetch`. .. method:: View.Modify(kind, data) - Modify the view, by calling :cfunc:`MsiViewModify`. *kind* can be one of + Modify the view, by calling :c:func:`MsiViewModify`. *kind* can be one of ``MSIMODIFY_SEEK``, ``MSIMODIFY_REFRESH``, ``MSIMODIFY_INSERT``, ``MSIMODIFY_UPDATE``, ``MSIMODIFY_ASSIGN``, ``MSIMODIFY_REPLACE``, ``MSIMODIFY_MERGE``, ``MSIMODIFY_DELETE``, ``MSIMODIFY_INSERT_TEMPORARY``, @@ -195,7 +195,7 @@ View Objects .. method:: View.Close() - Close the view, through :cfunc:`MsiViewClose`. + Close the view, through :c:func:`MsiViewClose`. .. seealso:: @@ -214,7 +214,7 @@ Summary Information Objects .. method:: SummaryInformation.GetProperty(field) - Return a property of the summary, through :cfunc:`MsiSummaryInfoGetProperty`. + Return a property of the summary, through :c:func:`MsiSummaryInfoGetProperty`. *field* is the name of the property, and can be one of the constants ``PID_CODEPAGE``, ``PID_TITLE``, ``PID_SUBJECT``, ``PID_AUTHOR``, ``PID_KEYWORDS``, ``PID_COMMENTS``, ``PID_TEMPLATE``, ``PID_LASTAUTHOR``, @@ -226,12 +226,12 @@ Summary Information Objects .. method:: SummaryInformation.GetPropertyCount() Return the number of summary properties, through - :cfunc:`MsiSummaryInfoGetPropertyCount`. + :c:func:`MsiSummaryInfoGetPropertyCount`. .. method:: SummaryInformation.SetProperty(field, value) - Set a property through :cfunc:`MsiSummaryInfoSetProperty`. *field* can have the + Set a property through :c:func:`MsiSummaryInfoSetProperty`. *field* can have the same values as in :meth:`GetProperty`, *value* is the new value of the property. Possible value types are integer and string. @@ -239,7 +239,7 @@ Summary Information Objects .. method:: SummaryInformation.Persist() Write the modified properties to the summary information stream, using - :cfunc:`MsiSummaryInfoPersist`. + :c:func:`MsiSummaryInfoPersist`. .. seealso:: @@ -258,7 +258,7 @@ Record Objects .. method:: Record.GetFieldCount() Return the number of fields of the record, through - :cfunc:`MsiRecordGetFieldCount`. + :c:func:`MsiRecordGetFieldCount`. .. method:: Record.GetInteger(field) @@ -275,25 +275,25 @@ Record Objects .. method:: Record.SetString(field, value) - Set *field* to *value* through :cfunc:`MsiRecordSetString`. *field* must be an + Set *field* to *value* through :c:func:`MsiRecordSetString`. *field* must be an integer; *value* a string. .. method:: Record.SetStream(field, value) Set *field* to the contents of the file named *value*, through - :cfunc:`MsiRecordSetStream`. *field* must be an integer; *value* a string. + :c:func:`MsiRecordSetStream`. *field* must be an integer; *value* a string. .. method:: Record.SetInteger(field, value) - Set *field* to *value* through :cfunc:`MsiRecordSetInteger`. Both *field* and + Set *field* to *value* through :c:func:`MsiRecordSetInteger`. Both *field* and *value* must be an integer. .. method:: Record.ClearData() - Set all fields of the record to 0, through :cfunc:`MsiRecordClearData`. + Set all fields of the record to 0, through :c:func:`MsiRecordClearData`. .. seealso:: diff --git a/Doc/library/msvcrt.rst b/Doc/library/msvcrt.rst index 7636b6f..889a0c5 100644 --- a/Doc/library/msvcrt.rst +++ b/Doc/library/msvcrt.rst @@ -143,5 +143,5 @@ Other Functions .. function:: heapmin() - Force the :cfunc:`malloc` heap to clean itself up and return unused blocks to + Force the :c:func:`malloc` heap to clean itself up and return unused blocks to the operating system. On failure, this raises :exc:`IOError`. diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst index 4e41293..e7f9afe 100644 --- a/Doc/library/multiprocessing.rst +++ b/Doc/library/multiprocessing.rst @@ -406,7 +406,7 @@ The :mod:`multiprocessing` package mostly replicates the API of the .. method:: terminate() Terminate the process. On Unix this is done using the ``SIGTERM`` signal; - on Windows :cfunc:`TerminateProcess` is used. Note that exit handlers and + on Windows :c:func:`TerminateProcess` is used. Note that exit handlers and finally clauses, etc., will not be executed. Note that descendant processes of the process will *not* be terminated -- diff --git a/Doc/library/os.rst b/Doc/library/os.rst index 0a8f06f..b22c2e9 100644 --- a/Doc/library/os.rst +++ b/Doc/library/os.rst @@ -122,7 +122,7 @@ process and user. On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause memory leaks. Refer to the system documentation for - :cfunc:`putenv`. + :c:func:`putenv`. If :func:`putenv` is not provided, a modified copy of this mapping may be passed to the appropriate process-creation functions to cause child processes @@ -394,7 +394,7 @@ process and user. .. function:: setpgrp() - Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on + Call the system call :c:func:`setpgrp` or :c:func:`setpgrp(0, 0)` depending on which version is implemented (if any). See the Unix manual for the semantics. Availability: Unix. @@ -402,7 +402,7 @@ process and user. .. function:: setpgid(pid, pgrp) - Call the system call :cfunc:`setpgid` to set the process group id of the + Call the system call :c:func:`setpgid` to set the process group id of the process with id *pid* to the process group with id *pgrp*. See the Unix manual for the semantics. @@ -443,14 +443,14 @@ process and user. .. function:: getsid(pid) - Call the system call :cfunc:`getsid`. See the Unix manual for the semantics. + Call the system call :c:func:`getsid`. See the Unix manual for the semantics. Availability: Unix. .. function:: setsid() - Call the system call :cfunc:`setsid`. See the Unix manual for the semantics. + Call the system call :c:func:`setsid`. See the Unix manual for the semantics. Availability: Unix. @@ -468,7 +468,7 @@ process and user. .. function:: strerror(code) Return the error message corresponding to the error code in *code*. - On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown + On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown error number, :exc:`ValueError` is raised. Availability: Unix, Windows. @@ -541,7 +541,7 @@ These functions create new :term:`file objects <file object>`. (See also :func:` ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised. On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is - set on the file descriptor (which the :cfunc:`fdopen` implementation already + set on the file descriptor (which the :c:func:`fdopen` implementation already does on most platforms). Availability: Unix, Windows. @@ -677,7 +677,7 @@ as internal buffering of data. .. function:: fsync(fd) Force write of file with filedescriptor *fd* to disk. On Unix, this calls the - native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function. + native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` function. If you're starting with a buffered Python :term:`file object` *f*, first do ``f.flush()``, and then do ``os.fsync(f.fileno())``, to ensure that all internal @@ -1117,13 +1117,13 @@ Files and Directories .. function:: major(device) Extract the device major number from a raw device number (usually the - :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`). + :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`). .. function:: minor(device) Extract the device minor number from a raw device number (usually the - :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`). + :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`). .. function:: makedev(major, minor) @@ -1271,8 +1271,8 @@ Files and Directories .. function:: stat(path) - Perform a :cfunc:`stat` system call on the given path. The return value is an - object whose attributes correspond to the members of the :ctype:`stat` + Perform a :c:func:`stat` system call on the given path. The return value is an + object whose attributes correspond to the members of the :c:type:`stat` structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links), :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner), @@ -1306,12 +1306,12 @@ Files and Directories For backward compatibility, the return value of :func:`stat` is also accessible as a tuple of at least 10 integers giving the most important (and portable) - members of the :ctype:`stat` structure, in the order :attr:`st_mode`, + members of the :c:type:`stat` structure, in the order :attr:`st_mode`, :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`, :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by some implementations. The standard module :mod:`stat` defines functions and constants that are useful - for extracting information from a :ctype:`stat` structure. (On Windows, some + for extracting information from a :c:type:`stat` structure. (On Windows, some items are filled with dummy values.) .. note:: @@ -1352,9 +1352,9 @@ Files and Directories .. function:: statvfs(path) - Perform a :cfunc:`statvfs` system call on the given path. The return value is + Perform a :c:func:`statvfs` system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and - correspond to the members of the :ctype:`statvfs` structure, namely: + correspond to the members of the :c:type:`statvfs` structure, namely: :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`, :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`, :attr:`f_flag`, :attr:`f_namemax`. @@ -1514,7 +1514,7 @@ The various :func:`exec\*` functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this is the ``argv[0]`` -passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo', +passed to a program's :c:func:`main`. For example, ``os.execv('/bin/echo', ['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem to be ignored. @@ -1918,7 +1918,7 @@ written in Python, such as a mail server's external command delivery program. There is no option to wait for the application to close, and no way to retrieve the application's exit status. The *path* parameter is relative to the current directory. If you want to use an absolute path, make sure the first character - is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function + is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` function doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that the path is properly encoded for Win32. @@ -1928,13 +1928,13 @@ written in Python, such as a mail server's external command delivery program. .. function:: system(command) Execute the command (a string) in a subshell. This is implemented by calling - the Standard C function :cfunc:`system`, and has the same limitations. + the Standard C function :c:func:`system`, and has the same limitations. Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the executed command. On Unix, the return value is the exit status of the process encoded in the format specified for :func:`wait`. Note that POSIX does not specify the meaning - of the return value of the C :cfunc:`system` function, so the return value of + of the return value of the C :c:func:`system` function, so the return value of the Python function is system-dependent. On Windows, the return value is that returned by the system shell after running diff --git a/Doc/library/ossaudiodev.rst b/Doc/library/ossaudiodev.rst index 82a263f..3128b0a 100644 --- a/Doc/library/ossaudiodev.rst +++ b/Doc/library/ossaudiodev.rst @@ -56,7 +56,7 @@ the standard audio interface for Linux and recent versions of FreeBSD. what went wrong. (If :mod:`ossaudiodev` receives an error from a system call such as - :cfunc:`open`, :cfunc:`write`, or :cfunc:`ioctl`, it raises :exc:`IOError`. + :c:func:`open`, :c:func:`write`, or :c:func:`ioctl`, it raises :exc:`IOError`. Errors detected directly by :mod:`ossaudiodev` result in :exc:`OSSAudioError`.) (For backwards compatibility, the exception class is also available as diff --git a/Doc/library/platform.rst b/Doc/library/platform.rst index f4ef680..1fe1031 100644 --- a/Doc/library/platform.rst +++ b/Doc/library/platform.rst @@ -27,8 +27,8 @@ Cross Platform returned as strings. Values that cannot be determined are returned as given by the parameter presets. - If bits is given as ``''``, the :cfunc:`sizeof(pointer)` (or - :cfunc:`sizeof(long)` on Python version < 1.5.2) is used as indicator for the + If bits is given as ``''``, the :c:func:`sizeof(pointer)` (or + :c:func:`sizeof(long)` on Python version < 1.5.2) is used as indicator for the supported pointer size. The function relies on the system's :file:`file` command to do the actual work. @@ -215,7 +215,7 @@ Mac OS Platform Entries which cannot be determined are set to ``''``. All tuple entries are strings. - Documentation for the underlying :cfunc:`gestalt` API is available online at + Documentation for the underlying :c:func:`gestalt` API is available online at http://www.rgaros.nl/gestalt/. diff --git a/Doc/library/posix.rst b/Doc/library/posix.rst index d65b999..07db2b2 100644 --- a/Doc/library/posix.rst +++ b/Doc/library/posix.rst @@ -38,13 +38,13 @@ Large File Support Several operating systems (including AIX, HP-UX, Irix and Solaris) provide support for files that are larger than 2 GB from a C programming model where -:ctype:`int` and :ctype:`long` are 32-bit values. This is typically accomplished +:c:type:`int` and :c:type:`long` are 32-bit values. This is typically accomplished by defining the relevant size and offset types as 64-bit values. Such files are sometimes referred to as :dfn:`large files`. -Large file support is enabled in Python when the size of an :ctype:`off_t` is -larger than a :ctype:`long` and the :ctype:`long long` type is available and is -at least as large as an :ctype:`off_t`. +Large file support is enabled in Python when the size of an :c:type:`off_t` is +larger than a :c:type:`long` and the :c:type:`long long` type is available and is +at least as large as an :c:type:`off_t`. It may be necessary to configure and compile Python with certain compiler flags to enable this mode. For example, it is enabled by default with recent versions of Irix, but with Solaris 2.6 and 2.7 you need to do something like:: diff --git a/Doc/library/re.rst b/Doc/library/re.rst index 9787bcb..206f4d9 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -1057,14 +1057,14 @@ Simulating scanf() .. index:: single: scanf() -Python does not currently have an equivalent to :cfunc:`scanf`. Regular +Python does not currently have an equivalent to :c:func:`scanf`. Regular expressions are generally more powerful, though also more verbose, than -:cfunc:`scanf` format strings. The table below offers some more-or-less -equivalent mappings between :cfunc:`scanf` format tokens and regular +:c:func:`scanf` format strings. The table below offers some more-or-less +equivalent mappings between :c:func:`scanf` format tokens and regular expressions. +--------------------------------+---------------------------------------------+ -| :cfunc:`scanf` Token | Regular Expression | +| :c:func:`scanf` Token | Regular Expression | +================================+=============================================+ | ``%c`` | ``.`` | +--------------------------------+---------------------------------------------+ @@ -1089,7 +1089,7 @@ To extract the filename and numbers from a string like :: /usr/sbin/sendmail - 0 errors, 4 warnings -you would use a :cfunc:`scanf` format like :: +you would use a :c:func:`scanf` format like :: %s - %d errors, %d warnings diff --git a/Doc/library/select.rst b/Doc/library/select.rst index 5e848b0..6730910 100644 --- a/Doc/library/select.rst +++ b/Doc/library/select.rst @@ -5,9 +5,9 @@ :synopsis: Wait for I/O completion on multiple streams. -This module provides access to the :cfunc:`select` and :cfunc:`poll` functions -available in most operating systems, :cfunc:`epoll` available on Linux 2.5+ and -:cfunc:`kqueue` available on most BSD. +This module provides access to the :c:func:`select` and :c:func:`poll` functions +available in most operating systems, :c:func:`epoll` available on Linux 2.5+ and +:c:func:`kqueue` available on most BSD. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since @@ -19,8 +19,8 @@ The module defines the following: .. exception:: error The exception raised when an error occurs. The accompanying value is a pair - containing the numeric error code from :cdata:`errno` and the corresponding - string, as would be printed by the C function :cfunc:`perror`. + containing the numeric error code from :c:data:`errno` and the corresponding + string, as would be printed by the C function :c:func:`perror`. .. function:: epoll(sizehint=-1) @@ -53,7 +53,7 @@ The module defines the following: .. function:: select(rlist, wlist, xlist[, timeout]) - This is a straightforward interface to the Unix :cfunc:`select` system call. + This is a straightforward interface to the Unix :c:func:`select` system call. The first three arguments are sequences of 'waitable objects': either integers representing file descriptors or objects with a parameterless method named :meth:`fileno` returning such an integer: @@ -90,7 +90,7 @@ The module defines the following: .. index:: single: WinSock File objects on Windows are not acceptable, but sockets are. On Windows, - the underlying :cfunc:`select` function is provided by the WinSock + the underlying :c:func:`select` function is provided by the WinSock library, and does not handle file descriptors that don't originate from WinSock. @@ -189,13 +189,13 @@ Edge and Level Trigger Polling (epoll) Objects Polling Objects --------------- -The :cfunc:`poll` system call, supported on most Unix systems, provides better +The :c:func:`poll` system call, supported on most Unix systems, provides better scalability for network servers that service many, many clients at the same -time. :cfunc:`poll` scales better because the system call only requires listing -the file descriptors of interest, while :cfunc:`select` builds a bitmap, turns +time. :c:func:`poll` scales better because the system call only requires listing +the file descriptors of interest, while :c:func:`select` builds a bitmap, turns on bits for the fds of interest, and then afterward the whole bitmap has to be -linearly scanned again. :cfunc:`select` is O(highest file descriptor), while -:cfunc:`poll` is O(number of file descriptors). +linearly scanned again. :c:func:`select` is O(highest file descriptor), while +:c:func:`poll` is O(number of file descriptors). .. method:: poll.register(fd[, eventmask]) diff --git a/Doc/library/signal.rst b/Doc/library/signal.rst index 7d8d7d6..698b1e7 100644 --- a/Doc/library/signal.rst +++ b/Doc/library/signal.rst @@ -68,7 +68,7 @@ The variables defined in the :mod:`signal` module are: All the signal numbers are defined symbolically. For example, the hangup signal is defined as :const:`signal.SIGHUP`; the variable names are identical to the names used in C programs, as found in ``<signal.h>``. The Unix man page for - ':cfunc:`signal`' lists the existing signals (on some systems this is + ':c:func:`signal`' lists the existing signals (on some systems this is :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that not all systems define the same set of signal names; only those names defined by the system are defined by this module. @@ -210,7 +210,7 @@ The :mod:`signal` module defines the following functions: Note that installing a signal handler with :func:`signal` will reset the restart behaviour to interruptible by implicitly calling - :cfunc:`siginterrupt` with a true *flag* value for the given signal. + :c:func:`siginterrupt` with a true *flag* value for the given signal. .. function:: signal(signalnum, handler) diff --git a/Doc/library/socket.rst b/Doc/library/socket.rst index c061b04..3a378ea 100644 --- a/Doc/library/socket.rst +++ b/Doc/library/socket.rst @@ -118,7 +118,7 @@ The module :mod:`socket` exports the following constants and functions: The accompanying value is a pair ``(h_errno, string)`` representing an error returned by a library call. *string* represents the description of *h_errno*, as - returned by the :cfunc:`hstrerror` C function. + returned by the :c:func:`hstrerror` C function. .. exception:: gaierror @@ -126,7 +126,7 @@ The module :mod:`socket` exports the following constants and functions: This exception is raised for address-related errors, for :func:`getaddrinfo` and :func:`getnameinfo`. The accompanying value is a pair ``(error, string)`` representing an error returned by a library call. *string* represents the - description of *error*, as returned by the :cfunc:`gai_strerror` C function. The + description of *error*, as returned by the :c:func:`gai_strerror` C function. The *error* value will match one of the :const:`EAI_\*` constants defined in this module. @@ -415,7 +415,7 @@ The module :mod:`socket` exports the following constants and functions: Convert an IPv4 address from dotted-quad string format (for example, '123.45.67.89') to 32-bit packed binary format, as a bytes object four characters in length. This is useful when conversing with a program that uses the standard C - library and needs objects of type :ctype:`struct in_addr`, which is the C type + library and needs objects of type :c:type:`struct in_addr`, which is the C type for the 32-bit packed binary this function returns. :func:`inet_aton` also accepts strings with less than three dots; see the @@ -423,7 +423,7 @@ The module :mod:`socket` exports the following constants and functions: If the IPv4 address string passed to this function is invalid, :exc:`socket.error` will be raised. Note that exactly what is valid depends on - the underlying C implementation of :cfunc:`inet_aton`. + the underlying C implementation of :c:func:`inet_aton`. :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used instead for IPv4/v6 dual stack support. @@ -434,7 +434,7 @@ The module :mod:`socket` exports the following constants and functions: Convert a 32-bit packed IPv4 address (a bytes object four characters in length) to its standard dotted-quad string representation (for example, '123.45.67.89'). This is useful when conversing with a program that uses the - standard C library and needs objects of type :ctype:`struct in_addr`, which + standard C library and needs objects of type :c:type:`struct in_addr`, which is the C type for the 32-bit packed binary data this function takes as an argument. @@ -448,14 +448,14 @@ The module :mod:`socket` exports the following constants and functions: Convert an IP address from its family-specific string format to a packed, binary format. :func:`inet_pton` is useful when a library or network protocol - calls for an object of type :ctype:`struct in_addr` (similar to - :func:`inet_aton`) or :ctype:`struct in6_addr`. + calls for an object of type :c:type:`struct in_addr` (similar to + :func:`inet_aton`) or :c:type:`struct in6_addr`. Supported values for *address_family* are currently :const:`AF_INET` and :const:`AF_INET6`. If the IP address string *ip_string* is invalid, :exc:`socket.error` will be raised. Note that exactly what is valid depends on both the value of *address_family* and the underlying implementation of - :cfunc:`inet_pton`. + :c:func:`inet_pton`. Availability: Unix (maybe not all platforms). @@ -465,8 +465,8 @@ The module :mod:`socket` exports the following constants and functions: Convert a packed IP address (a bytes object of some number of characters) to its standard, family-specific string representation (for example, ``'7.10.0.5'`` or ``'5aef:2b::8'``). :func:`inet_ntop` is useful when a library or network protocol - returns an object of type :ctype:`struct in_addr` (similar to :func:`inet_ntoa`) - or :ctype:`struct in6_addr`. + returns an object of type :c:type:`struct in_addr` (similar to :func:`inet_ntoa`) + or :c:type:`struct in6_addr`. Supported values for *address_family* are currently :const:`AF_INET` and :const:`AF_INET6`. If the string *packed_ip* is not the correct length for the @@ -541,10 +541,10 @@ correspond to Unix system calls applicable to sockets. .. method:: socket.connect_ex(address) Like ``connect(address)``, but return an error indicator instead of raising an - exception for errors returned by the C-level :cfunc:`connect` call (other + exception for errors returned by the C-level :c:func:`connect` call (other problems, such as "host not found," can still raise exceptions). The error indicator is ``0`` if the operation succeeded, otherwise the value of the - :cdata:`errno` variable. This is useful to support, for example, asynchronous + :c:data:`errno` variable. This is useful to support, for example, asynchronous connects. diff --git a/Doc/library/stat.rst b/Doc/library/stat.rst index 9100910..b2aec43 100644 --- a/Doc/library/stat.rst +++ b/Doc/library/stat.rst @@ -9,8 +9,8 @@ The :mod:`stat` module defines constants and functions for interpreting the results of :func:`os.stat`, :func:`os.fstat` and :func:`os.lstat` (if they -exist). For complete details about the :cfunc:`stat`, :cfunc:`fstat` and -:cfunc:`lstat` calls, consult the documentation for your system. +exist). For complete details about the :c:func:`stat`, :c:func:`fstat` and +:c:func:`lstat` calls, consult the documentation for your system. The :mod:`stat` module defines the following functions to test for specific file types: @@ -68,7 +68,7 @@ mode: Normally, you would use the :func:`os.path.is\*` functions for testing the type of a file; the functions here are useful when you are doing multiple tests of -the same file and wish to avoid the overhead of the :cfunc:`stat` system call +the same file and wish to avoid the overhead of the :c:func:`stat` system call for each test. These are also useful when checking for information about a file that isn't handled by :mod:`os.path`, like the tests for block and character devices. diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 3770fd8..0e2fd38 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -217,7 +217,7 @@ Numeric Types --- :class:`int`, :class:`float`, :class:`complex` There are three distinct numeric types: :dfn:`integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating point -numbers are usually implemented using :ctype:`double` in C; information +numbers are usually implemented using :c:type:`double` in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in :data:`sys.float_info`. Complex numbers have a real and imaginary @@ -1378,7 +1378,7 @@ String objects have one unique built-in operation: the ``%`` operator (modulo). This is also known as the string *formatting* or *interpolation* operator. Given ``format % values`` (where *format* is a string), ``%`` conversion specifications in *format* are replaced with zero or more elements of *values*. -The effect is similar to the using :cfunc:`sprintf` in the C language. +The effect is similar to the using :c:func:`sprintf` in the C language. If *format* requires a single argument, *values* may be a single non-tuple object. [#]_ Otherwise, *values* must be a tuple with exactly the number of diff --git a/Doc/library/struct.rst b/Doc/library/struct.rst index 7878a54..9e6ea85 100644 --- a/Doc/library/struct.rst +++ b/Doc/library/struct.rst @@ -157,46 +157,46 @@ is, when the format string starts with one of ``'<'``, ``'>'``, ``'!'`` or ``'='``. When using native size, the size of the packed value is platform-dependent. -+--------+-------------------------+--------------------+----------------+------------+ -| Format | C Type | Python type | Standard size | Notes | -+========+=========================+====================+================+============+ -| ``x`` | pad byte | no value | | | -+--------+-------------------------+--------------------+----------------+------------+ -| ``c`` | :ctype:`char` | bytes of length 1 | 1 | | -+--------+-------------------------+--------------------+----------------+------------+ -| ``b`` | :ctype:`signed char` | integer | 1 | \(1),\(4) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``B`` | :ctype:`unsigned char` | integer | 1 | \(4) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``?`` | :ctype:`_Bool` | bool | 1 | \(2) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``h`` | :ctype:`short` | integer | 2 | \(4) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``H`` | :ctype:`unsigned short` | integer | 2 | \(4) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``i`` | :ctype:`int` | integer | 4 | \(4) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``I`` | :ctype:`unsigned int` | integer | 4 | \(4) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``l`` | :ctype:`long` | integer | 4 | \(4) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``L`` | :ctype:`unsigned long` | integer | 4 | \(4) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``q`` | :ctype:`long long` | integer | 8 | \(3), \(4) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``Q`` | :ctype:`unsigned long | integer | 8 | \(3), \(4) | -| | long` | | | | -+--------+-------------------------+--------------------+----------------+------------+ -| ``f`` | :ctype:`float` | float | 4 | \(5) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``d`` | :ctype:`double` | float | 8 | \(5) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``s`` | :ctype:`char[]` | bytes | | \(1) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``p`` | :ctype:`char[]` | bytes | | \(1) | -+--------+-------------------------+--------------------+----------------+------------+ -| ``P`` | :ctype:`void \*` | integer | | \(6) | -+--------+-------------------------+--------------------+----------------+------------+ ++--------+--------------------------+--------------------+----------------+------------+ +| Format | C Type | Python type | Standard size | Notes | ++========+==========================+====================+================+============+ +| ``x`` | pad byte | no value | | | ++--------+--------------------------+--------------------+----------------+------------+ +| ``c`` | :c:type:`char` | bytes of length 1 | 1 | | ++--------+--------------------------+--------------------+----------------+------------+ +| ``b`` | :c:type:`signed char` | integer | 1 | \(1),\(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``B`` | :c:type:`unsigned char` | integer | 1 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``?`` | :c:type:`_Bool` | bool | 1 | \(2) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``h`` | :c:type:`short` | integer | 2 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``H`` | :c:type:`unsigned short` | integer | 2 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``i`` | :c:type:`int` | integer | 4 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``I`` | :c:type:`unsigned int` | integer | 4 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``l`` | :c:type:`long` | integer | 4 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``L`` | :c:type:`unsigned long` | integer | 4 | \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``q`` | :c:type:`long long` | integer | 8 | \(3), \(4) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``Q`` | :c:type:`unsigned long | integer | 8 | \(3), \(4) | +| | long` | | | | ++--------+--------------------------+--------------------+----------------+------------+ +| ``f`` | :c:type:`float` | float | 4 | \(5) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``d`` | :c:type:`double` | float | 8 | \(5) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``s`` | :c:type:`char[]` | bytes | | \(1) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``p`` | :c:type:`char[]` | bytes | | \(1) | ++--------+--------------------------+--------------------+----------------+------------+ +| ``P`` | :c:type:`void \*` | integer | | \(6) | ++--------+--------------------------+--------------------+----------------+------------+ Notes: @@ -206,14 +206,14 @@ Notes: which are encoded using UTF-8. (2) - The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by - C99. If this type is not available, it is simulated using a :ctype:`char`. In + The ``'?'`` conversion code corresponds to the :c:type:`_Bool` type defined by + C99. If this type is not available, it is simulated using a :c:type:`char`. In standard mode, it is always represented by one byte. (3) The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if - the platform C compiler supports C :ctype:`long long`, or, on Windows, - :ctype:`__int64`. They are always available in standard modes. + the platform C compiler supports C :c:type:`long long`, or, on Windows, + :c:type:`__int64`. They are always available in standard modes. (4) When attempting to pack a non-integer using any of the integer conversion diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst index 1c8a79c..3671407 100644 --- a/Doc/library/subprocess.rst +++ b/Doc/library/subprocess.rst @@ -277,7 +277,7 @@ This module also defines four shortcut functions: ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the returned output will contain output or error messages. A trailing newline is stripped from the output. The exit status for the command can be interpreted - according to the rules for the C function :cfunc:`wait`. Example:: + according to the rules for the C function :c:func:`wait`. Example:: >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') @@ -387,7 +387,7 @@ Instances of the :class:`Popen` class have the following methods: .. method:: Popen.terminate() Stop the child. On Posix OSs the method sends SIGTERM to the - child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called + child. On Windows the Win32 API function :c:func:`TerminateProcess` is called to stop the child. diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index 0bb6f3a..352eb62 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -312,7 +312,7 @@ always available. .. function:: getdlopenflags() - Return the current value of the flags that are used for :cfunc:`dlopen` calls. + Return the current value of the flags that are used for :c:func:`dlopen` calls. The flag constants are defined in the :mod:`ctypes` and :mod:`DLFCN` modules. Availability: Unix. @@ -457,8 +457,8 @@ always available. +---------------------------------------+---------------------------------+ - This function wraps the Win32 :cfunc:`GetVersionEx` function; see the - Microsoft documentation on :cfunc:`OSVERSIONINFOEX` for more information + This function wraps the Win32 :c:func:`GetVersionEx` function; see the + Microsoft documentation on :c:func:`OSVERSIONINFOEX` for more information about these fields. Availability: Windows. @@ -561,7 +561,7 @@ always available. .. data:: maxsize - An integer giving the maximum value a variable of type :ctype:`Py_ssize_t` can + An integer giving the maximum value a variable of type :c:type:`Py_ssize_t` can take. It's usually ``2**31 - 1`` on a 32-bit platform and ``2**63 - 1`` on a 64-bit platform. @@ -714,7 +714,7 @@ always available. .. function:: setdlopenflags(n) - Set the flags used by the interpreter for :cfunc:`dlopen` calls, such as when + Set the flags used by the interpreter for :c:func:`dlopen` calls, such as when the interpreter loads extension modules. Among other things, this will enable a lazy resolving of symbols when importing a module, if called as ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as diff --git a/Doc/library/time.rst b/Doc/library/time.rst index d3b4305..4a14bbb 100644 --- a/Doc/library/time.rst +++ b/Doc/library/time.rst @@ -71,8 +71,8 @@ An explanation of some terminology and conventions is in order. * On the other hand, the precision of :func:`time` and :func:`sleep` is better than their Unix equivalents: times are expressed as floating point numbers, :func:`time` returns the most accurate time available (using Unix - :cfunc:`gettimeofday` where available), and :func:`sleep` will accept a time - with a nonzero fraction (Unix :cfunc:`select` is used to implement this, where + :c:func:`gettimeofday` where available), and :func:`sleep` will accept a time + with a nonzero fraction (Unix :c:func:`select` is used to implement this, where available). * The time value as returned by :func:`gmtime`, :func:`localtime`, and @@ -178,7 +178,7 @@ The module defines the following functions and data items: On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function - :cfunc:`QueryPerformanceCounter`. The resolution is typically better than one + :c:func:`QueryPerformanceCounter`. The resolution is typically better than one microsecond. diff --git a/Doc/library/warnings.rst b/Doc/library/warnings.rst index 25e5db3..309fec5 100644 --- a/Doc/library/warnings.rst +++ b/Doc/library/warnings.rst @@ -13,7 +13,7 @@ warrant raising an exception and terminating the program. For example, one might want to issue a warning when a program uses an obsolete module. Python programmers issue warnings by calling the :func:`warn` function defined -in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see +in this module. (C programmers use :c:func:`PyErr_WarnEx`; see :ref:`exceptionhandling` for details). Warning messages are normally written to ``sys.stderr``, but their disposition diff --git a/Doc/library/winsound.rst b/Doc/library/winsound.rst index d54c999..8356062 100644 --- a/Doc/library/winsound.rst +++ b/Doc/library/winsound.rst @@ -22,7 +22,7 @@ provided by Windows platforms. It includes functions and several constants. .. function:: PlaySound(sound, flags) - Call the underlying :cfunc:`PlaySound` function from the Platform API. The + Call the underlying :c:func:`PlaySound` function from the Platform API. The *sound* parameter may be a filename, audio data as a string, or ``None``. Its interpretation depends on the value of *flags*, which can be a bitwise ORed combination of the constants described below. If the *sound* parameter is @@ -32,7 +32,7 @@ provided by Windows platforms. It includes functions and several constants. .. function:: MessageBeep(type=MB_OK) - Call the underlying :cfunc:`MessageBeep` function from the Platform API. This + Call the underlying :c:func:`MessageBeep` function from the Platform API. This plays a sound as specified in the registry. The *type* argument specifies which sound to play; possible values are ``-1``, ``MB_ICONASTERISK``, ``MB_ICONEXCLAMATION``, ``MB_ICONHAND``, ``MB_ICONQUESTION``, and ``MB_OK``, all diff --git a/Doc/library/zlib.rst b/Doc/library/zlib.rst index c325df3..a56f521 100644 --- a/Doc/library/zlib.rst +++ b/Doc/library/zlib.rst @@ -113,7 +113,7 @@ The available exception and functions in this module are: *bufsize* is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you don't have to get this value exactly right; tuning it will only save a few calls - to :cfunc:`malloc`. The default size is 16384. + to :c:func:`malloc`. The default size is 16384. .. function:: decompressobj([wbits]) diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst index f6a6f80..f8f0455 100644 --- a/Doc/reference/expressions.rst +++ b/Doc/reference/expressions.rst @@ -651,7 +651,7 @@ the call. An implementation may provide built-in functions whose positional parameters do not have names, even if they are 'named' for the purpose of documentation, and which therefore cannot be supplied by keyword. In CPython, this is the - case for functions implemented in C that use :cfunc:`PyArg_ParseTuple` to + case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to parse their arguments. If there are more positional arguments than there are formal parameter slots, a diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst index 84e83b5..04665f8 100644 --- a/Doc/tutorial/inputoutput.rst +++ b/Doc/tutorial/inputoutput.rst @@ -208,7 +208,7 @@ Old string formatting --------------------- The ``%`` operator can also be used for string formatting. It interprets the -left argument much like a :cfunc:`sprintf`\ -style format string to be applied +left argument much like a :c:func:`sprintf`\ -style format string to be applied to the right argument, and returns the string resulting from this formatting operation. For example:: diff --git a/Doc/whatsnew/2.2.rst b/Doc/whatsnew/2.2.rst index 89e4d76..412c1d0 100644 --- a/Doc/whatsnew/2.2.rst +++ b/Doc/whatsnew/2.2.rst @@ -754,7 +754,7 @@ Here are the changes 2.2 introduces: * Classes can define methods called :meth:`__truediv__` and :meth:`__floordiv__` to overload the two division operators. At the C level, there are also slots in - the :ctype:`PyNumberMethods` structure so extension types can define the two + the :c:type:`PyNumberMethods` structure so extension types can define the two operators. * Python 2.2 supports some command-line arguments for testing whether code will @@ -983,7 +983,7 @@ New and Improved Modules Jun-ichiro "itojun" Hagino.) * Two new format characters were added to the :mod:`struct` module for 64-bit - integers on platforms that support the C :ctype:`long long` type. ``q`` is for + integers on platforms that support the C :c:type:`long long` type. ``q`` is for a signed 64-bit integer, and ``Q`` is for an unsigned one. The value is returned in Python's long integer type. (Contributed by Tim Peters.) @@ -1057,16 +1057,16 @@ code, none of the changes described here will affect you very much. at much higher speeds than Python-based functions and should reduce the overhead of profiling and tracing. This will be of interest to authors of development environments for Python. Two new C functions were added to Python's API, - :cfunc:`PyEval_SetProfile` and :cfunc:`PyEval_SetTrace`. The existing + :c:func:`PyEval_SetProfile` and :c:func:`PyEval_SetTrace`. The existing :func:`sys.setprofile` and :func:`sys.settrace` functions still exist, and have simply been changed to use the new C-level interface. (Contributed by Fred L. Drake, Jr.) * Another low-level API, primarily of interest to implementors of Python - debuggers and development tools, was added. :cfunc:`PyInterpreterState_Head` and - :cfunc:`PyInterpreterState_Next` let a caller walk through all the existing - interpreter objects; :cfunc:`PyInterpreterState_ThreadHead` and - :cfunc:`PyThreadState_Next` allow looping over all the thread states for a given + debuggers and development tools, was added. :c:func:`PyInterpreterState_Head` and + :c:func:`PyInterpreterState_Next` let a caller walk through all the existing + interpreter objects; :c:func:`PyInterpreterState_ThreadHead` and + :c:func:`PyThreadState_Next` allow looping over all the thread states for a given interpreter. (Contributed by David Beazley.) * The C-level interface to the garbage collector has been changed to make it @@ -1078,19 +1078,19 @@ code, none of the changes described here will affect you very much. To upgrade an extension module to the new API, perform the following steps: -* Rename :cfunc:`Py_TPFLAGS_GC` to :cfunc:`PyTPFLAGS_HAVE_GC`. +* Rename :c:func:`Py_TPFLAGS_GC` to :c:func:`PyTPFLAGS_HAVE_GC`. -* Use :cfunc:`PyObject_GC_New` or :cfunc:`PyObject_GC_NewVar` to allocate - objects, and :cfunc:`PyObject_GC_Del` to deallocate them. +* Use :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar` to allocate + objects, and :c:func:`PyObject_GC_Del` to deallocate them. -* Rename :cfunc:`PyObject_GC_Init` to :cfunc:`PyObject_GC_Track` and - :cfunc:`PyObject_GC_Fini` to :cfunc:`PyObject_GC_UnTrack`. +* Rename :c:func:`PyObject_GC_Init` to :c:func:`PyObject_GC_Track` and + :c:func:`PyObject_GC_Fini` to :c:func:`PyObject_GC_UnTrack`. -* Remove :cfunc:`PyGC_HEAD_SIZE` from object size calculations. +* Remove :c:func:`PyGC_HEAD_SIZE` from object size calculations. -* Remove calls to :cfunc:`PyObject_AS_GC` and :cfunc:`PyObject_FROM_GC`. +* Remove calls to :c:func:`PyObject_AS_GC` and :c:func:`PyObject_FROM_GC`. -* A new ``et`` format sequence was added to :cfunc:`PyArg_ParseTuple`; ``et`` +* A new ``et`` format sequence was added to :c:func:`PyArg_ParseTuple`; ``et`` takes both a parameter and an encoding name, and converts the parameter to the given encoding if the parameter turns out to be a Unicode string, or leaves it alone if it's an 8-bit string, assuming it to already be in the desired @@ -1099,10 +1099,10 @@ code, none of the changes described here will affect you very much. specified new encoding. (Contributed by M.-A. Lemburg, and used for the MBCS support on Windows described in the following section.) -* A different argument parsing function, :cfunc:`PyArg_UnpackTuple`, has been +* A different argument parsing function, :c:func:`PyArg_UnpackTuple`, has been added that's simpler and presumably faster. Instead of specifying a format string, the caller simply gives the minimum and maximum number of arguments - expected, and a set of pointers to :ctype:`PyObject\*` variables that will be + expected, and a set of pointers to :c:type:`PyObject\*` variables that will be filled in with argument values. * Two new flags :const:`METH_NOARGS` and :const:`METH_O` are available in method @@ -1111,14 +1111,14 @@ code, none of the changes described here will affect you very much. corresponding method that uses :const:`METH_VARARGS`. Also, the old :const:`METH_OLDARGS` style of writing C methods is now officially deprecated. -* Two new wrapper functions, :cfunc:`PyOS_snprintf` and :cfunc:`PyOS_vsnprintf` +* Two new wrapper functions, :c:func:`PyOS_snprintf` and :c:func:`PyOS_vsnprintf` were added to provide cross-platform implementations for the relatively new - :cfunc:`snprintf` and :cfunc:`vsnprintf` C lib APIs. In contrast to the standard - :cfunc:`sprintf` and :cfunc:`vsprintf` functions, the Python versions check the + :c:func:`snprintf` and :c:func:`vsnprintf` C lib APIs. In contrast to the standard + :c:func:`sprintf` and :c:func:`vsprintf` functions, the Python versions check the bounds of the buffer used to protect against buffer overruns. (Contributed by M.-A. Lemburg.) -* The :cfunc:`_PyTuple_Resize` function has lost an unused parameter, so now it +* The :c:func:`_PyTuple_Resize` function has lost an unused parameter, so now it takes 2 parameters instead of 3. The third argument was never used, and can simply be discarded when porting code from earlier versions to Python 2.2. @@ -1219,7 +1219,7 @@ Some of the more notable changes are: operator, but these features were rarely used and therefore buggy. The :meth:`tolist` method and the :attr:`start`, :attr:`stop`, and :attr:`step` attributes are also being deprecated. At the C level, the fourth argument to - the :cfunc:`PyRange_New` function, ``repeat``, has also been deprecated. + the :c:func:`PyRange_New` function, ``repeat``, has also been deprecated. * There were a bunch of patches to the dictionary implementation, mostly to fix potential core dumps if a dictionary contains objects that sneakily changed @@ -1242,8 +1242,8 @@ Some of the more notable changes are: up to display the output. This patch makes it possible to import such scripts, in case they're also usable as modules. (Implemented by David Bolen.) -* On platforms where Python uses the C :cfunc:`dlopen` function to load - extension modules, it's now possible to set the flags used by :cfunc:`dlopen` +* On platforms where Python uses the C :c:func:`dlopen` function to load + extension modules, it's now possible to set the flags used by :c:func:`dlopen` using the :func:`sys.getdlopenflags` and :func:`sys.setdlopenflags` functions. (Contributed by Bram Stolk.) diff --git a/Doc/whatsnew/2.3.rst b/Doc/whatsnew/2.3.rst index 3894f87..0cc29f6 100644 --- a/Doc/whatsnew/2.3.rst +++ b/Doc/whatsnew/2.3.rst @@ -1797,8 +1797,8 @@ Pymalloc: A Specialized Object Allocator Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a feature added to Python 2.1. Pymalloc is intended to be faster than the system -:cfunc:`malloc` and to have less memory overhead for allocation patterns typical -of Python programs. The allocator uses C's :cfunc:`malloc` function to get large +:c:func:`malloc` and to have less memory overhead for allocation patterns typical +of Python programs. The allocator uses C's :c:func:`malloc` function to get large pools of memory and then fulfills smaller memory requests from these pools. In 2.1 and 2.2, pymalloc was an experimental feature and wasn't enabled by @@ -1814,13 +1814,13 @@ runtime. There's one particularly common error that causes problems. There are a number of memory allocation functions in Python's C API that have previously just been -aliases for the C library's :cfunc:`malloc` and :cfunc:`free`, meaning that if +aliases for the C library's :c:func:`malloc` and :c:func:`free`, meaning that if you accidentally called mismatched functions the error wouldn't be noticeable. When the object allocator is enabled, these functions aren't aliases of -:cfunc:`malloc` and :cfunc:`free` any more, and calling the wrong function to +:c:func:`malloc` and :c:func:`free` any more, and calling the wrong function to free memory may get you a core dump. For example, if memory was allocated using -:cfunc:`PyObject_Malloc`, it has to be freed using :cfunc:`PyObject_Free`, not -:cfunc:`free`. A few modules included with Python fell afoul of this and had to +:c:func:`PyObject_Malloc`, it has to be freed using :c:func:`PyObject_Free`, not +:c:func:`free`. A few modules included with Python fell afoul of this and had to be fixed; doubtless there are more third-party modules that will have the same problem. @@ -1831,14 +1831,14 @@ one family for allocating chunks of memory and another family of functions specifically for allocating Python objects. * To allocate and free an undistinguished chunk of memory use the "raw memory" - family: :cfunc:`PyMem_Malloc`, :cfunc:`PyMem_Realloc`, and :cfunc:`PyMem_Free`. + family: :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc`, and :c:func:`PyMem_Free`. * The "object memory" family is the interface to the pymalloc facility described above and is biased towards a large number of "small" allocations: - :cfunc:`PyObject_Malloc`, :cfunc:`PyObject_Realloc`, and :cfunc:`PyObject_Free`. + :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc`, and :c:func:`PyObject_Free`. * To allocate and free Python objects, use the "object" family - :cfunc:`PyObject_New`, :cfunc:`PyObject_NewVar`, and :cfunc:`PyObject_Del`. + :c:func:`PyObject_New`, :c:func:`PyObject_NewVar`, and :c:func:`PyObject_Del`. Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging features to catch memory overwrites and doubled frees in both extension modules @@ -1877,10 +1877,10 @@ Changes to Python's build process and to the C API include: (:file:`libpython2.3.so`) by supplying :option:`--enable-shared` when running Python's :program:`configure` script. (Contributed by Ondrej Palkovsky.) -* The :cmacro:`DL_EXPORT` and :cmacro:`DL_IMPORT` macros are now deprecated. +* The :c:macro:`DL_EXPORT` and :c:macro:`DL_IMPORT` macros are now deprecated. Initialization functions for Python extension modules should now be declared - using the new macro :cmacro:`PyMODINIT_FUNC`, while the Python core will - generally use the :cmacro:`PyAPI_FUNC` and :cmacro:`PyAPI_DATA` macros. + using the new macro :c:macro:`PyMODINIT_FUNC`, while the Python core will + generally use the :c:macro:`PyAPI_FUNC` and :c:macro:`PyAPI_DATA` macros. * The interpreter can be compiled without any docstrings for the built-in functions and modules by supplying :option:`--without-doc-strings` to the @@ -1888,19 +1888,19 @@ Changes to Python's build process and to the C API include: but will also mean that you can't get help for Python's built-ins. (Contributed by Gustavo Niemeyer.) -* The :cfunc:`PyArg_NoArgs` macro is now deprecated, and code that uses it +* The :c:func:`PyArg_NoArgs` macro is now deprecated, and code that uses it should be changed. For Python 2.2 and later, the method definition table can specify the :const:`METH_NOARGS` flag, signalling that there are no arguments, and the argument checking can then be removed. If compatibility with pre-2.2 versions of Python is important, the code could use ``PyArg_ParseTuple(args, "")`` instead, but this will be slower than using :const:`METH_NOARGS`. -* :cfunc:`PyArg_ParseTuple` accepts new format characters for various sizes of - unsigned integers: ``B`` for :ctype:`unsigned char`, ``H`` for :ctype:`unsigned - short int`, ``I`` for :ctype:`unsigned int`, and ``K`` for :ctype:`unsigned +* :c:func:`PyArg_ParseTuple` accepts new format characters for various sizes of + unsigned integers: ``B`` for :c:type:`unsigned char`, ``H`` for :c:type:`unsigned + short int`, ``I`` for :c:type:`unsigned int`, and ``K`` for :c:type:`unsigned long long`. -* A new function, :cfunc:`PyObject_DelItemString(mapping, char \*key)` was added +* A new function, :c:func:`PyObject_DelItemString(mapping, char \*key)` was added as shorthand for ``PyObject_DelItem(mapping, PyString_New(key))``. * File objects now manage their internal string buffer differently, increasing @@ -1910,7 +1910,7 @@ Changes to Python's build process and to the C API include: * It's now possible to define class and static methods for a C extension type by setting either the :const:`METH_CLASS` or :const:`METH_STATIC` flags in a - method's :ctype:`PyMethodDef` structure. + method's :c:type:`PyMethodDef` structure. * Python now includes a copy of the Expat XML parser's source code, removing any dependence on a system version or local installation of Expat. diff --git a/Doc/whatsnew/2.4.rst b/Doc/whatsnew/2.4.rst index fadde50..3a12a79 100644 --- a/Doc/whatsnew/2.4.rst +++ b/Doc/whatsnew/2.4.rst @@ -469,7 +469,7 @@ PEP 327: Decimal Data Type ========================== Python has always supported floating-point (FP) numbers, based on the underlying -C :ctype:`double` type, as a data type. However, while most programming +C :c:type:`double` type, as a data type. However, while most programming languages provide a floating-point type, many people (even programmers) are unaware that floating-point numbers don't represent certain decimal fractions accurately. The new :class:`Decimal` type can represent these fractions @@ -498,7 +498,7 @@ mantissa is multiplied by 4 (2 to the power of the exponent 2); 1.25 \* 4 equals 5. Modern systems usually provide floating-point support that conforms to a -standard called IEEE 754. C's :ctype:`double` type is usually implemented as a +standard called IEEE 754. C's :c:type:`double` type is usually implemented as a 64-bit IEEE 754 number, which uses 52 bits of space for the mantissa. This means that numbers can only be specified to 52 bits of precision. If you're trying to represent numbers whose expansion repeats endlessly, the expansion is @@ -736,7 +736,7 @@ display conventions that are localized to a particular country or language. However, the module was careful to not change the numeric locale because various functions in Python's implementation required that the numeric locale remain set to the ``'C'`` locale. Often this was because the code was using the C -library's :cfunc:`atof` function. +library's :c:func:`atof` function. Not setting the numeric locale caused trouble for extensions that used third- party C libraries, however, because they wouldn't have the correct locale set. @@ -746,11 +746,11 @@ numbers in the current locale. The solution described in the PEP is to add three new functions to the Python API that perform ASCII-only conversions, ignoring the locale setting: -* :cfunc:`PyOS_ascii_strtod(str, ptr)` and :cfunc:`PyOS_ascii_atof(str, ptr)` - both convert a string to a C :ctype:`double`. +* :c:func:`PyOS_ascii_strtod(str, ptr)` and :c:func:`PyOS_ascii_atof(str, ptr)` + both convert a string to a C :c:type:`double`. -* :cfunc:`PyOS_ascii_formatd(buffer, buf_len, format, d)` converts a - :ctype:`double` to an ASCII string. +* :c:func:`PyOS_ascii_formatd(buffer, buf_len, format, d)` converts a + :c:type:`double` to an ASCII string. The code for these functions came from the GLib library (http://library.gnome.org/devel/glib/stable/), whose developers kindly @@ -938,7 +938,7 @@ Optimizations * The machinery for growing and shrinking lists was optimized for speed and for space efficiency. Appending and popping from lists now runs faster due to more efficient code paths and less frequent use of the underlying system - :cfunc:`realloc`. List comprehensions also benefit. :meth:`list.extend` was + :c:func:`realloc`. List comprehensions also benefit. :meth:`list.extend` was also optimized and no longer converts its argument into a temporary list before extending the base list. (Contributed by Raymond Hettinger.) @@ -1445,34 +1445,34 @@ Build and C API Changes Some of the changes to Python's build process and to the C API are: * Three new convenience macros were added for common return values from - extension functions: :cmacro:`Py_RETURN_NONE`, :cmacro:`Py_RETURN_TRUE`, and - :cmacro:`Py_RETURN_FALSE`. (Contributed by Brett Cannon.) + extension functions: :c:macro:`Py_RETURN_NONE`, :c:macro:`Py_RETURN_TRUE`, and + :c:macro:`Py_RETURN_FALSE`. (Contributed by Brett Cannon.) -* Another new macro, :cmacro:`Py_CLEAR(obj)`, decreases the reference count of +* Another new macro, :c:macro:`Py_CLEAR(obj)`, decreases the reference count of *obj* and sets *obj* to the null pointer. (Contributed by Jim Fulton.) -* A new function, :cfunc:`PyTuple_Pack(N, obj1, obj2, ..., objN)`, constructs +* A new function, :c:func:`PyTuple_Pack(N, obj1, obj2, ..., objN)`, constructs tuples from a variable length argument list of Python objects. (Contributed by Raymond Hettinger.) -* A new function, :cfunc:`PyDict_Contains(d, k)`, implements fast dictionary +* A new function, :c:func:`PyDict_Contains(d, k)`, implements fast dictionary lookups without masking exceptions raised during the look-up process. (Contributed by Raymond Hettinger.) -* The :cmacro:`Py_IS_NAN(X)` macro returns 1 if its float or double argument +* The :c:macro:`Py_IS_NAN(X)` macro returns 1 if its float or double argument *X* is a NaN. (Contributed by Tim Peters.) * C code can avoid unnecessary locking by using the new - :cfunc:`PyEval_ThreadsInitialized` function to tell if any thread operations + :c:func:`PyEval_ThreadsInitialized` function to tell if any thread operations have been performed. If this function returns false, no lock operations are needed. (Contributed by Nick Coghlan.) -* A new function, :cfunc:`PyArg_VaParseTupleAndKeywords`, is the same as - :cfunc:`PyArg_ParseTupleAndKeywords` but takes a :ctype:`va_list` instead of a +* A new function, :c:func:`PyArg_VaParseTupleAndKeywords`, is the same as + :c:func:`PyArg_ParseTupleAndKeywords` but takes a :c:type:`va_list` instead of a number of arguments. (Contributed by Greg Chapman.) * A new method flag, :const:`METH_COEXISTS`, allows a function defined in slots - to co-exist with a :ctype:`PyCFunction` having the same name. This can halve + to co-exist with a :c:type:`PyCFunction` having the same name. This can halve the access time for a method such as :meth:`set.__contains__`. (Contributed by Raymond Hettinger.) @@ -1486,8 +1486,8 @@ Some of the changes to Python's build process and to the C API are: though that processor architecture doesn't call that register "the TSC register". (Contributed by Jeremy Hylton.) -* The :ctype:`tracebackobject` type has been renamed to - :ctype:`PyTracebackObject`. +* The :c:type:`tracebackobject` type has been renamed to + :c:type:`PyTracebackObject`. .. ====================================================================== diff --git a/Doc/whatsnew/2.5.rst b/Doc/whatsnew/2.5.rst index c7f7d58..79d8ad2 100644 --- a/Doc/whatsnew/2.5.rst +++ b/Doc/whatsnew/2.5.rst @@ -870,31 +870,31 @@ to be able to remove the string-exception feature in a few releases. PEP 353: Using ssize_t as the index type ======================================== -A wide-ranging change to Python's C API, using a new :ctype:`Py_ssize_t` type -definition instead of :ctype:`int`, will permit the interpreter to handle more +A wide-ranging change to Python's C API, using a new :c:type:`Py_ssize_t` type +definition instead of :c:type:`int`, will permit the interpreter to handle more data on 64-bit platforms. This change doesn't affect Python's capacity on 32-bit platforms. -Various pieces of the Python interpreter used C's :ctype:`int` type to store +Various pieces of the Python interpreter used C's :c:type:`int` type to store sizes or counts; for example, the number of items in a list or tuple were stored -in an :ctype:`int`. The C compilers for most 64-bit platforms still define -:ctype:`int` as a 32-bit type, so that meant that lists could only hold up to +in an :c:type:`int`. The C compilers for most 64-bit platforms still define +:c:type:`int` as a 32-bit type, so that meant that lists could only hold up to ``2**31 - 1`` = 2147483647 items. (There are actually a few different programming models that 64-bit C compilers can use -- see http://www.unix.org/version2/whatsnew/lp64_wp.html for a discussion -- but the -most commonly available model leaves :ctype:`int` as 32 bits.) +most commonly available model leaves :c:type:`int` as 32 bits.) A limit of 2147483647 items doesn't really matter on a 32-bit platform because you'll run out of memory before hitting the length limit. Each list item requires space for a pointer, which is 4 bytes, plus space for a -:ctype:`PyObject` representing the item. 2147483647\*4 is already more bytes +:c:type:`PyObject` representing the item. 2147483647\*4 is already more bytes than a 32-bit address space can contain. It's possible to address that much memory on a 64-bit platform, however. The pointers for a list that size would only require 16 GiB of space, so it's not unreasonable that Python programmers might construct lists that large. Therefore, the Python interpreter had to be changed to use some type other than -:ctype:`int`, and this will be a 64-bit type on 64-bit platforms. The change +:c:type:`int`, and this will be a 64-bit type on 64-bit platforms. The change will cause incompatibilities on 64-bit machines, so it was deemed worth making the transition now, while the number of 64-bit users is still relatively small. (In 5 or 10 years, we may *all* be on 64-bit machines, and the transition would @@ -902,15 +902,15 @@ be more painful then.) This change most strongly affects authors of C extension modules. Python strings and container types such as lists and tuples now use -:ctype:`Py_ssize_t` to store their size. Functions such as -:cfunc:`PyList_Size` now return :ctype:`Py_ssize_t`. Code in extension modules -may therefore need to have some variables changed to :ctype:`Py_ssize_t`. +:c:type:`Py_ssize_t` to store their size. Functions such as +:c:func:`PyList_Size` now return :c:type:`Py_ssize_t`. Code in extension modules +may therefore need to have some variables changed to :c:type:`Py_ssize_t`. -The :cfunc:`PyArg_ParseTuple` and :cfunc:`Py_BuildValue` functions have a new -conversion code, ``n``, for :ctype:`Py_ssize_t`. :cfunc:`PyArg_ParseTuple`'s -``s#`` and ``t#`` still output :ctype:`int` by default, but you can define the -macro :cmacro:`PY_SSIZE_T_CLEAN` before including :file:`Python.h` to make -them return :ctype:`Py_ssize_t`. +The :c:func:`PyArg_ParseTuple` and :c:func:`Py_BuildValue` functions have a new +conversion code, ``n``, for :c:type:`Py_ssize_t`. :c:func:`PyArg_ParseTuple`'s +``s#`` and ``t#`` still output :c:type:`int` by default, but you can define the +macro :c:macro:`PY_SSIZE_T_CLEAN` before including :file:`Python.h` to make +them return :c:type:`Py_ssize_t`. :pep:`353` has a section on conversion guidelines that extension authors should read to learn about supporting 64-bit platforms. @@ -954,8 +954,8 @@ interpreter will check that the type returned is correct, and raises a :exc:`TypeError` if this requirement isn't met. A corresponding :attr:`nb_index` slot was added to the C-level -:ctype:`PyNumberMethods` structure to let C extensions implement this protocol. -:cfunc:`PyNumber_Index(obj)` can be used in extension code to call the +:c:type:`PyNumberMethods` structure to let C extensions implement this protocol. +:c:func:`PyNumber_Index(obj)` can be used in extension code to call the :meth:`__index__` function and retrieve its result. @@ -1179,7 +1179,7 @@ marked in the following list. (Contributed by Bob Ippolito at the NeedForSpeed sprint.) * The :mod:`re` module got a 1 or 2% speedup by switching to Python's allocator - functions instead of the system's :cfunc:`malloc` and :cfunc:`free`. + functions instead of the system's :c:func:`malloc` and :c:func:`free`. (Contributed by Jack Diederich at the NeedForSpeed sprint.) * The code generator's peephole optimizer now performs simple constant folding @@ -1203,7 +1203,7 @@ marked in the following list. Sean Reifschneider at the NeedForSpeed sprint.) * Importing now caches the paths tried, recording whether they exist or not so - that the interpreter makes fewer :cfunc:`open` and :cfunc:`stat` calls on + that the interpreter makes fewer :c:func:`open` and :c:func:`stat` calls on startup. (Contributed by Martin von Löwis and Georg Brandl.) .. Patch 921466 @@ -1568,7 +1568,7 @@ complete list of changes, or look through the SVN logs for all the details. reporting ``('CPython', 'trunk', '45313:45315')``. This information is also available to C extensions via the - :cfunc:`Py_GetBuildInfo` function that returns a string of build information + :c:func:`Py_GetBuildInfo` function that returns a string of build information like this: ``"trunk:45355:45356M, Apr 13 2006, 07:42:19"``. (Contributed by Barry Warsaw.) @@ -1690,7 +1690,7 @@ attributes of the :class:`CDLL` object. :: result = libc.printf("Line of output\n") Type constructors for the various C types are provided: :func:`c_int`, -:func:`c_float`, :func:`c_double`, :func:`c_char_p` (equivalent to :ctype:`char +:func:`c_float`, :func:`c_double`, :func:`c_char_p` (equivalent to :c:type:`char \*`), and so forth. Unlike Python's types, the C versions are all mutable; you can assign to their :attr:`value` attribute to change the wrapped value. Python integers and strings will be automatically converted to the corresponding C @@ -1720,7 +1720,7 @@ attribute of the function object to change this:: ``ctypes.pythonapi`` object. This object does *not* release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code. There's a :class:`py_object()` type -constructor that will create a :ctype:`PyObject \*` pointer. A simple usage:: +constructor that will create a :c:type:`PyObject \*` pointer. A simple usage:: import ctypes @@ -2087,8 +2087,8 @@ Changes to Python's build process and to the C API include: http://scan.coverity.com for the statistics. * The largest change to the C API came from :pep:`353`, which modifies the - interpreter to use a :ctype:`Py_ssize_t` type definition instead of - :ctype:`int`. See the earlier section :ref:`pep-353` for a discussion of this + interpreter to use a :c:type:`Py_ssize_t` type definition instead of + :c:type:`int`. See the earlier section :ref:`pep-353` for a discussion of this change. * The design of the bytecode compiler has changed a great deal, no longer @@ -2113,10 +2113,10 @@ Changes to Python's build process and to the C API include: discusses the design. To start learning about the code, read the definition of the various AST nodes in :file:`Parser/Python.asdl`. A Python script reads this file and generates a set of C structure definitions in - :file:`Include/Python-ast.h`. The :cfunc:`PyParser_ASTFromString` and - :cfunc:`PyParser_ASTFromFile`, defined in :file:`Include/pythonrun.h`, take + :file:`Include/Python-ast.h`. The :c:func:`PyParser_ASTFromString` and + :c:func:`PyParser_ASTFromFile`, defined in :file:`Include/pythonrun.h`, take Python source as input and return the root of an AST representing the contents. - This AST can then be turned into a code object by :cfunc:`PyAST_Compile`. For + This AST can then be turned into a code object by :c:func:`PyAST_Compile`. For more information, read the source code, and then ask questions on python-dev. The AST code was developed under Jeremy Hylton's management, and implemented by @@ -2138,55 +2138,55 @@ Changes to Python's build process and to the C API include: Note that this change means extension modules must be more careful when allocating memory. Python's API has many different functions for allocating - memory that are grouped into families. For example, :cfunc:`PyMem_Malloc`, - :cfunc:`PyMem_Realloc`, and :cfunc:`PyMem_Free` are one family that allocates - raw memory, while :cfunc:`PyObject_Malloc`, :cfunc:`PyObject_Realloc`, and - :cfunc:`PyObject_Free` are another family that's supposed to be used for + memory that are grouped into families. For example, :c:func:`PyMem_Malloc`, + :c:func:`PyMem_Realloc`, and :c:func:`PyMem_Free` are one family that allocates + raw memory, while :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc`, and + :c:func:`PyObject_Free` are another family that's supposed to be used for creating Python objects. Previously these different families all reduced to the platform's - :cfunc:`malloc` and :cfunc:`free` functions. This meant it didn't matter if - you got things wrong and allocated memory with the :cfunc:`PyMem` function but - freed it with the :cfunc:`PyObject` function. With 2.5's changes to obmalloc, + :c:func:`malloc` and :c:func:`free` functions. This meant it didn't matter if + you got things wrong and allocated memory with the :c:func:`PyMem` function but + freed it with the :c:func:`PyObject` function. With 2.5's changes to obmalloc, these families now do different things and mismatches will probably result in a segfault. You should carefully test your C extension modules with Python 2.5. -* The built-in set types now have an official C API. Call :cfunc:`PySet_New` - and :cfunc:`PyFrozenSet_New` to create a new set, :cfunc:`PySet_Add` and - :cfunc:`PySet_Discard` to add and remove elements, and :cfunc:`PySet_Contains` - and :cfunc:`PySet_Size` to examine the set's state. (Contributed by Raymond +* The built-in set types now have an official C API. Call :c:func:`PySet_New` + and :c:func:`PyFrozenSet_New` to create a new set, :c:func:`PySet_Add` and + :c:func:`PySet_Discard` to add and remove elements, and :c:func:`PySet_Contains` + and :c:func:`PySet_Size` to examine the set's state. (Contributed by Raymond Hettinger.) * C code can now obtain information about the exact revision of the Python - interpreter by calling the :cfunc:`Py_GetBuildInfo` function that returns a + interpreter by calling the :c:func:`Py_GetBuildInfo` function that returns a string of build information like this: ``"trunk:45355:45356M, Apr 13 2006, 07:42:19"``. (Contributed by Barry Warsaw.) * Two new macros can be used to indicate C functions that are local to the current file so that a faster calling convention can be used. - :cfunc:`Py_LOCAL(type)` declares the function as returning a value of the + :c:func:`Py_LOCAL(type)` declares the function as returning a value of the specified *type* and uses a fast-calling qualifier. - :cfunc:`Py_LOCAL_INLINE(type)` does the same thing and also requests the - function be inlined. If :cfunc:`PY_LOCAL_AGGRESSIVE` is defined before + :c:func:`Py_LOCAL_INLINE(type)` does the same thing and also requests the + function be inlined. If :c:func:`PY_LOCAL_AGGRESSIVE` is defined before :file:`python.h` is included, a set of more aggressive optimizations are enabled for the module; you should benchmark the results to find out if these optimizations actually make the code faster. (Contributed by Fredrik Lundh at the NeedForSpeed sprint.) -* :cfunc:`PyErr_NewException(name, base, dict)` can now accept a tuple of base +* :c:func:`PyErr_NewException(name, base, dict)` can now accept a tuple of base classes as its *base* argument. (Contributed by Georg Brandl.) -* The :cfunc:`PyErr_Warn` function for issuing warnings is now deprecated in - favour of :cfunc:`PyErr_WarnEx(category, message, stacklevel)` which lets you +* The :c:func:`PyErr_Warn` function for issuing warnings is now deprecated in + favour of :c:func:`PyErr_WarnEx(category, message, stacklevel)` which lets you specify the number of stack frames separating this function and the caller. A - *stacklevel* of 1 is the function calling :cfunc:`PyErr_WarnEx`, 2 is the + *stacklevel* of 1 is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that, and so forth. (Added by Neal Norwitz.) * The CPython interpreter is still written in C, but the code can now be compiled with a C++ compiler without errors. (Implemented by Anthony Baxter, Martin von Löwis, Skip Montanaro.) -* The :cfunc:`PyRange_New` function was removed. It was never documented, never +* The :c:func:`PyRange_New` function was removed. It was never documented, never used in the core code, and had dangerously lax error checking. In the unlikely case that your extensions were using it, you can replace it by something like the following:: @@ -2203,7 +2203,7 @@ Port-Specific Changes --------------------- * MacOS X (10.3 and higher): dynamic loading of modules now uses the - :cfunc:`dlopen` function instead of MacOS-specific functions. + :c:func:`dlopen` function instead of MacOS-specific functions. * MacOS X: an :option:`--enable-universalsdk` switch was added to the :program:`configure` script that compiles the interpreter as a universal binary @@ -2259,15 +2259,15 @@ code: Setting :attr:`rpc_paths` to ``None`` or an empty tuple disables this path checking. -* C API: Many functions now use :ctype:`Py_ssize_t` instead of :ctype:`int` to +* C API: Many functions now use :c:type:`Py_ssize_t` instead of :c:type:`int` to allow processing more data on 64-bit machines. Extension code may need to make the same change to avoid warnings and to support 64-bit machines. See the earlier section :ref:`pep-353` for a discussion of this change. * C API: The obmalloc changes mean that you must be careful to not mix usage - of the :cfunc:`PyMem_\*` and :cfunc:`PyObject_\*` families of functions. Memory - allocated with one family's :cfunc:`\*_Malloc` must be freed with the - corresponding family's :cfunc:`\*_Free` function. + of the :c:func:`PyMem_\*` and :c:func:`PyObject_\*` families of functions. Memory + allocated with one family's :c:func:`\*_Malloc` must be freed with the + corresponding family's :c:func:`\*_Free` function. .. ====================================================================== diff --git a/Doc/whatsnew/2.6.rst b/Doc/whatsnew/2.6.rst index fa237ca..be2c6ff 100644 --- a/Doc/whatsnew/2.6.rst +++ b/Doc/whatsnew/2.6.rst @@ -123,7 +123,7 @@ about features that will be removed in Python 3.0. You can run code with this switch to see how much work will be necessary to port code to 3.0. The value of this switch is available to Python code as the boolean variable :data:`sys.py3kwarning`, -and to C extension code as :cdata:`Py_Py3kWarningFlag`. +and to C extension code as :c:data:`Py_Py3kWarningFlag`. .. seealso:: @@ -979,10 +979,10 @@ can be used to include Unicode characters:: print len(s) # 12 Unicode characters At the C level, Python 3.0 will rename the existing 8-bit -string type, called :ctype:`PyStringObject` in Python 2.x, -to :ctype:`PyBytesObject`. Python 2.6 uses ``#define`` -to support using the names :cfunc:`PyBytesObject`, -:cfunc:`PyBytes_Check`, :cfunc:`PyBytes_FromStringAndSize`, +string type, called :c:type:`PyStringObject` in Python 2.x, +to :c:type:`PyBytesObject`. Python 2.6 uses ``#define`` +to support using the names :c:func:`PyBytesObject`, +:c:func:`PyBytes_Check`, :c:func:`PyBytes_FromStringAndSize`, and all the other functions and macros used with strings. Instances of the :class:`bytes` type are immutable just @@ -1014,8 +1014,8 @@ and some of the methods of lists, such as :meth:`append`, bytearray(b'ABCde') There's also a corresponding C API, with -:cfunc:`PyByteArray_FromObject`, -:cfunc:`PyByteArray_FromStringAndSize`, +:c:func:`PyByteArray_FromObject`, +:c:func:`PyByteArray_FromStringAndSize`, and various other functions. .. seealso:: @@ -1134,7 +1134,7 @@ indicate that the external caller is done. .. XXX PyObject_GetBuffer not documented in c-api -The *flags* argument to :cfunc:`PyObject_GetBuffer` specifies +The *flags* argument to :c:func:`PyObject_GetBuffer` specifies constraints upon the memory returned. Some examples are: * :const:`PyBUF_WRITABLE` indicates that the memory must be writable. @@ -1145,7 +1145,7 @@ constraints upon the memory returned. Some examples are: requests a C-contiguous (last dimension varies the fastest) or Fortran-contiguous (first dimension varies the fastest) array layout. -Two new argument codes for :cfunc:`PyArg_ParseTuple`, +Two new argument codes for :c:func:`PyArg_ParseTuple`, ``s*`` and ``z*``, return locked buffer objects for a parameter. .. seealso:: @@ -1639,7 +1639,7 @@ Some smaller changes made to the core Python language are: :meth:`__hash__` method inherited from a parent class, so assigning ``None`` was implemented as an override. At the C level, extensions can set ``tp_hash`` to - :cfunc:`PyObject_HashNotImplemented`. + :c:func:`PyObject_HashNotImplemented`. (Fixed by Nick Coghlan and Amaury Forgeot d'Arc; :issue:`2235`.) * The :exc:`GeneratorExit` exception now subclasses @@ -1709,7 +1709,7 @@ Optimizations By default, this change is only applied to types that are included with the Python core. Extension modules may not necessarily be compatible with this cache, - so they must explicitly add :cmacro:`Py_TPFLAGS_HAVE_VERSION_TAG` + so they must explicitly add :c:macro:`Py_TPFLAGS_HAVE_VERSION_TAG` to the module's ``tp_flags`` field to enable the method cache. (To be compatible with the method cache, the extension module's code must not directly access and modify the ``tp_dict`` member of @@ -2288,7 +2288,7 @@ changes, or look through the Subversion logs for all the details. (Contributed by Raymond Hettinger; :issue:`1861`.) * The :mod:`select` module now has wrapper functions - for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls. + for the Linux :c:func:`epoll` and BSD :c:func:`kqueue` system calls. :meth:`modify` method was added to the existing :class:`poll` objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor or file object and an event mask, modifying the recorded event mask @@ -2321,13 +2321,13 @@ changes, or look through the Subversion logs for all the details. Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor to be used; when a signal is received, a byte is written to that file descriptor. There's also a C-level function, - :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor. + :c:func:`PySignal_SetWakeupFd`, for setting the descriptor. Event loops will use this by opening a pipe to create two descriptors, one for reading and one for writing. The writable descriptor will be passed to :func:`set_wakeup_fd`, and the readable descriptor will be added to the list of descriptors monitored by the event loop via - :cfunc:`select` or :cfunc:`poll`. + :c:func:`select` or :c:func:`poll`. On receiving a signal, a byte will be written and the main event loop will be woken up, avoiding the need to poll. @@ -2388,7 +2388,7 @@ changes, or look through the Subversion logs for all the details. has been updated from version 2.3.2 in Python 2.5 to version 2.4.1. -* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type, +* The :mod:`struct` module now supports the C99 :c:type:`_Bool` type, using the format character ``'?'``. (Contributed by David Remahl.) @@ -2396,7 +2396,7 @@ changes, or look through the Subversion logs for all the details. now have :meth:`terminate`, :meth:`kill`, and :meth:`send_signal` methods. On Windows, :meth:`send_signal` only supports the :const:`SIGTERM` signal, and all these methods are aliases for the Win32 API function - :cfunc:`TerminateProcess`. + :c:func:`TerminateProcess`. (Contributed by Christian Heimes.) * A new variable in the :mod:`sys` module, :attr:`float_info`, is an @@ -2981,7 +2981,7 @@ Changes to Python's build process and to the C API include: * Python now must be compiled with C89 compilers (after 19 years!). This means that the Python source tree has dropped its - own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which + own implementations of :c:func:`memmove` and :c:func:`strerror`, which are in the C89 standard library. * Python 2.6 can be built with Microsoft Visual Studio 2008 (version @@ -3003,7 +3003,7 @@ Changes to Python's build process and to the C API include: * The new buffer interface, previously described in `the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__, - adds :cfunc:`PyObject_GetBuffer` and :cfunc:`PyBuffer_Release`, + adds :c:func:`PyObject_GetBuffer` and :c:func:`PyBuffer_Release`, as well as a few other functions. * Python's use of the C stdio library is now thread-safe, or at least @@ -3011,27 +3011,27 @@ Changes to Python's build process and to the C API include: bug occurred if one thread closed a file object while another thread was reading from or writing to the object. In 2.6 file objects have a reference count, manipulated by the - :cfunc:`PyFile_IncUseCount` and :cfunc:`PyFile_DecUseCount` + :c:func:`PyFile_IncUseCount` and :c:func:`PyFile_DecUseCount` functions. File objects can't be closed unless the reference count - is zero. :cfunc:`PyFile_IncUseCount` should be called while the GIL + is zero. :c:func:`PyFile_IncUseCount` should be called while the GIL is still held, before carrying out an I/O operation using the - ``FILE *`` pointer, and :cfunc:`PyFile_DecUseCount` should be called + ``FILE *`` pointer, and :c:func:`PyFile_DecUseCount` should be called immediately after the GIL is re-acquired. (Contributed by Antoine Pitrou and Gregory P. Smith.) * Importing modules simultaneously in two different threads no longer deadlocks; it will now raise an :exc:`ImportError`. A new API - function, :cfunc:`PyImport_ImportModuleNoBlock`, will look for a + function, :c:func:`PyImport_ImportModuleNoBlock`, will look for a module in ``sys.modules`` first, then try to import it after acquiring an import lock. If the import lock is held by another thread, an :exc:`ImportError` is raised. (Contributed by Christian Heimes.) * Several functions return information about the platform's - floating-point support. :cfunc:`PyFloat_GetMax` returns + floating-point support. :c:func:`PyFloat_GetMax` returns the maximum representable floating point value, - and :cfunc:`PyFloat_GetMin` returns the minimum - positive value. :cfunc:`PyFloat_GetInfo` returns an object + and :c:func:`PyFloat_GetMin` returns the minimum + positive value. :c:func:`PyFloat_GetInfo` returns an object containing more information from the :file:`float.h` file, such as ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"`` (smallest difference between 1.0 and the next largest value @@ -3039,7 +3039,7 @@ Changes to Python's build process and to the C API include: (Contributed by Christian Heimes; :issue:`1534`.) * C functions and methods that use - :cfunc:`PyComplex_AsCComplex` will now accept arguments that + :c:func:`PyComplex_AsCComplex` will now accept arguments that have a :meth:`__complex__` method. In particular, the functions in the :mod:`cmath` module will now accept objects with this method. This is a backport of a Python 3.0 change. @@ -3053,15 +3053,15 @@ Changes to Python's build process and to the C API include: * Many C extensions define their own little macro for adding integers and strings to the module's dictionary in the ``init*`` function. Python 2.6 finally defines standard macros - for adding values to a module, :cmacro:`PyModule_AddStringMacro` - and :cmacro:`PyModule_AddIntMacro()`. (Contributed by + for adding values to a module, :c:macro:`PyModule_AddStringMacro` + and :c:macro:`PyModule_AddIntMacro()`. (Contributed by Christian Heimes.) * Some macros were renamed in both 3.0 and 2.6 to make it clearer that they are macros, - not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`, - :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and - :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`. + not functions. :c:macro:`Py_Size()` became :c:macro:`Py_SIZE()`, + :c:macro:`Py_Type()` became :c:macro:`Py_TYPE()`, and + :c:macro:`Py_Refcnt()` became :c:macro:`Py_REFCNT()`. The mixed-case macros are still available in Python 2.6 for backward compatibility. (:issue:`1629`) @@ -3119,7 +3119,7 @@ Port-Specific Changes: Windows * The :mod:`socket` module's socket objects now have an :meth:`ioctl` method that provides a limited interface to the - :cfunc:`WSAIoctl` system interface. + :c:func:`WSAIoctl` system interface. * The :mod:`_winreg` module now has a function, :func:`ExpandEnvironmentStrings`, @@ -3265,13 +3265,13 @@ that may require changes to your code: the implementation now explicitly checks for this case and raises an :exc:`ImportError`. -* C API: the :cfunc:`PyImport_Import` and :cfunc:`PyImport_ImportModule` +* C API: the :c:func:`PyImport_Import` and :c:func:`PyImport_ImportModule` functions now default to absolute imports, not relative imports. This will affect C extensions that import other modules. * C API: extension data types that shouldn't be hashable should define their ``tp_hash`` slot to - :cfunc:`PyObject_HashNotImplemented`. + :c:func:`PyObject_HashNotImplemented`. * The :mod:`socket` module exception :exc:`socket.error` now inherits from :exc:`IOError`. Previously it wasn't a subclass of diff --git a/Doc/whatsnew/2.7.rst b/Doc/whatsnew/2.7.rst index b2725c9..d5ac782 100644 --- a/Doc/whatsnew/2.7.rst +++ b/Doc/whatsnew/2.7.rst @@ -149,8 +149,8 @@ A partial list of 3.1 features that were backported to 2.7: ``float(repr(x))`` recovers ``x``. * Float-to-string and string-to-float conversions are correctly rounded. The :func:`round` function is also now correctly rounded. -* The :ctype:`PyCapsule` type, used to provide a C API for extension modules. -* The :cfunc:`PyLong_AsLongAndOverflow` C API function. +* The :c:type:`PyCapsule` type, used to provide a C API for extension modules. +* The :c:func:`PyLong_AsLongAndOverflow` C API function. Other new Python3-mode warnings include: @@ -313,7 +313,7 @@ added as a more powerful replacement for the This means Python now supports three different modules for parsing command-line arguments: :mod:`getopt`, :mod:`optparse`, and :mod:`argparse`. The :mod:`getopt` module closely resembles the C -library's :cfunc:`getopt` function, so it remains useful if you're writing a +library's :c:func:`getopt` function, so it remains useful if you're writing a Python prototype that will eventually be rewritten in C. :mod:`optparse` becomes redundant, but there are no plans to remove it because there are many scripts still using it, and there's no @@ -1484,7 +1484,7 @@ changes, or look through the Subversion logs for all the details. * The :mod:`ssl` module's :class:`ssl.SSLSocket` objects now support the buffer API, which fixed a test suite failure (fix by Antoine Pitrou; :issue:`7133`) and automatically set - OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error + OpenSSL's :c:macro:`SSL_MODE_AUTO_RETRY`, which will prevent an error code being returned from :meth:`recv` operations that trigger an SSL renegotiation (fix by Antoine Pitrou; :issue:`8222`). @@ -2053,49 +2053,49 @@ Changes to Python's build process and to the C API include: debugged doesn't hold the GIL; the macro now acquires it before printing. (Contributed by Victor Stinner; :issue:`3632`.) -* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any +* :c:func:`Py_AddPendingCall` is now thread-safe, letting any worker thread submit notifications to the main Python thread. This is particularly useful for asynchronous IO operations. (Contributed by Kristján Valur Jónsson; :issue:`4293`.) -* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object; +* New function: :c:func:`PyCode_NewEmpty` creates an empty code object; only the filename, function name, and first line number are required. This is useful for extension modules that are attempting to construct a more useful traceback stack. Previously such - extensions needed to call :cfunc:`PyCode_New`, which had many + extensions needed to call :c:func:`PyCode_New`, which had many more arguments. (Added by Jeffrey Yasskin.) -* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new - exception class, just as the existing :cfunc:`PyErr_NewException` does, +* New function: :c:func:`PyErr_NewExceptionWithDoc` creates a new + exception class, just as the existing :c:func:`PyErr_NewException` does, but takes an extra ``char *`` argument containing the docstring for the new exception class. (Added by 'lekma' on the Python bug tracker; :issue:`7033`.) -* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object +* New function: :c:func:`PyFrame_GetLineNumber` takes a frame object and returns the line number that the frame is currently executing. Previously code would need to get the index of the bytecode instruction currently executing, and then look up the line number corresponding to that address. (Added by Jeffrey Yasskin.) -* New functions: :cfunc:`PyLong_AsLongAndOverflow` and - :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long - integer as a C :ctype:`long` or :ctype:`long long`. +* New functions: :c:func:`PyLong_AsLongAndOverflow` and + :c:func:`PyLong_AsLongLongAndOverflow` approximates a Python long + integer as a C :c:type:`long` or :c:type:`long long`. If the number is too large to fit into the output type, an *overflow* flag is set and returned to the caller. (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.) * New function: stemming from the rewrite of string-to-float conversion, - a new :cfunc:`PyOS_string_to_double` function was added. The old - :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions + a new :c:func:`PyOS_string_to_double` function was added. The old + :c:func:`PyOS_ascii_strtod` and :c:func:`PyOS_ascii_atof` functions are now deprecated. -* New function: :cfunc:`PySys_SetArgvEx` sets the value of +* New function: :c:func:`PySys_SetArgvEx` sets the value of ``sys.argv`` and can optionally update ``sys.path`` to include the directory containing the script named by ``sys.argv[0]`` depending on the value of an *updatepath* parameter. This function was added to close a security hole for applications - that embed Python. The old function, :cfunc:`PySys_SetArgv`, would + that embed Python. The old function, :c:func:`PySys_SetArgv`, would always update ``sys.path``, and sometimes it would add the current directory. This meant that, if you ran an application embedding Python in a directory controlled by someone else, attackers could @@ -2103,8 +2103,8 @@ Changes to Python's build process and to the C API include: :file:`os.py`) that your application would then import and run. If you maintain a C/C++ application that embeds Python, check - whether you're calling :cfunc:`PySys_SetArgv` and carefully consider - whether the application should be using :cfunc:`PySys_SetArgvEx` + whether you're calling :c:func:`PySys_SetArgv` and carefully consider + whether the application should be using :c:func:`PySys_SetArgvEx` with *updatepath* set to false. Security issue reported as `CVE-2008-5983 @@ -2112,14 +2112,14 @@ Changes to Python's build process and to the C API include: discussed in :issue:`5753`, and fixed by Antoine Pitrou. * New macros: the Python header files now define the following macros: - :cmacro:`Py_ISALNUM`, - :cmacro:`Py_ISALPHA`, - :cmacro:`Py_ISDIGIT`, - :cmacro:`Py_ISLOWER`, - :cmacro:`Py_ISSPACE`, - :cmacro:`Py_ISUPPER`, - :cmacro:`Py_ISXDIGIT`, - and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`. + :c:macro:`Py_ISALNUM`, + :c:macro:`Py_ISALPHA`, + :c:macro:`Py_ISDIGIT`, + :c:macro:`Py_ISLOWER`, + :c:macro:`Py_ISSPACE`, + :c:macro:`Py_ISUPPER`, + :c:macro:`Py_ISXDIGIT`, + and :c:macro:`Py_TOLOWER`, :c:macro:`Py_TOUPPER`. All of these functions are analogous to the C standard macros for classifying characters, but ignore the current locale setting, because in @@ -2129,15 +2129,15 @@ Changes to Python's build process and to the C API include: .. XXX these macros don't seem to be described in the c-api docs. -* Removed function: :cmacro:`PyEval_CallObject` is now only available +* Removed function: :c:macro:`PyEval_CallObject` is now only available as a macro. A function version was being kept around to preserve ABI linking compatibility, but that was in 1997; it can certainly be deleted by now. (Removed by Antoine Pitrou; :issue:`8276`.) -* New format codes: the :cfunc:`PyFormat_FromString`, - :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` functions now +* New format codes: the :c:func:`PyFormat_FromString`, + :c:func:`PyFormat_FromStringV`, and :c:func:`PyErr_Format` functions now accept ``%lld`` and ``%llu`` format codes for displaying - C's :ctype:`long long` types. + C's :c:type:`long long` types. (Contributed by Mark Dickinson; :issue:`7228`.) * The complicated interaction between threads and process forking has @@ -2153,17 +2153,17 @@ Changes to Python's build process and to the C API include: Python 2.7 acquires the import lock before performing an :func:`os.fork`, and will also clean up any locks created using the :mod:`threading` module. C extension modules that have internal - locks, or that call :cfunc:`fork()` themselves, will not benefit + locks, or that call :c:func:`fork()` themselves, will not benefit from this clean-up. (Fixed by Thomas Wouters; :issue:`1590864`.) -* The :cfunc:`Py_Finalize` function now calls the internal +* The :c:func:`Py_Finalize` function now calls the internal :func:`threading._shutdown` function; this prevents some exceptions from being raised when an interpreter shuts down. (Patch by Adam Olsen; :issue:`1722344`.) -* When using the :ctype:`PyMemberDef` structure to define attributes +* When using the :c:type:`PyMemberDef` structure to define attributes of a type, Python will no longer let you try to delete or set a :const:`T_STRING_INPLACE` attribute. @@ -2190,7 +2190,7 @@ Changes to Python's build process and to the C API include: :issue:`6491`.) * The :program:`configure` script now checks for floating-point rounding bugs - on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING` + on certain 32-bit Intel chips and defines a :c:macro:`X87_DOUBLE_ROUNDING` preprocessor definition. No code currently uses this definition, but it's available if anyone wishes to use it. (Added by Mark Dickinson; :issue:`2937`.) @@ -2211,7 +2211,7 @@ Changes to Python's build process and to the C API include: Capsules ------------------- -Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a +Python 3.1 adds a new C datatype, :c:type:`PyCapsule`, for providing a C API to an extension module. A capsule is essentially the holder of a C ``void *`` pointer, and is made available as a module attribute; for example, the :mod:`socket` module's API is exposed as ``socket.CAPI``, @@ -2221,10 +2221,10 @@ object, and then get the ``void *`` pointer, which will usually point to an array of pointers to the module's various API functions. There is an existing data type already used for this, -:ctype:`PyCObject`, but it doesn't provide type safety. Evil code +:c:type:`PyCObject`, but it doesn't provide type safety. Evil code written in pure Python could cause a segmentation fault by taking a -:ctype:`PyCObject` from module A and somehow substituting it for the -:ctype:`PyCObject` in module B. Capsules know their own name, +:c:type:`PyCObject` from module A and somehow substituting it for the +:c:type:`PyCObject` in module B. Capsules know their own name, and getting the pointer requires providing the name:: void *vtable; @@ -2237,15 +2237,15 @@ and getting the pointer requires providing the name:: vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI"); You are assured that ``vtable`` points to whatever you're expecting. -If a different capsule was passed in, :cfunc:`PyCapsule_IsValid` would +If a different capsule was passed in, :c:func:`PyCapsule_IsValid` would detect the mismatched name and return false. Refer to :ref:`using-capsules` for more information on using these objects. Python 2.7 now uses capsules internally to provide various -extension-module APIs, but the :cfunc:`PyCObject_AsVoidPtr` was +extension-module APIs, but the :c:func:`PyCObject_AsVoidPtr` was modified to handle capsules, preserving compile-time compatibility -with the :ctype:`CObject` interface. Use of -:cfunc:`PyCObject_AsVoidPtr` will signal a +with the :c:type:`CObject` interface. Use of +:c:func:`PyCObject_AsVoidPtr` will signal a :exc:`PendingDeprecationWarning`, which is silent by default. Implemented in Python 3.1 and backported to 2.7 by Larry Hastings; @@ -2272,7 +2272,7 @@ Port-Specific Changes: Windows tested and documented. (Implemented by Brian Curtin: :issue:`7347`.) -* The new :cfunc:`_beginthreadex` API is used to start threads, and +* The new :c:func:`_beginthreadex` API is used to start threads, and the native thread-local storage functions are now used. (Contributed by Kristján Valur Jónsson; :issue:`3582`.) @@ -2280,7 +2280,7 @@ Port-Specific Changes: Windows can be the constants :const:`CTRL_C_EVENT`, :const:`CTRL_BREAK_EVENT`, or any integer. The first two constants will send Control-C and Control-Break keystroke events to - subprocesses; any other value will use the :cfunc:`TerminateProcess` + subprocesses; any other value will use the :c:func:`TerminateProcess` API. (Contributed by Miki Tebeka; :issue:`1220212`.) * The :func:`os.listdir` function now correctly fails @@ -2453,17 +2453,17 @@ For C extensions: family of functions will now raise a :exc:`TypeError` exception instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`). -* Use the new :cfunc:`PyOS_string_to_double` function instead of the old - :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions, +* Use the new :c:func:`PyOS_string_to_double` function instead of the old + :c:func:`PyOS_ascii_strtod` and :c:func:`PyOS_ascii_atof` functions, which are now deprecated. For applications that embed Python: -* The :cfunc:`PySys_SetArgvEx` function was added, letting +* The :c:func:`PySys_SetArgvEx` function was added, letting applications close a security hole when the existing - :cfunc:`PySys_SetArgv` function was used. Check whether you're - calling :cfunc:`PySys_SetArgv` and carefully consider whether the - application should be using :cfunc:`PySys_SetArgvEx` with + :c:func:`PySys_SetArgv` function was used. Check whether you're + calling :c:func:`PySys_SetArgv` and carefully consider whether the + application should be using :c:func:`PySys_SetArgvEx` with *updatepath* set to false. .. ====================================================================== diff --git a/Doc/whatsnew/3.0.rst b/Doc/whatsnew/3.0.rst index afec5fc..b7f7233 100644 --- a/Doc/whatsnew/3.0.rst +++ b/Doc/whatsnew/3.0.rst @@ -850,21 +850,21 @@ to the C API. * :pep:`3121`: Extension Module Initialization & Finalization. -* :pep:`3123`: Making :cmacro:`PyObject_HEAD` conform to standard C. +* :pep:`3123`: Making :c:macro:`PyObject_HEAD` conform to standard C. * No more C API support for restricted execution. -* :cfunc:`PyNumber_Coerce`, :cfunc:`PyNumber_CoerceEx`, - :cfunc:`PyMember_Get`, and :cfunc:`PyMember_Set` C APIs are removed. +* :c:func:`PyNumber_Coerce`, :c:func:`PyNumber_CoerceEx`, + :c:func:`PyMember_Get`, and :c:func:`PyMember_Set` C APIs are removed. -* New C API :cfunc:`PyImport_ImportModuleNoBlock`, works like - :cfunc:`PyImport_ImportModule` but won't block on the import lock +* New C API :c:func:`PyImport_ImportModuleNoBlock`, works like + :c:func:`PyImport_ImportModule` but won't block on the import lock (returning an error instead). * Renamed the boolean conversion C-level slot and method: ``nb_nonzero`` is now ``nb_bool``. -* Removed :cmacro:`METH_OLDARGS` and :cmacro:`WITH_CYCLE_GC` from the C API. +* Removed :c:macro:`METH_OLDARGS` and :c:macro:`WITH_CYCLE_GC` from the C API. .. ====================================================================== diff --git a/Doc/whatsnew/3.1.rst b/Doc/whatsnew/3.1.rst index cebb829..64ae1c1 100644 --- a/Doc/whatsnew/3.1.rst +++ b/Doc/whatsnew/3.1.rst @@ -497,21 +497,21 @@ Changes to Python's build process and to the C API include: (Contributed by Mark Dickinson; :issue:`4258`.) -* The :cfunc:`PyLong_AsUnsignedLongLong()` function now handles a negative +* The :c:func:`PyLong_AsUnsignedLongLong()` function now handles a negative *pylong* by raising :exc:`OverflowError` instead of :exc:`TypeError`. (Contributed by Mark Dickinson and Lisandro Dalcrin; :issue:`5175`.) -* Deprecated :cfunc:`PyNumber_Int`. Use :cfunc:`PyNumber_Long` instead. +* Deprecated :c:func:`PyNumber_Int`. Use :c:func:`PyNumber_Long` instead. (Contributed by Mark Dickinson; :issue:`4910`.) -* Added a new :cfunc:`PyOS_string_to_double` function to replace the - deprecated functions :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof`. +* Added a new :c:func:`PyOS_string_to_double` function to replace the + deprecated functions :c:func:`PyOS_ascii_strtod` and :c:func:`PyOS_ascii_atof`. (Contributed by Mark Dickinson; :issue:`5914`.) -* Added :ctype:`PyCapsule` as a replacement for the :ctype:`PyCObject` API. +* Added :c:type:`PyCapsule` as a replacement for the :c:type:`PyCObject` API. The principal difference is that the new type has a well defined interface for passing typing safety information and a less complicated signature for calling a destructor. The old type had a problematic API and is now diff --git a/Doc/whatsnew/3.2.rst b/Doc/whatsnew/3.2.rst index 533d038..084e105 100644 --- a/Doc/whatsnew/3.2.rst +++ b/Doc/whatsnew/3.2.rst @@ -577,8 +577,8 @@ require changes to your code: * "t#" format has been removed: use "s#" or "s*" instead * "w" and "w#" formats has been removed: use "w*" instead -* The :ctype:`PyCObject` type, deprecated in 3.1, has been removed. To wrap - opaque C pointers in Python objects, the :ctype:`PyCapsule` API should be used +* The :c:type:`PyCObject` type, deprecated in 3.1, has been removed. To wrap + opaque C pointers in Python objects, the :c:type:`PyCapsule` API should be used instead; the new type has a well-defined interface for passing typing safety information and a less complicated signature for calling a destructor. |