update to new C roles and directives

This commit is contained in:
Sandro Tosi 2012-01-14 16:42:02 +01:00
parent bbd41d0874
commit 98ed08f24e
122 changed files with 2837 additions and 2837 deletions

View File

@ -13,7 +13,7 @@ sequence types). When used on object types for which they do not apply, they
will raise a Python exception.
It is not possible to use these functions on objects that are not properly
initialized, such as a list object that has been created by :cfunc:`PyList_New`,
initialized, such as a list object that has been created by :c:func:`PyList_New`,
but whose items have not been set to some non-\ ``NULL`` value yet.
.. toctree::

View File

@ -6,20 +6,20 @@ 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)
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: void _PyObject_Del(PyObject *op)
.. c:function:: void _PyObject_Del(PyObject *op)
.. 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
@ -28,17 +28,17 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
@ -47,7 +47,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
@ -59,20 +59,20 @@ Allocating Objects on the Heap
improving the memory management efficiency.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
.. cfunction:: PyObject* Py_InitModule(char *name, PyMethodDef *methods)
.. c:function:: PyObject* Py_InitModule(char *name, PyMethodDef *methods)
Create a new module object based on a name and table of functions,
returning the new module object.
@ -82,7 +82,7 @@ Allocating Objects on the Heap
*methods* argument.
.. cfunction:: PyObject* Py_InitModule3(char *name, PyMethodDef *methods, char *doc)
.. c:function:: PyObject* Py_InitModule3(char *name, PyMethodDef *methods, char *doc)
Create a new module object based on a name and table of functions,
returning the new module object. If *doc* is non-*NULL*, it will be used
@ -93,7 +93,7 @@ Allocating Objects on the Heap
*methods* argument.
.. cfunction:: PyObject* Py_InitModule4(char *name, PyMethodDef *methods, char *doc, PyObject *self, int apiver)
.. c:function:: PyObject* Py_InitModule4(char *name, PyMethodDef *methods, char *doc, PyObject *self, int apiver)
Create a new module object based on a name and table of functions,
returning the new module object. If *doc* is non-*NULL*, it will be used
@ -107,7 +107,7 @@ Allocating Objects on the Heap
.. note::
Most uses of this function should probably be using the
:cfunc:`Py_InitModule3` instead; only use this if you are sure you need
:c:func:`Py_InitModule3` instead; only use this if you are sure you need
it.
.. versionchanged:: 2.3
@ -115,7 +115,7 @@ Allocating Objects on the Heap
*methods* argument.
.. cvar:: PyObject _Py_NoneStruct
.. c:var:: PyObject _Py_NoneStruct
Object which is visible in Python as ``None``. This should only be
accessed using the ``Py_None`` macro, which evaluates to a pointer to this

View File

@ -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
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.
@ -38,7 +38,7 @@ area. Also, you won't have to release any memory yourself, except with the
raised. Unicode objects are converted to C strings using the default
encoding. If this conversion fails, a :exc:`UnicodeError` is raised.
``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int (or :ctype:`Py_ssize_t`, see below)]
``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int (or :c:type:`Py_ssize_t`, see below)]
This variant on ``s`` stores into two C variables, the first one a pointer
to a character string, the second one its length. In this case the Python
string may contain embedded null bytes. Unicode objects pass back a
@ -47,8 +47,8 @@ area. Also, you won't have to release any memory yourself, except with the
a reference to the raw internal data representation.
Starting with Python 2.5 the type of the length argument can be controlled
by defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before including
:file:`Python.h`. If the macro is defined, length is a :ctype:`Py_ssize_t`
by defining the macro :c:macro:`PY_SSIZE_T_CLEAN` before including
:file:`Python.h`. If the macro is defined, length is a :c:type:`Py_ssize_t`
rather than an int.
``s*`` (string, Unicode, or any buffer compatible object) [Py_buffer]
@ -76,14 +76,14 @@ area. Also, you won't have to release any memory yourself, except with the
Convert a Python Unicode object to a C pointer to a NUL-terminated buffer
of 16-bit Unicode (UTF-16) data. As with ``s``, there is no need to
provide storage for the Unicode data buffer; a pointer to the existing
Unicode data is stored into the :ctype:`Py_UNICODE` pointer variable whose
Unicode data is stored into the :c:type:`Py_UNICODE` pointer variable whose
address you pass.
``u#`` (Unicode) [Py_UNICODE \*, int]
This variant on ``u`` stores into two C variables, the first one a pointer
to a Unicode data buffer, the second one its length. Non-Unicode objects
are handled by interpreting their read-buffer pointer as pointer to a
:ctype:`Py_UNICODE` array.
:c:type:`Py_UNICODE` array.
``es`` (string, Unicode or character buffer compatible object) [const char \*encoding, char \*\*buffer]
This variant on ``s`` is used for encoding Unicode and objects convertible
@ -91,18 +91,18 @@ area. Also, you won't have to release any memory yourself, except with the
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
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 the default 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
The 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
: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 free the allocated buffer after use.
:c:func:`PyMem_Free` to free the allocated buffer after use.
``et`` (string, Unicode or character buffer compatible object) [const char \*encoding, char \*\*buffer]
Same as ``es`` except that 8-bit string objects are passed through without
@ -115,10 +115,10 @@ area. Also, you won't have to release any memory yourself, except with the
allows input data which contains NUL 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
a :c:type:`const char\*` which points to the name of an encoding as a
NUL-terminated string, or *NULL*, in which case the default encoding is
used. An exception is raised if the named encoding is not known to Python.
The second argument must be a :ctype:`char\*\*`; the value of the pointer
The 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
@ -129,11 +129,11 @@ area. Also, you won't have to release any memory yourself, except with the
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
responsible for calling :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
: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.
@ -148,71 +148,71 @@ area. Also, you won't have to release any memory yourself, except with the
``b`` (integer) [unsigned char]
Convert a nonnegative Python integer to an unsigned tiny int, stored in a C
:ctype:`unsigned char`.
:c:type:`unsigned char`.
``B`` (integer) [unsigned char]
Convert a Python integer to a tiny int without overflow checking, stored in
a C :ctype:`unsigned char`.
a C :c:type:`unsigned char`.
.. versionadded:: 2.3
``h`` (integer) [short int]
Convert a Python integer to a C :ctype:`short int`.
Convert a Python integer to a C :c:type:`short int`.
``H`` (integer) [unsigned short int]
Convert a Python integer to a C :ctype:`unsigned short int`, without
Convert a Python integer to a C :c:type:`unsigned short int`, without
overflow checking.
.. versionadded:: 2.3
``i`` (integer) [int]
Convert a Python integer to a plain C :ctype:`int`.
Convert a Python integer to a plain C :c:type:`int`.
``I`` (integer) [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.
.. versionadded:: 2.3
``l`` (integer) [long int]
Convert a Python integer to a C :ctype:`long int`.
Convert a Python integer to a C :c:type:`long int`.
``k`` (integer) [unsigned long]
Convert a Python integer or long integer to a C :ctype:`unsigned long`
Convert a Python integer or long integer to a C :c:type:`unsigned long`
without overflow checking.
.. versionadded:: 2.3
``L`` (integer) [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`
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`` (integer) [unsigned PY_LONG_LONG]
Convert a Python integer or long integer to a C :ctype:`unsigned long long`
Convert a Python integer or long 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
support :c:type:`unsigned long long` (or :c:type:`unsigned _int64` on
Windows).
.. versionadded:: 2.3
``n`` (integer) [Py_ssize_t]
Convert a Python integer or long integer to a C :ctype:`Py_ssize_t`.
Convert a Python integer or long integer to a C :c:type:`Py_ssize_t`.
.. versionadded:: 2.5
``c`` (string of length 1) [char]
Convert a Python character, represented as a string of length 1, to a C
:ctype:`char`.
:c:type:`char`.
``f`` (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`` (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`` (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.
``O`` (object) [PyObject \*]
Store a Python object (without any conversion) in a C object pointer. The
@ -222,20 +222,20 @@ area. Also, you won't have to release any memory yourself, except with the
``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\*`)
the 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 \*`.
address of a C 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\*`
: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
@ -244,17 +244,17 @@ area. Also, you won't have to release any memory yourself, except with the
``S`` (string) [PyStringObject \*]
Like ``O`` but requires that the Python object is a string object. Raises
:exc:`TypeError` if the object is not a string object. The C variable may
also be declared as :ctype:`PyObject\*`.
also be declared as :c:type:`PyObject\*`.
``U`` (Unicode string) [PyUnicodeObject \*]
Like ``O`` but requires that the Python object is a Unicode object. Raises
:exc:`TypeError` if the object is not a Unicode object. The C variable may
also be declared as :ctype:`PyObject\*`.
also be declared as :c:type:`PyObject\*`.
``t#`` (read-only character buffer) [char \*, int]
Like ``s#``, but accepts any object which implements the read-only buffer
interface. The :ctype:`char\*` variable is set to point to the first byte
of the buffer, and the :ctype:`int` is set to the length of the buffer.
interface. The :c:type:`char\*` variable is set to point to the first byte
of the buffer, and the :c:type:`int` is set to the length of the buffer.
Only single-segment buffer objects are accepted; :exc:`TypeError` is raised
for all others.
@ -266,8 +266,8 @@ area. Also, you won't have to release any memory yourself, except with the
``w#`` (read-write character buffer) [char \*, Py_ssize_t]
Like ``s#``, but accepts any object which implements the read-write buffer
interface. The :ctype:`char \*` variable is set to point to the first byte
of the buffer, and the :ctype:`Py_ssize_t` is set to the length of the
interface. The :c:type:`char \*` variable is set to point to the first byte
of the buffer, and the :c:type:`Py_ssize_t` is set to the length of the
buffer. Only single-segment buffer objects are accepted; :exc:`TypeError`
is raised for all others.
@ -302,13 +302,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
specified, :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).
exception that :c:func:`PyArg_ParseTuple` raises).
``;``
The list of format units ends here; the string after the semicolon is used
@ -325,40 +325,40 @@ format units above, where these parameters are used as input values; they
should match 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
format must be exhausted. On success, the :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
When the :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.
.. 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
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_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
@ -369,7 +369,7 @@ and the following format units are left untouched.
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
@ -378,7 +378,7 @@ and the following format units are left untouched.
should be passed as *args*; it must actually be a tuple. The length of the
tuple must be at least *min* and no more than *max*; *min* and *max* may be
equal. Additional arguments must be passed to the function, each of which
should be a pointer to a :ctype:`PyObject\*` variable; these will be filled
should be a pointer to a :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
@ -401,26 +401,26 @@ and the following format units are left untouched.
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)
.. versionadded:: 2.2
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *min* and *max*. This might
This function used an :c:type:`int` type for *min* and *max*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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.
the :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
: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
@ -430,10 +430,10 @@ and the following format units are left untouched.
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.
by :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
@ -469,62 +469,62 @@ and the following format units are left untouched.
length is ignored and ``None`` is returned.
``i`` (integer) [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`` (integer) [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`` (integer) [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`` (integer) [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`` (integer) [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`` (integer) [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`` (integer/long) [unsigned int]
Convert a C :ctype:`unsigned int` to a Python integer object or a Python
Convert a C :c:type:`unsigned int` to a Python integer object or a Python
long integer object, if it is larger than ``sys.maxint``.
``k`` (integer/long) [unsigned long]
Convert a C :ctype:`unsigned long` to a Python integer object or a
Convert a C :c:type:`unsigned long` to a Python integer object or a
Python long integer object, if it is larger than ``sys.maxint``.
``L`` (long) [PY_LONG_LONG]
Convert a C :ctype:`long long` to a Python long integer object. Only
available on platforms that support :ctype:`long long`.
Convert a C :c:type:`long long` to a Python long integer object. Only
available on platforms that support :c:type:`long long`.
``K`` (long) [unsigned PY_LONG_LONG]
Convert a C :ctype:`unsigned long long` to a Python long integer object.
Only available on platforms that support :ctype:`unsigned long long`.
Convert a C :c:type:`unsigned long long` to a Python long integer object.
Only available on platforms that support :c:type:`unsigned long long`.
``n`` (int) [Py_ssize_t]
Convert a C :ctype:`Py_ssize_t` to a Python integer or long integer.
Convert a C :c:type:`Py_ssize_t` to a Python integer or long integer.
.. versionadded:: 2.5
``c`` (string of length 1) [char]
Convert a C :ctype:`int` representing a character to a Python string of
Convert a C :c:type:`int` representing a character to a Python string of
length 1.
``d`` (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`` (float) [float]
Same as ``d``.
``D`` (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`
found an error and 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.
@ -539,7 +539,7 @@ and the following format units are left untouched.
``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 \*`) as its argument and should return a "new" Python
:c:type:`void \*`) as its argument and should return a "new" Python
object, or *NULL* if an error occurred.
``(items)`` (tuple) [*matching-items*]
@ -558,7 +558,7 @@ and the following format units are left untouched.
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.

View File

@ -11,26 +11,26 @@ 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`.
.. versionadded:: 2.3
.. 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.
@ -38,7 +38,7 @@ are available, however.
.. versionadded:: 2.4
.. cmacro:: Py_RETURN_TRUE
.. c:macro:: Py_RETURN_TRUE
Return :const:`Py_True` from a function, properly incrementing its reference
count.
@ -46,7 +46,7 @@ are available, however.
.. versionadded:: 2.4
.. 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*.

View File

@ -27,7 +27,7 @@ should be noted that array elements may be multi-byte values.
An example user of the buffer interface is the file object's :meth:`write`
method. Any object that can export a series of bytes through the buffer
interface can be written to a file. There are a number of format codes to
:cfunc:`PyArg_ParseTuple` that operate against an object's buffer interface,
:c:func:`PyArg_ParseTuple` that operate against an object's buffer interface,
returning data from the target object.
Starting from version 1.6, Python has been providing Python-level buffer
@ -47,49 +47,49 @@ The new-style Py_buffer struct
==============================
.. 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
@ -114,16 +114,16 @@ The new-style Py_buffer struct
}
.. 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
@ -136,14 +136,14 @@ 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.
.. cfunction:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
.. c:function:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
Export *obj* into a :ctype:`Py_buffer`, *view*. These arguments must
Export *obj* into a :c:type:`Py_buffer`, *view*. These arguments must
never be *NULL*. The *flags* argument is a bit field indicating what
kind of buffer the caller is prepared to deal with and therefore what
kind of buffer the exporter is allowed to return. The buffer interface
@ -156,131 +156,131 @@ Buffer related functions
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.
0 is returned on success and -1 on error.
The following table gives possible values to the *flags* arguments.
+------------------------------+---------------------------------------------------+
| Flag | Description |
+==============================+===================================================+
| :cmacro:`PyBUF_SIMPLE` | This is the default flag state. The returned |
| | buffer may or may not have writable memory. The |
| | format of the data will be assumed to be unsigned |
| | bytes. This is a "stand-alone" flag 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` | The returned buffer must be writable. If it is |
| | not writable, then raise an error. |
+------------------------------+---------------------------------------------------+
| :cmacro:`PyBUF_STRIDES` | This implies :cmacro:`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` | 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` | These flags indicate that the contiguity returned |
|:cmacro:`PyBUF_F_CONTIGUOUS` | buffer must be respectively, C-contiguous (last |
|:cmacro:`PyBUF_ANY_CONTIGUOUS`| 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 |
| | strides buffer info structure will be filled in |
| | correctly. |
| | |
+------------------------------+---------------------------------------------------+
| :cmacro:`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`. |
| | |
| | |
| | |
+------------------------------+---------------------------------------------------+
| :cmacro:`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 |
| | for what 'kind' of data is actually stored. An |
| | exporter should always be able to provide this |
| | information if requested. If format is not |
| | explicitly requested then the format must be |
| | returned as *NULL* (which means ``'B'``, or |
| | unsigned bytes) |
+------------------------------+---------------------------------------------------+
| :cmacro:`PyBUF_STRIDED` | This is equivalent to ``(PyBUF_STRIDES | |
| | PyBUF_WRITABLE)``. |
+------------------------------+---------------------------------------------------+
| :cmacro:`PyBUF_STRIDED_RO` | This is equivalent to ``(PyBUF_STRIDES)``. |
| | |
+------------------------------+---------------------------------------------------+
| :cmacro:`PyBUF_RECORDS` | This is equivalent to ``(PyBUF_STRIDES | |
| | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
+------------------------------+---------------------------------------------------+
| :cmacro:`PyBUF_RECORDS_RO` | This is equivalent to ``(PyBUF_STRIDES | |
| | PyBUF_FORMAT)``. |
+------------------------------+---------------------------------------------------+
| :cmacro:`PyBUF_FULL` | This is equivalent to ``(PyBUF_INDIRECT | |
| | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
+------------------------------+---------------------------------------------------+
| :cmacro:`PyBUF_FULL_RO` | This is equivalent to ``(PyBUF_INDIRECT | |
| | PyBUF_FORMAT)``. |
+------------------------------+---------------------------------------------------+
| :cmacro:`PyBUF_CONTIG` | This is equivalent to ``(PyBUF_ND | |
| | PyBUF_WRITABLE)``. |
+------------------------------+---------------------------------------------------+
| :cmacro:`PyBUF_CONTIG_RO` | This is equivalent to ``(PyBUF_ND)``. |
| | |
+------------------------------+---------------------------------------------------+
+-------------------------------+---------------------------------------------------+
| Flag | Description |
+===============================+===================================================+
| :c:macro:`PyBUF_SIMPLE` | This is the default flag state. The returned |
| | buffer may or may not have writable memory. The |
| | format of the data will be assumed to be unsigned |
| | bytes. This is a "stand-alone" flag 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. |
| | |
+-------------------------------+---------------------------------------------------+
| :c:macro:`PyBUF_WRITABLE` | The returned buffer must be writable. If it is |
| | not writable, then raise an error. |
+-------------------------------+---------------------------------------------------+
| :c:macro:`PyBUF_STRIDES` | 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). |
| | |
+-------------------------------+---------------------------------------------------+
| :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*. |
| | |
| | |
| | |
+-------------------------------+---------------------------------------------------+
|:c:macro:`PyBUF_C_CONTIGUOUS` | These flags indicate that the contiguity returned |
|:c:macro:`PyBUF_F_CONTIGUOUS` | buffer must be respectively, C-contiguous (last |
|:c:macro:`PyBUF_ANY_CONTIGUOUS`| dimension varies the fastest), Fortran contiguous |
| | (first dimension varies the fastest) or either |
| | one. All of these flags imply |
| | :c:macro:`PyBUF_STRIDES` and guarantee that the |
| | strides buffer info structure will be filled in |
| | correctly. |
| | |
+-------------------------------+---------------------------------------------------+
| :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 :c:macro:`PyBUF_STRIDES`. |
| | |
| | |
| | |
+-------------------------------+---------------------------------------------------+
| :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 |
| | for what 'kind' of data is actually stored. An |
| | exporter should always be able to provide this |
| | information if requested. If format is not |
| | explicitly requested then the format must be |
| | returned as *NULL* (which means ``'B'``, or |
| | unsigned bytes) |
+-------------------------------+---------------------------------------------------+
| :c:macro:`PyBUF_STRIDED` | This is equivalent to ``(PyBUF_STRIDES | |
| | PyBUF_WRITABLE)``. |
+-------------------------------+---------------------------------------------------+
| :c:macro:`PyBUF_STRIDED_RO` | This is equivalent to ``(PyBUF_STRIDES)``. |
| | |
+-------------------------------+---------------------------------------------------+
| :c:macro:`PyBUF_RECORDS` | This is equivalent to ``(PyBUF_STRIDES | |
| | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
+-------------------------------+---------------------------------------------------+
| :c:macro:`PyBUF_RECORDS_RO` | This is equivalent to ``(PyBUF_STRIDES | |
| | PyBUF_FORMAT)``. |
+-------------------------------+---------------------------------------------------+
| :c:macro:`PyBUF_FULL` | This is equivalent to ``(PyBUF_INDIRECT | |
| | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
+-------------------------------+---------------------------------------------------+
| :c:macro:`PyBUF_FULL_RO` | This is equivalent to ``(PyBUF_INDIRECT | |
| | PyBUF_FORMAT)``. |
+-------------------------------+---------------------------------------------------+
| :c:macro:`PyBUF_CONTIG` | This is equivalent to ``(PyBUF_ND | |
| | PyBUF_WRITABLE)``. |
+-------------------------------+---------------------------------------------------+
| :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 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
@ -295,13 +295,13 @@ MemoryView objects
A :class:`memoryview` object exposes the new C level buffer interface as a
Python object which can then be passed around like any other object.
.. cfunction:: PyObject *PyMemoryView_FromObject(PyObject *obj)
.. c:function:: PyObject *PyMemoryView_FromObject(PyObject *obj)
Create a memoryview object from an object that defines the new buffer
interface.
.. cfunction:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view)
.. c:function:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view)
Create a memoryview object wrapping the given buffer-info structure *view*.
The memoryview object then owns the buffer, which means you shouldn't
@ -309,7 +309,7 @@ Python object which can then be passed around like any other object.
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
@ -318,13 +318,13 @@ Python object which can then be passed around like 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-info structure wrapped by the given
object. The object **must** be a memoryview instance; this macro doesn't
@ -337,7 +337,7 @@ Old-style buffer objects
.. index:: single: PyBufferProcs
More information on the old buffer interface is provided in the section
:ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`.
:ref:`buffer-structs`, under the description for :c:type:`PyBufferProcs`.
A "buffer object" is defined in the :file:`bufferobject.h` header (included by
:file:`Python.h`). These objects look very similar to string objects at the
@ -356,36 +356,36 @@ system library, or it could be used to pass around structured data in its
native, in-memory format.
.. ctype:: PyBufferObject
.. c:type:: PyBufferObject
This subtype of :ctype:`PyObject` represents a buffer object.
This subtype of :c:type:`PyObject` represents a buffer object.
.. cvar:: PyTypeObject PyBuffer_Type
.. c:var:: PyTypeObject PyBuffer_Type
.. index:: single: BufferType (in module types)
The instance of :ctype:`PyTypeObject` which represents the Python buffer type;
The instance of :c:type:`PyTypeObject` which represents the Python buffer type;
it is the same object as ``buffer`` and ``types.BufferType`` in the Python
layer. .
.. cvar:: int Py_END_OF_BUFFER
.. c:var:: int Py_END_OF_BUFFER
This constant may be passed as the *size* parameter to
:cfunc:`PyBuffer_FromObject` or :cfunc:`PyBuffer_FromReadWriteObject`. It
indicates that the new :ctype:`PyBufferObject` should refer to *base*
:c:func:`PyBuffer_FromObject` or :c:func:`PyBuffer_FromReadWriteObject`. It
indicates that the new :c:type:`PyBufferObject` should refer to *base*
object from the specified *offset* to the end of its exported buffer.
Using this enables the caller to avoid querying the *base* object for its
length.
.. cfunction:: int PyBuffer_Check(PyObject *p)
.. c:function:: int PyBuffer_Check(PyObject *p)
Return true if the argument has type :cdata:`PyBuffer_Type`.
Return true if the argument has type :c:data:`PyBuffer_Type`.
.. cfunction:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
.. c:function:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
Return a new read-only buffer object. This raises :exc:`TypeError` if
*base* doesn't support the read-only buffer protocol or doesn't provide
@ -397,24 +397,24 @@ native, in-memory format.
length of the *base* object's exported buffer data.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *offset* and *size*. This
This function used an :c:type:`int` type for *offset* and *size*. This
might require changes in your code for properly supporting 64-bit
systems.
.. cfunction:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
.. c:function:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
Return a new writable buffer object. Parameters and exceptions are similar
to those for :cfunc:`PyBuffer_FromObject`. If the *base* object does not
to those for :c:func:`PyBuffer_FromObject`. If the *base* object does not
export the writeable buffer protocol, then :exc:`TypeError` is raised.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *offset* and *size*. This
This function used an :c:type:`int` type for *offset* and *size*. This
might require changes in your code for properly supporting 64-bit
systems.
.. cfunction:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size)
.. c:function:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size)
Return a new read-only buffer object that reads from a specified location
in memory, with a specified size. The caller is responsible for ensuring
@ -424,27 +424,27 @@ native, in-memory format.
*size* parameter; :exc:`ValueError` will be raised in that case.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size)
.. c:function:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size)
Similar to :cfunc:`PyBuffer_FromMemory`, but the returned buffer is
Similar to :c:func:`PyBuffer_FromMemory`, but the returned buffer is
writable.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: PyObject* PyBuffer_New(Py_ssize_t size)
.. c:function:: PyObject* PyBuffer_New(Py_ssize_t size)
Return a new writable buffer object that maintains its own memory buffer of
*size* bytes. :exc:`ValueError` is returned if *size* is not zero or
positive. Note that the memory buffer (as returned by
:cfunc:`PyObject_AsWriteBuffer`) is not specifically aligned.
:c:func:`PyObject_AsWriteBuffer`) is not specifically aligned.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.

View File

@ -10,26 +10,26 @@ Byte Array Objects
.. versionadded:: 2.6
.. 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.
@ -38,7 +38,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.
@ -46,29 +46,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*.
@ -77,11 +77,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`.

View File

@ -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*.

View File

@ -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

View File

@ -12,12 +12,12 @@ will go away in Python 3. When creating new types for extension modules, you
will want to work with type objects (section :ref:`typeobjects`).
.. ctype:: PyClassObject
.. c:type:: PyClassObject
The C structure of the objects used to describe built-in classes.
.. cvar:: PyObject* PyClass_Type
.. c:var:: PyObject* PyClass_Type
.. index:: single: ClassType (in module types)
@ -25,13 +25,13 @@ will want to work with type objects (section :ref:`typeobjects`).
``types.ClassType`` in the Python layer.
.. cfunction:: int PyClass_Check(PyObject *o)
.. c:function:: int PyClass_Check(PyObject *o)
Return true if the object *o* is a class object, including instances of types
derived from the standard class object. Return false in all other cases.
.. cfunction:: int PyClass_IsSubclass(PyObject *klass, PyObject *base)
.. c:function:: int PyClass_IsSubclass(PyObject *klass, PyObject *base)
Return true if *klass* is a subclass of *base*. Return false in all other cases.
@ -41,23 +41,23 @@ will want to work with type objects (section :ref:`typeobjects`).
There are very few functions specific to instance objects.
.. cvar:: PyTypeObject PyInstance_Type
.. c:var:: PyTypeObject PyInstance_Type
Type object for class instances.
.. cfunction:: int PyInstance_Check(PyObject *obj)
.. c:function:: int PyInstance_Check(PyObject *obj)
Return true if *obj* is an instance.
.. cfunction:: PyObject* PyInstance_New(PyObject *class, PyObject *arg, PyObject *kw)
.. c:function:: PyObject* PyInstance_New(PyObject *class, PyObject *arg, PyObject *kw)
Create a new instance of a specific class. The parameters *arg* and *kw* are
used as the positional and keyword parameters to the object's constructor.
.. cfunction:: PyObject* PyInstance_NewRaw(PyObject *class, PyObject *dict)
.. c:function:: PyObject* PyInstance_NewRaw(PyObject *class, PyObject *dict)
Create a new instance of a specific class without calling its constructor.
*class* is the class of new object. The *dict* parameter will be used as the

View File

@ -13,47 +13,47 @@ CObjects
The CObject API is deprecated as of Python 2.7. Please switch to the new
:ref:`capsules` API.
.. ctype:: PyCObject
.. c:type:: PyCObject
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.
.. cfunction:: int PyCObject_Check(PyObject *p)
.. c:function:: int PyCObject_Check(PyObject *p)
Return true if its argument is a :ctype:`PyCObject`.
Return true if its argument is a :c:type:`PyCObject`.
.. cfunction:: PyObject* PyCObject_FromVoidPtr(void* cobj, void (*destr)(void *))
.. c:function:: PyObject* PyCObject_FromVoidPtr(void* cobj, void (*destr)(void *))
Create a :ctype:`PyCObject` from the ``void *`` *cobj*. The *destr* function
Create a :c:type:`PyCObject` from the ``void *`` *cobj*. The *destr* function
will be called when the object is reclaimed, unless it is *NULL*.
.. cfunction:: PyObject* PyCObject_FromVoidPtrAndDesc(void* cobj, void* desc, void (*destr)(void *, void *))
.. c:function:: PyObject* PyCObject_FromVoidPtrAndDesc(void* cobj, void* desc, void (*destr)(void *, void *))
Create a :ctype:`PyCObject` from the :ctype:`void \*` *cobj*. The *destr*
Create a :c:type:`PyCObject` from the :c:type:`void \*` *cobj*. The *destr*
function will be called when the object is reclaimed. The *desc* argument can
be used to pass extra callback data for the destructor function.
.. cfunction:: void* PyCObject_AsVoidPtr(PyObject* self)
.. c:function:: void* PyCObject_AsVoidPtr(PyObject* self)
Return the object :ctype:`void \*` that the :ctype:`PyCObject` *self* was
Return the object :c:type:`void \*` that the :c:type:`PyCObject` *self* was
created with.
.. cfunction:: void* PyCObject_GetDesc(PyObject* self)
.. c:function:: void* PyCObject_GetDesc(PyObject* self)
Return the description :ctype:`void \*` that the :ctype:`PyCObject` *self* was
Return the description :c:type:`void \*` that the :c:type:`PyCObject` *self* was
created with.
.. cfunction:: int PyCObject_SetVoidPtr(PyObject* self, void* cobj)
.. c:function:: int PyCObject_SetVoidPtr(PyObject* self, void* cobj)
Set the void pointer inside *self* to *cobj*. The :ctype:`PyCObject` must not
Set the void pointer inside *self* to *cobj*. The :c:type:`PyCObject` must not
have an associated destructor. Return true on success, false on failure.

View File

@ -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

View File

@ -3,19 +3,19 @@
Codec registry and support functions
====================================
.. cfunction:: int PyCodec_Register(PyObject *search_function)
.. c:function:: int PyCodec_Register(PyObject *search_function)
Register a new codec search function.
As side effect, this tries to load the :mod:`encodings` package, if not yet
done, to make sure that it is always first in the list of search functions.
.. cfunction:: int PyCodec_KnownEncoding(const char *encoding)
.. c:function:: int PyCodec_KnownEncoding(const char *encoding)
Return ``1`` or ``0`` depending on whether there is a registered codec for
the given *encoding*.
.. cfunction:: PyObject* PyCodec_Encode(PyObject *object, const char *encoding, const char *errors)
.. c:function:: PyObject* PyCodec_Encode(PyObject *object, const char *encoding, const char *errors)
Generic codec based encoding API.
@ -24,7 +24,7 @@ Codec registry and support functions
be *NULL* to use the default method defined for the codec. Raises a
:exc:`LookupError` if no encoder can be found.
.. cfunction:: PyObject* PyCodec_Decode(PyObject *object, const char *encoding, const char *errors)
.. c:function:: PyObject* PyCodec_Decode(PyObject *object, const char *encoding, const char *errors)
Generic codec based decoding API.
@ -42,27 +42,27 @@ lower-case characters, which makes encodings looked up through this mechanism
effectively case-insensitive. If no codec is found, a :exc:`KeyError` is set
and *NULL* returned.
.. cfunction:: PyObject* PyCodec_Encoder(const char *encoding)
.. c:function:: PyObject* PyCodec_Encoder(const char *encoding)
Get an encoder function for the given *encoding*.
.. cfunction:: PyObject* PyCodec_Decoder(const char *encoding)
.. c:function:: PyObject* PyCodec_Decoder(const char *encoding)
Get a decoder function for the given *encoding*.
.. cfunction:: PyObject* PyCodec_IncrementalEncoder(const char *encoding, const char *errors)
.. c:function:: PyObject* PyCodec_IncrementalEncoder(const char *encoding, const char *errors)
Get an :class:`IncrementalEncoder` object for the given *encoding*.
.. cfunction:: PyObject* PyCodec_IncrementalDecoder(const char *encoding, const char *errors)
.. c:function:: PyObject* PyCodec_IncrementalDecoder(const char *encoding, const char *errors)
Get an :class:`IncrementalDecoder` object for the given *encoding*.
.. cfunction:: PyObject* PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)
.. c:function:: PyObject* PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)
Get a :class:`StreamReader` factory function for the given *encoding*.
.. cfunction:: PyObject* PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)
.. c:function:: PyObject* PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)
Get a :class:`StreamWriter` factory function for the given *encoding*.
@ -70,7 +70,7 @@ and *NULL* returned.
Registry API for Unicode encoding error handlers
------------------------------------------------
.. cfunction:: int PyCodec_RegisterError(const char *name, PyObject *error)
.. c:function:: int PyCodec_RegisterError(const char *name, PyObject *error)
Register the error handling callback function *error* under the given *name*.
This callback function will be called by a codec when it encounters
@ -89,29 +89,29 @@ Registry API for Unicode encoding error handlers
Return ``0`` on success, ``-1`` on error.
.. cfunction:: PyObject* PyCodec_LookupError(const char *name)
.. c:function:: PyObject* PyCodec_LookupError(const char *name)
Lookup the error handling callback function registered under *name*. As a
special case *NULL* can be passed, in which case the error handling callback
for "strict" will be returned.
.. cfunction:: PyObject* PyCodec_StrictErrors(PyObject *exc)
.. c:function:: PyObject* PyCodec_StrictErrors(PyObject *exc)
Raise *exc* as an exception.
.. cfunction:: PyObject* PyCodec_IgnoreErrors(PyObject *exc)
.. c:function:: PyObject* PyCodec_IgnoreErrors(PyObject *exc)
Ignore the unicode error, skipping the faulty input.
.. cfunction:: PyObject* PyCodec_ReplaceErrors(PyObject *exc)
.. c:function:: PyObject* PyCodec_ReplaceErrors(PyObject *exc)
Replace the unicode encode error with ``?`` or ``U+FFFD``.
.. cfunction:: PyObject* PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
.. c:function:: PyObject* PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
Replace the unicode encode error with XML character references.
.. cfunction:: PyObject* PyCodec_BackslashReplaceErrors(PyObject *exc)
.. c:function:: PyObject* PyCodec_BackslashReplaceErrors(PyObject *exc)
Replace the unicode encode error with backslash escapes (``\x``, ``\u`` and
``\U``).

View File

@ -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,103 +34,103 @@ 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.
If *divisor* is null, this method returns zero and sets
:cdata:`errno` to :cdata:`EDOM`.
:c:data:`errno` to :c:data:`EDOM`.
.. 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.
If *num* is null and *exp* is not a positive real number,
this method returns zero and sets :cdata:`errno` to :cdata:`EDOM`.
this method returns zero and sets :c:data:`errno` to :c:data:`EDOM`.
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`.
.. versionchanged:: 2.2
Allowed subtypes to be accepted.
.. 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`.
.. versionadded:: 2.2
.. 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*.
Upon failure, this method returns ``-1.0`` as a real value.
.. versionchanged:: 2.6

View File

@ -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::

View File

@ -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,13 +85,13 @@ The following functions provide locale-independent string to number conversions.
.. versionadded:: 2.7
.. cfunction:: double PyOS_ascii_strtod(const char *nptr, char **endptr)
.. c:function:: double PyOS_ascii_strtod(const char *nptr, char **endptr)
Convert a string to a :ctype:`double`. This function behaves like the Standard C
function :cfunc:`strtod` does in the C locale. It does this without changing the
Convert a string to a :c:type:`double`. This function behaves like the Standard C
function :c:func:`strtod` does in the C locale. It does this without changing the
current locale, since that would not be thread-safe.
:cfunc:`PyOS_ascii_strtod` should typically be used for reading configuration
:c:func:`PyOS_ascii_strtod` should typically be used for reading configuration
files or other non-user input that should be locale independent.
See the Unix man page :manpage:`strtod(2)` for details.
@ -99,14 +99,14 @@ The following functions provide locale-independent string to number conversions.
.. versionadded:: 2.4
.. deprecated:: 2.7
Use :cfunc:`PyOS_string_to_double` instead.
Use :c:func:`PyOS_string_to_double` instead.
.. cfunction:: char* PyOS_ascii_formatd(char *buffer, size_t buf_len, const char *format, double d)
.. c:function:: char* PyOS_ascii_formatd(char *buffer, size_t buf_len, const char *format, double d)
Convert a :ctype:`double` to a string using the ``'.'`` as the decimal
separator. *format* is a :cfunc:`printf`\ -style format string specifying the
Convert a :c:type:`double` to a string using the ``'.'`` as the decimal
separator. *format* is a :c:func:`printf`\ -style format string specifying the
number format. Allowed conversion characters are ``'e'``, ``'E'``, ``'f'``,
``'F'``, ``'g'`` and ``'G'``.
@ -119,9 +119,9 @@ The following functions provide locale-independent string to number conversions.
instead.
.. 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'``,
@ -139,7 +139,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
@ -148,34 +148,34 @@ 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:: 2.7
.. cfunction:: double PyOS_ascii_atof(const char *nptr)
.. c:function:: double PyOS_ascii_atof(const char *nptr)
Convert a string to a :ctype:`double` in a locale-independent way.
Convert a string to a :c:type:`double` in a locale-independent way.
See the Unix man page :manpage:`atof(2)` for details.
.. versionadded:: 2.4
.. deprecated:: 3.1
Use :cfunc:`PyOS_string_to_double` instead.
Use :c:func:`PyOS_string_to_double` instead.
.. 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.
.. versionadded:: 2.6
.. 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.
.. versionadded:: 2.6

View File

@ -8,89 +8,89 @@ 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*.
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 2.4
@ -98,14 +98,14 @@ Type-check macros:
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.
.. versionadded:: 2.4
.. 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.
@ -113,7 +113,7 @@ Macros to create objects:
.. versionadded:: 2.4
.. 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.
@ -121,7 +121,7 @@ Macros to create objects:
.. versionadded:: 2.4
.. 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
@ -131,90 +131,90 @@ Macros to create objects:
.. versionadded:: 2.4
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.
.. versionadded:: 2.4
.. 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.
.. versionadded:: 2.4
.. 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.
.. versionadded:: 2.4
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.
.. versionadded:: 2.4
.. 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.
.. versionadded:: 2.4
.. 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.
.. versionadded:: 2.4
.. 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.
.. versionadded:: 2.4
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.
.. versionadded:: 2.4
.. 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.
.. versionadded:: 2.4
.. 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.
.. versionadded:: 2.4
.. 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.
@ -223,7 +223,7 @@ and the type is not checked:
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()``.
@ -231,7 +231,7 @@ Macros for the convenience of modules implementing the DB API:
.. versionadded:: 2.4
.. 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()``.

View File

@ -9,39 +9,39 @@ Descriptor Objects
found in the dictionary of type objects.
.. cvar:: PyTypeObject PyProperty_Type
.. c:var:: PyTypeObject PyProperty_Type
The type object for the built-in descriptor types.
.. versionadded:: 2.2
.. cfunction:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
.. c:function:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
.. versionadded:: 2.2
.. cfunction:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
.. c:function:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
.. versionadded:: 2.2
.. cfunction:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
.. c:function:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
.. versionadded:: 2.2
.. cfunction:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
.. c:function:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
.. versionadded:: 2.2
.. cfunction:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
.. c:function:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
.. versionadded:: 2.3
.. 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
@ -50,6 +50,6 @@ found in the dictionary of type objects.
.. versionadded:: 2.2
.. cfunction:: PyObject* PyWrapper_New(PyObject *, PyObject *)
.. c:function:: PyObject* PyWrapper_New(PyObject *, PyObject *)
.. versionadded:: 2.2

View File

@ -8,23 +8,23 @@ 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.
@ -33,7 +33,7 @@ Dictionary Objects
Allowed subtypes to be accepted.
.. 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.
@ -41,12 +41,12 @@ Dictionary Objects
.. versionadded:: 2.4
.. 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
@ -55,12 +55,12 @@ Dictionary Objects
.. versionadded:: 2.2
.. 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``.
@ -69,74 +69,74 @@ Dictionary Objects
.. versionadded:: 2.4
.. 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*.
.. versionadded:: 1.6
.. 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: PyString_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
``PyString_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_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
@ -144,18 +144,18 @@ Dictionary Objects
``len(p)`` on a dictionary.
.. versionchanged:: 2.5
This function returned an :ctype:`int` type. This might require changes
This function returned an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. 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
@ -192,15 +192,15 @@ Dictionary Objects
}
.. versionchanged:: 2.5
This function used an :ctype:`int *` type for *ppos*. This might require
This function used an :c:type:`int *` type for *ppos*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
@ -208,7 +208,7 @@ Dictionary Objects
.. versionadded:: 2.2
.. 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.
@ -216,7 +216,7 @@ Dictionary Objects
.. versionadded:: 2.2
.. 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,

View File

@ -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
@ -41,7 +41,7 @@ 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
@ -52,35 +52,35 @@ 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
@ -88,22 +88,22 @@ 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
@ -116,7 +116,7 @@ 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
@ -131,111 +131,111 @@ 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. The *format* and subsequent
parameters help format the error message; they have the same meaning and
values as in :cfunc:`PyString_FromFormat`.
values as in :c:func:`PyString_FromFormat`.
.. 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.
.. versionadded:: 2.3
.. 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.
.. versionadded:: 2.3
.. 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
@ -243,13 +243,13 @@ is a separate error indicator for each thread.
use.
.. cfunction:: int PyErr_WarnEx(PyObject *category, char *message, int stacklevel)
.. c:function:: int PyErr_WarnEx(PyObject *category, char *message, int stacklevel)
Issue a warning message. The *category* argument is a warning category (see
below) or *NULL*; the *message* argument is a message string. *stacklevel* 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 *stacklevel* 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
@ -261,36 +261,36 @@ 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_Warn(PyObject *category, char *message)
.. c:function:: int PyErr_Warn(PyObject *category, char *message)
Issue a warning message. The *category* argument is a warning category (see
below) or *NULL*; the *message* argument is a message string. The warning will
appear to be issued from the function calling :cfunc:`PyErr_Warn`, equivalent to
calling :cfunc:`PyErr_WarnEx` with a *stacklevel* of 1.
appear to be issued from the function calling :c:func:`PyErr_Warn`, equivalent to
calling :c:func:`PyErr_WarnEx` with a *stacklevel* of 1.
Deprecated; use :cfunc:`PyErr_WarnEx` instead.
Deprecated; use :c:func:`PyErr_WarnEx` instead.
.. 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
@ -299,15 +299,15 @@ is a separate error indicator for each thread.
described there.
.. cfunction:: int PyErr_WarnPy3k(char *message, int stacklevel)
.. c:function:: int PyErr_WarnPy3k(char *message, int stacklevel)
Issue a :exc:`DeprecationWarning` with the given *message* and *stacklevel*
if the :cdata:`Py_Py3kWarningFlag` flag is enabled.
if the :c:data:`Py_Py3kWarningFlag` flag is enabled.
.. versionadded:: 2.6
.. cfunction:: int PyErr_CheckSignals()
.. c:function:: int PyErr_CheckSignals()
.. index::
module: signal
@ -324,21 +324,21 @@ 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
@ -350,13 +350,13 @@ is a separate error indicator for each thread.
.. versionadded:: 2.6
.. 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 class. The *name*
argument must be the name of the new exception, a C string of the form
``module.classname``. 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
@ -365,16 +365,16 @@ 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:: 2.7
.. 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
@ -393,33 +393,33 @@ Unicode Exception Objects
The following functions are used to create and modify Unicode exceptions from C.
.. cfunction:: PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
.. c:function:: PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
*object*, *length*, *start*, *end* and *reason*.
.. cfunction:: PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
.. c:function:: PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
Create a :class:`UnicodeEncodeError` object with the attributes *encoding*,
*object*, *length*, *start*, *end* and *reason*.
.. cfunction:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
Create a :class:`UnicodeTranslateError` object with the attributes *object*,
*length*, *start*, *end* and *reason*.
.. cfunction:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)
Return the *encoding* attribute of the given exception object.
.. cfunction:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)
Return the *object* attribute of the given exception object.
.. cfunction:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
@ -427,14 +427,14 @@ The following functions are used to create and modify Unicode exceptions from C.
*\*start*. *start* must not be *NULL*. Return ``0`` on success, ``-1`` on
failure.
.. cfunction:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
Set the *start* attribute of the given exception object to *start*. Return
``0`` on success, ``-1`` on failure.
.. cfunction:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
@ -442,20 +442,20 @@ The following functions are used to create and modify Unicode exceptions from C.
*\*end*. *end* must not be *NULL*. Return ``0`` on success, ``-1`` on
failure.
.. cfunction:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
Set the *end* attribute of the given exception object to *end*. Return ``0``
on success, ``-1`` on failure.
.. cfunction:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)
Return the *reason* attribute of the given exception object.
.. cfunction:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
@ -471,12 +471,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 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
@ -487,10 +487,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:
@ -500,70 +500,70 @@ 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), (4) |
+------------------------------------+----------------------------+----------+
| :cdata:`PyExc_Exception` | :exc:`Exception` | \(1) |
+------------------------------------+----------------------------+----------+
| :cdata:`PyExc_StandardError` | :exc:`StandardError` | \(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), (4) |
+-------------------------------------+----------------------------+----------+
| :c:data:`PyExc_Exception` | :exc:`Exception` | \(1) |
+-------------------------------------+----------------------------+----------+
| :c:data:`PyExc_StandardError` | :exc:`StandardError` | \(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

View File

@ -7,79 +7,79 @@ File Objects
.. index:: object: file
Python's built-in file objects are implemented entirely on the :ctype:`FILE\*`
Python's built-in file objects are implemented entirely on the :c:type:`FILE\*`
support from the C standard library. This is an implementation detail and may
change in future releases of Python.
.. ctype:: PyFileObject
.. c:type:: PyFileObject
This subtype of :ctype:`PyObject` represents a Python file object.
This subtype of :c:type:`PyObject` represents a Python file object.
.. cvar:: PyTypeObject PyFile_Type
.. c:var:: PyTypeObject PyFile_Type
.. index:: single: FileType (in module types)
This instance of :ctype:`PyTypeObject` represents the Python file type. This is
This instance of :c:type:`PyTypeObject` represents the Python file type. This is
exposed to Python programs as ``file`` and ``types.FileType``.
.. cfunction:: int PyFile_Check(PyObject *p)
.. c:function:: int PyFile_Check(PyObject *p)
Return true if its argument is a :ctype:`PyFileObject` or a subtype of
:ctype:`PyFileObject`.
Return true if its argument is a :c:type:`PyFileObject` or a subtype of
:c:type:`PyFileObject`.
.. versionchanged:: 2.2
Allowed subtypes to be accepted.
.. cfunction:: int PyFile_CheckExact(PyObject *p)
.. c:function:: int PyFile_CheckExact(PyObject *p)
Return true if its argument is a :ctype:`PyFileObject`, but not a subtype of
:ctype:`PyFileObject`.
Return true if its argument is a :c:type:`PyFileObject`, but not a subtype of
:c:type:`PyFileObject`.
.. versionadded:: 2.2
.. cfunction:: PyObject* PyFile_FromString(char *filename, char *mode)
.. c:function:: PyObject* PyFile_FromString(char *filename, char *mode)
.. index:: single: fopen()
On success, return a new file object that is opened on the file given by
*filename*, with a file mode given by *mode*, where *mode* has the same
semantics as the standard C routine :cfunc:`fopen`. On failure, return *NULL*.
semantics as the standard C routine :c:func:`fopen`. On failure, return *NULL*.
.. cfunction:: PyObject* PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE*))
.. c:function:: PyObject* PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE*))
Create a new :ctype:`PyFileObject` from the already-open standard C file
Create a new :c:type:`PyFileObject` from the already-open standard C file
pointer, *fp*. The function *close* will be called when the file should be
closed. Return *NULL* and close the file using *close* on failure.
*close* is optional and can be set to *NULL*.
.. cfunction:: FILE* PyFile_AsFile(PyObject \*p)
.. c:function:: FILE* PyFile_AsFile(PyObject \*p)
Return the file object associated with *p* as a :ctype:`FILE\*`.
Return the file object associated with *p* as a :c:type:`FILE\*`.
If the caller will ever use the returned :ctype:`FILE\*` object while
the :term:`GIL` is released it must also call the :cfunc:`PyFile_IncUseCount` and
:cfunc:`PyFile_DecUseCount` functions described below as appropriate.
If the caller will ever use the returned :c:type:`FILE\*` object while
the :term:`GIL` is released it must also call the :c:func:`PyFile_IncUseCount` and
:c:func:`PyFile_DecUseCount` functions described below as appropriate.
.. cfunction:: void PyFile_IncUseCount(PyFileObject \*p)
.. c:function:: void PyFile_IncUseCount(PyFileObject \*p)
Increments the PyFileObject's internal use count to indicate
that the underlying :ctype:`FILE\*` is being used.
that the underlying :c:type:`FILE\*` is being used.
This prevents Python from calling f_close() on it from another thread.
Callers of this must call :cfunc:`PyFile_DecUseCount` when they are
finished with the :ctype:`FILE\*`. Otherwise the file object will
Callers of this must call :c:func:`PyFile_DecUseCount` when they are
finished with the :c:type:`FILE\*`. Otherwise the file object will
never be closed by Python.
The :term:`GIL` must be held while calling this function.
The suggested use is to call this after :cfunc:`PyFile_AsFile` and before
The suggested use is to call this after :c:func:`PyFile_AsFile` and before
you release the GIL::
FILE *fp = PyFile_AsFile(p);
@ -94,11 +94,11 @@ change in future releases of Python.
.. versionadded:: 2.6
.. cfunction:: void PyFile_DecUseCount(PyFileObject \*p)
.. c:function:: void PyFile_DecUseCount(PyFileObject \*p)
Decrements the PyFileObject's internal unlocked_count member to
indicate that the caller is done with its own use of the :ctype:`FILE\*`.
This may only be called to undo a prior call to :cfunc:`PyFile_IncUseCount`.
indicate that the caller is done with its own use of the :c:type:`FILE\*`.
This may only be called to undo a prior call to :c:func:`PyFile_IncUseCount`.
The :term:`GIL` must be held while calling this function (see the example
above).
@ -106,7 +106,7 @@ change in future releases of Python.
.. versionadded:: 2.6
.. cfunction:: PyObject* PyFile_GetLine(PyObject *p, int n)
.. c:function:: PyObject* PyFile_GetLine(PyObject *p, int n)
.. index:: single: EOFError (built-in exception)
@ -120,20 +120,20 @@ change in future releases of Python.
raised if the end of the file is reached immediately.
.. cfunction:: PyObject* PyFile_Name(PyObject *p)
.. c:function:: PyObject* PyFile_Name(PyObject *p)
Return the name of the file specified by *p* as a string object.
.. cfunction:: void PyFile_SetBufSize(PyFileObject *p, int n)
.. c:function:: void PyFile_SetBufSize(PyFileObject *p, int n)
.. index:: single: setvbuf()
Available on systems with :cfunc:`setvbuf` only. This should only be called
Available on systems with :c:func:`setvbuf` only. This should only be called
immediately after file object creation.
.. cfunction:: int PyFile_SetEncoding(PyFileObject *p, const char *enc)
.. c:function:: int PyFile_SetEncoding(PyFileObject *p, const char *enc)
Set the file's encoding for Unicode output to *enc*. Return 1 on success and 0
on failure.
@ -141,7 +141,7 @@ change in future releases of Python.
.. versionadded:: 2.3
.. cfunction:: int PyFile_SetEncodingAndErrors(PyFileObject *p, const char *enc, *errors)
.. c:function:: int PyFile_SetEncodingAndErrors(PyFileObject *p, const char *enc, *errors)
Set the file's encoding for Unicode output to *enc*, and its error
mode to *err*. Return 1 on success and 0 on failure.
@ -149,7 +149,7 @@ change in future releases of Python.
.. versionadded:: 2.6
.. cfunction:: int PyFile_SoftSpace(PyObject *p, int newflag)
.. c:function:: int PyFile_SoftSpace(PyObject *p, int newflag)
.. index:: single: softspace (file attribute)
@ -163,7 +163,7 @@ change in future releases of Python.
but doing so should not be needed.
.. 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
@ -173,7 +173,7 @@ change in future releases of Python.
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.

View File

@ -8,64 +8,64 @@ 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`.
.. versionchanged:: 2.2
Allowed subtypes to be accepted.
.. 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`.
.. versionadded:: 2.2
.. cfunction:: PyObject* PyFloat_FromString(PyObject *str, char **pend)
.. c:function:: PyObject* PyFloat_FromString(PyObject *str, char **pend)
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. The *pend* argument is ignored. It remains only for
backward compatibility.
.. 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.
This method returns ``-1.0`` upon failure, so one should call
:cfunc:`PyErr_Occurred` to check for errors.
:c:func:`PyErr_Occurred` to check for errors.
.. 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
@ -74,21 +74,21 @@ Floating Point Objects
.. versionadded:: 2.6
.. 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`.
.. versionadded:: 2.6
.. 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`.
.. versionadded:: 2.6
.. cfunction:: int PyFloat_ClearFreeList()
.. c:function:: int PyFloat_ClearFreeList()
Clear the float free list. Return the number of items that could not
be freed.
@ -96,7 +96,7 @@ Floating Point Objects
.. versionadded:: 2.6
.. cfunction:: void PyFloat_AsString(char *buf, PyFloatObject *v)
.. c:function:: void PyFloat_AsString(char *buf, PyFloatObject *v)
Convert the argument *v* to a string, using the same rules as
:func:`str`. The length of *buf* should be at least 100.
@ -108,7 +108,7 @@ Floating Point Objects
Use :func:`PyObject_Str` or :func:`PyOS_double_to_string` instead.
.. cfunction:: void PyFloat_AsReprString(char *buf, PyFloatObject *v)
.. c:function:: void PyFloat_AsReprString(char *buf, PyFloatObject *v)
Same as PyFloat_AsString, except uses the same rules as
:func:`repr`. The length of *buf* should be at least 100.

View File

@ -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.

View File

@ -30,40 +30,40 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *newsize*. This might
This function used an :c:type:`int` type for *newsize*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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
@ -72,44 +72,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
@ -121,7 +121,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
@ -130,12 +130,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`
@ -151,15 +151,15 @@ must name its arguments exactly *visit* and *arg*:
.. versionadded:: 2.4
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.

View File

@ -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

View File

@ -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
@ -34,20 +34,20 @@ Importing Modules
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`.
.. versionadded:: 2.6
.. 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__
@ -65,11 +65,11 @@ Importing Modules
Failing imports remove incomplete module objects.
.. versionchanged:: 2.6
The function is an alias for :cfunc:`PyImport_ImportModuleLevel` with
The function is an alias for :c:func:`PyImport_ImportModuleLevel` with
-1 as level, meaning relative import.
.. 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
@ -83,7 +83,7 @@ Importing Modules
.. versionadded:: 2.5
.. cfunction:: PyObject* PyImport_Import(PyObject *name)
.. c:function:: PyObject* PyImport_Import(PyObject *name)
.. index::
module: rexec
@ -98,7 +98,7 @@ Importing Modules
Always uses absolute imports.
.. cfunction:: PyObject* PyImport_ReloadModule(PyObject *m)
.. c:function:: PyObject* PyImport_ReloadModule(PyObject *m)
.. index:: builtin: reload
@ -108,7 +108,7 @@ Importing Modules
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
@ -118,12 +118,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
@ -133,7 +133,7 @@ Importing Modules
or *NULL* with an exception set if an error occurred. Before Python 2.4, the
module could still be created in error cases. Starting with Python 2.4, *name*
is removed from :attr:`sys.modules` in error cases, and 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.
@ -142,7 +142,7 @@ Importing Modules
:cmember:`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.
@ -151,26 +151,26 @@ Importing Modules
*name* is removed from :attr:`sys.modules` in error cases.
.. 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``.
.. 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:: 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`
@ -183,41 +183,41 @@ Importing Modules
.. versionadded:: 2.6
.. 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
@ -233,30 +233,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, void (*initfunc)(void))
.. c:function:: int PyImport_AppendInittab(const char *name, void (*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::
@ -266,11 +266,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`.

View File

@ -12,7 +12,7 @@ Initializing and finalizing the interpreter
===========================================
.. cfunction:: void Py_Initialize()
.. c:function:: void Py_Initialize()
.. index::
single: Py_SetProgramName()
@ -31,40 +31,40 @@ Initializing and finalizing the interpreter
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_SetPythonHome`, :cfunc:`PyEval_InitThreads`,
:cfunc:`PyEval_ReleaseLock`, and :cfunc:`PyEval_AcquireLock`. This initializes
exception of :c:func:`Py_SetProgramName`, :c:func:`Py_SetPythonHome`, :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:`__builtin__`, :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.
.. versionadded:: 2.4
.. 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
@ -83,25 +83,25 @@ Initializing and finalizing the interpreter
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.
Process-wide parameters
=======================
.. cfunction:: void Py_SetProgramName(char *name)
.. c:function:: void Py_SetProgramName(char *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.
This is used by :cfunc:`Py_GetPath` and some other functions below to find
of the ``argv[0]`` argument to the :c:func:`main` function of the program.
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 character string in static storage whose contents will not
@ -109,20 +109,20 @@ Process-wide parameters
interpreter will change the contents of this storage.
.. cfunction:: char* Py_GetProgramName()
.. c:function:: char* 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:: char* Py_GetPrefix()
.. c:function:: char* 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
@ -131,11 +131,11 @@ Process-wide parameters
It is only useful on Unix. See also the next function.
.. cfunction:: char* Py_GetExecPrefix()
.. c:function:: char* 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`
@ -166,7 +166,7 @@ Process-wide parameters
platform.
.. cfunction:: char* Py_GetProgramFullPath()
.. c:function:: char* Py_GetProgramFullPath()
.. index::
single: Py_SetProgramName()
@ -174,19 +174,19 @@ Process-wide parameters
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:: char* Py_GetPath()
.. c:function:: char* Py_GetPath()
.. index::
triple: module; search; path
single: path (in module sys)
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
@ -198,7 +198,7 @@ Process-wide parameters
.. XXX should give the exact rules
.. 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 ::
@ -213,7 +213,7 @@ Process-wide parameters
modify its value. The value is available to Python code as ``sys.version``.
.. cfunction:: const char* Py_GetPlatform()
.. c:function:: const char* Py_GetPlatform()
.. index:: single: platform (in module sys)
@ -226,7 +226,7 @@ Process-wide parameters
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
@ -238,7 +238,7 @@ Process-wide parameters
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::
@ -252,7 +252,7 @@ Process-wide parameters
``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 ::
@ -266,7 +266,7 @@ Process-wide parameters
``sys.version``.
.. cfunction:: void PySys_SetArgvEx(int argc, char **argv, int updatepath)
.. c:function:: void PySys_SetArgvEx(int argc, char **argv, int updatepath)
.. index::
single: main()
@ -274,12 +274,12 @@ Process-wide parameters
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
@ -301,7 +301,7 @@ Process-wide parameters
On versions before 2.6.6, 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");
@ -311,12 +311,12 @@ Process-wide parameters
check w/ Guido.
.. cfunction:: void PySys_SetArgv(int argc, char **argv)
.. c:function:: void PySys_SetArgv(int argc, char **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(char *home)
.. c:function:: void Py_SetPythonHome(char *home)
Set the default "home" directory, that is, the location of the standard
Python libraries. See :envvar:`PYTHONHOME` for the meaning of the
@ -328,10 +328,10 @@ Process-wide parameters
this storage.
.. cfunction:: char* Py_GetPythonHome()
.. c:function:: 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.
@ -368,9 +368,9 @@ a file, so that other Python threads can run in the meantime.
single: PyThreadState
The Python interpreter keeps some thread-specific bookkeeping information
inside a data structure called :ctype:`PyThreadState`. There's also one
global variable pointing to the current :ctype:`PyThreadState`: it can
be retrieved using :cfunc:`PyThreadState_Get`.
inside a data structure called :c:type:`PyThreadState`. There's also one
global variable pointing to the current :c:type:`PyThreadState`: it can
be retrieved using :c:func:`PyThreadState_Get`.
Releasing the GIL from extension code
-------------------------------------
@ -394,8 +394,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. These two macros are still available when Python is compiled without
thread support (they simply have an empty expansion).
@ -445,7 +445,7 @@ storing their thread state pointer, before you can start using the Python/C
API. When you are done, you should reset the thread state pointer, release
the GIL, and finally free the thread state data structure.
The :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` functions do
The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do
all of the above automatically. The typical idiom for calling into Python
from a C thread is::
@ -459,14 +459,14 @@ from a C thread is::
/* 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
Note that the :c:func:`PyGILState_\*` functions assume there is only one global
interpreter (created automatically by :c:func:`Py_Initialize`). Python
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
@ -474,12 +474,12 @@ 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:`pthread_atfork` would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling :cfunc:`fork`
:c:func:`pthread_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.
@ -489,7 +489,7 @@ High-level API
These are the most commonly used types and functions when writing C extension
code, or when embedding the Python interpreter:
.. 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
@ -502,14 +502,14 @@ code, or when embedding the Python interpreter:
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()
@ -519,14 +519,14 @@ code, or when embedding the Python interpreter:
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
@ -539,7 +539,7 @@ code, or when embedding the Python interpreter:
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
@ -548,9 +548,9 @@ code, or when embedding the Python interpreter:
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.
@ -558,7 +558,7 @@ code, or when embedding the Python interpreter:
.. versionadded:: 2.4
.. 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
@ -567,7 +567,7 @@ code, or when embedding the Python interpreter:
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
@ -576,23 +576,23 @@ code, or when embedding the Python interpreter:
when thread support is disabled at compile time.)
.. 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
and is not released.
.. 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.
@ -600,24 +600,24 @@ code, or when embedding the Python interpreter:
The following functions use thread-local storage, and are not compatible
with sub-interpreters:
.. 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 and be able
to call arbitrary Python code. Failure is a fatal error.
@ -625,20 +625,20 @@ with sub-interpreters:
.. versionadded:: 2.3
.. 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.
.. versionadded:: 2.3
.. cfunction:: PyThreadState PyGILState_GetThisThreadState()
.. c:function:: PyThreadState PyGILState_GetThisThreadState()
Get the current thread state for this thread. May return ``NULL`` if no
GILState API has been used on the current thread. Note that the main thread
@ -652,33 +652,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.
@ -690,47 +690,47 @@ 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:: 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
@ -743,7 +743,7 @@ been created.
meant that an exception was raised.
.. 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
@ -756,18 +756,18 @@ been created.
.. versionadded:: 2.3
.. 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.
If this thread already has the lock, deadlock ensues.
:cfunc:`PyEval_RestoreThread` is a higher-level function which is always
:c:func:`PyEval_RestoreThread` is a higher-level function which is always
available (even when thread support isn't enabled or when threads have
not been initialized).
.. 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
@ -775,29 +775,29 @@ been created.
that it represents the current thread state --- if it isn't, a fatal error is
reported.
:cfunc:`PyEval_SaveThread` is a higher-level function which is always
:c:func:`PyEval_SaveThread` is a higher-level function which is always
available (even when thread support isn't enabled or when threads have
not been initialized).
.. 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.
.. warning::
This function does not change the current thread state. Please use
:cfunc:`PyEval_RestoreThread` or :cfunc:`PyEval_AcquireThread`
:c:func:`PyEval_RestoreThread` or :c:func:`PyEval_AcquireThread`
instead.
.. cfunction:: void PyEval_ReleaseLock()
.. c:function:: void PyEval_ReleaseLock()
Release the global interpreter lock. The lock must have been created earlier.
.. warning::
This function does not change the current thread state. Please use
:cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_ReleaseThread`
:c:func:`PyEval_SaveThread` or :c:func:`PyEval_ReleaseThread`
instead.
@ -808,11 +808,11 @@ While in most uses, you will only embed a single Python interpreter, there
are cases where you need to create several independent interpreters in the
same process and perhaps even in the same thread. Sub-interpreters allow
you to do that. You can switch between sub-interpreters using the
:cfunc:`PyThreadState_Swap` function. You can create and destroy them
:c:func:`PyThreadState_Swap` function. You can create and destroy them
using the following functions:
.. cfunction:: PyThreadState* Py_NewInterpreter()
.. c:function:: PyThreadState* Py_NewInterpreter()
.. index::
module: builtins
@ -854,13 +854,13 @@ using the following functions:
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)
.. cfunction:: void Py_EndInterpreter(PyThreadState *tstate)
.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
.. index:: single: Py_Finalize()
@ -869,7 +869,7 @@ using the following functions:
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.
@ -890,11 +890,11 @@ instances or classes between sub-interpreters, since import operations executed
by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
modules.
Also note that combining this functionality with :cfunc:`PyGILState_\*` APIs
Also note that combining this functionality with :c:func:`PyGILState_\*` APIs
is delicate, because these APIs assume a bijection between Python thread states
and OS-level threads, an assumption broken by the presence of sub-interpreters.
It is highly recommended that you don't switch sub-interpreters between a pair
of matching :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` calls.
of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
of Python code from non-Python created threads will probably be broken when using
sub-interpreters.
@ -916,7 +916,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:: int Py_AddPendingCall(int (*func)(void *), void *arg)
.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)
.. index:: single: Py_AddPendingCall()
@ -964,10 +964,10 @@ 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`,
@ -995,18 +995,18 @@ 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
@ -1015,37 +1015,37 @@ 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
@ -1055,13 +1055,13 @@ 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:
@ -1113,14 +1113,14 @@ 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.
.. versionadded:: 2.2
.. 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.
@ -1128,18 +1128,18 @@ These functions are only intended to be used by advanced debugging tools.
.. versionadded:: 2.2
.. 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*.
.. versionadded:: 2.2
.. 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.
.. versionadded:: 2.2

View File

@ -8,39 +8,39 @@ Plain Integer Objects
.. index:: object: integer
.. ctype:: PyIntObject
.. c:type:: PyIntObject
This subtype of :ctype:`PyObject` represents a Python integer object.
This subtype of :c:type:`PyObject` represents a Python integer object.
.. cvar:: PyTypeObject PyInt_Type
.. c:var:: PyTypeObject PyInt_Type
.. index:: single: IntType (in modules types)
This instance of :ctype:`PyTypeObject` represents the Python plain integer type.
This instance of :c:type:`PyTypeObject` represents the Python plain integer type.
This is the same object as ``int`` and ``types.IntType``.
.. cfunction:: int PyInt_Check(PyObject *o)
.. c:function:: int PyInt_Check(PyObject *o)
Return true if *o* is of type :cdata:`PyInt_Type` or a subtype of
:cdata:`PyInt_Type`.
Return true if *o* is of type :c:data:`PyInt_Type` or a subtype of
:c:data:`PyInt_Type`.
.. versionchanged:: 2.2
Allowed subtypes to be accepted.
.. cfunction:: int PyInt_CheckExact(PyObject *o)
.. c:function:: int PyInt_CheckExact(PyObject *o)
Return true if *o* is of type :cdata:`PyInt_Type`, but not a subtype of
:cdata:`PyInt_Type`.
Return true if *o* is of type :c:data:`PyInt_Type`, but not a subtype of
:c:data:`PyInt_Type`.
.. versionadded:: 2.2
.. cfunction:: PyObject* PyInt_FromString(char *str, char **pend, int base)
.. c:function:: PyObject* PyInt_FromString(char *str, char **pend, int base)
Return a new :ctype:`PyIntObject` or :ctype:`PyLongObject` based on the string
Return a new :c:type:`PyIntObject` or :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
@ -49,13 +49,13 @@ Plain Integer Objects
8 will be used; otherwise radix 10 will be used. If *base* is not ``0``, it
must be between ``2`` and ``36``, inclusive. Leading spaces are ignored. If
there are no digits, :exc:`ValueError` will be raised. If the string represents
a number too large to be contained within the machine's :ctype:`long int` type
and overflow warnings are being suppressed, a :ctype:`PyLongObject` will be
a number too large to be contained within the machine's :c:type:`long int` type
and overflow warnings are being suppressed, a :c:type:`PyLongObject` will be
returned. If overflow warnings are not being suppressed, *NULL* will be
returned in this case.
.. cfunction:: PyObject* PyInt_FromLong(long ival)
.. c:function:: PyObject* PyInt_FromLong(long ival)
Create a new integer object with a value of *ival*.
@ -66,7 +66,7 @@ Plain Integer Objects
undefined. :-)
.. cfunction:: PyObject* PyInt_FromSsize_t(Py_ssize_t ival)
.. c:function:: PyObject* PyInt_FromSsize_t(Py_ssize_t ival)
Create a new integer object with a value of *ival*. If the value is larger
than ``LONG_MAX`` or smaller than ``LONG_MIN``, a long integer object is
@ -75,7 +75,7 @@ Plain Integer Objects
.. versionadded:: 2.5
.. cfunction:: PyObject* PyInt_FromSize_t(size_t ival)
.. c:function:: PyObject* PyInt_FromSize_t(size_t ival)
Create a new integer object with a value of *ival*. If the value exceeds
``LONG_MAX``, a long integer object is returned.
@ -83,47 +83,47 @@ Plain Integer Objects
.. versionadded:: 2.5
.. cfunction:: long PyInt_AsLong(PyObject *io)
.. c:function:: long PyInt_AsLong(PyObject *io)
Will first attempt to cast the object to a :ctype:`PyIntObject`, if it is not
Will first attempt to cast the object to a :c:type:`PyIntObject`, if it is not
already one, and then return its value. If there is an error, ``-1`` is
returned, and the caller should check ``PyErr_Occurred()`` to find out whether
there was an error, or whether the value just happened to be -1.
.. cfunction:: long PyInt_AS_LONG(PyObject *io)
.. c:function:: long PyInt_AS_LONG(PyObject *io)
Return the value of the object *io*. No error checking is performed.
.. cfunction:: unsigned long PyInt_AsUnsignedLongMask(PyObject *io)
.. c:function:: unsigned long PyInt_AsUnsignedLongMask(PyObject *io)
Will first attempt to cast the object to a :ctype:`PyIntObject` or
:ctype:`PyLongObject`, if it is not already one, and then return its value as
Will first attempt to cast the object to a :c:type:`PyIntObject` or
:c:type:`PyLongObject`, if it is not already one, and then return its value as
unsigned long. This function does not check for overflow.
.. versionadded:: 2.3
.. cfunction:: unsigned PY_LONG_LONG PyInt_AsUnsignedLongLongMask(PyObject *io)
.. c:function:: unsigned PY_LONG_LONG PyInt_AsUnsignedLongLongMask(PyObject *io)
Will first attempt to cast the object to a :ctype:`PyIntObject` or
:ctype:`PyLongObject`, if it is not already one, and then return its value as
Will first attempt to cast the object to a :c:type:`PyIntObject` or
:c:type:`PyLongObject`, if it is not already one, and then return its value as
unsigned long long, without checking for overflow.
.. versionadded:: 2.3
.. cfunction:: Py_ssize_t PyInt_AsSsize_t(PyObject *io)
.. c:function:: Py_ssize_t PyInt_AsSsize_t(PyObject *io)
Will first attempt to cast the object to a :ctype:`PyIntObject` or
:ctype:`PyLongObject`, if it is not already one, and then return its value as
:ctype:`Py_ssize_t`.
Will first attempt to cast the object to a :c:type:`PyIntObject` or
:c:type:`PyLongObject`, if it is not already one, and then return its value as
:c:type:`Py_ssize_t`.
.. versionadded:: 2.5
.. cfunction:: long PyInt_GetMax()
.. c:function:: long PyInt_GetMax()
.. index:: single: LONG_MAX
@ -131,7 +131,7 @@ Plain Integer Objects
(:const:`LONG_MAX`, as defined in the system header files).
.. cfunction:: int PyInt_ClearFreeList()
.. c:function:: int PyInt_ClearFreeList()
Clear the integer free list. Return the number of items that could not
be freed.

View File

@ -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, PyInt_FromLong(2L));
PyTuple_SetItem(t, 2, PyString_FromString("three"));
Here, :cfunc:`PyInt_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:`PyInt_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
@ -370,7 +370,7 @@ indicator is either *NULL* or ``-1``, depending on the function's return type.
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`. These exceptions are always explicitly documented.
:c:func:`PyErr_Occurred`. These exceptions are always explicitly documented.
.. index::
single: PyErr_SetString()
@ -379,11 +379,11 @@ ambiguous 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.
.. index::
@ -424,7 +424,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::
@ -491,10 +491,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
@ -520,20 +520,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:`__builtin__`, :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
@ -557,22 +557,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.
@ -592,11 +592,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 ``--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
@ -625,11 +625,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.

View File

@ -10,12 +10,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

View File

@ -12,23 +12,23 @@ 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.
.. versionadded:: 2.2
.. 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`.
.. versionadded:: 2.2
.. 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
@ -37,22 +37,22 @@ sentinel value is returned.
.. versionadded:: 2.2
.. 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.
.. versionadded:: 2.2
.. 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`.
.. versionadded:: 2.2
.. 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

View File

@ -8,18 +8,18 @@ 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.
@ -28,7 +28,7 @@ List Objects
Allowed subtypes to be accepted.
.. 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.
@ -36,7 +36,7 @@ List Objects
.. versionadded:: 2.2
.. 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.
@ -44,15 +44,15 @@ List Objects
If *len* 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`.
.. versionchanged:: 2.5
This function used an :ctype:`int` for *size*. This might require
This function used an :c:type:`int` for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: Py_ssize_t PyList_Size(PyObject *list)
.. c:function:: Py_ssize_t PyList_Size(PyObject *list)
.. index:: builtin: len
@ -60,20 +60,20 @@ List Objects
``len(list)`` on a list object.
.. versionchanged:: 2.5
This function returned an :ctype:`int`. This might require changes in
This function returned an :c:type:`int`. This might require changes in
your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This macro returned an :ctype:`int`. This might require changes in your
This macro returned an :c:type:`int`. This might require changes in your
code for properly supporting 64-bit systems.
.. 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 *index* in the list pointed to by *list*. The
position must be positive, indexing from the end of the list is not
@ -81,20 +81,20 @@ List Objects
:exc:`IndexError` exception.
.. versionchanged:: 2.5
This function used an :ctype:`int` for *index*. This might require
This function used an :c:type:`int` for *index*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This macro used an :ctype:`int` for *i*. This might require changes in
This macro used an :c:type:`int` for *i*. This might require changes in
your code for properly supporting 64-bit systems.
.. 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.
@ -105,46 +105,46 @@ List Objects
an item already in the list at the affected position.
.. versionchanged:: 2.5
This function used an :ctype:`int` for *index*. This might require
This function used an :c:type:`int` for *index*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
it being replaced; any reference in *list* at position *i* will be
leaked.
.. versionchanged:: 2.5
This macro used an :ctype:`int` for *i*. This might require
This macro used an :c:type:`int` for *i*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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)``.
.. versionchanged:: 2.5
This function used an :ctype:`int` for *index*. This might require
This function used an :c:type:`int` for *index*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
@ -152,11 +152,11 @@ List Objects
supported.
.. versionchanged:: 2.5
This function used an :ctype:`int` for *low* and *high*. This might
This function used an :c:type:`int` for *low* and *high*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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
@ -165,23 +165,23 @@ List Objects
slicing from Python, are not supported.
.. versionchanged:: 2.5
This function used an :ctype:`int` for *low* and *high*. This might
This function used an :c:type:`int` for *low* and *high*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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

View File

@ -8,100 +8,100 @@ Long Integer Objects
.. index:: object: long integer
.. ctype:: PyLongObject
.. c:type:: PyLongObject
This subtype of :ctype:`PyObject` represents a Python long integer object.
This subtype of :c:type:`PyObject` represents a Python long integer object.
.. cvar:: PyTypeObject PyLong_Type
.. c:var:: PyTypeObject PyLong_Type
.. index:: single: LongType (in modules types)
This instance of :ctype:`PyTypeObject` represents the Python long integer type.
This instance of :c:type:`PyTypeObject` represents the Python long integer type.
This is the same object as ``long`` and ``types.LongType``.
.. 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`.
.. versionchanged:: 2.2
Allowed subtypes to be accepted.
.. 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`.
.. versionadded:: 2.2
.. 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.
.. 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.
.. versionadded:: 2.6
.. 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.
.. versionadded:: 2.6
.. 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 with a value of *v*, or *NULL*
Return a new :c:type:`PyLongObject` object with a value of *v*, or *NULL*
on failure.
.. versionadded:: 2.6
.. cfunction:: PyObject* PyLong_FromSize_t(size_t v)
.. c:function:: PyObject* PyLong_FromSize_t(size_t v)
Return a new :ctype:`PyLongObject` object with a value of *v*, or *NULL*
Return a new :c:type:`PyLongObject` object with a value of *v*, or *NULL*
on failure.
.. versionadded:: 2.6
.. 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 is
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 determined
@ -112,7 +112,7 @@ Long Integer Objects
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 long integer value. The first
parameter, *u*, points to the first character of the Unicode string, *length*
@ -123,14 +123,14 @@ Long Integer Objects
.. versionadded:: 1.6
.. versionchanged:: 2.5
This function used an :ctype:`int` for *length*. This might require
This function used an :c:type:`int` for *length*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: PyObject* PyLong_FromVoidPtr(void *p)
.. c:function:: PyObject* PyLong_FromVoidPtr(void *p)
Create a Python integer or long integer from the pointer *p*. The pointer value
can be retrieved from the resulting value using :cfunc:`PyLong_AsVoidPtr`.
can be retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`.
.. versionadded:: 1.5.2
@ -138,20 +138,20 @@ Long Integer Objects
If the integer is larger than LONG_MAX, a positive long integer is returned.
.. 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`, an :exc:`OverflowError` is raised
and ``-1`` will be returned.
.. 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
@ -162,9 +162,9 @@ Long Integer Objects
.. versionadded:: 2.7
.. 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
@ -175,61 +175,61 @@ Long Integer Objects
.. versionadded:: 2.7
.. 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*. If
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.
.. versionadded:: 2.6
.. 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:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
.. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
.. index::
single: PY_SSIZE_T_MAX
Return a :ctype:`Py_ssize_t` representation of the contents of *pylong*. If
Return a :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.
.. versionadded:: 2.6
.. 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 long integer. If
*pylong* cannot be represented as a :ctype:`long long`, an
Return a C :c:type:`long long` from a Python long integer. If
*pylong* cannot be represented as a :c:type:`long long`, an
:exc:`OverflowError` is raised and ``-1`` is returned.
.. versionadded:: 2.2
.. 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 long integer. If
*pylong* cannot be represented as an :ctype:`unsigned long long`, an
Return a C :c:type:`unsigned long long` from a Python long 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.
@ -240,35 +240,35 @@ Long Integer Objects
: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 long integer, without checking
Return a C :c:type:`unsigned long` from a Python long integer, without checking
for overflow.
.. versionadded:: 2.3
.. 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 long integer, without
Return a C :c:type:`unsigned long long` from a Python long integer, without
checking for overflow.
.. versionadded:: 2.3
.. 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 or long integer *pylong* to a C :ctype:`void` pointer.
Convert a Python integer or long 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`.
.. versionadded:: 1.5.2

View File

@ -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,62 +22,62 @@ Mapping Protocol
expression ``len(o)``.
.. versionchanged:: 2.5
These functions returned an :ctype:`int` type. This might require
These functions returned an :c:type:`int` type. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 ``o[key]``, returning ``True`` on success
and ``False`` on an exception. 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 ``o[key]``, returning ``True`` on success and ``False``
on an exception. 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 ``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 ``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 ``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``.

View File

@ -20,17 +20,17 @@ 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.
native :c:type:`long` type.
.. versionchanged:: 2.4
*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*.
@ -38,7 +38,7 @@ file format (currently 2).
*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*.
@ -55,31 +55,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
@ -88,7 +88,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
@ -96,5 +96,5 @@ written using these routines?
*NULL*.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *len*. This might require
This function used an :c:type:`int` type for *len*. This might require
changes in your code for properly supporting 64-bit systems.

View File

@ -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.

View File

@ -10,21 +10,21 @@ Method Objects
There are some useful functions that are useful for working with method objects.
.. 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, PyObject *class)
.. c:function:: PyObject* PyMethod_New(PyObject *func, PyObject *self, PyObject *class)
Return a new method object, with *func* being any callable object; this is the
function that will be called when the method is called. If this method should
@ -33,39 +33,39 @@ There are some useful functions that are useful for working with method objects.
class which provides the unbound method..
.. cfunction:: PyObject* PyMethod_Class(PyObject *meth)
.. c:function:: PyObject* PyMethod_Class(PyObject *meth)
Return the class object from which the method *meth* was created; if this was
created from an instance, it will be the class of the instance.
.. cfunction:: PyObject* PyMethod_GET_CLASS(PyObject *meth)
.. c:function:: PyObject* PyMethod_GET_CLASS(PyObject *meth)
Macro version of :cfunc:`PyMethod_Class` which avoids error checking.
Macro version of :c:func:`PyMethod_Class` which avoids error checking.
.. 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* if it is bound, otherwise
return *NULL*.
.. 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.

View File

@ -10,15 +10,15 @@ 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.
@ -26,15 +26,15 @@ There are only a few functions special to module objects.
Allowed subtypes to be accepted.
.. 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`.
.. versionadded:: 2.2
.. cfunction:: PyObject* PyModule_New(const char *name)
.. c:function:: PyObject* PyModule_New(const char *name)
.. index::
single: __name__ (module attribute)
@ -46,18 +46,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)
@ -67,7 +67,7 @@ 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)
.. index::
single: __file__ (module attribute)
@ -78,7 +78,7 @@ There are only a few functions special to module objects.
raise :exc:`SystemError` and return *NULL*.
.. 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
@ -87,7 +87,7 @@ There are only a few functions special to module objects.
.. versionadded:: 2.0
.. 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
@ -96,7 +96,7 @@ There are only a few functions special to module objects.
.. versionadded:: 2.0
.. 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
@ -104,7 +104,7 @@ There are only a few functions special to module objects.
.. versionadded:: 2.0
.. 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_AddIntMacro(module, AF_INET)`` adds the int
@ -113,7 +113,7 @@ There are only a few functions special to module objects.
.. versionadded:: 2.6
.. cfunction:: int PyModule_AddStringMacro(PyObject *module, macro)
.. c:function:: int PyModule_AddStringMacro(PyObject *module, macro)
Add a string constant to *module*.

View File

@ -7,22 +7,22 @@ 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.
Properly handle returning :c:data:`Py_None` from within a C function.
.. versionadded:: 2.4

View File

@ -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_Divide(PyObject *o1, PyObject *o2)
.. c:function:: PyObject* PyNumber_Divide(PyObject *o1, PyObject *o2)
Returns the result of dividing *o1* by *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.
@ -44,7 +44,7 @@ Number Protocol
.. versionadded:: 2.2
.. 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
@ -55,13 +55,13 @@ Number Protocol
.. versionadded:: 2.2
.. 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
@ -69,29 +69,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
@ -99,71 +99,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_InPlaceDivide(PyObject *o1, PyObject *o2)
.. c:function:: PyObject* PyNumber_InPlaceDivide(PyObject *o1, PyObject *o2)
Returns the result 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_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
@ -172,7 +172,7 @@ Number Protocol
.. versionadded:: 2.2
.. 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
@ -183,64 +183,64 @@ Number Protocol
.. versionadded:: 2.2
.. 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:: int PyNumber_Coerce(PyObject **p1, PyObject **p2)
.. c:function:: int PyNumber_Coerce(PyObject **p1, PyObject **p2)
.. index:: builtin: coerce
This function takes the addresses of two variables of type :ctype:`PyObject\*`.
This function takes the addresses of two variables of type :c:type:`PyObject\*`.
If the objects pointed to by ``*p1`` and ``*p2`` have the same type, increment
their reference count and return ``0`` (success). If the objects can be
converted to a common numeric type, replace ``*p1`` and ``*p2`` by their
@ -250,14 +250,14 @@ Number Protocol
&o2)`` is equivalent to the Python statement ``o1, o2 = coerce(o1, o2)``.
.. cfunction:: int PyNumber_CoerceEx(PyObject **p1, PyObject **p2)
.. c:function:: int PyNumber_CoerceEx(PyObject **p1, PyObject **p2)
This function is similar to :cfunc:`PyNumber_Coerce`, except that it returns
This function is similar to :c:func:`PyNumber_Coerce`, except that it returns
``1`` when the conversion is not possible and when no error is raised.
Reference counts are still not increased in this case.
.. cfunction:: PyObject* PyNumber_Int(PyObject *o)
.. c:function:: PyObject* PyNumber_Int(PyObject *o)
.. index:: builtin: int
@ -266,7 +266,7 @@ Number Protocol
instead. This is the equivalent of the Python expression ``int(o)``.
.. cfunction:: PyObject* PyNumber_Long(PyObject *o)
.. c:function:: PyObject* PyNumber_Long(PyObject *o)
.. index:: builtin: long
@ -274,7 +274,7 @@ Number Protocol
failure. This is the equivalent of the Python expression ``long(o)``.
.. cfunction:: PyObject* PyNumber_Float(PyObject *o)
.. c:function:: PyObject* PyNumber_Float(PyObject *o)
.. index:: builtin: float
@ -282,7 +282,7 @@ 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 or long on success or *NULL* with a
:exc:`TypeError` exception raised on failure.
@ -290,18 +290,18 @@ Number Protocol
.. versionadded:: 2.5
.. 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.
.. versionadded:: 2.6
.. 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 or long but the attempt to
@ -314,7 +314,7 @@ Number Protocol
.. versionadded:: 2.5
.. 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).

View File

@ -13,7 +13,7 @@ shortcomings of the protocol, and has been backported to Python 2.6. See
:ref:`bufferobjects` for more information.
.. 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
@ -24,11 +24,11 @@ shortcomings of the protocol, and has been backported to Python 2.6. See
.. versionadded:: 1.6
.. versionchanged:: 2.5
This function used an :ctype:`int *` type for *buffer_len*. This might
This function used an :c:type:`int *` type for *buffer_len*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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
@ -39,11 +39,11 @@ shortcomings of the protocol, and has been backported to Python 2.6. See
.. versionadded:: 1.6
.. versionchanged:: 2.5
This function used an :ctype:`int *` type for *buffer_len*. This might
This function used an :c:type:`int *` type for *buffer_len*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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``.
@ -51,7 +51,7 @@ shortcomings of the protocol, and has been backported to Python 2.6. See
.. versionadded:: 2.2
.. 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 writeable memory location. The *obj* argument must
support the single-segment, character buffer interface. On success,
@ -61,6 +61,6 @@ shortcomings of the protocol, and has been backported to Python 2.6. See
.. versionadded:: 1.6
.. versionchanged:: 2.5
This function used an :ctype:`int *` type for *buffer_len*. This might
This function used an :c:type:`int *` type for *buffer_len*. This might
require changes in your code for properly supporting 64-bit systems.

View File

@ -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,10 +109,10 @@ Object Protocol
*opid*.
.. note::
If *o1* and *o2* are the same object, :cfunc:`PyObject_RichCompareBool`
If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool`
will always return ``1`` for :const:`Py_EQ` and ``0`` for :const:`Py_NE`.
.. cfunction:: int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
.. c:function:: int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
.. index:: builtin: cmp
@ -122,18 +122,18 @@ Object Protocol
the Python statement ``result = cmp(o1, o2)``.
.. cfunction:: int PyObject_Compare(PyObject *o1, PyObject *o2)
.. c:function:: int PyObject_Compare(PyObject *o1, PyObject *o2)
.. index:: builtin: cmp
Compare the values of *o1* and *o2* using a routine provided by *o1*, if one
exists, otherwise with a routine provided by *o2*. Returns the result of the
comparison on success. On error, the value returned is undefined; use
:cfunc:`PyErr_Occurred` to detect an error. This is equivalent to the Python
:c:func:`PyErr_Occurred` to detect an error. This is equivalent to the Python
expression ``cmp(o1, o2)``.
.. cfunction:: PyObject* PyObject_Repr(PyObject *o)
.. c:function:: PyObject* PyObject_Repr(PyObject *o)
.. index:: builtin: repr
@ -143,7 +143,7 @@ Object Protocol
by reverse quotes.
.. cfunction:: PyObject* PyObject_Str(PyObject *o)
.. c:function:: PyObject* PyObject_Str(PyObject *o)
.. index:: builtin: str
@ -153,15 +153,15 @@ Object Protocol
by the :keyword:`print` statement.
.. cfunction:: PyObject* PyObject_Bytes(PyObject *o)
.. c:function:: PyObject* PyObject_Bytes(PyObject *o)
.. index:: builtin: bytes
Compute a bytes representation of object *o*. In 2.x, this is just a alias
for :cfunc:`PyObject_Str`.
for :c:func:`PyObject_Str`.
.. cfunction:: PyObject* PyObject_Unicode(PyObject *o)
.. c:function:: PyObject* PyObject_Unicode(PyObject *o)
.. index:: builtin: unicode
@ -171,11 +171,11 @@ Object Protocol
function.
.. 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
@ -195,13 +195,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*
@ -216,13 +216,13 @@ is considered sufficient for this determination.
Older versions of Python did not support a tuple as the second argument.
.. 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)
.. index:: builtin: apply
@ -236,7 +236,7 @@ is considered sufficient for this determination.
.. versionadded:: 2.2
.. cfunction:: PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args)
.. c:function:: PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args)
.. index:: builtin: apply
@ -247,52 +247,52 @@ is considered sufficient for this determination.
``callable_object(*args)``.
.. cfunction:: PyObject* PyObject_CallFunction(PyObject *callable, char *format, ...)
.. c:function:: PyObject* PyObject_CallFunction(PyObject *callable, char *format, ...)
.. index:: builtin: apply
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 ``apply(callable, args)`` or
``callable(*args)``. Note that if you only pass :ctype:`PyObject \*` args,
:cfunc:`PyObject_CallFunctionObjArgs` is a faster alternative.
``callable(*args)``. Note that if you only 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.
.. versionadded:: 2.2
.. 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.
.. versionadded:: 2.2
.. cfunction:: long PyObject_Hash(PyObject *o)
.. c:function:: long PyObject_Hash(PyObject *o)
.. index:: builtin: hash
@ -300,7 +300,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,
@ -310,21 +310,21 @@ is considered sufficient for this determination.
.. versionadded:: 2.6
.. 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
@ -333,11 +333,11 @@ 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*.
@ -345,7 +345,7 @@ is considered sufficient for this determination.
.. versionadded:: 2.2
.. 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
@ -355,29 +355,29 @@ is considered sufficient for this determination.
returned. This is the equivalent to the Python expression ``len(o)``.
.. versionchanged:: 2.5
These functions returned an :ctype:`int` type. This might require
These functions returned an :c:type:`int` type. This might require
changes in your code for properly supporting 64-bit systems.
.. 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:: int PyObject_AsFileDescriptor(PyObject *o)
.. c:function:: int PyObject_AsFileDescriptor(PyObject *o)
Derives a file descriptor from a Python object. If the object is an integer or
long integer, its value is returned. If not, the object's :meth:`fileno` method
@ -385,16 +385,16 @@ is considered sufficient for this determination.
is returned as the file descriptor value. Returns ``-1`` on failure.
.. 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

View File

@ -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.
@ -65,10 +65,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`.

View File

@ -5,51 +5,51 @@
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:: int PyEval_GetRestricted()
.. c:function:: int PyEval_GetRestricted()
If there is a current frame and it is executing in restricted mode, return true,
otherwise false.
.. 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*.

View File

@ -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,140 +22,140 @@ Sequence Protocol
Python expression ``len(o)``.
.. versionchanged:: 2.5
These functions returned an :ctype:`int` type. This might require
These functions returned an :c:type:`int` type. This might require
changes in your code for properly supporting 64-bit systems.
.. 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``.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *count*. This might require
This function used an :c:type:`int` type for *count*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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``.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *count*. This might require
This function used an :c:type:`int` type for *count*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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]``.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *i*. This might require
This function used an :c:type:`int` type for *i*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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]``.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *i1* and *i2*. This might
This function used an :c:type:`int` type for *i1* and *i2*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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*.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *i*. This might require
This function used an :c:type:`int` type for *i*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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]``.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *i*. This might require
This function used an :c:type:`int` type for *i*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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``.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *i1* and *i2*. This might
This function used an :c:type:`int` type for *i1* and *i2*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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]``.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *i1* and *i2*. This might
This function used an :c:type:`int` type for *i1* and *i2*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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)``.
.. versionchanged:: 2.5
This function returned an :ctype:`int` type. This might require changes
This function returned an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. 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)``.
.. versionchanged:: 2.5
This function returned an :ctype:`int` type. This might require changes
This function returned an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. 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
@ -165,28 +165,28 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *i*. This might require
This function used an :c:type:`int` type for *i*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
@ -195,24 +195,24 @@ Sequence Protocol
.. versionadded:: 2.4
.. 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` on *o* is true and without adjustment for negative
:c:func:`PySequence_GetItem` but without checking that
:c:func:`PySequence_Check` on *o* is true and without adjustment for negative
indices.
.. versionadded:: 2.3
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *i*. This might require
This function used an :c:type:`int` type for *i*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.

View File

@ -16,20 +16,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
@ -37,53 +37,53 @@ 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.
.. versionadded:: 2.6
.. 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.
.. versionadded:: 2.6
.. 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
@ -92,7 +92,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
@ -108,7 +108,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
@ -117,16 +117,16 @@ or :class:`frozenset` or instances of their subtypes.
:class:`set`, :class:`frozenset`, or an instance of a subtype.
.. versionchanged:: 2.5
This function returned an :ctype:`int`. This might require changes in
This function returned an :c:type:`int`. This might require changes in
your code for properly supporting 64-bit systems.
.. 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
@ -135,7 +135,7 @@ 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. Does not apply to :class:`frozenset`
instances. Return 0 on success or -1 on failure. Raise a :exc:`TypeError` if
@ -145,14 +145,14 @@ or :class:`frozenset` or instances of their subtypes.
.. versionchanged:: 2.6
Now works with instances of :class:`frozenset` or its subtypes.
Like :cfunc:`PyTuple_SetItem` in that it can be used to fill-in the
Like :c:func:`PyTuple_SetItem` in that it can be used to fill-in the
values of brand new frozensets before they are exposed to other code.
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
@ -162,7 +162,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
@ -170,6 +170,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.

View File

@ -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
@ -40,18 +40,18 @@ Slice Objects
You probably do not want to use this function. If you want to use slice
objects in versions of Python prior to 2.3, you would probably do well to
incorporate the source of :cfunc:`PySlice_GetIndicesEx`, suitably renamed,
incorporate the source of :c:func:`PySlice_GetIndicesEx`, suitably renamed,
in the source of your extension.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *length* and an
:ctype:`int *` type for *start*, *stop*, and *step*. This might require
This function used an :c:type:`int` type for *length* and an
:c:type:`int *` type for *start*, *stop*, and *step*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
@ -62,7 +62,7 @@ Slice Objects
.. versionadded:: 2.3
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *length* and an
:ctype:`int *` type for *start*, *stop*, *step*, and *slicelength*. This
This function used an :c:type:`int` type for *length* and an
:c:type:`int *` type for *start*, *stop*, *step*, and *slicelength*. This
might require changes in your code for properly supporting 64-bit
systems.

View File

@ -17,20 +17,20 @@ called with a non-string parameter.
.. index:: object: string
.. ctype:: PyStringObject
.. c:type:: PyStringObject
This subtype of :ctype:`PyObject` represents a Python string object.
This subtype of :c:type:`PyObject` represents a Python string object.
.. cvar:: PyTypeObject PyString_Type
.. c:var:: PyTypeObject PyString_Type
.. index:: single: StringType (in module types)
This instance of :ctype:`PyTypeObject` represents the Python string type; it is
This instance of :c:type:`PyTypeObject` represents the Python string type; it is
the same object as ``str`` and ``types.StringType`` in the Python layer. .
.. cfunction:: int PyString_Check(PyObject *o)
.. c:function:: int PyString_Check(PyObject *o)
Return true if the object *o* is a string object or an instance of a subtype of
the string type.
@ -39,7 +39,7 @@ called with a non-string parameter.
Allowed subtypes to be accepted.
.. cfunction:: int PyString_CheckExact(PyObject *o)
.. c:function:: int PyString_CheckExact(PyObject *o)
Return true if the object *o* is a string object, but not an instance of a
subtype of the string type.
@ -47,27 +47,27 @@ called with a non-string parameter.
.. versionadded:: 2.2
.. cfunction:: PyObject* PyString_FromString(const char *v)
.. c:function:: PyObject* PyString_FromString(const char *v)
Return a new string 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* PyString_FromStringAndSize(const char *v, Py_ssize_t len)
.. c:function:: PyObject* PyString_FromStringAndSize(const char *v, Py_ssize_t len)
Return a new string 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
string are uninitialized.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *len*. This might require
This function used an :c:type:`int` type for *len*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: PyObject* PyString_FromFormat(const char *format, ...)
.. c:function:: PyObject* PyString_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 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* string. The
@ -144,31 +144,31 @@ called with a non-string parameter.
Support for `"%lld"` and `"%llu"` added.
.. cfunction:: PyObject* PyString_FromFormatV(const char *format, va_list vargs)
.. c:function:: PyObject* PyString_FromFormatV(const char *format, va_list vargs)
Identical to :cfunc:`PyString_FromFormat` except that it takes exactly two
Identical to :c:func:`PyString_FromFormat` except that it takes exactly two
arguments.
.. cfunction:: Py_ssize_t PyString_Size(PyObject *string)
.. c:function:: Py_ssize_t PyString_Size(PyObject *string)
Return the length of the string in string object *string*.
.. versionchanged:: 2.5
This function returned an :ctype:`int` type. This might require changes
This function returned an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. cfunction:: Py_ssize_t PyString_GET_SIZE(PyObject *string)
.. c:function:: Py_ssize_t PyString_GET_SIZE(PyObject *string)
Macro form of :cfunc:`PyString_Size` but without error checking.
Macro form of :c:func:`PyString_Size` but without error checking.
.. versionchanged:: 2.5
This macro returned an :ctype:`int` type. This might require changes in
This macro returned an :c:type:`int` type. This might require changes in
your code for properly supporting 64-bit systems.
.. cfunction:: char* PyString_AsString(PyObject *string)
.. c:function:: char* PyString_AsString(PyObject *string)
Return a NUL-terminated representation of the contents of *string*. The pointer
refers to the internal buffer of *string*, not a copy. The data must not be
@ -176,16 +176,16 @@ called with a non-string parameter.
``PyString_FromStringAndSize(NULL, size)``. It must not be deallocated. If
*string* is a Unicode object, this function computes the default encoding of
*string* and operates on that. If *string* is not a string object at all,
:cfunc:`PyString_AsString` returns *NULL* and raises :exc:`TypeError`.
:c:func:`PyString_AsString` returns *NULL* and raises :exc:`TypeError`.
.. cfunction:: char* PyString_AS_STRING(PyObject *string)
.. c:function:: char* PyString_AS_STRING(PyObject *string)
Macro form of :cfunc:`PyString_AsString` but without error checking. Only
Macro form of :c:func:`PyString_AsString` but without error checking. Only
string objects are supported; no Unicode objects should be passed.
.. cfunction:: int PyString_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
.. c:function:: int PyString_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*.
@ -200,14 +200,14 @@ called with a non-string parameter.
``PyString_FromStringAndSize(NULL, size)``. It must not be deallocated. If
*string* is a Unicode object, this function computes the default encoding of
*string* and operates on that. If *string* is not a string object at all,
:cfunc:`PyString_AsStringAndSize` returns ``-1`` and raises :exc:`TypeError`.
:c:func:`PyString_AsStringAndSize` returns ``-1`` and raises :exc:`TypeError`.
.. versionchanged:: 2.5
This function used an :ctype:`int *` type for *length*. This might
This function used an :c:type:`int *` type for *length*. This might
require changes in your code for properly supporting 64-bit systems.
.. cfunction:: void PyString_Concat(PyObject **string, PyObject *newpart)
.. c:function:: void PyString_Concat(PyObject **string, PyObject *newpart)
Create a new string object in *\*string* containing the contents of *newpart*
appended to *string*; the caller will own the new reference. The reference to
@ -216,13 +216,13 @@ called with a non-string parameter.
*\*string* will be set to *NULL*; the appropriate exception will be set.
.. cfunction:: void PyString_ConcatAndDel(PyObject **string, PyObject *newpart)
.. c:function:: void PyString_ConcatAndDel(PyObject **string, PyObject *newpart)
Create a new string object in *\*string* containing the contents of *newpart*
appended to *string*. This version decrements the reference count of *newpart*.
.. cfunction:: int _PyString_Resize(PyObject **string, Py_ssize_t newsize)
.. c:function:: int _PyString_Resize(PyObject **string, Py_ssize_t newsize)
A way to resize a string object even though it is "immutable". Only use this to
build up a brand new string object; don't use this if the string may already be
@ -235,16 +235,16 @@ called with a non-string parameter.
set to *NULL*, a memory exception is set, and ``-1`` is returned.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *newsize*. This might
This function used an :c:type:`int` type for *newsize*. This might
require changes in your code for properly supporting 64-bit systems.
.. cfunction:: PyObject* PyString_Format(PyObject *format, PyObject *args)
.. c:function:: PyObject* PyString_Format(PyObject *format, PyObject *args)
Return a new string object from *format* and *args*. Analogous to ``format %
args``. The *args* argument must be a tuple.
.. cfunction:: void PyString_InternInPlace(PyObject **string)
.. c:function:: void PyString_InternInPlace(PyObject **string)
Intern the argument *\*string* in place. The argument must be the address of a
pointer variable pointing to a Python string object. If there is an existing
@ -261,10 +261,10 @@ called with a non-string parameter.
This function is not available in 3.x and does not have a PyBytes alias.
.. cfunction:: PyObject* PyString_InternFromString(const char *v)
.. c:function:: PyObject* PyString_InternFromString(const char *v)
A combination of :cfunc:`PyString_FromString` and
:cfunc:`PyString_InternInPlace`, returning either a new string object that has
A combination of :c:func:`PyString_FromString` and
:c:func:`PyString_InternInPlace`, returning either a new string object that has
been interned, or a new ("owned") reference to an earlier interned string object
with the same value.
@ -273,7 +273,7 @@ called with a non-string parameter.
This function is not available in 3.x and does not have a PyBytes alias.
.. cfunction:: PyObject* PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
.. c:function:: PyObject* PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
Create an object by decoding *size* bytes of the encoded buffer *s* using the
codec registered for *encoding*. *encoding* and *errors* have the same meaning
@ -286,11 +286,11 @@ called with a non-string parameter.
This function is not available in 3.x and does not have a PyBytes alias.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: PyObject* PyString_AsDecodedObject(PyObject *str, const char *encoding, const char *errors)
.. c:function:: PyObject* PyString_AsDecodedObject(PyObject *str, const char *encoding, const char *errors)
Decode a string object by passing it to the codec registered for *encoding* and
return the result as Python object. *encoding* and *errors* have the same
@ -303,9 +303,9 @@ called with a non-string parameter.
This function is not available in 3.x and does not have a PyBytes alias.
.. cfunction:: PyObject* PyString_Encode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
.. c:function:: PyObject* PyString_Encode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)
Encode the :ctype:`char` buffer of the given size by passing it to the codec
Encode the :c:type:`char` buffer of the given size by passing it to the codec
registered for *encoding* and return a Python object. *encoding* and *errors*
have the same meaning as the parameters of the same name in the string
:meth:`encode` method. The codec to be used is looked up using the Python codec
@ -316,11 +316,11 @@ called with a non-string parameter.
This function is not available in 3.x and does not have a PyBytes alias.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: PyObject* PyString_AsEncodedObject(PyObject *str, const char *encoding, const char *errors)
.. c:function:: PyObject* PyString_AsEncodedObject(PyObject *str, const char *encoding, const char *errors)
Encode a string object using the codec registered for *encoding* and return the
result as Python object. *encoding* and *errors* have the same meaning as the

View File

@ -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,79 +26,79 @@ 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`:
.. 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:: PyMethodDef
.. c:type:: PyMethodDef
Structure used to describe a method of an extension type. This structure has
four fields:
@ -119,10 +119,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.
@ -136,27 +136,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
: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*.
@ -164,15 +164,15 @@ 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.
.. data:: METH_OLDARGS
This calling convention is deprecated. The method must be of type
:ctype:`PyCFunction`. The second argument is *NULL* if no arguments are
:c:type:`PyCFunction`. The second argument is *NULL* if no arguments are
given, a single object if exactly one argument is given, and a tuple of
objects if more than one argument is given. There is no way for a function
using this convention to distinguish between a call with multiple arguments
@ -225,7 +225,7 @@ definition with the same method name.
.. versionadded:: 2.4
.. ctype:: PyMemberDef
.. c:type:: PyMemberDef
Structure which describes an attribute of a type which corresponds to a C
struct member. Its fields are:
@ -277,22 +277,22 @@ 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*).
.. cfunction:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name)
.. c:function:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name)
Return a bound method object for an extension type implemented in C. This
can be useful in the implementation of a :attr:`tp_getattro` or
:attr:`tp_getattr` handler that does not use the
:cfunc:`PyObject_GenericGetAttr` function.
:c:func:`PyObject_GenericGetAttr` function.

View File

@ -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,38 +56,38 @@ 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(char *s)
.. c:function:: void PySys_AddWarnOption(char *s)
Append *s* to :data:`sys.warnoptions`.
.. cfunction:: void PySys_SetPath(char *path)
.. c:function:: void PySys_SetPath(char *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).
@ -103,7 +103,7 @@ 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 above, but write to :data:`sys.stderr` or *stderr* instead.
@ -114,7 +114,7 @@ Process Control
===============
.. cfunction:: void Py_FatalError(const char *message)
.. c:function:: void Py_FatalError(const char *message)
.. index:: single: abort()
@ -122,30 +122,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*.

View File

@ -8,20 +8,20 @@ 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.
@ -30,7 +30,7 @@ Tuple Objects
Allowed subtypes to be accepted.
.. 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.
@ -38,16 +38,16 @@ Tuple Objects
.. versionadded:: 2.2
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *len*. This might require
This function used an :c:type:`int` type for *len*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
@ -56,59 +56,59 @@ Tuple Objects
.. versionadded:: 2.4
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *n*. This might require
This function used an :c:type:`int` type for *n*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function returned an :ctype:`int` type. This might require changes
This function returned an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function returned an :ctype:`int` type. This might require changes
This function returned an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *pos*. This might require
This function used an :c:type:`int` type for *pos*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *pos*. This might require
This function used an :c:type:`int` type for *pos*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *low* and *high*. This might
This function used an :c:type:`int` type for *low* and *high*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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.
@ -118,13 +118,13 @@ Tuple Objects
This function "steals" a reference to *o*.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *pos*. This might require
This function used an :c:type:`int` type for *pos*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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::
@ -132,11 +132,11 @@ Tuple Objects
This function "steals" a reference to *o*.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *pos*. This might require
This function used an :c:type:`int` type for *pos*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
@ -153,11 +153,11 @@ Tuple Objects
Removed unused third parameter, *last_is_sticky*.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *newsize*. This might
This function used an :c:type:`int` type for *newsize*. This might
require changes in your code for properly supporting 64-bit systems.
.. cfunction:: int PyTuple_ClearFreeList()
.. c:function:: int PyTuple_ClearFreeList()
Clear the free list. Return the total number of freed items.

View File

@ -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,13 +21,13 @@ 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.
@ -35,14 +35,14 @@ Type Objects
.. versionadded:: 2.2
.. cfunction:: unsigned int PyType_ClearCache()
.. c:function:: unsigned int PyType_ClearCache()
Clear the internal lookup cache. Return the current version tag.
.. versionadded:: 2.6
.. 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
@ -51,13 +51,13 @@ Type Objects
.. versionadded:: 2.6
.. 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`.
@ -65,28 +65,28 @@ Type Objects
.. versionadded:: 2.0
.. 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*.
.. versionadded:: 2.2
.. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
.. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
.. versionadded:: 2.2
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *nitems*. This might require
This function used an :c:type:`int` type for *nitems*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
.. c:function:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
.. versionadded:: 2.2
.. 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

View File

@ -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,
cmpfunc, 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,11 +65,11 @@ type objects) *must* have the :attr:`ob_size` field.
This field is not inherited by subtypes.
.. versionchanged:: 2.5
This field used to be an :ctype:`int` type. This might require changes
This field used to be an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. 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
@ -83,16 +83,16 @@ 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: in Python 2.2, it is set to ``&PyType_Type``; in Python 2.2.1
and later it is initialized 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.
In Python 2.2, this field is not inherited by subtypes. In 2.2.1, and in 2.3
and beyond, it 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.
@ -100,7 +100,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
@ -127,7 +127,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.
@ -149,7 +149,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
@ -170,14 +170,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
@ -186,15 +186,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.
@ -205,7 +205,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
@ -223,39 +223,39 @@ 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:: cmpfunc PyTypeObject.tp_compare
.. c:member:: cmpfunc PyTypeObject.tp_compare
An optional pointer to the three-way comparison function.
The signature is the same as for :cfunc:`PyObject_Compare`. The function should
The signature is the same as for :c:func:`PyObject_Compare`. The function should
return ``1`` if *self* greater than *other*, ``0`` if *self* is equal to
*other*, and ``-1`` if *self* less than *other*. It should return ``-1`` and
set an exception condition when an error occurred during the comparison.
@ -266,14 +266,14 @@ type objects) *must* have the :attr:`ob_size` field.
:attr:`tp_compare`, :attr:`tp_richcompare`, and :attr:`tp_hash` are all *NULL*.
.. 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
@ -286,7 +286,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
@ -296,7 +296,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
@ -306,7 +306,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
@ -316,25 +316,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, two possibilities exist: if the :attr:`tp_compare`
and :attr:`tp_richcompare` fields are both *NULL*, a default hash value based on
@ -346,39 +346,39 @@ type objects) *must* have the :attr:`ob_size` field.
:attr:`tp_compare`, :attr:`tp_richcompare` and :attr:`tp_hash` are all *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 by
the print statement.
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
@ -386,12 +386,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
@ -399,7 +399,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
@ -409,7 +409,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
@ -433,19 +433,19 @@ 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.
.. data:: Py_TPFLAGS_HAVE_GETCHARBUFFER
If this bit is set, the :ctype:`PyBufferProcs` struct referenced by
If this bit is set, the :c:type:`PyBufferProcs` struct referenced by
:attr:`tp_as_buffer` has the :attr:`bf_getcharbuffer` field.
.. data:: Py_TPFLAGS_HAVE_SEQUENCE_IN
If this bit is set, the :ctype:`PySequenceMethods` struct referenced by
If this bit is set, the :c:type:`PySequenceMethods` struct referenced by
:attr:`tp_as_sequence` has the :attr:`sq_contains` field.
@ -457,23 +457,23 @@ type objects) *must* have the :attr:`ob_size` field.
.. data:: Py_TPFLAGS_HAVE_INPLACEOPS
If this bit is set, the :ctype:`PySequenceMethods` struct referenced by
:attr:`tp_as_sequence` and the :ctype:`PyNumberMethods` structure referenced by
If this bit is set, the :c:type:`PySequenceMethods` struct referenced by
:attr:`tp_as_sequence` and the :c:type:`PyNumberMethods` structure referenced by
:attr:`tp_as_number` contain the fields for in-place operators. In particular,
this means that the :ctype:`PyNumberMethods` structure has the fields
this means that the :c:type:`PyNumberMethods` structure has the fields
:attr:`nb_inplace_add`, :attr:`nb_inplace_subtract`,
:attr:`nb_inplace_multiply`, :attr:`nb_inplace_divide`,
:attr:`nb_inplace_remainder`, :attr:`nb_inplace_power`,
:attr:`nb_inplace_lshift`, :attr:`nb_inplace_rshift`, :attr:`nb_inplace_and`,
:attr:`nb_inplace_xor`, and :attr:`nb_inplace_or`; and the
:ctype:`PySequenceMethods` struct has the fields :attr:`sq_inplace_concat` and
:c:type:`PySequenceMethods` struct has the fields :attr:`sq_inplace_concat` and
:attr:`sq_inplace_repeat`.
.. data:: Py_TPFLAGS_CHECKTYPES
If this bit is set, the binary and ternary operations in the
:ctype:`PyNumberMethods` structure referenced by :attr:`tp_as_number` accept
:c:type:`PyNumberMethods` structure referenced by :attr:`tp_as_number` accept
arguments of arbitrary object types, and do their own type conversions if
needed. If this bit is clear, those operations require that all arguments have
the current type as their type, and the caller is supposed to perform a coercion
@ -532,20 +532,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; but those fields also exist when
@ -563,7 +563,7 @@ type objects) *must* have the :attr:`ob_size` field.
:const:`Py_TPFLAGS_HAVE_ITER`, and :const:`Py_TPFLAGS_HAVE_CLASS`.
.. 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
@ -575,7 +575,7 @@ The following three fields only exist if the
:const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag bit is set.
.. 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
@ -584,8 +584,8 @@ The following three fields only exist if the
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
@ -597,7 +597,7 @@ The following three fields only exist if the
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.
@ -605,8 +605,8 @@ The following three fields only exist if the
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
@ -616,7 +616,7 @@ The following three fields only exist if the
bit set.
.. 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.
@ -645,7 +645,7 @@ The following three fields only exist if the
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,
@ -654,7 +654,7 @@ The following three fields only exist if the
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
@ -672,7 +672,7 @@ The following three fields only exist if the
bit set.
.. 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)``.
@ -694,7 +694,7 @@ The following three fields only exist if the
:attr:`tp_compare`, :attr:`tp_richcompare`, and :attr:`tp_hash` are all *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 |
@ -716,13 +716,13 @@ The following three fields only exist if the
The next field only exists if the :const:`Py_TPFLAGS_HAVE_WEAKREFS` flag bit is
set.
.. 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
@ -751,19 +751,19 @@ The next two fields only exist if the :const:`Py_TPFLAGS_HAVE_ITER` flag bit is
set.
.. 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, and classic instances always
have this function, even if they don't define an :meth:`__iter__` method).
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`
@ -776,7 +776,7 @@ set.
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.
@ -784,9 +784,9 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
:const:`Py_TPFLAGS_HAVE_CLASS` flag bit is set.
.. 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
@ -796,9 +796,9 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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.
@ -809,9 +809,9 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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
@ -836,7 +836,7 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
} 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
@ -847,13 +847,13 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
: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__`).
@ -861,7 +861,7 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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.
@ -874,7 +874,7 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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.
@ -887,12 +887,12 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
.. 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.
@ -920,7 +920,7 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
taken from the type object, and :attr:`ob_size` is taken from the instance. The
absolute value is taken because long 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
@ -940,7 +940,7 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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.
@ -970,7 +970,7 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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.
@ -993,11 +993,11 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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.
@ -1029,16 +1029,16 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
being linked with Python 2.2.
.. cmember:: destructor PyTypeObject.tp_free
.. c:member:: destructor PyTypeObject.tp_free
An optional pointer to an instance deallocation function.
The signature of this function has changed slightly: in Python 2.2 and 2.2.1,
its signature is :ctype:`destructor`::
its signature is :c:type:`destructor`::
void tp_free(PyObject *)
In Python 2.3 and beyond, its signature is :ctype:`freefunc`::
In Python 2.3 and beyond, its signature is :c:type:`freefunc`::
void tp_free(void *)
@ -1047,11 +1047,11 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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.
@ -1066,14 +1066,14 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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. (VERSION NOTE: in Python 2.2, it was not
inherited. It is inherited in 2.2.1 and later versions.)
.. cmember:: PyObject* PyTypeObject.tp_bases
.. c:member:: PyObject* PyTypeObject.tp_bases
Tuple of base types.
@ -1083,25 +1083,25 @@ The next fields, up to and including :attr:`tp_weaklist`, only exist if the
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.
@ -1112,22 +1112,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.
@ -1150,7 +1150,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. Almost every function below is used by the
@ -1215,9 +1215,9 @@ on the flag bit :const:`Py_TPFLAGS_CHECKTYPES`:
the coercion method specified by the :attr:`nb_coerce` member to convert the
arguments:
.. cmember:: coercion PyNumberMethods.nb_coerce
.. c:member:: coercion PyNumberMethods.nb_coerce
This function is used by :cfunc:`PyNumber_CoerceEx` and has the same
This function is used by :c:func:`PyNumber_CoerceEx` and has the same
signature. The first argument is always a pointer to an object of the
defined type. If the conversion to a common "larger" type is possible, the
function replaces the pointers with new references to the converted objects
@ -1243,26 +1243,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.
@ -1275,32 +1275,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
@ -1308,27 +1308,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
@ -1349,45 +1349,45 @@ pointer/length pair. These chunks are called :dfn:`segments` and are presumed
to be non-contiguous in memory.
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.
.. note::
It is very important that your :ctype:`PyTypeObject` structure uses
It is very important that your :c:type:`PyTypeObject` structure uses
:const:`Py_TPFLAGS_DEFAULT` for the value of the :attr:`tp_flags` member rather
than ``0``. This tells the Python runtime that your :ctype:`PyBufferProcs`
than ``0``. This tells the Python runtime that your :c:type:`PyBufferProcs`
structure contains the :attr:`bf_getcharbuffer` slot. Older versions of Python
did not have this member, so a new Python interpreter using an old extension
needs to be able to test for its presence before using it.
.. ctype:: PyBufferProcs
.. c:type:: PyBufferProcs
Structure used to hold the function pointers which define an implementation of
the buffer protocol.
The first slot is :attr:`bf_getreadbuffer`, of type :ctype:`getreadbufferproc`.
The first slot is :attr:`bf_getreadbuffer`, of type :c:type:`getreadbufferproc`.
If this slot is *NULL*, then the object does not support reading from the
internal data. This is non-sensical, so implementors should fill this in, but
callers should test that the slot contains a non-*NULL* value.
The next slot is :attr:`bf_getwritebuffer` having type
:ctype:`getwritebufferproc`. This slot may be *NULL* if the object does not
:c:type:`getwritebufferproc`. This slot may be *NULL* if the object does not
allow writing into its returned buffers.
The third slot is :attr:`bf_getsegcount`, with type :ctype:`getsegcountproc`.
The third slot is :attr:`bf_getsegcount`, with type :c:type:`getsegcountproc`.
This slot must not be *NULL* and is used to inform the caller how many segments
the object contains. Simple objects such as :ctype:`PyString_Type` and
:ctype:`PyBuffer_Type` objects contain a single segment.
the object contains. Simple objects such as :c:type:`PyString_Type` and
:c:type:`PyBuffer_Type` objects contain a single segment.
.. index:: single: PyType_HasFeature()
The last slot is :attr:`bf_getcharbuffer`, of type :ctype:`getcharbufferproc`.
The last slot is :attr:`bf_getcharbuffer`, of type :c:type:`getcharbufferproc`.
This slot will only be present if the :const:`Py_TPFLAGS_HAVE_GETCHARBUFFER`
flag is present in the :attr:`tp_flags` field of the object's
:ctype:`PyTypeObject`. Before using this slot, the caller should test whether it
is present by using the :cfunc:`PyType_HasFeature` function. If the flag is
:c:type:`PyTypeObject`. Before using this slot, the caller should test whether it
is present by using the :c:func:`PyType_HasFeature` function. If the flag is
present, :attr:`bf_getcharbuffer` may be *NULL*, indicating that the object's
contents cannot be used as *8-bit characters*. The slot function may also raise
an error if the object's contents cannot be interpreted as 8-bit characters.
@ -1411,7 +1411,7 @@ member in the :ctype:`PyTypeObject` structure should be *NULL*. Otherwise, the
buffer interface or that the :attr:`bf_getcharbuffer` slot is non-*NULL*.
.. ctype:: Py_ssize_t (*readbufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)
.. c:type:: Py_ssize_t (*readbufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)
Return a pointer to a readable segment of the buffer in ``*ptrptr``. This
function is allowed to raise an exception, in which case it must return ``-1``.
@ -1421,7 +1421,7 @@ member in the :ctype:`PyTypeObject` structure should be *NULL*. Otherwise, the
``*ptrptr`` to a pointer to that memory.
.. ctype:: Py_ssize_t (*writebufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)
.. c:type:: Py_ssize_t (*writebufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)
Return a pointer to a writable memory buffer in ``*ptrptr``, and the length of
that segment as the function return value. The memory buffer must correspond to
@ -1435,14 +1435,14 @@ member in the :ctype:`PyTypeObject` structure should be *NULL*. Otherwise, the
segment. That indicates a blatant programming error in the C code.
.. ctype:: Py_ssize_t (*segcountproc) (PyObject *self, Py_ssize_t *lenp)
.. c:type:: Py_ssize_t (*segcountproc) (PyObject *self, Py_ssize_t *lenp)
Return the number of memory segments which comprise the buffer. If *lenp* is
not *NULL*, the implementation must report the sum of the sizes (in bytes) of
all segments in ``*lenp``. The function cannot fail.
.. ctype:: Py_ssize_t (*charbufferproc) (PyObject *self, Py_ssize_t segment, const char **ptrptr)
.. c:type:: Py_ssize_t (*charbufferproc) (PyObject *self, Py_ssize_t segment, const char **ptrptr)
Return the size of the segment *segment* that *ptrptr* is set to. ``*ptrptr``
is set to the memory buffer. Returns ``-1`` on error.

View File

@ -18,39 +18,39 @@ 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 ``unicode`` and ``types.UnicodeType``.
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.
@ -59,7 +59,7 @@ access internal read-only data of Unicode objects:
Allowed subtypes to be accepted.
.. 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.
@ -67,39 +67,39 @@ access internal read-only data of Unicode objects:
.. versionadded:: 2.2
.. 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).
.. versionchanged:: 2.5
This function returned an :ctype:`int` type. This might require changes
This function returned an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. 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).
.. versionchanged:: 2.5
This function returned an :ctype:`int` type. This might require changes
This function returned an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. 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.
@ -114,86 +114,86 @@ 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.
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.
@ -206,7 +206,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
@ -216,11 +216,11 @@ APIs:
is *NULL*.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
@ -232,7 +232,7 @@ APIs:
.. versionadded:: 2.6
.. 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*.
@ -240,9 +240,9 @@ APIs:
.. versionadded:: 2.6
.. 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*
@ -317,7 +317,7 @@ APIs:
.. versionadded:: 2.6
.. cfunction:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)
.. c:function:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)
Identical to :func:`PyUnicode_FromFormat` except that it takes exactly two
arguments.
@ -325,25 +325,25 @@ APIs:
.. versionadded:: 2.6
.. 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` buffer, *NULL* if *unicode* is not a Unicode object.
Note that the resulting :ctype:`Py_UNICODE*` string may contain embedded
:c:type:`Py_UNICODE` buffer, *NULL* if *unicode* is not a Unicode object.
Note that the resulting :c:type:`Py_UNICODE*` string may contain embedded
null characters, which would cause the string to be truncated when used in
most C functions.
.. cfunction:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
.. c:function:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Return the length of the Unicode object.
.. versionchanged:: 2.5
This function returned an :ctype:`int` type. This might require changes
This function returned an :c:type:`int` type. This might require changes
in your code for properly supporting 64-bit systems.
.. 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.
@ -360,46 +360,46 @@ 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`.
wchar_t Support
"""""""""""""""
:ctype:`wchar_t` support for platforms which support it:
:c:type:`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*.
Return *NULL* on failure.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
required by the application. Also, note that the :ctype:`wchar_t*` string
to make sure that the :c:type:`wchar_t` string is 0-terminated in case this is
required by the application. Also, note that the :c:type:`wchar_t*` string
might contain null characters, which would cause the string to be truncated
when used with most C functions.
.. versionchanged:: 2.5
This function returned an :ctype:`int` type and used an :ctype:`int`
This function returned an :c:type:`int` type and used an :c:type:`int`
type for *size*. This might require changes in your code for properly
supporting 64-bit systems.
@ -417,7 +417,7 @@ have the same semantics as the ones of the built-in :func:`unicode` Unicode
object constructor.
Setting encoding to *NULL* causes the default encoding to be used which is
ASCII. The file system calls should use :cdata:`Py_FileSystemDefaultEncoding`
ASCII. The file system calls should use :c:data:`Py_FileSystemDefaultEncoding`
as the encoding for file names. 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).
@ -436,7 +436,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
@ -445,24 +445,24 @@ These are the generic codec APIs:
the codec.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 *s* of the given *size* and return a Python
Encode the :c:type:`Py_UNICODE` buffer *s* of the given *size* and return a Python
string 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 string object.
*encoding* and *errors* have the same meaning as the parameters of the same name
@ -477,19 +477,19 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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*.
@ -497,21 +497,21 @@ These are the UTF-8 codec APIs:
.. versionadded:: 2.4
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 *s* of the given *size* using UTF-8 and return a
Encode the :c:type:`Py_UNICODE` buffer *s* of the given *size* using UTF-8 and return a
Python string object. Return *NULL* if an exception was raised by the codec.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 string
object. Error handling is "strict". Return *NULL* if an exception was raised
@ -524,7 +524,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 *size* bytes from a UTF-32 encoded buffer string and return the
corresponding Unicode object. *errors* (if non-*NULL*) defines the error
@ -554,10 +554,10 @@ These are the UTF-32 codec APIs:
.. versionadded:: 2.6
.. 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*.
@ -565,7 +565,7 @@ These are the UTF-32 codec APIs:
.. versionadded:: 2.6
.. 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::
@ -585,7 +585,7 @@ These are the UTF-32 codec APIs:
.. versionadded:: 2.6
.. cfunction:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode)
.. c:function:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode)
Return a Python string using the UTF-32 encoding in native byte order. The
string always starts with a BOM mark. Error handling is "strict". Return
@ -600,7 +600,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 *size* bytes from a UTF-16 encoded buffer string and return the
corresponding Unicode object. *errors* (if non-*NULL*) defines the error
@ -627,14 +627,14 @@ These are the UTF-16 codec APIs:
Return *NULL* if an exception was raised by the codec.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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*.
@ -642,12 +642,12 @@ These are the UTF-16 codec APIs:
.. versionadded:: 2.4
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size* and an :ctype:`int *`
This function used an :c:type:`int` type for *size* and an :c:type:`int *`
type for *consumed*. This might require changes in your code for
properly supporting 64-bit systems.
.. 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 string object holding the UTF-16 encoded value of the Unicode
data in *s*. Output is written according to the following byte order::
@ -659,18 +659,18 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. cfunction:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode)
.. c:function:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode)
Return a Python string using the UTF-16 encoding in native byte order. The
string always starts with a BOM mark. Error handling is "strict". Return
@ -683,23 +683,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.
@ -715,28 +715,28 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
@ -749,28 +749,28 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
@ -784,27 +784,27 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 return
Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Latin-1 and return
a Python string object. Return *NULL* if an exception was raised by the codec.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 string
object. Error handling is "strict". Return *NULL* if an exception was raised
@ -818,27 +818,27 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 return a
Encode the :c:type:`Py_UNICODE` buffer of the given *size* using ASCII and return a
Python string object. Return *NULL* if an exception was raised by the codec.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 string
object. Error handling is "strict". Return *NULL* if an exception was raised
@ -871,7 +871,7 @@ characters to different code points.
These are the mapping codec APIs:
.. 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
@ -884,22 +884,22 @@ These are the mapping codec APIs:
Allowed unicode string as mapping argument.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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
@ -908,9 +908,9 @@ These are the mapping codec APIs:
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 *size* by applying a
Translate a :c:type:`Py_UNICODE` buffer of the given *size* 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,7 +922,7 @@ The following codec API is special in that maps Unicode to Unicode.
:exc:`LookupError`) are left untouched and are copied as-is.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
@ -935,37 +935,37 @@ DBCS) is a class of encodings, not just one. The target encoding is defined by
the user settings on the machine running the codec.
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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*.
.. versionadded:: 2.5
.. 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 a
Encode the :c:type:`Py_UNICODE` buffer of the given *size* using MBCS and return a
Python string object. Return *NULL* if an exception was raised by the codec.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *size*. This might require
This function used an :c:type:`int` type for *size*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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 string
object. Error handling is "strict". Return *NULL* if an exception was raised
@ -987,12 +987,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
@ -1000,18 +1000,18 @@ They all return *NULL* or ``-1`` if an exception occurs.
set. Separators are not included in the resulting list.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *maxsplit*. This might require
This function used an :c:type:`int` type for *maxsplit*. This might require
changes in your code for properly supporting 64-bit systems.
.. 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.
@ -1027,25 +1027,25 @@ 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *start* and *end*. This
This function used an :c:type:`int` type for *start* and *end*. This
might require changes in your code for properly supporting 64-bit
systems.
.. 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
@ -1054,40 +1054,40 @@ They all return *NULL* or ``-1`` if an exception occurs.
occurred and an exception has been set.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *start* and *end*. This
This function used an :c:type:`int` type for *start* and *end*. This
might require changes in your code for properly supporting 64-bit
systems.
.. 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.
.. versionchanged:: 2.5
This function returned an :ctype:`int` type and used an :ctype:`int`
This function returned an :c:type:`int` type and used an :c:type:`int`
type for *start* and *end*. This might require changes in your code for
properly supporting 64-bit systems.
.. 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.
.. versionchanged:: 2.5
This function used an :ctype:`int` type for *maxcount*. This might
This function used an :c:type:`int` type for *maxcount*. This might
require changes in your code for properly supporting 64-bit systems.
.. 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_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:
@ -1103,13 +1103,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.

View File

@ -16,20 +16,20 @@ 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, char **argv)
.. c:function:: int Py_Main(int argc, char **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`
prepared exactly as those which are passed to a C program's :c:func:`main`
function. 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 ``0`` if the interpreter exits normally (ie, without an
@ -41,40 +41,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
@ -87,39 +87,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. The user will be
@ -130,34 +130,34 @@ the same library that the Python runtime is using.
: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. 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
@ -165,25 +165,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
@ -194,39 +194,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
@ -237,14 +237,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
@ -252,13 +252,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
@ -268,39 +268,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
@ -316,7 +316,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`.

View File

@ -11,28 +11,28 @@ 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.
.. versionadded:: 2.2
.. cfunction:: int PyWeakref_CheckRef(ob)
.. c:function:: int PyWeakref_CheckRef(ob)
Return true if *ob* is a reference object.
.. versionadded:: 2.2
.. cfunction:: int PyWeakref_CheckProxy(ob)
.. c:function:: int PyWeakref_CheckProxy(ob)
Return true if *ob* is a proxy object.
.. versionadded:: 2.2
.. 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
@ -46,7 +46,7 @@ as much as it can.
.. versionadded:: 2.2
.. 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
@ -60,7 +60,7 @@ as much as it can.
.. versionadded:: 2.2
.. 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`.
@ -70,14 +70,14 @@ 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.
.. versionadded:: 2.2

View File

@ -426,7 +426,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]]]])

View File

@ -112,7 +112,7 @@ The directives are:
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.
@ -124,7 +124,7 @@ The directives are:
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.
@ -135,8 +135,8 @@ The directives are:
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
@ -147,7 +147,7 @@ The directives are:
Describes a global C variable. The signature should include the type, such
as::
.. cvar:: PyObject* PyClass_Type
.. c:var:: PyObject* PyClass_Type
.. describe:: data

View File

@ -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::
@ -218,8 +218,8 @@ Python extension. For example::
{NULL, NULL, 0, NULL}
};
Insert the above code just above the :cfunc:`main` function. Also, insert the
following two statements directly after :cfunc:`Py_Initialize`::
Insert the above code just above the :c:func:`main` function. Also, insert the
following two statements directly after :c:func:`Py_Initialize`::
numargs = argc;
Py_InitModule("emb", EmbMethods);

View File

@ -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
@ -127,77 +127,77 @@ 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
condition 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:`PyInt_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:`PyInt_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:`initspam`)
and initialize it in your module's initialization function (:c:func:`initspam`)
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,21 +316,21 @@ 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 passed to the interpreter in the module's
initialization function. The initialization function must be named
:cfunc:`initname`, where *name* is the name of the module, and should be the
:c:func:`initname`, where *name* is the name of the module, and should be the
only non-\ ``static`` item defined in the module file::
PyMODINIT_FUNC
@ -344,21 +344,21 @@ 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:`initspam` is called. (See below for comments about embedding Python.)
It calls :cfunc:`Py_InitModule`, which creates a "module object" (which is
:c:func:`initspam` is called. (See below for comments about embedding Python.)
It calls :c:func:`Py_InitModule`, which creates a "module object" (which is
inserted in the dictionary ``sys.modules`` under the key ``"spam"``), and
inserts built-in function objects into the newly created module based upon the
table (an array of :ctype:`PyMethodDef` structures) that was passed as its
second argument. :cfunc:`Py_InitModule` returns a pointer to the module object
table (an array of :c:type:`PyMethodDef` structures) that was passed as its
second argument. :c:func:`Py_InitModule` returns a pointer to the module object
that it creates (which is unused here). It may abort with a fatal error for
certain errors, or return *NULL* if the module could not be initialized
satisfactorily.
When embedding Python, the :cfunc:`initspam` function is not called
automatically unless there's an entry in the :cdata:`_PyImport_Inittab` table.
When embedding Python, the :c:func:`initspam` function is not called
automatically unless there's an entry in the :c:data:`_PyImport_Inittab` table.
The easiest way to handle this is to statically initialize your
statically-linked modules by directly calling :cfunc:`initspam` after the call
to :cfunc:`Py_Initialize`::
statically-linked modules by directly calling :c:func:`initspam` after the call
to :c:func:`Py_Initialize`::
int
main(int argc, char *argv[])
@ -378,12 +378,12 @@ 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. Note also that the :func:`reload` function can be used with
extension modules, and will call the module initialization function
(:cfunc:`initspam` in the example), but will not load the module again if it was
(:c:func:`initspam` in the example), but will not load the module again if it was
loaded from a dynamically loadable object file (:file:`.so` on Unix,
:file:`.dll` on Windows).
@ -447,7 +447,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::
@ -476,10 +476,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`.
@ -487,12 +487,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;
@ -506,25 +506,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 */
@ -532,12 +532,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;
@ -552,11 +552,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;
...
@ -576,7 +576,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, ...);
@ -586,7 +586,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!
@ -663,17 +663,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::
@ -737,19 +737,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
@ -781,18 +781,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.
@ -809,7 +809,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
@ -821,11 +821,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.
@ -861,9 +861,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.
@ -871,13 +871,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. [#]_
@ -891,7 +891,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).
@ -908,36 +908,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:`PyInt_FromLong` and :cfunc:`Py_BuildValue`, pass
object, such as :c:func:`PyInt_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:`PyInt_FromLong` maintains a cache of popular values and can return a
:c:func:`PyInt_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
@ -953,7 +953,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
@ -969,7 +969,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
@ -978,8 +978,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``.
@ -1006,8 +1006,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::
@ -1036,11 +1036,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
@ -1114,7 +1114,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
@ -1127,8 +1127,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.
@ -1138,7 +1138,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.
@ -1146,19 +1146,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
@ -1167,7 +1167,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)
@ -1270,8 +1270,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
initclient(void)

View File

@ -34,7 +34,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
@ -103,7 +103,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.
@ -119,7 +119,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`. ::
0, /* ob_size */
@ -145,7 +145,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::
@ -185,12 +185,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)
@ -200,7 +200,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:`initnoddy`::
:c:func:`initnoddy`::
if (PyType_Ready(&noddy_NoddyType) < 0)
return;
@ -288,7 +288,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.
@ -334,8 +334,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
@ -345,7 +345,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::
@ -530,8 +530,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:`initnoddy` to :cfunc:`initnoddy2` and update the module name
passed to :cfunc:`Py_InitModule3`.
We rename :c:func:`initnoddy` to :c:func:`initnoddy2` and update the module name
passed to :c:func:`Py_InitModule3`.
Finally, we update our :file:`setup.py` file to build the new module::
@ -597,7 +597,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",
@ -617,7 +617,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::
@ -662,8 +662,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.
@ -728,13 +728,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 2.4 and higher provide a :cfunc:`Py_VISIT` macro that automates calling
visit functions. With :cfunc:`Py_VISIT`, :cfunc:`Noddy_traverse` can be
Python 2.4 and higher provide 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
@ -748,7 +748,7 @@ 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
@ -778,19 +778,19 @@ to use it::
self->ob_type->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 2.4 and higher provide a :cfunc:`Py_CLEAR` that automates the careful
decrementing of reference counts. With :cfunc:`Py_CLEAR`, the
:cfunc:`Noddy_clear` function can be simplified::
Python 2.4 and higher provide 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
Noddy_clear(Noddy *self)
@ -845,7 +845,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\**. ::
@ -867,10 +867,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
initshoddy(void)
@ -889,12 +889,12 @@ the module's :cfunc:`init` function. ::
PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
}
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.
@ -906,7 +906,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
@ -984,8 +984,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)
@ -1026,7 +1026,7 @@ In Python, there are three ways to generate a textual representation of an
object: the :func:`repr` function (or equivalent back-tick syntax), the
:func:`str` function, and the :keyword:`print` statement. For most objects, the
:keyword:`print` statement is equivalent to the :func:`str` function, but it is
possible to special-case printing to a :ctype:`FILE\*` if necessary; this should
possible to special-case printing to a :c:type:`FILE\*` if necessary; this should
only be done if efficiency is identified as a problem and profiling suggests
that creating a temporary string object to be written to a file is too
expensive.
@ -1110,8 +1110,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 */
@ -1122,7 +1122,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.
@ -1138,7 +1138,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
@ -1147,7 +1147,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
@ -1162,7 +1162,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 {
@ -1247,9 +1247,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. The value in showing this is two-fold: it
demonstrates how basic attribute management can be done in a way that is
@ -1262,7 +1262,7 @@ look-up. It is called in the same situations where the :meth:`__getattr__`
method of a class would be called.
A likely way to handle this is (1) to implement a set of functions (such as
:cfunc:`newdatatype_getSize` and :cfunc:`newdatatype_setSize` in the example
:c:func:`newdatatype_getSize` and :c:func:`newdatatype_setSize` in the example
below), (2) provide a method table listing these functions, and (3) provide a
getattr function that returns the result of a lookup in that table. The method
table uses the same structure as the :attr:`tp_methods` field of the type
@ -1308,7 +1308,7 @@ Object Comparison
The :attr:`tp_compare` handler is called when comparisons are needed and the
object does not implement the specific rich comparison method which matches the
requested comparison. (It is always used if defined and the
:cfunc:`PyObject_Compare` or :cfunc:`PyObject_Cmp` functions are used, or if
:c:func:`PyObject_Compare` or :c:func:`PyObject_Cmp` functions are used, or if
:func:`cmp` is used from Python.) It is analogous to the :meth:`__cmp__` method.
This function should return ``-1`` if *obj1* is less than *obj2*, ``0`` if they
are equal, and ``1`` if *obj1* is greater than *obj2*. (It was previously
@ -1318,7 +1318,7 @@ future, other return values may be assigned a different meaning.)
A :attr:`tp_compare` handler may raise an exception. In this case it should
return a negative value. The caller has to test for the exception using
:cfunc:`PyErr_Occurred`.
:c:func:`PyErr_Occurred`.
Here is a sample implementation::
@ -1366,8 +1366,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. ::
@ -1399,11 +1399,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.
@ -1478,7 +1478,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
@ -1554,7 +1554,7 @@ function you want (for example, ``tp_print`` or ``tp_compare``). 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)) {

View File

@ -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
@ -263,7 +263,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`),

View File

@ -60,41 +60,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.
@ -103,7 +103,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.
@ -112,9 +112,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 *
@ -122,7 +122,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")::
@ -135,7 +135,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)".
@ -186,7 +186,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.
@ -267,16 +267,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::
@ -307,8 +307,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
@ -460,8 +460,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:

View File

@ -117,7 +117,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).
@ -126,7 +126,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::

View File

@ -980,7 +980,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 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?

View File

@ -537,7 +537,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.

View File

@ -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:`PyUnicode` are in 2.x. The following example
shows best practices with regards to :ctype:`PyUnicode`, :ctype:`PyString`,
and :ctype:`PyBytes`. ::
compatibility 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:`PyUnicode` 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"
@ -212,43 +212,43 @@ both 2.x and 3.0 is tricky. The following simple example demonstrates how. ::
CObject replaced with Capsule
=============================
The :ctype:`Capsule` object was introduced in Python 3.1 and 2.7 to replace
:ctype:`CObject`. CObjects were useful,
but the :ctype:`CObject` API was problematic: it didn't permit distinguishing
The :c:type:`Capsule` object was introduced in Python 3.1 and 2.7 to replace
:c:type:`CObject`. CObjects were useful,
but the :c:type:`CObject` API was problematic: it didn't permit distinguishing
between valid CObjects, which allowed mismatched CObjects to crash the
interpreter, and some of its APIs relied on undefined behavior in C.
(For further reading on the rationale behind Capsules, please see :issue:`5630`.)
If you're currently using CObjects, and you want to migrate to 3.1 or newer,
you'll need to switch to Capsules.
:ctype:`CObject` was deprecated in 3.1 and 2.7 and completely removed in
:c:type:`CObject` was deprecated in 3.1 and 2.7 and completely removed in
Python 3.2. If you only support 2.7, or 3.1 and above, you
can simply switch to :ctype:`Capsule`. If you need to support 3.0 or
can simply switch to :c:type:`Capsule`. If you need to support 3.0 or
versions of Python earlier than 2.7 you'll have to support both CObjects
and Capsules.
The following example header file :file:`capsulethunk.h` may
solve the problem for you;
simply write your code against the :ctype:`Capsule` API, include
simply write your code against the :c:type:`Capsule` API, include
this header file after ``"Python.h"``, and you'll automatically use CObjects
in Python 3.0 or versions earlier than 2.7.
:file:`capsulethunk.h` simulates Capsules using CObjects. However,
:ctype:`CObject` provides no place to store the capsule's "name". As a
result the simulated :ctype:`Capsule` objects created by :file:`capsulethunk.h`
:c:type:`CObject` provides no place to store the capsule's "name". As a
result the simulated :c:type:`Capsule` objects created by :file:`capsulethunk.h`
behave slightly differently from real Capsules. Specifically:
* The name parameter passed in to :cfunc:`PyCapsule_New` is ignored.
* The name parameter passed in to :c:func:`PyCapsule_New` is ignored.
* The name parameter passed in to :cfunc:`PyCapsule_IsValid` and
:cfunc:`PyCapsule_GetPointer` is ignored, and no error checking
* The name parameter passed in to :c:func:`PyCapsule_IsValid` and
:c:func:`PyCapsule_GetPointer` is ignored, and no error checking
of the name is performed.
* :cfunc:`PyCapsule_GetName` always returns NULL.
* :c:func:`PyCapsule_GetName` always returns NULL.
* :cfunc:`PyCapsule_SetName` always throws an exception and
* :c:func:`PyCapsule_SetName` always throws an exception and
returns failure. (Since there's no way to store a name
in a CObject, noisy failure of :cfunc:`PyCapsule_SetName`
in a CObject, noisy failure of :c:func:`PyCapsule_SetName`
was deemed preferable to silent failure here. If this is
inconveient, feel free to modify your local
copy as you see fit.)

View File

@ -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*).

View File

@ -53,7 +53,7 @@ The module defines the following functions:
.. function:: queryparams(device)
The device argument is an integer. The return value is a list of integers
containing the data returned by :cfunc:`ALqueryparams`.
containing the data returned by :c:func:`ALqueryparams`.
.. function:: getparams(device, list)

View File

@ -107,7 +107,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::

View File

@ -34,7 +34,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.

View File

@ -25,7 +25,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
@ -95,8 +95,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:
@ -238,9 +238,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 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
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()

View File

@ -54,7 +54,7 @@ arguments should be used in most instances.
optional *flag* identifies the mode used to open the file. It may be ``'r'``
(read only), ``'w'`` (read-write) , ``'c'`` (read-write - create if necessary;
the default) or ``'n'`` (read-write - truncate to zero length). The other
arguments are rarely used and are just passed to the low-level :cfunc:`dbopen`
arguments are rarely used and are just passed to the low-level :c:func:`dbopen`
function. Consult the Berkeley DB documentation for their use and
interpretation.

View File

@ -759,9 +759,9 @@ Encodings and Unicode
---------------------
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 ``--enable-unicode=ucs2`` or ``--enable-unicode=ucs4``, 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 Unicode object is used outside of CPU and memory, CPU endianness
and how these arrays are stored as bytes become an issue. Transforming a
unicode object into a sequence of bytes is called encoding and recreating the

View File

@ -38,7 +38,7 @@ The :mod:`commands` module defines the following 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`.
according to the rules for the C function :c:func:`wait`.
.. function:: getoutput(cmd)

View File

@ -40,7 +40,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.
@ -201,9 +201,9 @@ should be careful anyway.
``None``, integers, longs, byte strings 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, byte strings and unicode strings are
passed as pointer to the memory block that contains their data (:ctype:`char *`
or :ctype:`wchar_t *`). Python integers and Python longs are passed as the
platforms default C :ctype:`int` type, their value is masked to fit into the C
passed as pointer to the memory block that contains their data (:c:type:`char *`
or :c:type:`wchar_t *`). Python integers and Python longs 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
@ -217,48 +217,48 @@ Fundamental data types
:mod:`ctypes` defines a number of primitive C compatible data types :
+----------------------+----------------------------------------+----------------------------+
| ctypes type | C type | Python type |
+======================+========================================+============================+
| :class:`c_bool` | :ctype:`_Bool` | bool (1) |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_char` | :ctype:`char` | 1-character string |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_wchar` | :ctype:`wchar_t` | 1-character unicode string |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_byte` | :ctype:`char` | int/long |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_ubyte` | :ctype:`unsigned char` | int/long |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_short` | :ctype:`short` | int/long |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_ushort` | :ctype:`unsigned short` | int/long |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_int` | :ctype:`int` | int/long |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_uint` | :ctype:`unsigned int` | int/long |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_long` | :ctype:`long` | int/long |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_ulong` | :ctype:`unsigned long` | int/long |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_longlong` | :ctype:`__int64` or :ctype:`long long` | int/long |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_ulonglong` | :ctype:`unsigned __int64` or | int/long |
| | :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) | string or ``None`` |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_wchar_p` | :ctype:`wchar_t *` (NUL terminated) | unicode or ``None`` |
+----------------------+----------------------------------------+----------------------------+
| :class:`c_void_p` | :ctype:`void *` | int/long or ``None`` |
+----------------------+----------------------------------------+----------------------------+
+----------------------+------------------------------------------+----------------------------+
| ctypes type | C type | Python type |
+======================+==========================================+============================+
| :class:`c_bool` | :c:type:`_Bool` | bool (1) |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_char` | :c:type:`char` | 1-character string |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_wchar` | :c:type:`wchar_t` | 1-character unicode string |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_byte` | :c:type:`char` | int/long |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_ubyte` | :c:type:`unsigned char` | int/long |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_short` | :c:type:`short` | int/long |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_ushort` | :c:type:`unsigned short` | int/long |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_int` | :c:type:`int` | int/long |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_uint` | :c:type:`unsigned int` | int/long |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_long` | :c:type:`long` | int/long |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_ulong` | :c:type:`unsigned long` | int/long |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int/long |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int/long |
| | :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) | string or ``None`` |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | unicode or ``None`` |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_void_p` | :c:type:`void *` | int/long or ``None`` |
+----------------------+------------------------------------------+----------------------------+
(1)
The constructor accepts any object with a truth value.
@ -329,7 +329,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.
@ -440,7 +440,7 @@ integer, string, unicode, 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.
@ -1338,7 +1338,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)
@ -1355,7 +1355,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
@ -1500,7 +1500,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.
@ -1530,10 +1530,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
@ -2159,21 +2159,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 string.
@ -2181,13 +2181,13 @@ 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`.
@ -2195,150 +2195,150 @@ These are the fundamental ctypes data types:
.. 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:: 2.7
.. 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.
@ -2347,18 +2347,18 @@ These are the fundamental ctypes data types:
.. 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:

View File

@ -360,7 +360,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`.
@ -534,7 +534,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.
@ -641,7 +641,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
@ -669,8 +669,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
@ -681,7 +681,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`.
@ -1024,7 +1024,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.

View File

@ -13,7 +13,7 @@
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
The :mod:`dl` module defines an interface to the :cfunc:`dlopen` function, which
The :mod:`dl` module defines an interface to the :c:func:`dlopen` function, which
is the most common interface on Unix platforms for handling dynamically linked
libraries. It allows the program to call arbitrary functions in such a library.
@ -105,10 +105,10 @@ Dl objects, as returned by :func:`.open` above, have the following methods:
Call the function named *name* in the referenced shared object. The arguments
must be either Python integers, which will be passed as is, Python strings, to
which a pointer will be passed, or ``None``, which will be passed as *NULL*.
Note that strings should only be passed to functions as :ctype:`const char\*`,
Note that strings should only be passed to functions as :c:type:`const char\*`,
as Python will not like its string mutated.
There must be at most 10 arguments, and arguments not given will be treated as
``None``. The function's return value must be a C :ctype:`long`, which is a
``None``. The function's return value must be a C :c:type:`long`, which is a
Python integer.

View File

@ -220,7 +220,7 @@ The following exceptions are the exceptions that are actually 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.
@ -249,8 +249,8 @@ The following exceptions are the exceptions that are actually 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.
@ -342,7 +342,7 @@ The following exceptions are the exceptions that are actually 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 a plain integer, it specifies the system exit status (passed
to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
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.
@ -429,16 +429,16 @@ The following exceptions are the exceptions that are actually 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`.
.. versionadded:: 2.0
.. versionchanged:: 2.5
Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`.
Previous versions put the :c:func:`GetLastError` codes into :attr:`errno`.
.. exception:: ZeroDivisionError

View File

@ -13,7 +13,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
@ -31,17 +31,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]])
@ -97,7 +97,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]]])

View File

@ -29,8 +29,8 @@ The creation of objects is a little different in Python than in C: instead of
the 'current form' maintained by the library to which new FORMS objects are
added, all functions that add a FORMS object to a form are methods of the Python
object representing the form. Consequently, there are no Python equivalents for
the C functions :cfunc:`fl_addto_form` and :cfunc:`fl_end_form`, and the
equivalent of :cfunc:`fl_bgn_form` is called :func:`fl.make_form`.
the C functions :c:func:`fl_addto_form` and :c:func:`fl_end_form`, and the
equivalent of :c:func:`fl_bgn_form` is called :func:`fl.make_form`.
Watch out for the somewhat confusing terminology: FORMS uses the word
:dfn:`object` for the buttons, sliders etc. that you can place in a form. In
@ -44,7 +44,7 @@ easy way to add object classes written in Python. The FORMS interface to GL
event handling is available, though, so you can mix FORMS with pure GL windows.
**Please note:** importing :mod:`fl` implies a call to the GL function
:cfunc:`foreground` and to the FORMS routine :cfunc:`fl_init`.
:c:func:`foreground` and to the FORMS routine :c:func:`fl_init`.
.. _fl-functions:
@ -88,7 +88,7 @@ documentation:
.. function:: get_rgbmode()
Return the current rgb mode. This is the value of the C global variable
:cdata:`fl_rgbmode`.
:c:data:`fl_rgbmode`.
.. function:: show_message(str1, str2, str3)
@ -153,8 +153,8 @@ documentation:
mapcolor()
getmcolor()
See the description in the FORMS documentation of :cfunc:`fl_color`,
:cfunc:`fl_mapcolor` and :cfunc:`fl_getmcolor`.
See the description in the FORMS documentation of :c:func:`fl_color`,
:c:func:`fl_mapcolor` and :c:func:`fl_getmcolor`.
.. _form-objects:

View File

@ -30,7 +30,7 @@ It supports the following operations:
.. function:: init()
Initialization function. Calls :cfunc:`fminit`. It is normally not necessary to
Initialization function. Calls :c:func:`fminit`. It is normally not necessary to
call this function, since it is called automatically the first time the
:mod:`fm` module is imported.
@ -43,7 +43,7 @@ It supports the following operations:
.. function:: enumerate()
Returns a list of available font names. This is an interface to
:cfunc:`fmenumerate`.
:c:func:`fmenumerate`.
.. function:: prstr(string)

View File

@ -808,7 +808,7 @@ available. They are listed here in alphabetical order.
:exc:`IOError` is raised. When opening a file, it's preferable to use
:func:`open` instead of invoking the :class:`file` constructor directly.
The first two arguments are the same as for ``stdio``'s :cfunc:`fopen`:
The first two arguments are the same as for ``stdio``'s :c:func:`fopen`:
*name* is the file name to be opened, and *mode* is a string indicating how
the file is to be opened.
@ -841,7 +841,7 @@ available. They are listed here in alphabetical order.
binary mode, on systems that differentiate between binary and text files; on
systems that don't have this distinction, adding the ``'b'`` has no effect.
In addition to the standard :cfunc:`fopen` values *mode* may be ``'U'`` or
In addition to the standard :c:func:`fopen` values *mode* may be ``'U'`` or
``'rU'``. Python is usually built with universal newline support; supplying
``'U'`` opens the file as a text file, but lines may be terminated by any of the
following: the Unix end-of-line convention ``'\n'``, the Macintosh convention
@ -1662,8 +1662,8 @@ bypass these functions without concerns about missing something important.
.. [#] It is used relatively rarely so does not warrant being made into a statement.
.. [#] Specifying a buffer size currently has no effect on systems that don't have
:cfunc:`setvbuf`. The interface to specify the buffer size is not done using a
method that calls :cfunc:`setvbuf`, because that may dump core when called after
:c:func:`setvbuf`. The interface to specify the buffer size is not done using a
method that calls :c:func:`setvbuf`, because that may dump core when called after
any I/O has been performed, and there's no reliable way to determine whether
this is the case.

View File

@ -11,13 +11,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.
@ -32,11 +32,11 @@ exception:
be parsed, without the leading reference to the running program. Typically, this
means ``sys.argv[1:]``. *options* 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.

View File

@ -366,7 +366,7 @@ Note:
.. 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``.
.. versionadded:: 2.5
@ -379,7 +379,7 @@ Note:
.. 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``.
.. versionadded:: 2.5

View File

@ -219,7 +219,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
@ -560,7 +560,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 with 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.

View File

@ -41,7 +41,7 @@ Note the capitalization of the module name; this is a historical artifact.
This exception is raised on MacOS generated errors, either from functions in
this module or from other mac-specific modules like the toolbox interfaces. The
arguments are the integer error code (the :cdata:`OSErr` value) and a textual
arguments are the integer error code (the :c:data:`OSErr` value) and a textual
description of the error code. Symbolic names for all known error codes are
defined in the standard module :mod:`macerrors`.

View File

@ -459,7 +459,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::
@ -573,7 +573,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.
@ -671,7 +671,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::
@ -722,7 +722,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::

View File

@ -44,7 +44,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)
@ -60,7 +60,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.
@ -135,20 +135,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.
@ -166,7 +166,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.
@ -174,18 +174,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``,
@ -197,7 +197,7 @@ View Objects
.. method:: View.Close()
Close the view, through :cfunc:`MsiViewClose`.
Close the view, through :c:func:`MsiViewClose`.
.. seealso::
@ -216,7 +216,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``,
@ -228,12 +228,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.
@ -241,7 +241,7 @@ Summary Information Objects
.. method:: SummaryInformation.Persist()
Write the modified properties to the summary information stream, using
:cfunc:`MsiSummaryInfoPersist`.
:c:func:`MsiSummaryInfoPersist`.
.. seealso::
@ -260,7 +260,7 @@ Record Objects
.. method:: Record.GetFieldCount()
Return the number of fields of the record, through
:cfunc:`MsiRecordGetFieldCount`.
:c:func:`MsiRecordGetFieldCount`.
.. method:: Record.GetInteger(field)
@ -277,25 +277,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::

View File

@ -152,5 +152,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`.

View File

@ -408,7 +408,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 --

View File

@ -48,7 +48,7 @@ The :mod:`new` module defines the following functions:
.. function:: code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab)
This function is an interface to the :cfunc:`PyCode_New` C function.
This function is an interface to the :c:func:`PyCode_New` C function.
.. XXX This is still undocumented!

View File

@ -94,7 +94,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
@ -309,7 +309,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.
@ -317,7 +317,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.
@ -358,7 +358,7 @@ 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.
@ -367,7 +367,7 @@ process and user.
.. 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.
@ -385,7 +385,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.
@ -454,7 +454,7 @@ These functions create new file objects. (See also :func:`open`.)
.. versionchanged:: 2.5
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).
@ -477,7 +477,7 @@ These functions create new file objects. (See also :func:`open`.)
.. versionchanged:: 2.0
This function worked unreliably under Windows in earlier versions of Python.
This was due to the use of the :cfunc:`_popen` function from the libraries
This was due to the use of the :c:func:`_popen` function from the libraries
provided with Windows. Newer versions of Python do not use the broken
implementation from the Windows libraries.
@ -697,7 +697,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 Python file object *f*, first do ``f.flush()``, and
then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
@ -1142,7 +1142,7 @@ Files and Directories
.. function:: lstat(path)
Perform the equivalent of an :cfunc:`lstat` system call on the given path.
Perform the equivalent of an :c:func:`lstat` system call on the given path.
Similar to :func:`~os.stat`, but does not follow symbolic links. On
platforms that do not support symbolic links, this is an alias for
:func:`~os.stat`.
@ -1180,7 +1180,7 @@ 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`).
.. versionadded:: 2.3
@ -1188,7 +1188,7 @@ Files and Directories
.. 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`).
.. versionadded:: 2.3
@ -1343,11 +1343,11 @@ Files and Directories
.. function:: stat(path)
Perform the equivalent of a :cfunc:`stat` system call on the given path.
Perform the equivalent of a :c:func:`stat` system call on the given path.
(This function follows symlinks; to stat a symlink use :func:`lstat`.)
The return value is an object whose attributes correspond to the members
of the :ctype:`stat` structure, namely:
of the :c:type:`stat` structure, namely:
* :attr:`st_mode` - protection bits,
* :attr:`st_ino` - inode number,
@ -1404,7 +1404,7 @@ Files and Directories
For backward compatibility, the return value of :func:`~os.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.
@ -1412,7 +1412,7 @@ Files and Directories
.. index:: module: stat
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.)
Example::
@ -1461,9 +1461,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`.
@ -1473,7 +1473,7 @@ Files and Directories
For backward compatibility, the return value is also accessible as a tuple whose
values correspond to the attributes, in the order given above. The standard
module :mod:`statvfs` defines constants that are useful for extracting
information from a :ctype:`statvfs` structure when accessing it as a sequence;
information from a :c:type:`statvfs` structure when accessing it as a sequence;
this remains useful when writing code that needs to work with versions of Python
that don't support accessing the fields as attributes.
@ -1664,7 +1664,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.
@ -2117,7 +2117,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.
@ -2132,13 +2132,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

View File

@ -59,7 +59,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

View File

@ -33,8 +33,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.

View File

@ -104,7 +104,7 @@ methods:
Waits for and returns the status code of the child process. The status code
encodes both the return code of the process and information about whether it
exited using the :cfunc:`exit` system call or died due to a signal. Functions
exited using the :c:func:`exit` system call or died due to a signal. Functions
to help interpret the status code are defined in the :mod:`os` module; see
section :ref:`os-process` for the :func:`W\*` family of functions.

View File

@ -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`. Python longs are then used to represent
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`. Python longs are then used to represent
file sizes, offsets and other values that can exceed the range of a Python int.
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

View File

@ -1053,14 +1053,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`` | ``.`` |
+--------------------------------+---------------------------------------------+
@ -1085,7 +1085,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

View File

@ -31,7 +31,7 @@ restrictions can be imposed, depending on the application. For example, it
might be deemed "safe" for untrusted code to read any file within a specified
directory, but never to write a file. In this case, the supervisor may redefine
the built-in :func:`open` function so that it raises an exception whenever the
*mode* parameter is ``'w'``. It might also perform a :cfunc:`chroot`\ -like
*mode* parameter is ``'w'``. It might also perform a :c:func:`chroot`\ -like
operation on the *filename* parameter, such that root is always relative to some
safe "sandbox" area of the filesystem. In this case, the untrusted code would
still see an built-in :func:`open` function in its environment, with the same

View File

@ -42,8 +42,8 @@ various end-user mail programs.
from a buffered stream.
The optional *seekable* argument is provided as a workaround for certain stdio
libraries in which :cfunc:`tell` discards buffered data before discovering that
the :cfunc:`lseek` system call doesn't work. For maximum portability, you
libraries in which :c:func:`tell` discards buffered data before discovering that
the :c:func:`lseek` system call doesn't work. For maximum portability, you
should set the seekable argument to zero to prevent that initial :meth:`tell`
when passing in an unseekable object such as a file object created from a socket
object.

View File

@ -6,9 +6,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
@ -20,8 +20,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])
@ -60,7 +60,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:
@ -96,7 +96,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.
@ -195,13 +195,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])

Some files were not shown because too many files have changed in this diff Show More