diff --git a/Doc/c-api/abstract.rst b/Doc/c-api/abstract.rst index f5df09fa7fd786..bf4f8447bb2886 100644 --- a/Doc/c-api/abstract.rst +++ b/Doc/c-api/abstract.rst @@ -8,7 +8,7 @@ Abstract Objects Layer The functions in this chapter interact with Python objects regardless of their type, or with wide classes of object types (e.g. all numerical types, or all -sequence types). When used on object types for which they do not apply, they +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 diff --git a/Doc/c-api/allocation.rst b/Doc/c-api/allocation.rst index 59d913a0462382..fc4ae9055f1ac9 100644 --- a/Doc/c-api/allocation.rst +++ b/Doc/c-api/allocation.rst @@ -15,10 +15,10 @@ Allocating Objects on the Heap .. 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. Other fields of the object are - not initialized. Despite its name, this function is unrelated to the + reference. Returns the initialized object. Other fields of the object are + not initialized. Despite its name, this function is unrelated to the object's :meth:`~object.__init__` method (:c:member:`~PyTypeObject.tp_init` - slot). Specifically, this function does **not** call the object's + slot). Specifically, this function does **not** call the object's :meth:`!__init__` method. In general, consider this function to be a low-level routine. Use @@ -29,7 +29,7 @@ Allocating Objects on the Heap .. note:: This function only initializes the object's memory corresponding to the - initial :c:type:`PyObject` structure. It does not zero the rest. + initial :c:type:`PyObject` structure. It does not zero the rest. .. c:function:: PyVarObject* PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size) @@ -39,7 +39,7 @@ Allocating Objects on the Heap .. note:: - This function only initializes some of the object's memory. It does not + This function only initializes some of the object's memory. It does not zero the rest. @@ -48,7 +48,7 @@ Allocating Objects on the Heap Allocates a new Python object using the C structure type *TYPE* and the Python type object *typeobj* (``PyTypeObject*``) by calling :c:func:`PyObject_Malloc` to allocate memory and initializing it like - :c:func:`PyObject_Init`. The caller will own the only reference to the + :c:func:`PyObject_Init`. The caller will own the only reference to the object (i.e. its reference count will be one). Avoid calling this directly to allocate memory for an object; call the type's @@ -77,8 +77,8 @@ Allocating Objects on the Heap This macro does not construct a fully initialized object of the given type; it merely allocates memory and prepares it for further - initialization by :c:member:`~PyTypeObject.tp_init`. To construct a - fully initialized object, call *typeobj* instead. For example:: + initialization by :c:member:`~PyTypeObject.tp_init`. To construct a + fully initialized object, call *typeobj* instead. For example:: PyObject *foo = PyObject_CallNoArgs((PyObject *)&PyFoo_Type); @@ -100,7 +100,7 @@ Allocating Objects on the Heap * The memory is initialized like :c:func:`PyObject_InitVar`. This is useful for implementing objects like tuples, which are able to - determine their size at construction time. Embedding the array of fields + determine their size at construction time. Embedding the array of fields into the same allocation decreases the number of allocations, improving the memory management efficiency. @@ -127,8 +127,8 @@ Allocating Objects on the Heap This macro does not construct a fully initialized object of the given type; it merely allocates memory and prepares it for further - initialization by :c:member:`~PyTypeObject.tp_init`. To construct a - fully initialized object, call *typeobj* instead. For example:: + initialization by :c:member:`~PyTypeObject.tp_init`. To construct a + fully initialized object, call *typeobj* instead. For example:: PyObject *list_instance = PyObject_CallNoArgs((PyObject *)&PyList_Type); @@ -146,7 +146,7 @@ Allocating Objects on the Heap .. c:var:: PyObject _Py_NoneStruct - Object which is visible in Python as ``None``. This should only be accessed + Object which is visible in Python as ``None``. This should only be accessed using the :c:macro:`Py_None` macro, which evaluates to a pointer to this object. diff --git a/Doc/c-api/arg.rst b/Doc/c-api/arg.rst index 803572afc39ae3..684c7ea67d0107 100644 --- a/Doc/c-api/arg.rst +++ b/Doc/c-api/arg.rst @@ -6,23 +6,23 @@ Parsing arguments and building values ===================================== These functions are useful when creating your own extension functions and -methods. Additional information and examples are available in +methods. Additional information and examples are available in :ref:`extending-index`. 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 +strings* which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions. ----------------- Parsing arguments ----------------- -A format string consists of zero or more "format units." A format unit +A format string consists of zero or more "format units." A format unit describes one Python object; it is usually a single character or a parenthesized -sequence of format units. With a few exceptions, a format unit that is not a +sequence of format units. With a few exceptions, a format unit that is not a parenthesized sequence normally corresponds to a single address argument to -these functions. In the following description, the quoted form is the format +these functions. In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that matches the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed. @@ -47,18 +47,18 @@ Unless otherwise stated, buffers are not NUL-terminated. There are three ways strings and buffers can be converted to C: -* Formats such as ``y*`` and ``s*`` fill a :c:type:`Py_buffer` structure. +* Formats such as ``y*`` and ``s*`` fill a :c:type:`Py_buffer` structure. This locks the underlying buffer so that the caller can subsequently use the buffer even inside a :c:type:`Py_BEGIN_ALLOW_THREADS` block without the risk of mutable data being resized or destroyed. As a result, **you have to call** :c:func:`PyBuffer_Release` after you have finished processing the data (or in any early abort case). -* The ``es``, ``es#``, ``et`` and ``et#`` formats allocate the result buffer. +* The ``es``, ``es#``, ``et`` and ``et#`` formats allocate the result buffer. **You have to call** :c:func:`PyMem_Free` after you have finished processing the data (or in any early abort case). -* .. _c-arg-borrowed-buffer: +* .. _c-arg-borrowed-buffer: Other formats take a :class:`str` or a read-only :term:`bytes-like object`, such as :class:`bytes`, and provide a ``const char *`` pointer to @@ -80,7 +80,7 @@ There are three ways strings and buffers can be converted to C: ``s`` (:class:`str`) [const char \*] Convert a Unicode object to a C pointer to a character string. A pointer to an existing string is stored in the character pointer - variable whose address you pass. The C string is NUL-terminated. + variable whose address you pass. The C string is NUL-terminated. The Python string must not contain embedded null code points; if it does, a :exc:`ValueError` exception is raised. Unicode objects are converted to C strings using ``'utf-8'`` encoding. If this conversion fails, a @@ -88,7 +88,7 @@ There are three ways strings and buffers can be converted to C: .. note:: This format does not accept :term:`bytes-like objects - `. If you want to accept + `. If you want to accept filesystem paths and convert them to C character strings, it is preferable to use the ``O&`` format with :c:func:`PyUnicode_FSConverter` as *converter*. @@ -129,7 +129,7 @@ There are three ways strings and buffers can be converted to C: ``y`` (read-only :term:`bytes-like object`) [const char \*] This format converts a bytes-like object to a C pointer to a :ref:`borrowed ` character string; - it does not accept Unicode objects. The bytes buffer must not + it does not accept Unicode objects. The bytes buffer must not contain embedded null bytes; if it does, a :exc:`ValueError` exception is raised. @@ -139,7 +139,7 @@ There are three ways strings and buffers can be converted to C: ``y*`` (:term:`bytes-like object`) [Py_buffer] This variant on ``s*`` doesn't accept Unicode objects, only - bytes-like objects. **This is the recommended way to accept + bytes-like objects. **This is the recommended way to accept binary data.** ``y#`` (read-only :term:`bytes-like object`) [const char \*, :c:type:`Py_ssize_t`] @@ -148,18 +148,18 @@ There are three ways strings and buffers can be converted to C: ``S`` (:class:`bytes`) [PyBytesObject \*] Requires that the Python object is a :class:`bytes` object, without - attempting any conversion. Raises :exc:`TypeError` if the object is not - a bytes object. The C variable may also be declared as :c:expr:`PyObject*`. + attempting any conversion. Raises :exc:`TypeError` if the object is not + a bytes object. The C variable may also be declared as :c:expr:`PyObject*`. ``Y`` (:class:`bytearray`) [PyByteArrayObject \*] Requires that the Python object is a :class:`bytearray` object, without - attempting any conversion. Raises :exc:`TypeError` if the object is not + attempting any conversion. Raises :exc:`TypeError` if the object is not a :class:`bytearray` object. The C variable may also be declared as :c:expr:`PyObject*`. ``U`` (:class:`str`) [PyObject \*] Requires that the Python object is a Unicode object, without attempting - any conversion. Raises :exc:`TypeError` if the object is not a Unicode - object. The C variable may also be declared as :c:expr:`PyObject*`. + any conversion. Raises :exc:`TypeError` if the object is not a Unicode + object. The C variable may also be declared as :c:expr:`PyObject*`. ``w*`` (read-write :term:`bytes-like object`) [Py_buffer] This format accepts any object which implements the read-write buffer @@ -171,22 +171,22 @@ There are three ways strings and buffers can be converted to C: This variant on ``s`` is used for encoding Unicode into a character buffer. It only works for encoded data without embedded NUL bytes. - This format requires two arguments. The first is only used as input, and + This format requires two arguments. The first is only used as input, and must be a :c:expr:`const char*` which points to the name of an encoding as a NUL-terminated string, or ``NULL``, in which case ``'utf-8'`` encoding is used. - An exception is raised if the named encoding is not known to Python. The + An exception is raised if the named encoding is not known to Python. The second argument must be a :c:expr:`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. :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 :c:func:`PyMem_Free` to + allocated storage. The caller is responsible for calling :c:func:`PyMem_Free` to free the allocated buffer after use. ``et`` (:class:`str`, :class:`bytes` or :class:`bytearray`) [const char \*encoding, char \*\*buffer] Same as ``es`` except that byte string objects are passed through without - recoding them. Instead, the implementation assumes that the byte string object uses + recoding them. Instead, the implementation assumes that the byte string object uses the encoding passed in as parameter. ``es#`` (:class:`str`) [const char \*encoding, char \*\*buffer, :c:type:`Py_ssize_t` \*buffer_length] @@ -194,10 +194,10 @@ There are three ways strings and buffers can be converted to C: Unlike the ``es`` format, this variant allows input data which contains NUL characters. - It requires three arguments. The first is only used as input, and must be a + It requires three arguments. The first is only used as input, and must be a :c:expr:`const char*` which points to the name of an encoding as a NUL-terminated string, or ``NULL``, in which case ``'utf-8'`` encoding is used. - An exception is raised if the named encoding is not known to Python. The + An exception is raised if the named encoding is not known to Python. The second argument must be a :c:expr:`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. @@ -208,13 +208,13 @@ There are three ways strings and buffers can be converted to C: 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 + reference the newly allocated storage. The caller is 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), :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 + 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. In both cases, *\*buffer_length* is set to the length of the encoded data @@ -321,25 +321,25 @@ Other objects ------------- ``O`` (object) [PyObject \*] - Store a Python object (without any conversion) in a C object pointer. The C - program thus receives the actual object that was passed. A new + Store a Python object (without any conversion) in a C object pointer. The C + program thus receives the actual object that was passed. A new :term:`strong reference` to the object is not created (i.e. its reference count is not increased). The pointer stored is not ``NULL``. ``O!`` (object) [*typeobject*, PyObject \*] - Store a Python object in a C object pointer. This is similar to ``O``, but + 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 :c:expr:`PyObject*`) into which - the object pointer is stored. If the Python object does not have the required + the object pointer is stored. If the Python object does not have the required type, :exc:`TypeError` is raised. .. _o_ampersand: ``O&`` (object) [*converter*, *address*] - Convert a Python object to a C variable through a *converter* function. This + 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 :c:expr:`void *`. The *converter* + variable (of arbitrary type), converted to :c:expr:`void *`. The *converter* function in turn is called as follows:: status = converter(object, address); @@ -347,7 +347,7 @@ Other objects where *object* is the Python object to be converted and *address* is the :c:expr:`void*` argument that was passed to the ``PyArg_Parse*`` function. The returned *status* should be ``1`` for a successful conversion and ``0`` if - the conversion has failed. When the conversion fails, the *converter* function + the conversion has failed. When the conversion fails, the *converter* function should raise an exception and leave the content of *address* unmodified. .. c:macro:: Py_CLEANUP_SUPPORTED @@ -369,7 +369,7 @@ Other objects Tests the value passed in for truth (a boolean **p**\ redicate) and converts the result to its equivalent C true/false integer value. Sets the int to ``1`` if the expression was true and ``0`` if it was false. - This accepts any valid Python value. See :ref:`truth` for more + This accepts any valid Python value. See :ref:`truth` for more information about how Python tests values for truth. .. versionadded:: 3.3 @@ -377,8 +377,8 @@ Other objects ``(items)`` (sequence) [*matching-items*] The object must be a Python sequence (except :class:`str`, :class:`bytes` or :class:`bytearray`) whose length is the number of format units - in *items*. The C arguments must correspond to the individual format units in - *items*. Format units for sequences may be nested. + in *items*. The C arguments must correspond to the individual format units in + *items*. Format units for sequences may be nested. If *items* contains format units which store a :ref:`borrowed buffer ` (``s``, ``s#``, ``z``, ``z#``, ``y``, or ``y#``) @@ -405,8 +405,8 @@ Other objects .. versionadded:: 3.14 -A few other characters have a meaning in a format string. These may not occur -inside nested parentheses. They are: +A few other characters have a meaning in a format string. These may not occur +inside nested parentheses. They are: ``|`` Indicates that the remaining arguments in the Python argument list are optional. @@ -418,7 +418,7 @@ inside nested parentheses. They are: ``$`` :c:func:`PyArg_ParseTupleAndKeywords` only: Indicates that the remaining arguments in the Python argument list are - keyword-only. Currently, all keyword-only arguments must also be optional + keyword-only. Currently, all keyword-only arguments must also be optional arguments, so ``|`` must always be specified before ``$`` in the format string. @@ -431,7 +431,7 @@ inside nested parentheses. They are: ``;`` The list of format units ends here; the string after the semicolon is used as - the error message *instead* of the default error message. ``:`` and ``;`` + the error message *instead* of the default error message. ``:`` and ``;`` mutually exclude each other. Note that any Python object references which are provided to the caller are @@ -440,12 +440,12 @@ Note that any Python object references which are provided to the caller are Additional arguments passed to these functions must be addresses of variables whose type is determined by the format string; these are used to store values -from the input tuple. There are a few cases, as described in the list of format +from the input tuple. There are a few cases, as described in the list of 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 +and the format must be exhausted. On success, the ``PyArg_Parse*`` functions return true, otherwise they return false and raise an appropriate exception. When the ``PyArg_Parse*`` functions fail due to conversion failure in one @@ -458,7 +458,7 @@ API Functions .. 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 + local variables. Returns true on success; on failure, it returns false and raises the appropriate exception. @@ -504,7 +504,7 @@ API Functions .. c:function:: int PyArg_ValidateKeywordArguments(PyObject *) - Ensure that the keys in the keywords argument dictionary are strings. This + Ensure that the keys in the keywords argument dictionary are strings. This is only needed if :c:func:`PyArg_ParseTupleAndKeywords` is not used, since the latter already does this check. @@ -514,7 +514,7 @@ API Functions .. c:function:: int PyArg_Parse(PyObject *args, const char *format, ...) Parse the parameter of a function that takes a single positional parameter - into a local variable. Returns true on success; on failure, it returns + into a local variable. Returns true on success; on failure, it returns false and raises the appropriate exception. Example:: @@ -534,11 +534,11 @@ API Functions .. c:function:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) A simpler form of parameter retrieval which does not use a format string to - specify the types of the arguments. Functions which use this method to retrieve + specify the types of the arguments. Functions which use this method to retrieve their parameters should be declared as :c:macro:`METH_VARARGS` in function or - method tables. The tuple containing the actual parameters should be passed as - *args*; it must actually be a tuple. The length of the tuple must be at least - *min* and no more than *max*; *min* and *max* may be equal. Additional + method tables. The tuple containing the actual parameters should be passed as + *args*; it must actually be a tuple. The length of the tuple must be at least + *min* and no more than *max*; *min* and *max* may be equal. Additional arguments must be passed to the function, each of which should be a pointer to a :c:expr:`PyObject*` variable; these will be filled in with the values from *args*; they will contain :term:`borrowed references `. @@ -590,20 +590,20 @@ Building values .. c:function:: PyObject* Py_BuildValue(const char *format, ...) Create a new value based on a format string similar to those accepted by the - ``PyArg_Parse*`` family of functions and a sequence of values. Returns + ``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. - :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 + :c:func:`Py_BuildValue` does not always build a tuple. It builds a tuple only if + its format string contains two or more format units. If the format string is empty, it returns ``None``; if it contains exactly one format unit, it returns - whatever object is described by that format unit. To force it to return a tuple + whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string. When memory buffers are passed as parameters to supply data to build objects, as - for the ``s`` and ``s#`` formats, the required data is copied. Buffers provided + for the ``s`` and ``s#`` formats, the required data is copied. Buffers provided by the caller are never referenced by the objects created by - :c:func:`Py_BuildValue`. In other words, if your code invokes :c:func:`malloc` + :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. @@ -613,7 +613,7 @@ Building values and the entry in [square] brackets is the type of the C value(s) to be passed. The characters space, tab, colon and comma are ignored in format strings (but - not within format units such as ``s#``). This can be used to make long format + not within format units such as ``s#``). This can be used to make long format strings a tad more readable. ``s`` (:class:`str` or ``None``) [const char \*] @@ -626,11 +626,11 @@ Building values ``None`` is returned. ``y`` (:class:`bytes`) [const char \*] - This converts a C string to a Python :class:`bytes` object. If the C + This converts a C string to a Python :class:`bytes` object. If the C string pointer is ``NULL``, ``None`` is returned. ``y#`` (:class:`bytes`) [const char \*, :c:type:`Py_ssize_t`] - This converts a C string and its lengths to a Python object. If the C + This converts a C string and its lengths to a Python object. If the C string pointer is ``NULL``, ``None`` is returned. ``z`` (:class:`str` or ``None``) [const char \*] @@ -641,12 +641,12 @@ Building values ``u`` (:class:`str`) [const wchar_t \*] Convert a null-terminated :c:type:`wchar_t` buffer of Unicode (UTF-16 or UCS-4) - data to a Python Unicode object. If the Unicode buffer pointer is ``NULL``, + data to a Python Unicode object. If the Unicode buffer pointer is ``NULL``, ``None`` is returned. ``u#`` (:class:`str`) [const wchar_t \*, :c:type:`Py_ssize_t`] Convert a Unicode (UTF-16 or UCS-4) data buffer and its length to a Python - Unicode object. If the Unicode buffer pointer is ``NULL``, the length is ignored + Unicode object. If the Unicode buffer pointer is ``NULL``, the length is ignored and ``None`` is returned. ``U`` (:class:`str` or ``None``) [const char \*] @@ -725,7 +725,7 @@ Building values 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, :c:func:`Py_BuildValue` will return ``NULL`` but won't - raise an exception. If no exception has been raised yet, :exc:`SystemError` is + raise an exception. If no exception has been raised yet, :exc:`SystemError` is set. ``S`` (object) [PyObject \*] @@ -737,7 +737,7 @@ Building values argument list. ``O&`` (object) [*converter*, *anything*] - Convert *anything* to a Python object through a *converter* function. The + Convert *anything* to a Python object through a *converter* function. The function is called with *anything* (which should be compatible with :c:expr:`void*`) as its argument and should return a "new" Python object, or ``NULL`` if an error occurred. @@ -749,7 +749,7 @@ Building values Convert a sequence of C values to a Python list with the same number of items. ``{items}`` (:class:`dict`) [*matching-items*] - Convert a sequence of C values to a Python dictionary. Each pair of consecutive + Convert a sequence of C values to a Python dictionary. Each pair of consecutive C values adds one item to the dictionary, serving as key and value, respectively. diff --git a/Doc/c-api/bool.rst b/Doc/c-api/bool.rst index b4dc4849d044e1..cdd609a821ddb1 100644 --- a/Doc/c-api/bool.rst +++ b/Doc/c-api/bool.rst @@ -5,9 +5,9 @@ Boolean Objects --------------- -Booleans in Python are implemented as a subclass of integers. There are only -two booleans, :c:data:`Py_False` and :c:data:`Py_True`. As such, the normal -creation and deletion functions don't apply to booleans. The following macros +Booleans in Python are implemented as a subclass of integers. There are only +two booleans, :c:data:`Py_False` and :c:data:`Py_True`. As such, the normal +creation and deletion functions don't apply to booleans. The following macros are available, however. @@ -19,13 +19,13 @@ are available, however. .. c:function:: int PyBool_Check(PyObject *o) - Return true if *o* is of type :c:data:`PyBool_Type`. This function always + Return true if *o* is of type :c:data:`PyBool_Type`. This function always succeeds. .. c:var:: PyObject* Py_False - The Python ``False`` object. This object has no methods and is + The Python ``False`` object. This object has no methods and is :term:`immortal`. .. versionchanged:: 3.12 @@ -34,7 +34,7 @@ are available, however. .. c:var:: PyObject* Py_True - The Python ``True`` object. This object has no methods and is + The Python ``True`` object. This object has no methods and is :term:`immortal`. .. versionchanged:: 3.12 diff --git a/Doc/c-api/buffer.rst b/Doc/c-api/buffer.rst index d3081894eadaf5..9475e979ab6bbe 100644 --- a/Doc/c-api/buffer.rst +++ b/Doc/c-api/buffer.rst @@ -16,18 +16,18 @@ Buffer Protocol Certain objects available in Python wrap access to an underlying memory -array or *buffer*. Such objects include the built-in :class:`bytes` and +array or *buffer*. Such objects include the built-in :class:`bytes` and :class:`bytearray`, and some extension types like :class:`array.array`. Third-party libraries may define their own types for special purposes, such as image processing or numeric analysis. While each of these types have their own semantics, they share the common -characteristic of being backed by a possibly large memory buffer. It is +characteristic of being backed by a possibly large memory buffer. It is then desirable, in some situations, to access that buffer directly and without intermediate copying. Python provides such a facility at the C and Python level in the form of the -:ref:`buffer protocol `. This protocol has two sides: +:ref:`buffer protocol `. This protocol has two sides: .. index:: single: PyBufferProcs (C type) @@ -41,15 +41,15 @@ Python provides such a facility at the C and Python level in the form of the Python see :class:`memoryview`. Simple objects such as :class:`bytes` and :class:`bytearray` expose their -underlying buffer in byte-oriented form. Other forms are possible; for example, +underlying buffer in byte-oriented form. Other forms are possible; for example, the elements exposed by an :class:`array.array` can be multi-byte values. An example consumer of the buffer interface is the :meth:`~io.BufferedIOBase.write` method of file objects: any object that can export a series of bytes through -the buffer interface can be written to a file. While :meth:`!write` only +the buffer interface can be written to a file. While :meth:`!write` only needs read-only access to the internal contents of the object passed to it, other methods such as :meth:`~io.BufferedIOBase.readinto` need write access -to the contents of their argument. The buffer interface allows objects to +to the contents of their argument. The buffer interface allows objects to selectively allow or reject exporting of read-write and read-only buffers. There are two ways for a consumer of the buffer interface to acquire a buffer @@ -61,7 +61,7 @@ over a target object: ``y*``, ``w*`` or ``s*`` :ref:`format codes `. In both cases, :c:func:`PyBuffer_Release` must be called when the buffer -isn't needed anymore. Failure to do so could lead to various issues such as +isn't needed anymore. Failure to do so could lead to various issues such as resource leaks. .. versionadded:: 3.12 @@ -75,17 +75,17 @@ Buffer structure ================ Buffer structures (or simply "buffers") are useful as a way to expose the -binary data from another object to the Python programmer. They can also be -used as a zero-copy slicing mechanism. Using their ability to reference a +binary data from another object to the Python programmer. They can also be +used as a zero-copy slicing mechanism. Using their ability to reference a block of memory, it is possible to expose any data to the Python programmer -quite easily. The memory could be a large, constant array in a C extension, +quite easily. The memory could be a large, constant array in a C extension, it could be a raw block of memory for manipulation before passing to an operating system library, or it could be used to pass around structured data in its native, in-memory format. Contrary to most data types exposed by the Python interpreter, buffers -are not :c:type:`PyObject` pointers but rather simple C structures. This -allows them to be created and copied very simply. When a generic wrapper +are not :c:type:`PyObject` pointers but rather simple C structures. This +allows them to be created and copied very simply. When a generic wrapper around a buffer is needed, a :ref:`memoryview ` object can be created. @@ -142,7 +142,7 @@ a buffer, see :c:func:`PyObject_GetBuffer`. Important exception: If a consumer requests a buffer without the :c:macro:`PyBUF_FORMAT` flag, :c:member:`~Py_buffer.format` will - be set to ``NULL``, but :c:member:`~Py_buffer.itemsize` still has + be set to ``NULL``, but :c:member:`~Py_buffer.itemsize` still has the value for the original format. If :c:member:`~Py_buffer.shape` is present, the equality @@ -446,14 +446,14 @@ Buffer-related functions .. c:function:: int PyObject_CheckBuffer(PyObject *obj) - Return ``1`` if *obj* supports the buffer interface otherwise ``0``. When ``1`` is + Return ``1`` if *obj* supports the buffer interface otherwise ``0``. When ``1`` is returned, it doesn't guarantee that :c:func:`PyObject_GetBuffer` will - succeed. This function always succeeds. + succeed. This function always succeeds. .. c:function:: int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags) - Send a request to *exporter* to fill in *view* as specified by *flags*. + Send a request to *exporter* to fill in *view* as specified by *flags*. If the exporter cannot provide a buffer of the exact type, it MUST raise :exc:`BufferError`, set ``view->obj`` to ``NULL`` and return ``-1``. @@ -492,7 +492,7 @@ Buffer-related functions Return ``1`` if the memory defined by the *view* is C-style (*order* is ``'C'``) or Fortran-style (*order* is ``'F'``) :term:`contiguous` or either one - (*order* is ``'A'``). Return ``0`` otherwise. This function always succeeds. + (*order* is ``'A'``). Return ``0`` otherwise. This function always succeeds. .. c:function:: void* PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices) diff --git a/Doc/c-api/bytearray.rst b/Doc/c-api/bytearray.rst index e2b22ec3c794ae..43ec310c8269e0 100644 --- a/Doc/c-api/bytearray.rst +++ b/Doc/c-api/bytearray.rst @@ -25,13 +25,13 @@ Type check macros .. 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. This function always succeeds. + subtype of the bytearray type. This function always succeeds. .. 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. This function always succeeds. + subtype of the bytearray type. This function always succeeds. Direct API functions @@ -67,7 +67,7 @@ Direct API functions .. c:function:: char* PyByteArray_AsString(PyObject *bytearray) Return the contents of *bytearray* as a char array after checking for a - ``NULL`` pointer. The returned array always has an extra + ``NULL`` pointer. The returned array always has an extra null byte appended. diff --git a/Doc/c-api/bytes.rst b/Doc/c-api/bytes.rst index d47beee68eaa33..a8c2dd89b4e1d3 100644 --- a/Doc/c-api/bytes.rst +++ b/Doc/c-api/bytes.rst @@ -25,26 +25,26 @@ called with a non-bytes parameter. .. c:function:: int PyBytes_Check(PyObject *o) Return true if the object *o* is a bytes object or an instance of a subtype - of the bytes type. This function always succeeds. + of the bytes type. This function always succeeds. .. c:function:: int PyBytes_CheckExact(PyObject *o) Return true if the object *o* is a bytes object, but not an instance of a - subtype of the bytes type. This function always succeeds. + subtype of the bytes type. This function always succeeds. .. c:function:: PyObject* PyBytes_FromString(const char *v) Return a new bytes object with a copy of the string *v* as value on success, - and ``NULL`` on failure. The parameter *v* must not be ``NULL``; it will not be + and ``NULL`` on failure. The parameter *v* must not be ``NULL``; it will not be checked. .. c:function:: PyObject* PyBytes_FromStringAndSize(const char *v, Py_ssize_t len) Return a new bytes object with a copy of the string *v* as value and length - *len* on success, and ``NULL`` on failure. If *v* is ``NULL``, the contents of + *len* on success, and ``NULL`` on failure. If *v* is ``NULL``, the contents of the bytes object are uninitialized. @@ -52,9 +52,9 @@ called with a non-bytes parameter. Take a C :c:func:`printf`\ -style *format* string and a variable number of arguments, calculate the size of the resulting Python bytes object and return - a bytes object with the values formatted into it. The variable arguments + a bytes object with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the - *format* string. The following format characters are allowed: + *format* string. The following format characters are allowed: .. % XXX: This should be exactly the same as the table in PyErr_Format. .. % One should just refer to the other. @@ -136,12 +136,12 @@ called with a non-bytes parameter. .. c:function:: char* PyBytes_AsString(PyObject *o) - Return a pointer to the contents of *o*. The pointer + Return a pointer to the contents of *o*. The pointer refers to the internal buffer of *o*, which consists of ``len(o) + 1`` - bytes. The last byte in the buffer is always null, regardless of - whether there are any other null bytes. The data must not be + bytes. The last byte in the buffer is always null, regardless of + whether there are any other null bytes. The data must not be modified in any way, unless the object was just created using - ``PyBytes_FromStringAndSize(NULL, size)``. It must not be deallocated. If + ``PyBytes_FromStringAndSize(NULL, size)``. It must not be deallocated. If *o* is not a bytes object at all, :c:func:`PyBytes_AsString` returns ``NULL`` and raises :exc:`TypeError`. @@ -162,9 +162,9 @@ called with a non-bytes parameter. if it does, the function returns ``-1`` and a :exc:`ValueError` is raised. The buffer refers to an internal buffer of *obj*, which includes an - additional null byte at the end (not counted in *length*). The data + additional null byte at the end (not counted in *length*). The data must not be modified in any way, unless the object was just created using - ``PyBytes_FromStringAndSize(NULL, size)``. It must not be deallocated. If + ``PyBytes_FromStringAndSize(NULL, size)``. It must not be deallocated. If *obj* is not a bytes object at all, :c:func:`PyBytes_AsStringAndSize` returns ``-1`` and raises :exc:`TypeError`. @@ -176,8 +176,8 @@ called with a non-bytes parameter. .. c:function:: void PyBytes_Concat(PyObject **bytes, PyObject *newpart) Create a new bytes object in *\*bytes* containing the contents of *newpart* - appended to *bytes*; the caller will own the new reference. The reference to - the old value of *bytes* will be stolen. If the new object cannot be + appended to *bytes*; the caller will own the new reference. The reference to + the old value of *bytes* will be stolen. If the new object cannot be created, the old reference to *bytes* will still be discarded and the value of *\*bytes* will be set to ``NULL``; the appropriate exception will be set. @@ -185,7 +185,7 @@ called with a non-bytes parameter. .. c:function:: void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart) Create a new bytes object in *\*bytes* containing the contents of *newpart* - appended to *bytes*. This version releases the :term:`strong reference` + appended to *bytes*. This version releases the :term:`strong reference` to *newpart* (i.e. decrements its reference count). @@ -214,8 +214,8 @@ called with a non-bytes parameter. one, only more efficiently. Pass the address of an existing bytes object as an lvalue (it may be written into), and the new size - desired. On success, *\*bytes* holds the resized bytes object and ``0`` is - returned; the address in *\*bytes* may differ from its input value. If the + desired. On success, *\*bytes* holds the resized bytes object and ``0`` is + returned; the address in *\*bytes* may differ from its input value. If the reallocation fails, the original bytes object at *\*bytes* is deallocated, *\*bytes* is set to ``NULL``, :exc:`MemoryError` is set, and ``-1`` is returned. diff --git a/Doc/c-api/call.rst b/Doc/c-api/call.rst index 7198d6bc056eb4..77e92c77675240 100644 --- a/Doc/c-api/call.rst +++ b/Doc/c-api/call.rst @@ -254,7 +254,7 @@ please see individual documentation for details. .. c:function:: PyObject* PyObject_CallObject(PyObject *callable, PyObject *args) Call a callable Python object *callable*, with arguments given by the - tuple *args*. If no arguments are needed, then *args* can be *NULL*. + tuple *args*. If no arguments are needed, then *args* can be *NULL*. Return the result of the call on success, or raise an exception and return *NULL* on failure. @@ -266,7 +266,7 @@ please see individual documentation for details. Call a callable Python object *callable*, with a variable number of C arguments. The C arguments are described using a :c:func:`Py_BuildValue` style format - string. The format can be *NULL*, indicating that no arguments are provided. + string. The format can be *NULL*, indicating that no arguments are provided. Return the result of the call on success, or raise an exception and return *NULL* on failure. @@ -283,7 +283,7 @@ please see individual documentation for details. .. c:function:: PyObject* PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...) Call the method named *name* of object *obj* with a variable number of C - arguments. The C arguments are described by a :c:func:`Py_BuildValue` format + arguments. The C arguments are described by a :c:func:`Py_BuildValue` format string that should produce a tuple. The format can be *NULL*, indicating that no arguments are provided. @@ -304,7 +304,7 @@ please see individual documentation for details. .. c:function:: PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ...) Call a callable Python object *callable*, with a variable number of - :c:expr:`PyObject *` arguments. The arguments are provided as a variable number + :c:expr:`PyObject *` arguments. The arguments are provided as a variable number of parameters followed by *NULL*. Return the result of the call on success, or raise an exception and return @@ -317,8 +317,8 @@ please see individual documentation for details. .. c:function:: PyObject* PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ...) Call a method of the Python object *obj*, where the name of the method is given as a - Python string object in *name*. It is called with a variable number of - :c:expr:`PyObject *` arguments. The arguments are provided as a variable number + Python string object in *name*. It is called with a variable number of + :c:expr:`PyObject *` arguments. The arguments are provided as a variable number of parameters followed by *NULL*. Return the result of the call on success, or raise an exception and return @@ -400,5 +400,5 @@ Call Support API .. 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. + Determine if the object *o* is callable. Return ``1`` if the object is callable + and ``0`` otherwise. This function always succeeds. diff --git a/Doc/c-api/capsule.rst b/Doc/c-api/capsule.rst index 64dc4f5275b512..bad64374381448 100644 --- a/Doc/c-api/capsule.rst +++ b/Doc/c-api/capsule.rst @@ -16,7 +16,7 @@ Refer to :ref:`using-capsules` for more information on using these objects. 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:expr:`void*` - pointer) through Python code to other C code. It is often used to make a C + 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. @@ -24,7 +24,7 @@ Refer to :ref:`using-capsules` for more information on using these objects. .. c:type:: PyCapsule_Destructor - The type of a destructor callback for a capsule. Defined as:: + The type of a destructor callback for a capsule. Defined as:: typedef void (*PyCapsule_Destructor)(PyObject *); @@ -34,81 +34,81 @@ Refer to :ref:`using-capsules` for more information on using these objects. .. c:function:: int PyCapsule_CheckExact(PyObject *p) - Return true if its argument is a :c:type:`PyCapsule`. This function always + Return true if its argument is a :c:type:`PyCapsule`. This function always succeeds. .. c:function:: PyObject* PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor) - Create a :c:type:`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``. - The *name* string may either be ``NULL`` or a pointer to a valid C string. If - non-``NULL``, this string must outlive the capsule. (Though it is permitted to + The *name* string may either be ``NULL`` or a pointer to a valid C string. If + non-``NULL``, this string must outlive the capsule. (Though it is permitted to free it inside the *destructor*.) If the *destructor* argument is not ``NULL``, it will be called with the capsule as its argument when it is destroyed. 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 + be specified as ``modulename.attributename``. This will enable other modules to import the capsule using :c:func:`PyCapsule_Import`. .. c:function:: void* PyCapsule_GetPointer(PyObject *capsule, const char *name) - Retrieve the *pointer* stored in the capsule. On failure, set an exception + 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 :c:func:`!strcmp` to compare capsule + be ``NULL``. Python uses the C function :c:func:`!strcmp` to compare capsule names. .. c:function:: PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule) - Return the current destructor stored in the capsule. On failure, set an + 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`` + It is legal for a capsule to have a ``NULL`` destructor. This makes a ``NULL`` return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: void* PyCapsule_GetContext(PyObject *capsule) - Return the current context stored in the capsule. On failure, set an + 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`` + It is legal for a capsule to have a ``NULL`` context. This makes a ``NULL`` return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: const char* PyCapsule_GetName(PyObject *capsule) - Return the current name stored in the capsule. On failure, set an exception + 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 + It is legal for a capsule to have a ``NULL`` name. This makes a ``NULL`` return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or :c:func:`PyErr_Occurred` to disambiguate. .. 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 + 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 + ``module.attribute``. The *name* stored in the capsule must match this string exactly. This function splits *name* on the ``.`` character, and imports the first element. It then processes further elements using attribute lookups. - Return the capsule's internal *pointer* on success. On failure, set an + Return the capsule's internal *pointer* on success. On failure, set an exception and return ``NULL``. .. note:: @@ -124,9 +124,9 @@ Refer to :ref:`using-capsules` for more information on using these objects. .. c:function:: int PyCapsule_IsValid(PyObject *capsule, const char *name) - Determines whether or not *capsule* is a valid capsule. A valid capsule is + Determines whether or not *capsule* is a valid capsule. A valid capsule is non-``NULL``, passes :c:func:`PyCapsule_CheckExact`, has a non-``NULL`` pointer - stored in it, and its internal name matches the *name* parameter. (See + stored in it, and its internal name matches the *name* parameter. (See :c:func:`PyCapsule_GetPointer` for information on how capsule names are compared.) @@ -135,35 +135,35 @@ Refer to :ref:`using-capsules` for more information on using these objects. 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. + Return ``0`` otherwise. This function will not fail. .. 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. + Return ``0`` on success. Return nonzero and set an exception on failure. .. 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. + Return ``0`` on success. Return nonzero and set an exception on failure. .. 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 + 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 ``NULL``, no attempt is made to free it. - Return ``0`` on success. Return nonzero and set an exception on failure. + Return ``0`` on success. Return nonzero and set an exception on failure. .. c:function:: int PyCapsule_SetPointer(PyObject *capsule, void *pointer) - Set the void pointer inside *capsule* to *pointer*. The pointer may not be + Set the void pointer inside *capsule* to *pointer*. The pointer may not be ``NULL``. - Return ``0`` on success. Return nonzero and set an exception on failure. + Return ``0`` on success. Return nonzero and set an exception on failure. diff --git a/Doc/c-api/cell.rst b/Doc/c-api/cell.rst index 61eb994c370946..aa784fb2525957 100644 --- a/Doc/c-api/cell.rst +++ b/Doc/c-api/cell.rst @@ -8,9 +8,9 @@ Cell Objects "Cell" objects are used to implement variables referenced by multiple scopes. For each such variable, a cell object is created to store the value; the local variables of each stack frame that references the value contains a reference to -the cells from outer scopes which also use that variable. When the value is +the cells from outer scopes which also use that variable. When the value is accessed, the value contained in the cell is used instead of the cell object -itself. This de-referencing of the cell object requires support from the +itself. This de-referencing of the cell object requires support from the generated byte-code; these are not automatically de-referenced when accessed. Cell objects are not likely to be useful elsewhere. @@ -27,7 +27,7 @@ Cell objects are not likely to be useful elsewhere. .. c:function:: int PyCell_Check(PyObject *ob) - Return true if *ob* is a cell object; *ob* must not be ``NULL``. This + Return true if *ob* is a cell object; *ob* must not be ``NULL``. This function always succeeds. @@ -51,8 +51,8 @@ Cell objects are not likely to be useful elsewhere. .. 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* + 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* must be non-``NULL``. On success, return ``0``. @@ -61,6 +61,6 @@ Cell objects are not likely to be useful elsewhere. .. c:function:: void PyCell_SET(PyObject *cell, PyObject *value) - Sets the value of the cell object *cell* to *value*. No reference counts are + 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 be a cell object. diff --git a/Doc/c-api/code.rst b/Doc/c-api/code.rst index 717b0da8f87c7f..bf649e11b90541 100644 --- a/Doc/c-api/code.rst +++ b/Doc/c-api/code.rst @@ -15,7 +15,7 @@ bound into a function. .. c:type:: PyCodeObject - The C structure of the objects used to describe code objects. The + The C structure of the objects used to describe code objects. The fields of this type are subject to change at any time. @@ -48,7 +48,7 @@ bound into a function. .. c:function:: PyCodeObject* PyUnstable_Code_New(int argcount, int kwonlyargcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, PyObject *qualname, int firstlineno, PyObject *linetable, PyObject *exceptiontable) - Return a new code object. If you need a dummy code object to create a frame, + Return a new code object. If you need a dummy code object to create a frame, use :c:func:`PyCode_NewEmpty` instead. Since the definition of the bytecode changes often, calling @@ -79,7 +79,7 @@ bound into a function. .. versionadded:: 3.8 as ``PyCode_NewWithPosOnlyArgs`` .. versionchanged:: 3.11 - Added ``qualname`` and ``exceptiontable`` parameters. + Added ``qualname`` and ``exceptiontable`` parameters. .. versionchanged:: 3.12 diff --git a/Doc/c-api/codec.rst b/Doc/c-api/codec.rst index 8ae5c4fecd6248..e5b0e721aab728 100644 --- a/Doc/c-api/codec.rst +++ b/Doc/c-api/codec.rst @@ -21,15 +21,15 @@ Codec registry and support functions .. c:function:: int PyCodec_KnownEncoding(const char *encoding) Return ``1`` or ``0`` depending on whether there is a registered codec for - the given *encoding*. This function always succeeds. + the given *encoding*. This function always succeeds. .. c:function:: PyObject* PyCodec_Encode(PyObject *object, const char *encoding, const char *errors) Generic codec based encoding API. *object* is passed through the encoder function found for the given - *encoding* using the error handling method defined by *errors*. *errors* may - be ``NULL`` to use the default method defined for the codec. Raises a + *encoding* using the error handling method defined by *errors*. *errors* may + be ``NULL`` to use the default method defined for the codec. Raises a :exc:`LookupError` if no encoder can be found. .. c:function:: PyObject* PyCodec_Decode(PyObject *object, const char *encoding, const char *errors) @@ -37,8 +37,8 @@ Codec registry and support functions Generic codec based decoding API. *object* is passed through the decoder function found for the given - *encoding* using the error handling method defined by *errors*. *errors* may - be ``NULL`` to use the default method defined for the codec. Raises a + *encoding* using the error handling method defined by *errors*. *errors* may + be ``NULL`` to use the default method defined for the codec. Raises a :exc:`LookupError` if no encoder can be found. @@ -47,7 +47,7 @@ Codec lookup API In the following functions, the *encoding* string is looked up converted to all lower-case characters, which makes encodings looked up through this mechanism -effectively case-insensitive. If no codec is found, a :exc:`KeyError` is set +effectively case-insensitive. If no codec is found, a :exc:`KeyError` is set and ``NULL`` returned. .. c:function:: PyObject* PyCodec_Encoder(const char *encoding) @@ -89,7 +89,7 @@ Registry API for Unicode encoding error handlers :exc:`UnicodeEncodeError`, :exc:`UnicodeDecodeError` or :exc:`UnicodeTranslateError` that holds information about the problematic sequence of characters or bytes and their offset in the original string (see - :ref:`unicodeexceptions` for functions to extract this information). The + :ref:`unicodeexceptions` for functions to extract this information). The callback must either raise the given exception, or return a two-item tuple containing the replacement for the problematic sequence, and an integer giving the offset in the original string at which encoding/decoding should be @@ -99,7 +99,7 @@ Registry API for Unicode encoding error handlers .. c:function:: PyObject* PyCodec_LookupError(const char *name) - Lookup the error handling callback function registered under *name*. As a + 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. diff --git a/Doc/c-api/complex.rst b/Doc/c-api/complex.rst index 16bd79475dc1e6..c5014b31ea876c 100644 --- a/Doc/c-api/complex.rst +++ b/Doc/c-api/complex.rst @@ -8,7 +8,7 @@ Complex Number Objects .. index:: pair: object; complex number Python's complex number objects are implemented as two distinct types when -viewed from the C API: one is the Python object exposed to Python programs, and +viewed from the C API: one is the Python object exposed to Python programs, and the other is a C structure which represents the actual complex number value. The API provides functions for working with both. @@ -18,13 +18,13 @@ Complex Numbers as C Structures Note that the functions which accept these structures as parameters and return them as results do so *by value* rather than dereferencing them through -pointers. This is consistent throughout the API. +pointers. This is consistent throughout the API. .. 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 + number object. Most of the functions for dealing with complex number objects use structures of this type as input or output values, as appropriate. .. c:member:: double real @@ -100,13 +100,13 @@ Complex Numbers as Python Objects .. c:function:: int PyComplex_Check(PyObject *p) Return true if its argument is a :c:type:`PyComplexObject` or a subtype of - :c:type:`PyComplexObject`. This function always succeeds. + :c:type:`PyComplexObject`. This function always succeeds. .. c:function:: int PyComplex_CheckExact(PyObject *p) Return true if its argument is a :c:type:`PyComplexObject`, but not a subtype of - :c:type:`PyComplexObject`. This function always succeeds. + :c:type:`PyComplexObject`. This function always succeeds. .. c:function:: PyObject* PyComplex_FromCComplex(Py_complex v) @@ -127,7 +127,7 @@ Complex Numbers as Python Objects If *op* is not a Python complex number object but has a :meth:`~object.__complex__` method, this method will first be called to - convert *op* to a Python complex number object. If :meth:`!__complex__` is + convert *op* to a Python complex number object. If :meth:`!__complex__` is not defined then it falls back to call :c:func:`PyFloat_AsDouble` and returns its result. @@ -143,7 +143,7 @@ Complex Numbers as Python Objects If *op* is not a Python complex number object but has a :meth:`~object.__complex__` method, this method will first be called to - convert *op* to a Python complex number object. If :meth:`!__complex__` is + convert *op* to a Python complex number object. If :meth:`!__complex__` is not defined then it falls back to call :c:func:`PyFloat_AsDouble` and returns ``0.0`` on success. @@ -159,8 +159,8 @@ Complex Numbers as Python Objects If *op* is not a Python complex number object but has a :meth:`~object.__complex__` method, this method will first be called to convert *op* to a Python complex - number object. If :meth:`!__complex__` is not defined then it falls back to - :meth:`~object.__float__`. If :meth:`!__float__` is not defined then it falls back + number object. If :meth:`!__complex__` is not defined then it falls back to + :meth:`~object.__float__`. If :meth:`!__float__` is not defined then it falls back to :meth:`~object.__index__`. Upon failure, this method returns :c:type:`Py_complex` diff --git a/Doc/c-api/concrete.rst b/Doc/c-api/concrete.rst index 880f7b15ce68e8..4d868dfc24e6b6 100644 --- a/Doc/c-api/concrete.rst +++ b/Doc/c-api/concrete.rst @@ -11,14 +11,14 @@ 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 :c:func:`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:: While the functions described in this chapter carefully check the type of the objects which are passed in, many of them do not check for ``NULL`` being passed - instead of a valid object. Allowing ``NULL`` to be passed in can cause memory + instead of a valid object. Allowing ``NULL`` to be passed in can cause memory access violations and immediate termination of the interpreter. diff --git a/Doc/c-api/contextvars.rst b/Doc/c-api/contextvars.rst index b7c6550ff34aac..0389549d709a3e 100644 --- a/Doc/c-api/contextvars.rst +++ b/Doc/c-api/contextvars.rst @@ -60,24 +60,24 @@ Type-check macros: .. c:function:: int PyContext_CheckExact(PyObject *o) Return true if *o* is of type :c:data:`PyContext_Type`. *o* must not be - ``NULL``. This function always succeeds. + ``NULL``. This function always succeeds. .. c:function:: int PyContextVar_CheckExact(PyObject *o) Return true if *o* is of type :c:data:`PyContextVar_Type`. *o* must not be - ``NULL``. This function always succeeds. + ``NULL``. This function always succeeds. .. c:function:: int PyContextToken_CheckExact(PyObject *o) Return true if *o* is of type :c:data:`PyContextToken_Type`. - *o* must not be ``NULL``. This function always succeeds. + *o* must not be ``NULL``. This function always succeeds. Context object management functions: .. c:function:: PyObject *PyContext_New(void) - Create a new empty context object. Returns ``NULL`` if an error + Create a new empty context object. Returns ``NULL`` if an error has occurred. .. c:function:: PyObject *PyContext_Copy(PyObject *ctx) @@ -98,7 +98,7 @@ Context object management functions: .. c:function:: int PyContext_Exit(PyObject *ctx) Deactivate the *ctx* context and restore the previous context as the - current context for the current thread. Returns ``0`` on success, + current context for the current thread. Returns ``0`` on success, and ``-1`` on error. .. c:function:: int PyContext_AddWatcher(PyContext_WatchCallback callback) @@ -124,7 +124,7 @@ Context object management functions: Enumeration of possible context object watcher events: - ``Py_CONTEXT_SWITCHED``: The :term:`current context` has switched to a - different context. The object passed to the watch callback is the + different context. The object passed to the watch callback is the now-current :class:`contextvars.Context` object, or None if no context is current. @@ -132,7 +132,7 @@ Context object management functions: .. c:type:: int (*PyContext_WatchCallback)(PyContextEvent event, PyObject *obj) - Context object watcher callback function. The object passed to the callback + Context object watcher callback function. The object passed to the callback is event-specific; see :c:type:`PyContextEvent` for details. If the callback returns with an exception set, it must return ``-1``; this @@ -152,14 +152,14 @@ Context variable functions: .. c:function:: PyObject *PyContextVar_New(const char *name, PyObject *def) - Create a new ``ContextVar`` object. The *name* parameter is used - for introspection and debug purposes. The *def* parameter specifies + Create a new ``ContextVar`` object. The *name* parameter is used + for introspection and debug purposes. The *def* parameter specifies a default value for the context variable, or ``NULL`` for no default. If an error has occurred, this function returns ``NULL``. .. c:function:: int PyContextVar_Get(PyObject *var, PyObject *default_value, PyObject **value) - Get the value of a context variable. Returns ``-1`` if an error has + Get the value of a context variable. Returns ``-1`` if an error has occurred during lookup, and ``0`` if no error occurred, whether or not a value was found. @@ -174,7 +174,7 @@ Context variable functions: .. c:function:: PyObject *PyContextVar_Set(PyObject *var, PyObject *value) - Set the value of *var* to *value* in the current context. Returns + Set the value of *var* to *value* in the current context. Returns a new token object for this change, or ``NULL`` if an error has occurred. .. c:function:: int PyContextVar_Reset(PyObject *var, PyObject *token) diff --git a/Doc/c-api/conversion.rst b/Doc/c-api/conversion.rst index c92ef4c653a675..debdf9a2c71594 100644 --- a/Doc/c-api/conversion.rst +++ b/Doc/c-api/conversion.rst @@ -8,7 +8,7 @@ String conversion and formatting Functions for number conversion and formatted string output. -.. c:function:: 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(3)`. @@ -54,15 +54,15 @@ The following functions provide locale-independent string to number conversions. long` value according to the given ``base``, which must be between ``2`` and ``36`` inclusive, or be the special value ``0``. - Leading white space and case of characters are ignored. If ``base`` is zero - it looks for a leading ``0b``, ``0o`` or ``0x`` to tell which base. If - these are absent it defaults to ``10``. Base must be 0 or between 2 and 36 - (inclusive). If ``ptr`` is non-``NULL`` it will contain a pointer to the + Leading white space and case of characters are ignored. If ``base`` is zero + it looks for a leading ``0b``, ``0o`` or ``0x`` to tell which base. If + these are absent it defaults to ``10``. Base must be 0 or between 2 and 36 + (inclusive). If ``ptr`` is non-``NULL`` it will contain a pointer to the end of the scan. If the converted value falls out of range of corresponding return type, range error occurs (:c:data:`errno` is set to :c:macro:`!ERANGE`) and - :c:macro:`!ULONG_MAX` is returned. If no conversion can be performed, ``0`` + :c:macro:`!ULONG_MAX` is returned. If no conversion can be performed, ``0`` is returned. See also the Unix man page :manpage:`strtoul(3)`. @@ -87,18 +87,18 @@ The following functions provide locale-independent string to number conversions. .. c:function:: double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception) Convert a string ``s`` to a :c:expr:`double`, raising a Python - exception on failure. The set of accepted strings corresponds to + 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. The conversion is independent of the current locale. - If ``endptr`` is ``NULL``, convert the whole string. Raise + If ``endptr`` is ``NULL``, convert the whole string. Raise :exc:`ValueError` and return ``-1.0`` if the string is not a valid representation of a floating-point number. If endptr is not ``NULL``, convert as much of the string as possible and set ``*endptr`` to point to the first unconverted - character. If no initial segment of the string is the valid + character. If no initial segment of the string is the valid representation of a floating-point number, set ``*endptr`` to point to the beginning of the string, raise ValueError, and return ``-1.0``. @@ -106,9 +106,9 @@ The following functions provide locale-independent string to number conversions. If ``s`` represents a value that is too large to store in a float (for example, ``"1e500"`` is such a string on many platforms) then if ``overflow_exception`` is ``NULL`` return ``Py_INFINITY`` (with - an appropriate sign) and don't set any exception. Otherwise, + an appropriate sign) and don't set any exception. Otherwise, ``overflow_exception`` must point to a Python exception object; - raise that exception and return ``-1.0``. In both cases, set + raise that exception and return ``-1.0``. In both cases, set ``*endptr`` to point to the first character after the converted value. If any other error occurs during the conversion (for example an @@ -124,8 +124,8 @@ The following functions provide locale-independent string to number conversions. *format_code*, *precision*, and *flags*. *format_code* must be one of ``'e'``, ``'E'``, ``'f'``, ``'F'``, - ``'g'``, ``'G'`` or ``'r'``. For ``'r'``, the supplied *precision* - must be 0 and is ignored. The ``'r'`` format code specifies the + ``'g'``, ``'G'`` or ``'r'``. For ``'r'``, the supplied *precision* + must be 0 and is ignored. The ``'r'`` format code specifies the standard :func:`repr` format. *flags* can be zero or more of the values ``Py_DTSF_SIGN``, @@ -137,7 +137,7 @@ The following functions provide locale-independent string to number conversions. * ``Py_DTSF_ADD_DOT_0`` means to ensure that the returned string will not look like an integer. - * ``Py_DTSF_ALT`` means to apply "alternate" formatting rules. See the + * ``Py_DTSF_ALT`` means to apply "alternate" formatting rules. See the documentation for the :c:func:`PyOS_snprintf` ``'#'`` specifier for details. @@ -158,7 +158,7 @@ The following functions provide locale-independent string to number conversions. identically to :c:func:`!strcmp` except that it ignores the case. -.. c:function:: int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size) +.. c:function:: int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size) Case insensitive comparison of strings. The function works almost identically to :c:func:`!strncmp` except that it ignores the case. diff --git a/Doc/c-api/coro.rst b/Doc/c-api/coro.rst index caa855a10d20ca..f2ca22235325c7 100644 --- a/Doc/c-api/coro.rst +++ b/Doc/c-api/coro.rst @@ -31,5 +31,5 @@ return. Create and return a new coroutine object based on the *frame* object, with ``__name__`` and ``__qualname__`` set to *name* and *qualname*. - A reference to *frame* is stolen by this function. The *frame* argument + A reference to *frame* is stolen by this function. The *frame* argument must not be ``NULL``. diff --git a/Doc/c-api/datetime.rst b/Doc/c-api/datetime.rst index d2d4d5309c7098..ac7c6a5ed4c1fd 100644 --- a/Doc/c-api/datetime.rst +++ b/Doc/c-api/datetime.rst @@ -9,7 +9,7 @@ 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 :c:macro:`!PyDateTime_IMPORT` must be invoked, usually as part of -the module initialisation function. The macro puts a pointer to a C structure +the module initialisation function. The macro puts a pointer to a C structure into a static variable, :c:data:`!PyDateTimeAPI`, that is used by the following macros. @@ -71,66 +71,66 @@ Type-check macros: .. c:function:: int PyDate_Check(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_DateType` or a subtype of - :c:data:`!PyDateTime_DateType`. *ob* must not be ``NULL``. This function always + :c:data:`!PyDateTime_DateType`. *ob* must not be ``NULL``. This function always succeeds. .. c:function:: int PyDate_CheckExact(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_DateType`. *ob* must not be - ``NULL``. This function always succeeds. + ``NULL``. This function always succeeds. .. c:function:: int PyDateTime_Check(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_DateTimeType` or a subtype of - :c:data:`!PyDateTime_DateTimeType`. *ob* must not be ``NULL``. This function always + :c:data:`!PyDateTime_DateTimeType`. *ob* must not be ``NULL``. This function always succeeds. .. c:function:: int PyDateTime_CheckExact(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_DateTimeType`. *ob* must not - be ``NULL``. This function always succeeds. + be ``NULL``. This function always succeeds. .. c:function:: int PyTime_Check(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_TimeType` or a subtype of - :c:data:`!PyDateTime_TimeType`. *ob* must not be ``NULL``. This function always + :c:data:`!PyDateTime_TimeType`. *ob* must not be ``NULL``. This function always succeeds. .. c:function:: int PyTime_CheckExact(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_TimeType`. *ob* must not be - ``NULL``. This function always succeeds. + ``NULL``. This function always succeeds. .. c:function:: int PyDelta_Check(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_DeltaType` or a subtype of - :c:data:`!PyDateTime_DeltaType`. *ob* must not be ``NULL``. This function always + :c:data:`!PyDateTime_DeltaType`. *ob* must not be ``NULL``. This function always succeeds. .. c:function:: int PyDelta_CheckExact(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_DeltaType`. *ob* must not be - ``NULL``. This function always succeeds. + ``NULL``. This function always succeeds. .. c:function:: int PyTZInfo_Check(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_TZInfoType` or a subtype of - :c:data:`!PyDateTime_TZInfoType`. *ob* must not be ``NULL``. This function always + :c:data:`!PyDateTime_TZInfoType`. *ob* must not be ``NULL``. This function always succeeds. .. c:function:: int PyTZInfo_CheckExact(PyObject *ob) Return true if *ob* is of type :c:data:`PyDateTime_TZInfoType`. *ob* must not be - ``NULL``. This function always succeeds. + ``NULL``. This function always succeeds. Macros to create objects: @@ -171,7 +171,7 @@ Macros to create objects: .. c:function:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds) Return a :class:`datetime.timedelta` object representing the given number - of days, seconds and microseconds. Normalization is performed so that the + of days, seconds and microseconds. Normalization is performed so that the resulting number of microseconds and seconds lie in the ranges documented for :class:`datetime.timedelta` objects. @@ -192,9 +192,9 @@ Macros to create objects: .. versionadded:: 3.7 -Macros to extract fields from date objects. The argument must be an instance of +Macros to extract fields from date objects. The argument must be an instance of :c:type:`PyDateTime_Date`, including subclasses (such as -:c:type:`PyDateTime_DateTime`). The argument must not be ``NULL``, and the type is +:c:type:`PyDateTime_DateTime`). The argument must not be ``NULL``, and the type is not checked: .. c:function:: int PyDateTime_GET_YEAR(PyDateTime_Date *o) @@ -212,7 +212,7 @@ not checked: Return the day, as an int from 1 through 31. -Macros to extract fields from datetime objects. The argument must be an +Macros to extract fields from datetime objects. The argument must be an instance of :c:type:`PyDateTime_DateTime`, including subclasses. The argument must not be ``NULL``, and the type is not checked: @@ -250,7 +250,7 @@ must not be ``NULL``, and the type is not checked: .. versionadded:: 3.10 -Macros to extract fields from time objects. The argument must be an instance of +Macros to extract fields from time objects. The argument must be an instance of :c:type:`PyDateTime_Time`, including subclasses. The argument must not be ``NULL``, and the type is not checked: @@ -288,7 +288,7 @@ and the type is not checked: .. versionadded:: 3.10 -Macros to extract fields from time delta objects. The argument must be an +Macros to extract fields from time delta objects. The argument must be an instance of :c:type:`PyDateTime_Delta`, including subclasses. The argument must not be ``NULL``, and the type is not checked: diff --git a/Doc/c-api/descriptor.rst b/Doc/c-api/descriptor.rst index b32c113e5f0457..e52f4b61260aba 100644 --- a/Doc/c-api/descriptor.rst +++ b/Doc/c-api/descriptor.rst @@ -33,7 +33,7 @@ found in the dictionary of type objects. .. c:function:: int PyDescr_IsData(PyObject *descr) Return non-zero if the descriptor objects *descr* describes a data attribute, or - ``0`` if it describes a method. *descr* must be a descriptor object; there is + ``0`` if it describes a method. *descr* must be a descriptor object; there is no error checking. diff --git a/Doc/c-api/dict.rst b/Doc/c-api/dict.rst index e55c5c80cb83c0..6592ab407f573f 100644 --- a/Doc/c-api/dict.rst +++ b/Doc/c-api/dict.rst @@ -16,19 +16,19 @@ Dictionary Objects .. c:var:: PyTypeObject PyDict_Type This instance of :c:type:`PyTypeObject` represents the Python dictionary - type. This is the same object as :class:`dict` in the Python layer. + type. This is the same object as :class:`dict` in the Python layer. .. 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. This function always succeeds. + type. This function always succeeds. .. 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. This function always succeeds. + the dict type. This function always succeeds. .. c:function:: PyObject* PyDict_New() @@ -39,7 +39,7 @@ Dictionary Objects .. c:function:: PyObject* PyDictProxy_New(PyObject *mapping) Return a :class:`types.MappingProxyType` object for a mapping which - enforces read-only behavior. This is normally used to create a view to + enforces read-only behavior. This is normally used to create a view to prevent modification of the dictionary for non-dynamic class types. @@ -50,8 +50,8 @@ Dictionary Objects .. 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``. + Determine if dictionary *p* contains *key*. If an item in *p* is matches + *key*, return ``1``, otherwise return ``0``. On error, return ``-1``. This is equivalent to the Python expression ``key in p``. @@ -71,9 +71,9 @@ Dictionary Objects .. c:function:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val) - Insert *val* into the dictionary *p* with a key of *key*. *key* must be + Insert *val* 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. This function *does not* steal a + ``0`` on success or ``-1`` on failure. This function *does not* steal a reference to *val*. @@ -117,7 +117,7 @@ Dictionary Objects .. c:function:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key) Return a :term:`borrowed reference` to the object from dictionary *p* which - has a key *key*. Return ``NULL`` if the key *key* is missing *without* + has a key *key*. Return ``NULL`` if the key *key* is missing *without* setting an exception. .. note:: @@ -135,7 +135,7 @@ Dictionary Objects Variant of :c:func:`PyDict_GetItem` that does not suppress exceptions. Return ``NULL`` **with** an exception set if an exception - occurred. Return ``NULL`` **without** an exception set if the key + occurred. Return ``NULL`` **without** an exception set if the key wasn't present. @@ -165,10 +165,10 @@ Dictionary Objects .. c:function:: PyObject* PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj) - This is the same as the Python-level :meth:`dict.setdefault`. If present, it - returns the value corresponding to *key* from the dictionary *p*. If the key + This is the same as the Python-level :meth:`dict.setdefault`. If present, it + returns the value corresponding to *key* from the dictionary *p*. If the key is not in the dict, it is inserted with value *defaultobj* and *defaultobj* - is returned. This function evaluates the hash function of *key* only once, + is returned. This function evaluates the hash function of *key* only once, instead of evaluating it independently for the lookup and the insertion. .. versionadded:: 3.4 @@ -241,20 +241,20 @@ Dictionary Objects .. index:: pair: built-in function; len - Return the number of items in the dictionary. This is equivalent to + Return the number of items in the dictionary. This is equivalent to ``len(p)`` on a dictionary. .. 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 + Iterate over all key-value pairs in the dictionary *p*. The :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 + pairs have been reported. The parameters *pkey* and *pvalue* should either point to :c:expr:`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 + 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 since the structure is sparse, the offsets are not consecutive. @@ -268,9 +268,9 @@ Dictionary Objects ... } - The dictionary *p* should not be mutated during iteration. It is safe to + The dictionary *p* should not be mutated during iteration. It is safe to modify the values of the keys as you iterate over the dictionary, but only - so long as the set of keys does not change. For example:: + so long as the set of keys does not change. For example:: PyObject *key, *value; Py_ssize_t pos = 0; @@ -291,7 +291,7 @@ Dictionary Objects } The function is not thread-safe in the :term:`free-threaded ` - build without external synchronization. You can use + build without external synchronization. You can use :c:macro:`Py_BEGIN_CRITICAL_SECTION` to lock the dictionary while iterating over it:: @@ -317,7 +317,7 @@ Dictionary Objects This is the same as ``PyDict_Merge(a, b, 1)`` in C, and is similar to ``a.update(b)`` in Python except that :c:func:`PyDict_Update` doesn't fall back to the iterating over a sequence of key value pairs if the second - argument has no "keys" attribute. Return ``0`` on success or ``-1`` if an + argument has no "keys" attribute. Return ``0`` on success or ``-1`` if an exception was raised. @@ -325,7 +325,7 @@ Dictionary Objects 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, - viewed as key-value pairs. In case of duplicate keys, the last wins if + viewed as key-value pairs. In case of duplicate keys, the last wins if *override* is true, else the first wins. Return ``0`` on success or ``-1`` if an exception was raised. Equivalent Python (except for the return value):: diff --git a/Doc/c-api/exceptions.rst b/Doc/c-api/exceptions.rst index 3ff4631a8e53c4..82df20fd379c09 100644 --- a/Doc/c-api/exceptions.rst +++ b/Doc/c-api/exceptions.rst @@ -8,28 +8,28 @@ 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 POSIX :c:data:`errno` variable: -there is a global indicator (per thread) of the last error that occurred. Most +exceptions. It is important to understand some of the basics of Python +exception handling. It works somewhat like the POSIX :c:data:`errno` variable: +there is a global indicator (per thread) of the last error that occurred. Most C API functions don't clear this on success, but will set it to indicate the -cause of the error on failure. Most C API functions also return an error +cause of the error on failure. Most C API 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 ``PyArg_*`` functions return ``1`` for success and ``0`` for failure). Concretely, the error indicator consists of three object pointers: the -exception's type, the exception's value, and the traceback object. Any +exception's type, the exception's value, and the traceback object. Any of those pointers can be ``NULL`` if non-set (although some combinations are forbidden, for example you can't have a non-``NULL`` traceback if the exception type is ``NULL``). When a function must fail because some function it called failed, it generally -doesn't set the error indicator; the function it called already set it. It is +doesn't set the error indicator; the function it called already set it. It is responsible for either handling the error and clearing the exception or returning after cleaning up any resources it holds (such as object references or memory allocations); it should *not* continue normally if it is not prepared to -handle the error. If returning due to an error, it is important to indicate to -the caller that an error has been set. If the error is not handled or carefully +handle the error. If returning due to an error, it is important to indicate to +the caller that an error has been set. If the error is not handled or carefully propagated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways. @@ -46,7 +46,7 @@ Printing and clearing .. c:function:: void PyErr_Clear() - Clear the error indicator. If the error indicator is not set, there is no + Clear the error indicator. If the error indicator is not set, there is no effect. @@ -57,7 +57,7 @@ Printing and clearing printed and the Python process will exit with the error code specified by the ``SystemExit`` instance. - Call this function **only** when the error indicator is set. Otherwise it + Call this function **only** when the error indicator is set. Otherwise it will cause a fatal error! If *set_sys_last_vars* is nonzero, the variable :data:`sys.last_exc` is @@ -82,7 +82,7 @@ Printing and clearing 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 - raise the exception. It is used, for example, when an exception occurs in an + raise the exception. It is used, for example, when an exception occurs in an :meth:`~object.__del__` method. The function is called with a single argument *obj* that identifies the context @@ -129,9 +129,9 @@ For convenience, some of these functions will always return a .. c:function:: void PyErr_SetString(PyObject *type, const char *message) - This is the most common way to set the error indicator. The first argument + 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. :c:data:`PyExc_RuntimeError`. You need not create a new + e.g. :c:data:`PyExc_RuntimeError`. You need not create a new :term:`strong reference` to it (e.g. with :c:func:`Py_INCREF`). The second argument is an error message; it is decoded from ``'utf-8'``. @@ -144,8 +144,8 @@ For convenience, some of these functions will always return a .. 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 + 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 :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded string. @@ -168,7 +168,7 @@ For convenience, some of these functions will always return a 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. + argument. It is mostly for internal use. .. c:function:: PyObject* PyErr_NoMemory() @@ -183,13 +183,13 @@ For convenience, some of these functions will always return a .. index:: single: strerror (C function) This is a convenience function to raise an exception when a C library function - has returned an error and set the C variable :c:data:`errno`. It constructs a + 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 + and then calls ``PyErr_SetObject(type, object)``. On Unix, when the :c:data:`errno` value is :c:macro:`!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 + 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. @@ -198,7 +198,7 @@ For convenience, some of these functions will always return a Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if *filenameObject* is not ``NULL``, it is passed to the constructor of *type* as - a third parameter. In the case of :exc:`OSError` exception, + a third parameter. In the case of :exc:`OSError` exception, this is used to define the :attr:`!filename` attribute of the exception instance. @@ -215,7 +215,7 @@ For convenience, some of these functions will always return a .. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename) Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but the filename - is given as a C string. *filename* is decoded from the :term:`filesystem + is given as a C string. *filename* is decoded from the :term:`filesystem encoding and error handler`. @@ -223,7 +223,7 @@ For convenience, some of these functions will always return a This is a convenience function to raise :exc:`OSError`. If called with *ierr* of ``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 + 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 :exc:`OSError` object with the :attr:`~OSError.winerror` attribute set to the error code, the :attr:`~OSError.strerror` attribute @@ -301,7 +301,7 @@ For convenience, some of these functions will always return a .. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) - Set file, line, and offset information for the current exception. If the + Set file, line, and offset information for the current exception. If the current exception is not a :exc:`SyntaxError`, then it sets additional attributes, which make the exception printing subsystem think the exception is a :exc:`SyntaxError`. @@ -327,33 +327,33 @@ For convenience, some of these functions will always return a This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``, where *message* indicates that an internal operation (e.g. a Python/C API - function) was invoked with an illegal argument. It is mostly for internal + function) was invoked with an illegal argument. It is mostly for internal use. Issuing warnings ================ -Use these functions to issue warnings from C code. They mirror similar -functions exported by the Python :mod:`warnings` module. They normally +Use these functions to issue warnings from C code. They mirror similar +functions exported by the Python :mod:`warnings` module. They normally print a warning message to *sys.stderr*; however, it is also possible that the user has specified that warnings are to be turned into -errors, and in that case they will raise an exception. It is also possible that +errors, and in that case they will raise an exception. It is also possible that the functions raise an exception because of a problem with the warning machinery. The return value is ``0`` if no exception is raised, or ``-1`` if an exception -is raised. (It is not possible to determine whether a warning message is +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 +intentional.) If an exception is raised, the caller should do its normal exception handling (for example, :c:func:`Py_DECREF` owned references and return an error value). .. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level) - Issue a warning message. The *category* argument is a warning category (see - below) or ``NULL``; the *message* argument is a UTF-8 encoded string. *stack_level* is a + Issue a warning message. The *category* argument is a warning category (see + below) or ``NULL``; the *message* argument is a UTF-8 encoded string. *stack_level* is a positive number giving a number of stack frames; the warning will be issued from - the currently executing line of code in that stack frame. A *stack_level* of 1 - is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that, + the currently executing line of code in that stack frame. A *stack_level* of 1 + is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that, and so forth. Warning categories must be subclasses of :c:data:`PyExc_Warning`; @@ -364,14 +364,14 @@ an error value). 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. + documentation. There is no C API for warning control. .. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry) - Issue a warning message with explicit control over all warning attributes. This + Issue a warning message with explicit control over all warning attributes. This is a straightforward wrapper around the Python function - :func:`warnings.warn_explicit`; see there for more information. The *module* + :func:`warnings.warn_explicit`; see there for more information. The *module* and *registry* arguments may be set to ``NULL`` to get the default effect described there. @@ -388,7 +388,7 @@ an error value). .. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...) Function similar to :c:func:`PyErr_WarnEx`, but use - :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is + :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is an ASCII-encoded string. .. versionadded:: 3.2 @@ -407,9 +407,9 @@ Querying the error indicator .. c:function:: PyObject* PyErr_Occurred() - Test whether the error indicator is set. If set, return the exception *type* + Test whether the error indicator is set. If set, return the exception *type* (the first argument to the last call to one of the ``PyErr_Set*`` - functions or to :c:func:`PyErr_Restore`). If not set, return ``NULL``. You do not + 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. @@ -418,23 +418,23 @@ Querying the error indicator .. note:: Do not compare the return value to a specific exception; use - :c:func:`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 be a subclass of the expected exception.) .. c:function:: int PyErr_ExceptionMatches(PyObject *exc) - Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This + 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. .. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc) - Return true if the *given* exception matches the exception type in *exc*. If + Return true if the *given* exception matches the exception type in *exc*. If *exc* is a class object, this also returns true when *given* is an instance - of a subclass. If *exc* is a tuple, all exception types in the tuple (and + of a subclass. If *exc* is a tuple, all exception types in the tuple (and recursively in subtuples) are searched for a match. @@ -481,8 +481,8 @@ Querying the error indicator Use :c:func:`PyErr_GetRaisedException` instead. 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 - set, it will be cleared and you own a reference to each object retrieved. The + If the error indicator is not set, set all three variables to ``NULL``. If it is + set, it will be cleared and you own a reference to each object retrieved. The value and traceback object may be ``NULL`` even when the type object is not. .. note:: @@ -512,12 +512,12 @@ Querying the error indicator *type*, *value*, and *traceback*, clearing the existing exception if one is set. If the objects are ``NULL``, the error - indicator is cleared. Do not pass a ``NULL`` type and non-``NULL`` value or - traceback. The exception type should be a class. Do not pass an invalid + indicator is cleared. Do not pass a ``NULL`` type and non-``NULL`` value or + traceback. The exception type should be a class. Do not pass an invalid exception type or value. (Violating these rules will cause subtle problems - later.) This call takes away a reference to each object: you must own a + later.) This call takes away a reference to each object: you must own a reference to each object before the call and after the call you no longer own - these references. (If you don't understand this, don't use this function. I + these references. (If you don't understand this, don't use this function. I warned you.) .. note:: @@ -536,8 +536,8 @@ Querying the error indicator 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. + 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. .. note:: @@ -563,14 +563,14 @@ Querying the error indicator This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception - state temporarily. Use :c:func:`PyErr_SetHandledException` to restore or + state temporarily. Use :c:func:`PyErr_SetHandledException` to restore or clear the exception state. .. versionadded:: 3.11 .. c:function:: void PyErr_SetHandledException(PyObject *exc) - Set the active exception, as known from ``sys.exception()``. This refers + Set the active exception, as known from ``sys.exception()``. This refers to an exception that was *already caught*, not to an exception that was freshly raised. To clear the exception state, pass ``NULL``. @@ -579,7 +579,7 @@ Querying the error indicator This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception - state temporarily. Use :c:func:`PyErr_GetHandledException` to get the exception + state temporarily. Use :c:func:`PyErr_GetHandledException` to get the exception state. .. versionadded:: 3.11 @@ -587,17 +587,17 @@ Querying the error indicator .. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback) Retrieve the old-style representation of the exception info, as known from - :func:`sys.exc_info`. This refers to an exception that was *already caught*, - not to an exception that was freshly raised. Returns new references for the - three objects, any of which may be ``NULL``. Does not modify the exception - info state. This function is kept for backwards compatibility. Prefer using + :func:`sys.exc_info`. This refers to an exception that was *already caught*, + not to an exception that was freshly raised. Returns new references for the + three objects, any of which may be ``NULL``. Does not modify the exception + info state. This function is kept for backwards compatibility. Prefer using :c:func:`PyErr_GetHandledException`. .. note:: This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception - state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the + state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the exception state. .. versionadded:: 3.3 @@ -605,9 +605,9 @@ Querying the error indicator .. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback) - Set the exception info, as known from ``sys.exc_info()``. This refers + Set the exception info, as known from ``sys.exc_info()``. This refers to an exception that was *already caught*, not to an exception that was - freshly raised. This function steals the references of the arguments. + freshly raised. This function steals the references of the arguments. To clear the exception state, pass ``NULL`` for all three arguments. This function is kept for backwards compatibility. Prefer using :c:func:`PyErr_SetHandledException`. @@ -616,7 +616,7 @@ Querying the error indicator This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception - state temporarily. Use :c:func:`PyErr_GetExcInfo` to read the exception + state temporarily. Use :c:func:`PyErr_GetExcInfo` to read the exception state. .. versionadded:: 3.3 @@ -643,7 +643,7 @@ Signal Handling If the function is called from the main thread and under the main Python interpreter, it checks whether a signal has been sent to the processes - and if so, invokes the corresponding signal handler. If the :mod:`signal` + and if so, invokes the corresponding signal handler. If the :mod:`signal` module is supported, this can invoke a signal handler written in Python. The function attempts to handle all pending signals, and then returns ``0``. @@ -674,7 +674,7 @@ Signal Handling This is equivalent to ``PyErr_SetInterruptEx(SIGINT)``. .. note:: - This function is async-signal-safe. It can be called without + This function is async-signal-safe. It can be called without an :term:`attached thread state` and from a C signal handler. @@ -685,7 +685,7 @@ Signal Handling single: KeyboardInterrupt (built-in exception) Simulate the effect of a signal arriving. The next time - :c:func:`PyErr_CheckSignals` is called, the Python signal handler for + :c:func:`PyErr_CheckSignals` is called, the Python signal handler for the given signal number will be called. This function can be called by C code that sets up its own signal handling @@ -697,11 +697,11 @@ Signal Handling :py:const:`signal.SIG_DFL` or :py:const:`signal.SIG_IGN`), it will be ignored. If *signum* is outside of the allowed range of signal numbers, ``-1`` - is returned. Otherwise, ``0`` is returned. The error indicator is + is returned. Otherwise, ``0`` is returned. The error indicator is never changed by this function. .. note:: - This function is async-signal-safe. It can be called without + This function is async-signal-safe. It can be called without an :term:`attached thread state` and from a C signal handler. .. versionadded:: 3.10 @@ -715,7 +715,7 @@ Signal Handling The value ``-1`` disables the feature; this is the initial state. This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any - error checking. *fd* should be a valid file descriptor. The function should + error checking. *fd* should be a valid file descriptor. The function should only be called from the main thread. .. versionchanged:: 3.5 @@ -729,13 +729,13 @@ Exception Classes 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``. + ``module.classname``. The *base* and *dict* arguments are normally ``NULL``. This creates a class object derived from :exc:`Exception` (accessible in C as :c:data:`PyExc_Exception`). The :attr:`~type.__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 - part (after the last dot). The *base* argument can be used to specify alternate + part (after the last dot). The *base* argument can be used to specify alternate base classes; it can either be only one class or a tuple of classes. The *dict* argument can be used to specify a dictionary of class variables and methods. @@ -772,7 +772,7 @@ Exception Objects .. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb) - Set the traceback associated with the exception to *tb*. Use ``Py_None`` to + Set the traceback associated with the exception to *tb*. Use ``Py_None`` to clear it. @@ -786,8 +786,8 @@ Exception Objects .. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx) - Set the context associated with the exception to *ctx*. Use ``NULL`` to clear - it. There is no type check to make sure that *ctx* is an exception instance. + Set the context associated with the exception to *ctx*. Use ``NULL`` to clear + it. There is no type check to make sure that *ctx* is an exception instance. This steals a reference to *ctx*. @@ -801,9 +801,9 @@ Exception Objects .. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause) - Set the cause associated with the exception to *cause*. Use ``NULL`` to clear - it. There is no type check to make sure that *cause* is either an exception - instance or ``None``. This steals a reference to *cause*. + Set the cause associated with the exception to *cause*. Use ``NULL`` to clear + it. There is no type check to make sure that *cause* is either an exception + instance or ``None``. This steals a reference to *cause*. The :attr:`~BaseException.__suppress_context__` attribute is implicitly set to ``True`` by this function. @@ -860,7 +860,7 @@ The following functions are used to create and modify Unicode exceptions from C. int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) Get the *start* attribute of the given exception object and place it into - *\*start*. *start* must not be ``NULL``. Return ``0`` on success, ``-1`` on + *\*start*. *start* must not be ``NULL``. Return ``0`` on success, ``-1`` on failure. If the :attr:`UnicodeError.object` is an empty sequence, the resulting @@ -886,7 +886,7 @@ The following functions are used to create and modify Unicode exceptions from C. int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end) Get the *end* attribute of the given exception object and place it into - *\*end*. *end* must not be ``NULL``. Return ``0`` on success, ``-1`` on + *\*end*. *end* must not be ``NULL``. Return ``0`` on success, ``-1`` on failure. If the :attr:`UnicodeError.object` is an empty sequence, the resulting @@ -896,7 +896,7 @@ The following functions are used to create and modify Unicode exceptions from C. 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`` + Set the *end* attribute of the given exception object to *end*. Return ``0`` on success, ``-1`` on failure. .. seealso:: :attr:`UnicodeError.end` @@ -911,7 +911,7 @@ The following functions are used to create and modify Unicode exceptions from C. int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason) int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason) - Set the *reason* attribute of the given exception object to *reason*. Return + Set the *reason* attribute of the given exception object to *reason*. Return ``0`` on success, ``-1`` on failure. @@ -921,7 +921,7 @@ Recursion Control ================= These two functions provide a way to perform safe recursive calls at the C -level, both in the core and in extension modules. They are needed if the +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). They are also not needed for *tp_call* implementations @@ -931,7 +931,7 @@ because the :ref:`call protocol ` takes care of recursion handling. Marks a point where a recursive C-level call is about to be performed. - The function then checks if the stack limit is reached. If this is the + The function then checks if the stack limit is reached. If this is the case, a :exc:`RecursionError` is set and a nonzero value is returned. Otherwise, zero is returned. @@ -944,16 +944,16 @@ because the :ref:`call protocol ` takes care of recursion handling. .. c:function:: void Py_LeaveRecursiveCall(void) - Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each + Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each *successful* invocation of :c:func:`Py_EnterRecursiveCall`. .. versionchanged:: 3.9 This function is now also available in the :ref:`limited API `. Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires -special recursion handling. In addition to protecting the stack, -:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The -following two functions facilitate this functionality. Effectively, +special recursion handling. In addition to protecting the stack, +:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The +following two functions facilitate this functionality. Effectively, these are the C equivalent to :func:`reprlib.recursive_repr`. .. c:function:: int Py_ReprEnter(PyObject *object) @@ -962,13 +962,13 @@ these are the C equivalent to :func:`reprlib.recursive_repr`. detect cycles. If the object has already been processed, the function returns a - positive integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation - should return a string object indicating a cycle. As examples, + positive integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation + should return a string object indicating a cycle. As examples, :class:`dict` objects return ``{...}`` and :class:`list` objects return ``[...]``. The function will return a negative integer if the recursion limit - is reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation should + is reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation should typically return ``NULL``. Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr` @@ -976,7 +976,7 @@ these are the C equivalent to :func:`reprlib.recursive_repr`. .. c:function:: void Py_ReprLeave(PyObject *object) - Ends a :c:func:`Py_ReprEnter`. Must be called once for each + Ends a :c:func:`Py_ReprEnter`. Must be called once for each invocation of :c:func:`Py_ReprEnter` that returns zero. diff --git a/Doc/c-api/file.rst b/Doc/c-api/file.rst index e9019a0d500f7e..d0e54a46b4179f 100644 --- a/Doc/c-api/file.rst +++ b/Doc/c-api/file.rst @@ -9,9 +9,9 @@ File Objects These APIs are a minimal emulation of the Python 2 C API for built-in file objects, which used to rely on the buffered I/O (:c:expr:`FILE*`) support -from the C standard library. In Python 3, files and streams use the new +from the C standard library. In Python 3, files and streams use the new :mod:`io` module, which defines several layers over the low-level unbuffered -I/O of the operating system. The functions described below are +I/O of the operating system. The functions described below are convenience C wrappers over these new APIs, and meant mostly for internal error reporting in the interpreter; third-party code is advised to access the :mod:`io` APIs instead. @@ -20,7 +20,7 @@ the :mod:`io` APIs instead. .. c:function:: PyObject* PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd) Create a Python file object from the file descriptor of an already - opened file *fd*. The arguments *name*, *encoding*, *errors* and *newline* + opened file *fd*. The arguments *name*, *encoding*, *errors* and *newline* can be ``NULL`` to use the defaults; *buffering* can be *-1* to use the default. *name* is ignored and kept for backward compatibility. Return ``NULL`` on failure. For a more comprehensive description of the arguments, @@ -38,11 +38,11 @@ the :mod:`io` APIs instead. .. c:function:: int PyObject_AsFileDescriptor(PyObject *p) - Return the file descriptor associated with *p* as an :c:expr:`int`. If the - object is an integer, its value is returned. If not, the + Return the file descriptor associated with *p* as an :c:expr:`int`. If the + object is an integer, its value is returned. If not, the object's :meth:`~io.IOBase.fileno` method is called if it exists; the method must return an integer, which is returned as the file descriptor - value. Sets an exception and returns ``-1`` on failure. + value. Sets an exception and returns ``-1`` on failure. .. c:function:: PyObject* PyFile_GetLine(PyObject *p, int n) @@ -50,12 +50,12 @@ the :mod:`io` APIs instead. .. index:: single: EOFError (built-in exception) Equivalent to ``p.readline([n])``, this function reads one line from the - object *p*. *p* may be a file object or any object with a + object *p*. *p* may be a file object or any object with a :meth:`~io.IOBase.readline` - method. If *n* is ``0``, exactly one line is read, regardless of the length of - the line. If *n* is greater than ``0``, no more than *n* bytes will be read - from the file; a partial line can be returned. In both cases, an empty string - is returned if the end of the file is reached immediately. If *n* is less than + method. If *n* is ``0``, exactly one line is read, regardless of the length of + the line. If *n* is greater than ``0``, no more than *n* bytes will be read + from the file; a partial line can be returned. In both cases, an empty string + is returned if the end of the file is reached immediately. If *n* is less than ``0``, however, one line is read regardless of length, but :exc:`EOFError` is raised if the end of the file is reached immediately. @@ -98,13 +98,13 @@ the :mod:`io` APIs instead. .. index:: single: Py_PRINT_RAW (C macro) - Write object *obj* to file object *p*. The only supported flag for *flags* is + Write object *obj* to file object *p*. The only supported flag for *flags* is :c:macro:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written - instead of the :func:`repr`. Return ``0`` on success or ``-1`` on failure; the + instead of the :func:`repr`. Return ``0`` on success or ``-1`` on failure; the appropriate exception will be set. .. c:function:: int PyFile_WriteString(const char *s, PyObject *p) - Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on + Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on failure; the appropriate exception will be set. diff --git a/Doc/c-api/float.rst b/Doc/c-api/float.rst index c5a7653efca26b..44e7ec2868ec4a 100644 --- a/Doc/c-api/float.rst +++ b/Doc/c-api/float.rst @@ -16,19 +16,19 @@ Floating-Point Objects .. c:var:: PyTypeObject PyFloat_Type This instance of :c:type:`PyTypeObject` represents the Python floating-point - type. This is the same object as :class:`float` in the Python layer. + type. This is the same object as :class:`float` in the Python layer. .. c:function:: int PyFloat_Check(PyObject *p) Return true if its argument is a :c:type:`PyFloatObject` or a subtype of - :c:type:`PyFloatObject`. This function always succeeds. + :c:type:`PyFloatObject`. This function always succeeds. .. c:function:: int PyFloat_CheckExact(PyObject *p) Return true if its argument is a :c:type:`PyFloatObject`, but not a subtype of - :c:type:`PyFloatObject`. This function always succeeds. + :c:type:`PyFloatObject`. This function always succeeds. .. c:function:: PyObject* PyFloat_FromString(PyObject *str) @@ -44,7 +44,7 @@ Floating-Point Objects .. c:function:: double PyFloat_AsDouble(PyObject *pyfloat) - Return a C :c:expr:`double` representation of the contents of *pyfloat*. If + Return a C :c:expr:`double` representation of the contents of *pyfloat*. If *pyfloat* is not a Python floating-point object but has a :meth:`~object.__float__` method, this method will first be called to convert *pyfloat* into a float. If :meth:`!__float__` is not defined then it falls back to :meth:`~object.__index__`. @@ -140,14 +140,14 @@ There are two problems on non-IEEE platforms: Unpack functions ^^^^^^^^^^^^^^^^ -The unpack routines read 2, 4 or 8 bytes, starting at *p*. *le* is an +The unpack routines read 2, 4 or 8 bytes, starting at *p*. *le* is an :c:expr:`int` argument, non-zero if the bytes string is in little-endian format (exponent last, at ``p+1``, ``p+3`` or ``p+6`` and ``p+7``), zero if big-endian (exponent first, at *p*). The :c:macro:`PY_BIG_ENDIAN` constant can be used to use the native endian: it is equal to ``1`` on big endian processor, or ``0`` on little endian processor. -Return value: The unpacked double. On error, this is ``-1.0`` and +Return value: The unpacked double. On error, this is ``-1.0`` and :c:func:`PyErr_Occurred` is true (and an exception is set, most likely :exc:`OverflowError`). diff --git a/Doc/c-api/function.rst b/Doc/c-api/function.rst index 5fb8567ef8c95f..c2f8263b64ba47 100644 --- a/Doc/c-api/function.rst +++ b/Doc/c-api/function.rst @@ -20,13 +20,13 @@ There are a few functions specific to Python functions. .. index:: single: MethodType (in module types) This is an instance of :c:type:`PyTypeObject` and represents the Python function - type. It is exposed to Python programmers as ``types.FunctionType``. + type. It is exposed to Python programmers as ``types.FunctionType``. .. c:function:: int PyFunction_Check(PyObject *o) Return true if *o* is a function object (has type :c:data:`PyFunction_Type`). - The parameter must not be ``NULL``. This function always succeeds. + The parameter must not be ``NULL``. This function always succeeds. .. c:function:: PyObject* PyFunction_New(PyObject *code, PyObject *globals) @@ -158,7 +158,7 @@ There are a few functions specific to Python functions. Clear watcher identified by *watcher_id* previously returned from :c:func:`PyFunction_AddWatcher` for the current interpreter. Return ``0`` on success, or ``-1`` and set an exception on error - (e.g. if the given *watcher_id* was never registered.) + (e.g. if the given *watcher_id* was never registered.) .. versionadded:: 3.12 @@ -197,7 +197,7 @@ There are a few functions specific to Python functions. runtime behavior depending on optimization decisions, it does not change the semantics of the Python code being executed. - If *event* is ``PyFunction_EVENT_DESTROY``, Taking a reference in the + If *event* is ``PyFunction_EVENT_DESTROY``, Taking a reference in the callback to the about-to-be-destroyed function will resurrect it, preventing it from being freed at this time. When the resurrected object is destroyed later, any watcher callbacks active at that time will be called again. diff --git a/Doc/c-api/gcsupport.rst b/Doc/c-api/gcsupport.rst index f6fa52b36c5ab3..c15d0a8d5e0b93 100644 --- a/Doc/c-api/gcsupport.rst +++ b/Doc/c-api/gcsupport.rst @@ -7,20 +7,20 @@ Supporting Cyclic Garbage Collection Python's support for detecting and collecting garbage which involves circular references requires support from object types which are "containers" for other -objects which may also be containers. Types which do not store references to +objects which may also be containers. Types which do not store references to other objects, or which only store references to atomic types (such as numbers or strings), do not need to provide any explicit support for garbage collection. To create a container type, the :c:member:`~PyTypeObject.tp_flags` field of the type object must include the :c:macro:`Py_TPFLAGS_HAVE_GC` and provide an implementation of the -:c:member:`~PyTypeObject.tp_traverse` handler. If instances of the type are mutable, a +:c:member:`~PyTypeObject.tp_traverse` handler. If instances of the type are mutable, a :c:member:`~PyTypeObject.tp_clear` implementation must also be provided. :c:macro:`Py_TPFLAGS_HAVE_GC` Objects with a type with this flag set must conform with the rules - documented here. For convenience these objects will be referred to as + documented here. For convenience these objects will be referred to as container objects. Constructors for container types must conform to two rules: @@ -139,8 +139,8 @@ rules: .. 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 - valid while being tracked. This should be called once all the fields + collector. The collector can run at unexpected times so objects must be + valid while being tracked. This should be called once all the fields followed by the :c:member:`~PyTypeObject.tp_traverse` handler become valid, usually near the end of the constructor. @@ -197,8 +197,8 @@ rules: .. c:function:: void PyObject_GC_UnTrack(void *op) Remove the object *op* from the set of container objects tracked by the - 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 + 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 (:c:member:`~PyTypeObject.tp_dealloc` handler) should call this for the object before any of the fields used by the :c:member:`~PyTypeObject.tp_traverse` handler become invalid. @@ -215,7 +215,7 @@ The :c:member:`~PyTypeObject.tp_traverse` handler accepts a function parameter o Type of the visitor function passed to the :c:member:`~PyTypeObject.tp_traverse` handler. The function should be called with an object to traverse as *object* and - the third parameter to the :c:member:`~PyTypeObject.tp_traverse` handler as *arg*. The + the third parameter to the :c:member:`~PyTypeObject.tp_traverse` handler as *arg*. The Python core uses several visitor functions to implement cyclic garbage detection; it's not expected that users will need to write their own visitor functions. @@ -225,22 +225,22 @@ The :c:member:`~PyTypeObject.tp_traverse` handler must have the following type: .. c:type:: int (*traverseproc)(PyObject *self, visitproc visit, void *arg) - Traversal function for a container object. Implementations must call the + Traversal function for a container object. Implementations must call the *visit* function for each object directly contained by *self*, with the parameters to *visit* being the contained object and the *arg* value passed - to the handler. The *visit* function must not be called with a ``NULL`` - object argument. If *visit* returns a non-zero value that value should be + to the handler. The *visit* function must not be called with a ``NULL`` + object argument. If *visit* returns a non-zero value that value should be returned immediately. To simplify writing :c:member:`~PyTypeObject.tp_traverse` handlers, a :c:func:`Py_VISIT` macro is -provided. In order to use this macro, the :c:member:`~PyTypeObject.tp_traverse` implementation +provided. In order to use this macro, the :c:member:`~PyTypeObject.tp_traverse` implementation must name its arguments exactly *visit* and *arg*: .. c:macro:: Py_VISIT(o) If the :c:expr:`PyObject *` *o* is not ``NULL``, call the *visit* callback, with arguments *o* - and *arg*. If *visit* returns a non-zero value, then return it. + and *arg*. If *visit* returns a non-zero value, then return it. Using this macro, :c:member:`~PyTypeObject.tp_traverse` handlers look like:: @@ -258,10 +258,10 @@ if the object is immutable. .. c:type:: int (*inquiry)(PyObject *self) - Drop references that may have created reference cycles. Immutable objects + 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 :c:func:`Py_DECREF` on a reference). The + reference cycles. Note that the object must still be valid after calling + this method (don't just call :c:func:`Py_DECREF` on a reference). The collector will call this method if it detects that this object is involved in a reference cycle. diff --git a/Doc/c-api/gen.rst b/Doc/c-api/gen.rst index 0eb5922f6da75f..3472a321246e12 100644 --- a/Doc/c-api/gen.rst +++ b/Doc/c-api/gen.rst @@ -22,14 +22,14 @@ than explicitly calling :c:func:`PyGen_New` or :c:func:`PyGen_NewWithQualName`. .. c:function:: int PyGen_Check(PyObject *ob) - Return true if *ob* is a generator object; *ob* must not be ``NULL``. This + Return true if *ob* is a generator object; *ob* must not be ``NULL``. This function always succeeds. .. c:function:: int PyGen_CheckExact(PyObject *ob) Return true if *ob*'s type is :c:type:`PyGen_Type`; *ob* must not be - ``NULL``. This function always succeeds. + ``NULL``. This function always succeeds. .. c:function:: PyObject* PyGen_New(PyFrameObject *frame) @@ -42,5 +42,5 @@ than explicitly calling :c:func:`PyGen_New` or :c:func:`PyGen_NewWithQualName`. Create and return a new generator object based on the *frame* object, with ``__name__`` and ``__qualname__`` set to *name* and *qualname*. - A reference to *frame* is stolen by this function. The *frame* argument + A reference to *frame* is stolen by this function. The *frame* argument must not be ``NULL``. diff --git a/Doc/c-api/import.rst b/Doc/c-api/import.rst index 8eabc0406b11ce..787a6048d74ed7 100644 --- a/Doc/c-api/import.rst +++ b/Doc/c-api/import.rst @@ -21,11 +21,11 @@ Importing Modules .. index:: pair: built-in function; __import__ - Import a module. This is best described by referring to the built-in Python + Import a module. This is best described by referring to the built-in Python function :func:`__import__`. The return value is a new reference to the imported module or top-level - package, or ``NULL`` with an exception set on failure. Like for + package, or ``NULL`` with an exception set on failure. Like for :func:`__import__`, the return value when a submodule of a package was requested is normally the top-level package, unless a non-empty *fromlist* was given. @@ -36,12 +36,12 @@ Importing Modules .. c:function:: PyObject* PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) - Import a module. This is best described by referring to the built-in Python + Import a module. This is best described by referring to the built-in Python function :func:`__import__`, as the standard :func:`__import__` function calls this function directly. The return value is a new reference to the imported module or top-level package, - or ``NULL`` with an exception set on failure. Like for :func:`__import__`, + or ``NULL`` with an exception set on failure. Like for :func:`__import__`, the return value when a submodule of a package was requested is normally the top-level package, unless a non-empty *fromlist* was given. @@ -59,9 +59,9 @@ Importing Modules .. c:function:: PyObject* PyImport_Import(PyObject *name) This is a higher-level interface that calls the current "import hook - function" (with an explicit *level* of 0, meaning absolute import). It + function" (with an explicit *level* of 0, meaning absolute import). It invokes the :func:`__import__` function from the ``__builtins__`` of the - current globals. This means that the import is done using whatever import + current globals. This means that the import is done using whatever import hooks are installed in the current environment. This function always uses absolute imports. @@ -69,7 +69,7 @@ Importing Modules .. c:function:: PyObject* PyImport_ReloadModule(PyObject *m) - Reload a module. Return a new reference to the reloaded module, or ``NULL`` with + Reload a module. Return a new reference to the reloaded module, or ``NULL`` with an exception set on failure (the module still exists in this case). @@ -115,24 +115,24 @@ Importing Modules Given a module name (possibly of the form ``package.module``) and a code object read from a Python bytecode file or obtained from the built-in function - :func:`compile`, load the module. Return a new reference to the module object, - or ``NULL`` with an exception set if an error occurred. *name* + :func:`compile`, load the module. Return a new reference to the module object, + or ``NULL`` with an exception set if an error occurred. *name* is removed from :data:`sys.modules` in error cases, even if *name* was already - in :data:`sys.modules` on entry to :c:func:`PyImport_ExecCodeModule`. Leaving + in :data:`sys.modules` on entry to :c:func:`PyImport_ExecCodeModule`. Leaving incompletely initialized modules in :data:`sys.modules` is dangerous, as imports of such modules have no way to know that the module object is an unknown (and probably damaged with respect to the module author's intents) state. The module's :attr:`~module.__spec__` and :attr:`~module.__loader__` will be - set, if not set already, with the appropriate values. The spec's loader + set, if not set already, with the appropriate values. The spec's loader will be set to the module's :attr:`!__loader__` (if set) and to an instance of :class:`~importlib.machinery.SourceFileLoader` otherwise. The module's :attr:`~module.__file__` attribute will be set to the code - object's :attr:`~codeobject.co_filename`. If applicable, + object's :attr:`~codeobject.co_filename`. If applicable, :attr:`~module.__cached__` will also be set. - This function will reload the module if it was already imported. See + This function will reload the module if it was already imported. See :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 @@ -159,7 +159,7 @@ Importing Modules Like :c:func:`PyImport_ExecCodeModuleEx`, but the :attr:`~module.__cached__` attribute of the module object is set to *cpathname* if it is - non-``NULL``. Of the three functions, this is the preferred one to use. + non-``NULL``. Of the three functions, this is the preferred one to use. .. versionadded:: 3.3 @@ -196,7 +196,7 @@ Importing Modules .. c:function:: const char * PyImport_GetMagicTag() Return the magic tag string for :pep:`3147` format Python bytecode file - names. Keep in mind that the value at ``sys.implementation.cache_tag`` is + names. Keep in mind that the value at ``sys.implementation.cache_tag`` is authoritative and should be used instead of this function. .. versionadded:: 3.2 @@ -204,13 +204,13 @@ Importing Modules .. 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. + ``sys.modules``). Note that this is a per-interpreter variable. .. c:function:: PyObject* PyImport_GetModule(PyObject *name) - Return the already imported module with the given name. If the + Return the already imported module with the given name. If the module has not been imported yet then returns ``NULL`` but does not set - an error. Returns ``NULL`` and sets an error if the lookup failed. + an error. Returns ``NULL`` and sets an error if the lookup failed. .. versionadded:: 3.7 @@ -218,8 +218,8 @@ Importing Modules Return a finder object for a :data:`sys.path`/:attr:`!pkg.__path__` item *path*, possibly by fetching it from the :data:`sys.path_importer_cache` - dict. If it wasn't yet cached, traverse :data:`sys.path_hooks` until a hook - is found that can handle the path item. Return ``None`` if no hook could; + dict. If it wasn't yet cached, traverse :data:`sys.path_hooks` until a hook + is found that can handle the path item. Return ``None`` if no hook could; this tells our caller that the :term:`path based finder` could not find a finder for this path item. Cache the result in :data:`sys.path_importer_cache`. Return a new reference to the finder object. @@ -227,10 +227,10 @@ Importing Modules .. c:function:: int PyImport_ImportFrozenModuleObject(PyObject *name) - Load a frozen module named *name*. Return ``1`` for success, ``0`` if the + 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 - :c:func:`PyImport_ImportModule`. (Note the misnomer --- this function would + failed. To access the imported module on a successful load, use + :c:func:`PyImport_ImportModule`. (Note the misnomer --- this function would reload the module if it was already imported.) .. versionadded:: 3.3 @@ -251,7 +251,7 @@ Importing Modules This is the structure type definition for frozen module descriptors, as generated by the :program:`freeze` utility (see :file:`Tools/freeze/` in the - Python source distribution). Its definition, found in :file:`Include/import.h`, + Python source distribution). Its definition, found in :file:`Include/import.h`, is:: struct _frozen { @@ -268,18 +268,18 @@ Importing Modules .. c:var:: const struct _frozen* PyImport_FrozenModules This pointer is initialized to point to an array of :c: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 + 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. .. c:function:: int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void)) - Add a single module to the existing table of built-in modules. This is a + Add a single module to the existing table of built-in modules. This is a 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 + 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 + on the first attempted import. This should be called before :c:func:`Py_Initialize`. @@ -302,12 +302,12 @@ Importing Modules .. c:function:: int PyImport_ExtendInittab(struct _inittab *newtab) - Add a collection of modules to the table of built-in modules. The *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 :c:member:`~_inittab.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 must be called before :c:func:`Py_Initialize`. + extend the internal table. In the event of failure, no modules are added to the + internal table. This must be called before :c:func:`Py_Initialize`. If Python is initialized multiple times, :c:func:`PyImport_AppendInittab` or :c:func:`PyImport_ExtendInittab` must be called before each Python diff --git a/Doc/c-api/index.rst b/Doc/c-api/index.rst index e9df2a304d975b..9640a630ee9a70 100644 --- a/Doc/c-api/index.rst +++ b/Doc/c-api/index.rst @@ -5,7 +5,7 @@ ################################## This manual documents the API used by C and C++ programmers who want to write -extension modules or embed Python. It is a companion to :ref:`extending-index`, +extension modules or embed Python. It is a companion to :ref:`extending-index`, which describes the general principles of extension writing but does not document the API functions in detail. diff --git a/Doc/c-api/init.rst b/Doc/c-api/init.rst index 409539dec17d73..82de07cd4cf132 100644 --- a/Doc/c-api/init.rst +++ b/Doc/c-api/init.rst @@ -15,7 +15,7 @@ on how to configure the interpreter prior to initialization. Before Python Initialization ============================ -In an application embedding Python, the :c:func:`Py_Initialize` function must +In an application embedding Python, the :c:func:`Py_Initialize` function must be called before using any other Python/C API functions; with the exception of a few functions and the :ref:`global configuration variables `. @@ -101,7 +101,7 @@ to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2. Initialization Configuration `. Issue a warning when comparing :class:`bytes` or :class:`bytearray` with - :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater + :class:`str` or :class:`bytes` with :class:`int`. Issue an error if greater or equal to ``2``. Set by the :option:`-b` option. @@ -258,7 +258,7 @@ to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2. :ref:`Python Initialization Configuration `. Disable the import of the module :mod:`site` and the site-dependent - manipulations of :data:`sys.path` that it entails. Also disable these + manipulations of :data:`sys.path` that it entails. Also disable these manipulations if :mod:`site` is explicitly imported later (call :func:`site.main` if you want them to be triggered). @@ -325,7 +325,7 @@ to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2. Initialization Configuration `. Print a message each time a module is initialized, showing the place - (filename or built-in module) from which it is loaded. If greater or equal + (filename or built-in module) from which it is loaded. If greater or equal to ``2``, print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit. @@ -351,7 +351,7 @@ Initializing and finalizing the interpreter triple: module; search; path single: Py_FinalizeEx (C function) - Initialize the Python interpreter. In an application embedding Python, + Initialize the Python interpreter. In an application embedding Python, this should be called before using any other Python/C API functions; see :ref:`Before Python Initialization ` for the few exceptions. @@ -360,7 +360,7 @@ Initializing and finalizing the interpreter It also initializes the module search path (``sys.path``). It does not set ``sys.argv``; use the :ref:`Python Initialization Configuration ` API for that. This is a no-op when called for a second time (without calling - :c:func:`Py_FinalizeEx` first). There is no return value; it is a fatal + :c:func:`Py_FinalizeEx` first). There is no return value; it is a fatal error if the initialization fails. Use :c:func:`Py_InitializeFromConfig` to customize the @@ -394,7 +394,7 @@ Initializing and finalizing the interpreter .. c:function:: int Py_IsInitialized() Return true (nonzero) when the Python interpreter has been initialized, false - (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until + (zero) if not. After :c:func:`Py_FinalizeEx` is called, this returns false until :c:func:`Py_Initialize` is called again. @@ -411,11 +411,11 @@ Initializing and finalizing the interpreter Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of Python/C API functions, and destroy all sub-interpreters (see :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since - the last call to :c:func:`Py_Initialize`. This is a no-op when called for a second + the last call to :c:func:`Py_Initialize`. This is a no-op when called for a second time (without calling :c:func:`Py_Initialize` again first). Since this is the reverse of :c:func:`Py_Initialize`, it should be called - in the same thread with the same interpreter active. That means + in the same thread with the same interpreter active. That means the main thread and the main interpreter. This should never be called while :c:func:`Py_RunMain` is running. @@ -424,12 +424,12 @@ Initializing and finalizing the interpreter ``-1`` is returned. Note that Python will do a best effort at freeing all memory allocated by the Python - interpreter. Therefore, any C-Extension should make sure to correctly clean up all + interpreter. Therefore, any C-Extension should make sure to correctly clean up all of the preveiously allocated PyObjects before using them in subsequent calls to - :c:func:`Py_Initialize`. Otherwise it could introduce vulnerabilities and incorrect + :c:func:`Py_Initialize`. Otherwise it could introduce vulnerabilities and incorrect behavior. - This function is provided for a number of reasons. An embedding application + This function is provided for a number of reasons. An embedding application might want to restart Python without having to restart the application itself. An application that has loaded the Python interpreter from a dynamically loadable library (or DLL) might want to free all memory allocated by Python @@ -439,16 +439,16 @@ Initializing and finalizing the interpreter **Bugs and caveats:** The destruction of modules and objects in modules is done in random order; this may cause destructors (:meth:`~object.__del__` methods) to fail - when they depend on other objects (even functions) or modules. Dynamically - loaded extension modules loaded by Python are not unloaded. Small amounts of + when they depend on other objects (even functions) or modules. Dynamically + loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, - please report it). Memory tied up in circular references between objects is not - freed. Interned strings will all be deallocated regardless of their reference count. - Some memory allocated by extension modules may not be freed. Some extensions may not + please report it). Memory tied up in circular references between objects is not + freed. Interned strings will all be deallocated regardless of their reference count. + 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 :c:func:`Py_Initialize` and :c:func:`Py_FinalizeEx` - more than once. :c:func:`Py_FinalizeEx` must not be called recursively from - within itself. Therefore, it must not be called by any code that may be run + more than once. :c:func:`Py_FinalizeEx` must not be called recursively from + within itself. Therefore, it must not be called by any code that may be run as part of the interpreter shutdown process, such as :py:mod:`atexit` handlers, object finalizers, or any code that may be run while flushing the stdout and stderr files. @@ -572,14 +572,14 @@ Process-wide parameters Initialization Configuration `. 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 + the first time, if it is called at all. It tells the interpreter the value of the ``argv[0]`` argument to the :c:func:`main` function of the program (converted to wide characters). This is used by 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 + the Python run-time libraries relative to the interpreter executable. The + default value is ``'python'``. The argument should point to a zero-terminated wide character string in static storage whose contents will not - change for the duration of the program's execution. No code in the Python + change for the duration of the program's execution. No code in the Python interpreter will change the contents of this storage. Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a @@ -590,7 +590,7 @@ Process-wide parameters .. c:function:: const char* Py_GetVersion() - Return the version of this Python interpreter. This is a string that looks + Return the version of this Python interpreter. This is a string that looks something like :: "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]" @@ -599,8 +599,8 @@ Process-wide parameters The first word (up to the first space character) is the current Python version; the first characters are the major and minor version separated by a - period. The returned string points into static storage; the caller should not - modify its value. The value is available to Python code as :data:`sys.version`. + period. The returned string points into static storage; the caller should not + modify its value. The value is available to Python code as :data:`sys.version`. See also the :c:var:`Py_Version` constant. @@ -609,12 +609,12 @@ Process-wide parameters .. index:: single: platform (in module sys) - Return the platform identifier for the current platform. On Unix, this is + Return the platform identifier for the current platform. On Unix, this is formed from the "official" name of the operating system, converted to lower case, followed by the major revision number; e.g., for Solaris 2.x, which is - also known as SunOS 5.x, the value is ``'sunos5'``. On macOS, it is - ``'darwin'``. On Windows, it is ``'win'``. The returned string points into - static storage; the caller should not modify its value. The value is available + also known as SunOS 5.x, the value is ``'sunos5'``. On macOS, it is + ``'darwin'``. On Windows, it is ``'win'``. The returned string points into + static storage; the caller should not modify its value. The value is available to Python code as ``sys.platform``. @@ -627,7 +627,7 @@ Process-wide parameters .. index:: single: copyright (in module sys) The returned string points into static storage; the caller should not modify its - value. The value is available to Python code as ``sys.copyright``. + value. The value is available to Python code as ``sys.copyright``. .. c:function:: const char* Py_GetCompiler() @@ -640,21 +640,21 @@ Process-wide parameters .. index:: single: version (in module sys) The returned string points into static storage; the caller should not modify its - value. The value is available to Python code as part of the variable + value. The value is available to Python code as part of the variable ``sys.version``. .. c:function:: const char* Py_GetBuildInfo() - Return information about the sequence number and build date and time of the + Return information about the sequence number and build date and time of the current Python interpreter instance, for example :: - "#67, Aug 1 1997, 22:34:28" + "#67, Aug 1 1997, 22:34:28" .. index:: single: version (in module sys) The returned string points into static storage; the caller should not modify its - value. The value is available to Python code as part of the variable + value. The value is available to Python code as part of the variable ``sys.version``. @@ -670,15 +670,15 @@ Process-wide parameters :c:member:`PyConfig.safe_path` should be used instead, see :ref:`Python Initialization Configuration `. - Set :data:`sys.argv` based on *argc* and *argv*. These parameters are + Set :data:`sys.argv` based on *argc* and *argv*. These parameters are 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 + 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 + string. If this function fails to initialize :data:`sys.argv`, a fatal condition is signalled using :c:func:`Py_FatalError`. - If *updatepath* is zero, this is all the function does. If *updatepath* + 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 following algorithm: @@ -744,12 +744,12 @@ Process-wide parameters Initialization Configuration `. Set the default "home" directory, that is, the location of the standard - Python libraries. See :envvar:`PYTHONHOME` for the meaning of the + Python libraries. See :envvar:`PYTHONHOME` for the meaning of the argument string. The argument should point to a zero-terminated character string in static storage whose contents will not change for the duration of the program's - execution. No code in the Python interpreter will change the contents of + execution. No code in the Python interpreter will change the contents of this storage. Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a @@ -769,7 +769,7 @@ Thread State and the Global Interpreter Lock single: lock, interpreter Unless on a :term:`free-threaded ` build of :term:`CPython`, -the Python interpreter is not fully thread-safe. In order to support +the Python interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there's a global lock, called the :term:`global interpreter lock` or :term:`GIL`, that must be held by the current thread before it can safely access Python objects. Without the lock, even the simplest @@ -782,7 +782,7 @@ reference count could end up being incremented only once instead of twice. Therefore, the rule exists that only the thread that has acquired the :term:`GIL` may operate on Python objects or call Python/C API functions. In order to emulate concurrency of execution, the interpreter regularly -tries to switch threads (see :func:`sys.setswitchinterval`). The lock is also +tries to switch threads (see :func:`sys.setswitchinterval`). The lock is also released around potentially blocking I/O operations like reading or writing a file, so that other Python threads can run in the meantime. @@ -796,9 +796,9 @@ referenced by this pointer is considered to be :term:`attached ` builds. On builds with the :term:`GIL` enabled, +:term:`free-threaded ` builds. On builds with the :term:`GIL` enabled, :term:`attaching ` a thread state will block until the :term:`GIL` -can be acquired. However, even on builds with the :term:`GIL` disabled, it is still required +can be acquired. However, even on builds with the :term:`GIL` disabled, it is still required to have an attached thread state to call most of the C API. In general, there will always be an :term:`attached thread state` when using Python's C API. @@ -875,7 +875,7 @@ Non-Python created threads When threads are created using the dedicated Python APIs (such as the :mod:`threading` module), a thread state is automatically associated to them -and the code showed above is therefore correct. However, when threads are +and the code showed above is therefore correct. However, when threads are created from C (for example by a third-party library with its own thread management), they don't hold the :term:`GIL`, because they don't have an :term:`attached thread state`. @@ -884,11 +884,11 @@ If you need to call Python code from these threads (often this will be part of a callback API provided by the aforementioned third-party library), you must first register these threads with the interpreter by creating an :term:`attached thread state` before you can start using the Python/C -API. When you are done, you should detach the :term:`thread state `, and +API. When you are done, you should detach the :term:`thread state `, and finally free it. The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do -all of the above automatically. The typical idiom for calling into Python +all of the above automatically. The typical idiom for calling into Python from a C thread is:: PyGILState_STATE gstate; @@ -902,7 +902,7 @@ from a C thread is:: PyGILState_Release(gstate); Note that the ``PyGILState_*`` functions assume there is only one global -interpreter (created automatically by :c:func:`Py_Initialize`). Python +interpreter (created automatically by :c:func:`Py_Initialize`). Python supports the creation of additional interpreters (using :c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the ``PyGILState_*`` API is unsupported. This is because :c:func:`PyGILState_Ensure` @@ -943,7 +943,7 @@ Cautions about fork() Another important thing to note about threads is their behaviour in the face 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. This has a +process forks only the thread that issued the fork will exist. This has a concrete impact both on how locks must be handled and on all stored state in CPython's runtime. @@ -964,9 +964,9 @@ always able to. The fact that all other threads go away also means that CPython's runtime state there must be cleaned up properly, which :func:`os.fork` -does. This means finalizing all other :c:type:`PyThreadState` objects +does. This means finalizing all other :c:type:`PyThreadState` objects belonging to the current interpreter and all other -:c:type:`PyInterpreterState` objects. Due to this and the special +:c:type:`PyInterpreterState` objects. Due to this and the special nature of the :ref:`"main" interpreter `, :c:func:`fork` should only be called in that interpreter's "main" thread, where the CPython global runtime was originally initialized. @@ -982,14 +982,14 @@ In the late stage of :term:`interpreter shutdown`, after attempting to wait for non-daemon threads to exit (though this can be interrupted by :class:`KeyboardInterrupt`) and running the :mod:`atexit` functions, the runtime is marked as *finalizing*: :c:func:`Py_IsFinalizing` and -:func:`sys.is_finalizing` return true. At this point, only the *finalization +:func:`sys.is_finalizing` return true. At this point, only the *finalization thread* that initiated finalization (typically the main thread) is allowed to acquire the :term:`GIL`. If any thread, other than the finalization thread, attempts to attach a :term:`thread state` during finalization, either explicitly or implicitly, the thread enters **a permanently blocked state** -where it remains until the program exits. In most cases this is harmless, but this can result +where it remains until the program exits. In most cases this is harmless, but this can result in deadlock if a later stage of finalization attempts to acquire a lock owned by the blocked thread, or otherwise waits on the blocked thread. @@ -1011,19 +1011,19 @@ code, or when embedding the Python interpreter: .. 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 + threads. Threads belonging to the same interpreter share their module administration and a few other internal items. There are no public members in this structure. Threads belonging to different interpreters initially share nothing, except - process state like available memory, open file descriptors and such. The global + process state like available memory, open file descriptors and such. The global interpreter lock is also shared by all threads, regardless of to which interpreter they belong. .. c:type:: PyThreadState - This data structure represents the state of a single thread. The only public + This data structure represents the state of a single thread. The only public data member is: .. c:member:: PyInterpreterState *interp @@ -1073,7 +1073,7 @@ code, or when embedding the Python interpreter: .. note:: Calling this function from a thread when the runtime is finalizing will hang the thread until the program exits, even if the thread was not - created by Python. Refer to + created by Python. Refer to :ref:`cautions-regarding-runtime-finalization` for more details. .. versionchanged:: 3.14 @@ -1127,7 +1127,7 @@ with sub-interpreters: 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 + its previous state before the Release(). For example, normal usage of the :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is acceptable. @@ -1139,7 +1139,7 @@ with sub-interpreters: to :c:func:`PyGILState_Release`. When the function returns, there will be an :term:`attached thread state` - and the thread will be able to call arbitrary Python code. Failure is a fatal error. + and the thread will be able to call arbitrary Python code. Failure is a fatal error. .. warning:: Calling this function when the runtime is finalizing is unsafe. Doing @@ -1153,7 +1153,7 @@ with sub-interpreters: .. c:function:: void PyGILState_Release(PyGILState_STATE) - Release any resources previously acquired. After this call, Python's state will + Release any resources previously acquired. After this call, Python's state will 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). @@ -1163,10 +1163,10 @@ with sub-interpreters: .. c:function:: PyThreadState* PyGILState_GetThisThreadState() - Get the :term:`attached thread state` for this thread. May return ``NULL`` if no - GILState API has been used on the current thread. Note that the main thread + Get the :term:`attached thread state` for this thread. May return ``NULL`` if no + GILState API has been used on the current thread. Note that the main thread always has such a thread-state, even if no auto-thread-state call has been - made on the main thread. This is mainly a helper/diagnostic function. + made on the main thread. This is mainly a helper/diagnostic function. .. note:: This function does not account for :term:`thread states ` created @@ -1182,7 +1182,7 @@ with sub-interpreters: This function can be called from any thread at any time. Only if it has had its :term:`thread state ` initialized via :c:func:`PyGILState_Ensure` will it return ``1``. - This is mainly a helper/diagnostic function. It can be useful + This is mainly a helper/diagnostic function. It can be useful for example in callback contexts or memory allocation functions when knowing that the :term:`GIL` is locked can allow the caller to perform sensitive actions or otherwise behave differently. @@ -1203,7 +1203,7 @@ example usage in the Python source distribution. This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``. Note that it contains an opening brace; it must be matched with a following - :c:macro:`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. @@ -1211,7 +1211,7 @@ example usage in the Python source distribution. This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains a closing brace; it must be matched with an earlier - :c:macro:`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. @@ -1240,7 +1240,7 @@ All of the following functions must be called after :c:func:`Py_Initialize`. .. c:function:: PyInterpreterState* PyInterpreterState_New() - Create a new interpreter state object. An :term:`attached thread state` is not needed, + Create a new interpreter state object. An :term:`attached thread state` is not needed, but may optionally exist if it is necessary to serialize calls to this function. @@ -1249,7 +1249,7 @@ All of the following functions must be called after :c:func:`Py_Initialize`. .. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp) - Reset all information in an interpreter state object. There must be + Reset all information in an interpreter state object. There must be an :term:`attached thread state` for the interpreter. .. audit-event:: cpython.PyInterpreterState_Clear "" c.PyInterpreterState_Clear @@ -1257,7 +1257,7 @@ All of the following functions must be called after :c:func:`Py_Initialize`. .. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp) - Destroy an interpreter state object. There **should not** be an + Destroy an interpreter state object. There **should not** be an :term:`attached thread state` for the target interpreter. The interpreter state must have been reset with a previous call to :c:func:`PyInterpreterState_Clear`. @@ -1269,7 +1269,7 @@ All of the following functions must be called after :c:func:`Py_Initialize`. .. c:function:: void PyThreadState_Clear(PyThreadState *tstate) - Reset all information in a :term:`thread state` object. *tstate* + Reset all information in a :term:`thread state` object. *tstate* must be :term:`attached ` .. versionchanged:: 3.9 @@ -1282,7 +1282,7 @@ All of the following functions must be called after :c:func:`Py_Initialize`. .. c:function:: void PyThreadState_Delete(PyThreadState *tstate) - Destroy a :term:`thread state` object. *tstate* should not + Destroy a :term:`thread state` object. *tstate* should not be :term:`attached ` to any thread. *tstate* must have been reset with a previous call to :c:func:`PyThreadState_Clear`. @@ -1360,7 +1360,7 @@ All of the following functions must be called after :c:func:`Py_Initialize`. .. c:function:: int64_t PyInterpreterState_GetID(PyInterpreterState *interp) - Return the interpreter's unique ID. If there was any error in doing + Return the interpreter's unique ID. If there was any error in doing so then ``-1`` is returned and an error is set. The caller must have an :term:`attached thread state`. @@ -1413,8 +1413,8 @@ All of the following functions must be called after :c:func:`Py_Initialize`. .. 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 - the dictionary. It is okay to call this function when no :term:`thread state` + information. Each extension should use a unique key to use to store state in + the dictionary. It is okay to call this function when no :term:`thread state` is :term:`attached `. If this function returns ``NULL``, no exception has been raised and the caller should assume no thread state is attached. @@ -1425,9 +1425,9 @@ All of the following functions must be called after :c:func:`Py_Initialize`. 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 function does not steal any references to *exc*. To prevent naive misuse, you - must write your own C extension to call this. Must be called with an :term:`attached thread state`. + must write your own C extension to call this. Must be called with an :term:`attached thread state`. Returns the number of thread states modified; this is normally one, but will be - zero if the thread id isn't found. If *exc* is ``NULL``, the pending + zero if the thread id isn't found. If *exc* is ``NULL``, the pending exception (if any) for the thread is cleared. This raises no exceptions. .. versionchanged:: 3.7 @@ -1444,7 +1444,7 @@ All of the following functions must be called after :c:func:`Py_Initialize`. .. note:: Calling this function from a thread when the runtime is finalizing will hang the thread until the program exits, even if the thread was not - created by Python. Refer to + created by Python. Refer to :ref:`cautions-regarding-runtime-finalization` for more details. .. versionchanged:: 3.8 @@ -1482,10 +1482,10 @@ same process and perhaps even in the same thread. Sub-interpreters allow you to do that. The "main" interpreter is the first one created when the runtime initializes. -It is usually the only Python interpreter in a process. Unlike sub-interpreters, +It is usually the only Python interpreter in a process. Unlike sub-interpreters, the main interpreter has unique process-global responsibilities like signal -handling. It is also responsible for execution during runtime initialization and -is usually the active interpreter during runtime finalization. The +handling. It is also responsible for execution during runtime initialization and +is usually the active interpreter during runtime finalization. The :c:func:`PyInterpreterState_Main` function returns a pointer to its state. You can switch between sub-interpreters using the :c:func:`PyThreadState_Swap` @@ -1591,13 +1591,13 @@ function. You can create and destroy them using the following functions: single: stderr (in module sys) single: stdin (in module sys) - Create a new sub-interpreter. This is an (almost) totally separate environment - for the execution of Python code. In particular, the new interpreter has + Create a new sub-interpreter. This is an (almost) totally separate environment + for the execution of Python code. In particular, the new interpreter has separate, independent versions of all imported modules, including the - fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The + fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`. The table of loaded modules (``sys.modules``) and the module search path - (``sys.path``) are also separate. The new environment has no ``sys.argv`` - variable. It has new standard I/O stream file objects ``sys.stdin``, + (``sys.path``) are also separate. The new environment has no ``sys.argv`` + variable. It has new standard I/O stream file objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying file descriptors). @@ -1605,10 +1605,10 @@ function. You can create and destroy them using the following functions: is initialized. Upon success, *tstate_p* will be set to the first :term:`thread state` - created in the new sub-interpreter. This thread state is + created in the new sub-interpreter. This thread state is :term:`attached `. Note that no actual thread is created; see the discussion of thread states - below. If creation of the new interpreter is unsuccessful, + below. If creation of the new interpreter is unsuccessful, *tstate_p* is set to ``NULL``; no exception is set since the exception state is stored in the :term:`attached thread state`, which might not exist. @@ -1644,7 +1644,7 @@ function. You can create and destroy them using the following functions: Note that the config is used only briefly and does not get modified. During initialization the config's values are converted into various - :c:type:`PyInterpreterState` values. A read-only copy of the config + :c:type:`PyInterpreterState` values. A read-only copy of the config may be stored internally on the :c:type:`PyInterpreterState`. .. index:: @@ -1653,13 +1653,13 @@ function. You can create and destroy them using the following functions: Extension modules are shared between (sub-)interpreters as follows: - * For modules using multi-phase initialization, + * For modules using multi-phase initialization, e.g. :c:func:`PyModule_FromDefAndSpec`, a separate module object is created and initialized for each interpreter. Only C-level static and global variables are shared between these module objects. - * For modules using single-phase initialization, + * For modules using single-phase initialization, e.g. :c:func:`PyModule_Create`, the first time a particular extension is imported, it is initialized normally, and a (shallow) copy of its module's dictionary is squirreled away. @@ -1690,9 +1690,9 @@ function. You can create and destroy them using the following functions: single: stderr (in module sys) single: stdin (in module sys) - Create a new sub-interpreter. This is essentially just a wrapper + Create a new sub-interpreter. This is essentially just a wrapper around :c:func:`Py_NewInterpreterFromConfig` with a config that - preserves the existing behavior. The result is an unisolated + preserves the existing behavior. The result is an unisolated sub-interpreter that shares the main interpreter's GIL, allows fork/exec, allows daemon threads, and allows single-phase init modules. @@ -1716,19 +1716,19 @@ A Per-Interpreter GIL Using :c:func:`Py_NewInterpreterFromConfig` you can create a sub-interpreter that is completely isolated from other interpreters, -including having its own GIL. The most important benefit of this +including having its own GIL. The most important benefit of this isolation is that such an interpreter can execute Python code without -being blocked by other interpreters or blocking any others. Thus a +being blocked by other interpreters or blocking any others. Thus a single Python process can truly take advantage of multiple CPU cores -when running Python code. The isolation also encourages a different +when running Python code. The isolation also encourages a different approach to concurrency than that of just using threads. (See :pep:`554`.) Using an isolated interpreter requires vigilance in preserving that -isolation. That especially means not sharing any objects or mutable -state without guarantees about thread-safety. Even objects that are +isolation. That especially means not sharing any objects or mutable +state without guarantees about thread-safety. Even objects that are otherwise immutable (e.g. ``None``, ``(1, 5)``) can't normally be shared -because of the refcount. One simple but less-efficient approach around +because of the refcount. One simple but less-efficient approach around this is to use a global lock around all use of some state (or object). Alternately, effectively immutable objects (like integers or strings) can be made safe in spite of their refcounts by making them :term:`immortal`. @@ -1742,8 +1742,8 @@ of free-threading, including races and hard-to-debug crashes. Aside from that, one of the main challenges of using multiple isolated interpreters is how to communicate between them safely (not break -isolation) and efficiently. The runtime and stdlib do not provide -any standard approach to this yet. A future stdlib module would help +isolation) and efficiently. The runtime and stdlib do not provide +any standard approach to this yet. A future stdlib module would help mitigate the effort of preserving isolation and expose effective tools for communicating (and sharing) data between interpreters. @@ -1755,8 +1755,8 @@ Bugs and caveats Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isn't perfect --- for example, using -low-level file operations like :func:`os.close` they can -(accidentally or maliciously) affect each other's open files. Because of the +low-level file operations like :func:`os.close` they can +(accidentally or maliciously) affect each other's open files. Because of the way extensions are shared between (sub-)interpreters, some extensions may not work properly; this is especially likely when using single-phase initialization or (static) global variables. @@ -1783,18 +1783,18 @@ Asynchronous Notifications ========================== A mechanism is provided to make asynchronous notifications to the main -interpreter thread. These notifications take the form of a function +interpreter thread. These notifications take the form of a function pointer and a void pointer argument. .. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg) - Schedule a function to be called from the main interpreter thread. On + Schedule a function to be called from the main interpreter thread. On success, ``0`` is returned and *func* is queued for being called in the - main thread. On failure, ``-1`` is returned without setting any exception. + main thread. On failure, ``-1`` is returned without setting any exception. When successfully queued, *func* will be *eventually* called from the - main interpreter thread with the argument *arg*. It will be called + main interpreter thread with the argument *arg*. It will be called asynchronously with respect to normally running Python code, but with both these conditions met: @@ -1803,7 +1803,7 @@ pointer and a void pointer argument. (*func* can therefore use the full C API). *func* must return ``0`` on success, or ``-1`` on failure with an exception - set. *func* won't be interrupted to perform another asynchronous + set. *func* won't be interrupted to perform another asynchronous notification recursively, but it can still be interrupted to switch threads if the :term:`thread state ` is detached. @@ -1814,10 +1814,10 @@ pointer and a void pointer argument. .. warning:: This is a low-level function, only useful for very special cases. There is no guarantee that *func* will be called as quick as - possible. If the main thread is busy executing a system call, - *func* won't be called before the system call returns. This + possible. If the main thread is busy executing a system call, + *func* won't be called before the system call returns. This function is generally **not** suitable for calling Python code from - arbitrary C threads. Instead, use the :ref:`PyGILState API`. + arbitrary C threads. Instead, use the :ref:`PyGILState API`. .. versionadded:: 3.1 @@ -1836,12 +1836,12 @@ Profiling and Tracing The Python interpreter provides some low-level support for attaching profiling -and execution tracing facilities. These are used for profiling, debugging, and +and execution tracing facilities. These are used for profiling, debugging, and coverage analysis tools. This C interface allows the profiling or tracing code to avoid the overhead of calling through Python-level callable objects, making a direct C function call -instead. The essential attributes of the facility have not changed; the +instead. The essential attributes of the facility have not changed; the interface allows trace functions to be installed per-thread, and the basic events reported to the trace function are the same as had been reported to the Python-level trace functions in previous versions. @@ -1858,25 +1858,25 @@ Python-level trace functions in previous versions. or :c:data:`PyTrace_OPCODE`, and *arg* depends on the value of *what*: +-------------------------------+----------------------------------------+ - | Value of *what* | Meaning of *arg* | + | Value of *what* | Meaning of *arg* | +===============================+========================================+ - | :c:data:`PyTrace_CALL` | Always :c:data:`Py_None`. | + | :c:data:`PyTrace_CALL` | Always :c:data:`Py_None`. | +-------------------------------+----------------------------------------+ - | :c:data:`PyTrace_EXCEPTION` | Exception information as returned by | - | | :func:`sys.exc_info`. | + | :c:data:`PyTrace_EXCEPTION` | Exception information as returned by | + | | :func:`sys.exc_info`. | +-------------------------------+----------------------------------------+ - | :c:data:`PyTrace_LINE` | Always :c:data:`Py_None`. | + | :c:data:`PyTrace_LINE` | Always :c:data:`Py_None`. | +-------------------------------+----------------------------------------+ - | :c:data:`PyTrace_RETURN` | Value being returned to the caller, | - | | or ``NULL`` if caused by an exception. | + | :c:data:`PyTrace_RETURN` | Value being returned to the caller, | + | | or ``NULL`` if caused by an exception. | +-------------------------------+----------------------------------------+ - | :c:data:`PyTrace_C_CALL` | Function object being called. | + | :c:data:`PyTrace_C_CALL` | Function object being called. | +-------------------------------+----------------------------------------+ - | :c:data:`PyTrace_C_EXCEPTION` | Function object being called. | + | :c:data:`PyTrace_C_EXCEPTION` | Function object being called. | +-------------------------------+----------------------------------------+ - | :c:data:`PyTrace_C_RETURN` | Function object being called. | + | :c:data:`PyTrace_C_RETURN` | Function object being called. | +-------------------------------+----------------------------------------+ - | :c:data:`PyTrace_OPCODE` | Always :c:data:`Py_None`. | + | :c:data:`PyTrace_OPCODE` | Always :c:data:`Py_None`. | +-------------------------------+----------------------------------------+ .. c:var:: int PyTrace_CALL @@ -1891,11 +1891,11 @@ Python-level trace functions in previous versions. .. c:var:: int PyTrace_EXCEPTION 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 + 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 + set within the frame being executed. The effect of this is that as exception propagation causes the Python stack to unwind, the callback is called upon - return to each frame as the exception propagates. Only trace functions receives + return to each frame as the exception propagates. Only trace functions receives these events; they are not needed by the profiler. @@ -1934,17 +1934,17 @@ Python-level trace functions in previous versions. .. c:var:: int PyTrace_OPCODE The value for the *what* parameter to :c:type:`Py_tracefunc` functions (but not - profiling functions) when a new opcode is about to be executed. This event is + profiling functions) when a new opcode is about to be executed. This event is not emitted by default: it must be explicitly requested by setting :attr:`~frame.f_trace_opcodes` to *1* on the frame. .. 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 + 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 the profile function needs to maintain state, using a different value for *obj* - for each thread provides a convenient and thread-safe place to store it. The + for each thread provides a convenient and thread-safe place to store it. The profile function is called for all monitored events except :c:data:`PyTrace_LINE` :c:data:`PyTrace_OPCODE` and :c:data:`PyTrace_EXCEPTION`. @@ -1967,10 +1967,10 @@ Python-level trace functions in previous versions. .. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj) - Set the tracing function to *func*. This is similar to + Set the tracing function to *func*. This is similar to :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number events and per-opcode events, but does not receive any event related to C function - objects being called. Any trace function registered using :c:func:`PyEval_SetTrace` + objects being called. Any trace function registered using :c:func:`PyEval_SetTrace` will not receive :c:data:`PyTrace_C_CALL`, :c:data:`PyTrace_C_EXCEPTION` or :c:data:`PyTrace_C_RETURN` as a value for the *what* parameter. @@ -2025,7 +2025,7 @@ Reference tracing Not that tracer functions **must not** create Python objects inside or otherwise the call will be re-entrant. The tracer also **must not** clear - any existing exception or set an exception. A :term:`thread state` will be active + any existing exception or set an exception. A :term:`thread state` will be active every time the tracer function is called. There must be an :term:`attached thread state` when calling this function. @@ -2091,7 +2091,7 @@ Thread Local Storage Support The Python interpreter provides low-level support for thread-local storage (TLS) which wraps the underlying native TLS implementation to support the -Python-level thread local storage API (:class:`threading.local`). The +Python-level thread local storage API (:class:`threading.local`). The CPython C level APIs are similar to those offered by pthreads and Windows: use a thread key and functions to associate a :c:expr:`void*` value per thread. @@ -2104,7 +2104,7 @@ you need to include :file:`pythread.h` to use thread-local storage. .. note:: None of these API functions handle memory management on behalf of the - :c:expr:`void*` values. You need to allocate and deallocate them yourself. + :c:expr:`void*` values. You need to allocate and deallocate them yourself. If the :c:expr:`void*` values happen to be :c:expr:`PyObject*`, these functions don't do refcount operations on them either. @@ -2114,7 +2114,7 @@ Thread Specific Storage (TSS) API --------------------------------- TSS API is introduced to supersede the use of the existing TLS API within the -CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of +CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of :c:expr:`int` to represent thread keys. .. versionadded:: 3.7 @@ -2126,7 +2126,7 @@ CPython interpreter. This API uses a new type :c:type:`Py_tss_t` instead of This data structure represents the state of a thread key, the definition of which may depend on the underlying TLS implementation, and it has an - internal field representing the key's initialization state. There are no + internal field representing the key's initialization state. There are no public members in this structure. When :ref:`Py_LIMITED_API ` is not defined, static allocation of @@ -2169,7 +2169,7 @@ is not possible due to its implementation being opaque at build time. Methods ~~~~~~~ -The parameter *key* of these functions must not be ``NULL``. Moreover, the +The parameter *key* of these functions must not be ``NULL``. Moreover, the behaviors of :c:func:`PyThread_tss_set` and :c:func:`PyThread_tss_get` are undefined if the given :c:type:`Py_tss_t` has not been initialized by :c:func:`PyThread_tss_create`. @@ -2183,9 +2183,9 @@ undefined if the given :c:type:`Py_tss_t` has not been initialized by .. c:function:: int PyThread_tss_create(Py_tss_t *key) - Return a zero value on successful initialization of a TSS key. The behavior + Return a zero value on successful initialization of a TSS key. The behavior is undefined if the value pointed to by the *key* argument is not - initialized by :c:macro:`Py_tss_NEEDS_INIT`. This function can be called + initialized by :c:macro:`Py_tss_NEEDS_INIT`. This function can be called repeatedly on the same key -- calling it on an already initialized key is a no-op and immediately returns success. @@ -2193,7 +2193,7 @@ undefined if the given :c:type:`Py_tss_t` has not been initialized by .. c:function:: void PyThread_tss_delete(Py_tss_t *key) Destroy a TSS key to forget the values associated with the key across all - threads, and change the key's initialization state to uninitialized. A + threads, and change the key's initialization state to uninitialized. A destroyed key is able to be initialized again by :c:func:`PyThread_tss_create`. This function can be called repeatedly on the same key -- calling it on an already destroyed key is a no-op. @@ -2202,14 +2202,14 @@ undefined if the given :c:type:`Py_tss_t` has not been initialized by .. c:function:: int PyThread_tss_set(Py_tss_t *key, void *value) Return a zero value to indicate successfully associating a :c:expr:`void*` - value with a TSS key in the current thread. Each thread has a distinct + value with a TSS key in the current thread. Each thread has a distinct mapping of the key to a :c:expr:`void*` value. .. c:function:: void* PyThread_tss_get(Py_tss_t *key) Return the :c:expr:`void*` value associated with a TSS key in the current - thread. This returns ``NULL`` if no value is associated with the key in the + thread. This returns ``NULL`` if no value is associated with the key in the current thread. @@ -2224,7 +2224,7 @@ Thread Local Storage (TLS) API .. note:: This version of the API does not support platforms where the native TLS key - is defined in a way that cannot be safely cast to ``int``. On such platforms, + is defined in a way that cannot be safely cast to ``int``. On such platforms, :c:func:`PyThread_create_key` will return immediately with a failure status, and the other TLS functions will all be no-ops on such platforms. @@ -2245,27 +2245,27 @@ The C-API provides a basic mutual exclusion lock. .. c:type:: PyMutex - A mutual exclusion lock. The :c:type:`!PyMutex` should be initialized to - zero to represent the unlocked state. For example:: + A mutual exclusion lock. The :c:type:`!PyMutex` should be initialized to + zero to represent the unlocked state. For example:: PyMutex mutex = {0}; - Instances of :c:type:`!PyMutex` should not be copied or moved. Both the + Instances of :c:type:`!PyMutex` should not be copied or moved. Both the contents and address of a :c:type:`!PyMutex` are meaningful, and it must remain at a fixed, writable location in memory. .. note:: A :c:type:`!PyMutex` currently occupies one byte, but the size should be - considered unstable. The size may change in future Python releases + considered unstable. The size may change in future Python releases without a deprecation period. .. versionadded:: 3.13 .. c:function:: void PyMutex_Lock(PyMutex *m) - Lock mutex *m*. If another thread has already locked it, the calling - thread will block until the mutex is unlocked. While blocked, the thread + Lock mutex *m*. If another thread has already locked it, the calling + thread will block until the mutex is unlocked. While blocked, the thread will temporarily detach the :term:`thread state ` if one exists. .. versionadded:: 3.13 @@ -2295,14 +2295,14 @@ Python Critical Section API --------------------------- The critical section API provides a deadlock avoidance layer on top of -per-object locks for :term:`free-threaded ` CPython. They are +per-object locks for :term:`free-threaded ` CPython. They are intended to replace reliance on the :term:`global interpreter lock`, and are no-ops in versions of Python with the global interpreter lock. Critical sections avoid deadlocks by implicitly suspending active critical sections and releasing the locks during calls to :c:func:`PyEval_SaveThread`. When :c:func:`PyEval_RestoreThread` is called, the most recent critical section -is resumed, and its locks reacquired. This means the critical section API +is resumed, and its locks reacquired. This means the critical section API provides weaker guarantees than traditional locks -- they are useful because their behavior is similar to the :term:`GIL`. @@ -2314,9 +2314,9 @@ change in future Python versions. .. note:: Operations that need to lock two objects at once must use - :c:macro:`Py_BEGIN_CRITICAL_SECTION2`. You *cannot* use nested critical + :c:macro:`Py_BEGIN_CRITICAL_SECTION2`. You *cannot* use nested critical sections to lock more than one object at once, because the inner critical - section may suspend the outer critical sections. This API does not provide + section may suspend the outer critical sections. This API does not provide a way to lock more than two objects at once. Example usage:: @@ -2331,7 +2331,7 @@ Example usage:: } In the above example, :c:macro:`Py_SETREF` calls :c:macro:`Py_DECREF`, which -can call arbitrary code through an object's deallocation function. The critical +can call arbitrary code through an object's deallocation function. The critical section API avoids potential deadlocks due to reentrancy and lock ordering by allowing the runtime to temporarily suspend the critical section if the code triggered by the finalizer blocks and calls :c:func:`PyEval_SaveThread`. @@ -2367,7 +2367,7 @@ code triggered by the finalizer blocks and calls :c:func:`PyEval_SaveThread`. .. c:macro:: Py_BEGIN_CRITICAL_SECTION2(a, b) Acquires the per-objects locks for the objects *a* and *b* and begins a - critical section. The locks are acquired in a consistent order (lowest + critical section. The locks are acquired in a consistent order (lowest address first) to avoid lock ordering deadlocks. In the free-threaded build, this macro expands to:: diff --git a/Doc/c-api/init_config.rst b/Doc/c-api/init_config.rst index 4fd10224262488..be5745030736ae 100644 --- a/Doc/c-api/init_config.rst +++ b/Doc/c-api/init_config.rst @@ -554,7 +554,7 @@ Runtime Python configuration API ================================ At runtime, it's possible to get and set configuration options using -:c:func:`PyConfig_Get` and :c:func:`PyConfig_Set` functions. +:c:func:`PyConfig_Get` and :c:func:`PyConfig_Set` functions. The configuration option *name* parameter must be a non-NULL null-terminated UTF-8 encoded string. See :ref:`Configuration Options `. @@ -802,7 +802,7 @@ PyStatus .. c:function:: void Py_ExitStatusException(PyStatus status) Call ``exit(exitcode)`` if *status* is an exit. Print the error - message and exit with a non-zero exit code if *status* is an error. Must + message and exit with a non-zero exit code if *status* is an error. Must only be called if ``PyStatus_Exception(status)`` is non-zero. .. note:: @@ -1183,10 +1183,10 @@ PyConfig single: argv (in module sys) Set :data:`sys.argv` command line arguments based on - :c:member:`~PyConfig.argv`. These parameters are similar to those passed + :c:member:`~PyConfig.argv`. These parameters are 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 + the executable hosting the Python interpreter. If there isn't a script that will be run, the first entry in :c:member:`~PyConfig.argv` can be an empty string. @@ -1210,7 +1210,7 @@ PyConfig * If :c:member:`argv[0] ` is equal to ``L"-m"`` (``python -m module``), prepend the current working directory. * If running a script (``python script.py``), prepend the script's - directory. If it's a symbolic link, resolve symbolic links. + directory. If it's a symbolic link, resolve symbolic links. * Otherwise (``python -c code`` and ``python``), prepend an empty string, which means the current working directory. @@ -1428,7 +1428,7 @@ PyConfig :term:`Filesystem error handler `: :func:`sys.getfilesystemencodeerrors`. - On Windows: use ``"surrogatepass"`` by default, or ``"replace"`` if + On Windows: use ``"surrogatepass"`` by default, or ``"replace"`` if :c:member:`~PyPreConfig.legacy_windows_fs_encoding` of :c:type:`PyPreConfig` is non-zero. @@ -1521,17 +1521,17 @@ PyConfig .. c:member:: int int_max_str_digits Configures the :ref:`integer string conversion length limitation - `. An initial value of ``-1`` means the value will + `. An initial value of ``-1`` means the value will be taken from the command line or environment or otherwise default to - 4300 (:data:`sys.int_info.default_max_str_digits`). A value of ``0`` - disables the limitation. Values greater than zero but less than 640 + 4300 (:data:`sys.int_info.default_max_str_digits`). A value of ``0`` + disables the limitation. Values greater than zero but less than 640 (:data:`sys.int_info.str_digits_check_threshold`) are unsupported and will produce an error. Configured by the :option:`-X int_max_str_digits <-X>` command line flag or the :envvar:`PYTHONINTMAXSTRDIGITS` environment variable. - Default: ``-1`` in Python mode. 4300 + Default: ``-1`` in Python mode. 4300 (:data:`sys.int_info.default_max_str_digits`) in isolated mode. .. versionadded:: 3.12 diff --git a/Doc/c-api/intro.rst b/Doc/c-api/intro.rst index acce3dc215d157..cb459085634e5d 100644 --- a/Doc/c-api/intro.rst +++ b/Doc/c-api/intro.rst @@ -8,25 +8,25 @@ Introduction ************ The Application Programmer's Interface to Python gives C and C++ programmers -access to the Python interpreter at a variety of levels. The API is equally +access to the Python interpreter at a variety of levels. The API is equally usable from C++, but for brevity it is generally referred to as the Python/C -API. There are two fundamentally different reasons for using the Python/C API. +API. There are two fundamentally different reasons for using the Python/C API. The first reason is to write *extension modules* for specific purposes; these -are C modules that extend the Python interpreter. This is probably the most -common use. The second reason is to use Python as a component in a larger +are C modules that extend the Python interpreter. This is probably the most +common use. The second reason is to use Python as a component in a larger application; this technique is generally referred to as :dfn:`embedding` Python in an application. Writing an extension module is a relatively well-understood process, where a -"cookbook" approach works well. There are several tools that automate the -process to some extent. While people have embedded Python in other +"cookbook" approach works well. There are several tools that automate the +process to some extent. While people have embedded Python in other applications since its early existence, the process of embedding Python is less straightforward than writing an extension. -Many API functions are useful independent of whether you're embedding or -extending Python; moreover, most applications that embed Python will need to -provide a custom extension as well, so it's probably a good idea to become -familiar with writing an extension before attempting to embed Python in a real +Many API functions are useful independent of whether you're embedding or +extending Python; moreover, most applications that embed Python will need to +provide a custom extension as well, so it's probably a good idea to become +familiar with writing an extension before attempting to embed Python in a real application. @@ -44,8 +44,8 @@ Coding standards ================ If you're writing C code for inclusion in CPython, you **must** follow the -guidelines and standards defined in :PEP:`7`. These guidelines apply -regardless of the version of Python you are contributing to. Following these +guidelines and standards defined in :PEP:`7`. These guidelines apply +regardless of the version of Python you are contributing to. Following these conventions is not necessary for your own third party extension modules, unless you eventually expect to contribute them to Python. @@ -72,10 +72,10 @@ This implies inclusion of the following standard headers: ````, headers are included. It is recommended to always define ``PY_SSIZE_T_CLEAN`` before including - ``Python.h``. See :ref:`arg-parsing` for a description of this macro. + ``Python.h``. See :ref:`arg-parsing` for a description of this macro. All user visible names defined by Python.h (except those defined by the included -standard headers) have one of the prefixes ``Py`` or ``_Py``. Names beginning +standard headers) have one of the prefixes ``Py`` or ``_Py``. Names beginning with ``_Py`` are for internal use by the Python implementation and should not be used by extension writers. Structure member names do not have a reserved prefix. @@ -86,17 +86,17 @@ used by extension writers. Structure member names do not have a reserved prefix. future Python versions, which may define additional names beginning with one of these prefixes. -The header files are typically installed with Python. On Unix, these are +The header files are typically installed with Python. On Unix, these are located in the directories :file:`{prefix}/include/pythonversion/` and :file:`{exec_prefix}/include/pythonversion/`, where :option:`prefix <--prefix>` and :option:`exec_prefix <--exec-prefix>` are defined by the corresponding parameters to Python's :program:`configure` script and *version* is -``'%d.%d' % sys.version_info[:2]``. On Windows, the headers are installed +``'%d.%d' % sys.version_info[:2]``. On Windows, the headers are installed in :file:`{prefix}/include`, where ``prefix`` is the installation directory specified to the installer. To include the headers, place both directories (if different) on your compiler's -search path for includes. Do *not* place the parent directories on the search +search path for includes. Do *not* place the parent directories on the search path and then use ``#include ``; this will break on multi-platform builds since the platform independent headers under :option:`prefix <--prefix>` include the platform specific headers from @@ -110,10 +110,10 @@ there is no need to do anything special to use the API from C++. Useful macros ============= -Several useful macros are defined in the Python header files. Many are +Several useful macros are defined in the Python header files. Many are defined closer to where they are useful (for example, :c:macro:`Py_RETURN_NONE`, :c:macro:`PyMODINIT_FUNC`). -Others of a more general utility are defined here. This is not necessarily a +Others of a more general utility are defined here. This is not necessarily a complete listing. @@ -148,11 +148,11 @@ complete listing. .. c:macro:: Py_CHARMASK(c) Argument must be a character or an integer in the range [-128, 127] or [0, - 255]. This macro returns ``c`` cast to an ``unsigned char``. + 255]. This macro returns ``c`` cast to an ``unsigned char``. .. c:macro:: Py_DEPRECATED(version) - Use this for deprecated declarations. The macro must be placed before the + Use this for deprecated declarations. The macro must be placed before the symbol name. Example:: @@ -199,7 +199,7 @@ complete listing. .. c:macro:: Py_STRINGIFY(x) - Convert ``x`` to a C string. E.g. ``Py_STRINGIFY(123)`` returns + Convert ``x`` to a C string. E.g. ``Py_STRINGIFY(123)`` returns ``"123"``. .. versionadded:: 3.4 @@ -208,20 +208,20 @@ complete listing. Use this when you have a code path that cannot be reached by design. For example, in the ``default:`` clause in a ``switch`` statement for which - all possible values are covered in ``case`` statements. Use this in places + all possible values are covered in ``case`` statements. Use this in places where you might be tempted to put an ``assert(0)`` or ``abort()`` call. In release mode, the macro helps the compiler to optimize the code, and - avoids a warning about unreachable code. For example, the macro is + avoids a warning about unreachable code. For example, the macro is implemented with ``__builtin_unreachable()`` on GCC in release mode. A use for ``Py_UNREACHABLE()`` is following a call a function that never returns but that is not declared :c:macro:`_Py_NO_RETURN`. If a code path is very unlikely code but can be reached under exceptional - case, this macro must not be used. For example, under low memory condition - or if a system call returns a value out of the expected range. In this - case, it's better to report the error to the caller. If the error cannot + case, this macro must not be used. For example, under low memory condition + or if a system call returns a value out of the expected range. In this + case, it's better to report the error to the caller. If the error cannot be reported to caller, :c:func:`Py_FatalError` can be used. .. versionadded:: 3.7 @@ -276,20 +276,20 @@ Objects, Types and Reference Counts .. index:: pair: object; type Most Python/C API functions have one or more arguments as well as a return value -of type :c:expr:`PyObject*`. This type is a pointer to an opaque data type -representing an arbitrary Python object. Since all Python object types are +of type :c:expr:`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 +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 -:c:type:`PyObject`, only pointer variables of type :c:expr:`PyObject*` can be -declared. The sole exception are the type objects; since these must never be +:c:type:`PyObject`, only pointer variables of type :c:expr:`PyObject*` can be +declared. The sole exception are the type objects; since these must never be 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 +:dfn:`reference count`. An object's type determines what kind of object it is (e.g., an integer, a list, or a user-defined function; there are many more as -explained in :ref:`types`). For each of the well-known types there is a macro +explained in :ref:`types`). For each of the well-known types there is a macro to check whether an object is of that type; for instance, ``PyList_Check(a)`` is true if (and only if) the object pointed to by *a* is a Python list. @@ -299,7 +299,7 @@ true if (and only if) the object pointed to by *a* is a Python list. Reference Counts ---------------- -The reference count is important because today's computers have a finite +The reference count is important because today's computers have a finite (and often severely limited) memory size; it counts how many different places there are that have a :term:`strong reference` to an object. Such a place could be another object, or a global (or static) C variable, @@ -308,7 +308,7 @@ When the last :term:`strong reference` to an object is released (i.e. its reference count becomes zero), the object is deallocated. If it contains references to other objects, those references are released. Those other objects may be deallocated in turn, if there are no more -references to them, and so on. (There's an obvious problem with +references to them, and so on. (There's an obvious problem with objects that reference each other here; for now, the solution is "don't do that.") @@ -316,47 +316,47 @@ is "don't do that.") single: Py_INCREF (C function) single: Py_DECREF (C function) -Reference counts are always manipulated explicitly. The normal way is +Reference counts are always manipulated explicitly. The normal way is to use the macro :c:func:`Py_INCREF` to take a new reference to an object (i.e. increment its reference count by one), and :c:func:`Py_DECREF` to release that reference (i.e. decrement the -reference count by one). The :c:func:`Py_DECREF` macro +reference count 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 -structure. The type-specific deallocator takes care of releasing references +called. The deallocator is a function pointer contained in the object's type +structure. The type-specific deallocator takes care of releasing references for other objects contained in the object if this is a compound object type, such as a list, as well as performing any additional finalization -that's needed. There's no chance that the reference count can overflow; at +that's needed. There's no chance that the reference count can overflow; at least as many bits are used to hold the reference count as there are distinct memory locations in virtual memory (assuming ``sizeof(Py_ssize_t) >= sizeof(void*)``). Thus, the reference count increment is a simple operation. It is not necessary to hold a :term:`strong reference` (i.e. increment the reference count) for every local variable that contains a pointer -to an object. In theory, the object's -reference count goes up by one when the variable is made to point to it and it -goes down by one when the variable goes out of scope. However, these two -cancel each other out, so at the end the reference count hasn't changed. The -only real reason to use the reference count is to prevent the object from being -deallocated as long as our variable is pointing to it. If we know that there -is at least one other reference to the object that lives at least as long as +to an object. In theory, the object's +reference count goes up by one when the variable is made to point to it and it +goes down by one when the variable goes out of scope. However, these two +cancel each other out, so at the end the reference count hasn't changed. The +only real reason to use the reference count is to prevent the object from being +deallocated as long as our variable is pointing to it. If we know that there +is at least one other reference to the object that lives at least as long as our variable, there is no need to take a new :term:`strong reference` (i.e. increment the reference count) temporarily. -An important situation where this arises is in objects that are passed as -arguments to C functions in an extension module that are called from Python; -the call mechanism guarantees to hold a reference to every argument for the +An important situation where this arises is in objects that are passed as +arguments to C functions in an extension module that are called from Python; +the call mechanism guarantees to hold a reference to every argument for the duration of the call. However, a common pitfall is to extract an object from a list and hold on to it -for a while without taking a new reference. Some other operation might +for a while without taking a new reference. Some other operation might conceivably remove the object from the list, releasing that reference, and possibly 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 :c:func:`Py_DECREF`, so almost any operation is potentially dangerous. -A safe approach is to always use the generic operations (functions whose name +A safe approach is to always use the generic operations (functions whose name begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``). These operations always create a new :term:`strong reference` (i.e. increment the reference count) of the object they return. @@ -369,22 +369,22 @@ they are done with the result; this soon becomes second nature. Reference Count Details ^^^^^^^^^^^^^^^^^^^^^^^ -The reference count behavior of functions in the Python/C API is best explained -in terms of *ownership of references*. Ownership pertains to references, never -to objects (objects are not owned: they are always shared). "Owning a +The reference count behavior of functions in the Python/C API is best explained +in terms of *ownership of references*. Ownership pertains to references, never +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 +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 releasing 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, +caller is said to receive a *new* reference. When no ownership is transferred, the caller is said to *borrow* the reference. Nothing needs to be done for a :term:`borrowed reference`. -Conversely, when a calling function passes in a reference to an object, there -are two possibilities: the function *steals* a reference to the object, or it -does not. *Stealing a reference* means that when you pass a reference to a +Conversely, when a calling function passes in a reference to an object, there +are two possibilities: the function *steals* a reference to the object, or it +does not. *Stealing a reference* means that when you pass a reference to a function, that function assumes that it now owns that reference, and you are not responsible for it any longer. @@ -393,8 +393,8 @@ responsible for it any longer. single: PyTuple_SetItem (C function) Few functions steal references; the two notable exceptions are -: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 +: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 create the tuple ``(1, 2, "three")`` could look like this (forgetting about @@ -408,20 +408,20 @@ error handling for the moment; a better way to code this is shown below):: PyTuple_SetItem(t, 2, PyUnicode_FromString("three")); Here, :c:func:`PyLong_FromLong` returns a new reference which is immediately -stolen by :c:func:`PyTuple_SetItem`. When you want to keep using an object +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, :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 +since tuples are an immutable data type. You should only use :c:func:`PyTuple_SetItem` for tuples that you are creating yourself. 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, :c:func:`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):: @@ -433,9 +433,9 @@ For example, the above two blocks of code could be replaced by the following 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 references +the function you are writing. In that case, their behaviour regarding references is much saner, since you don't have to take a new reference just so you -can give that reference away ("have it be stolen"). For example, this function +can give that reference away ("have it be stolen"). For example, this function sets all items of a list (actually, any mutable sequence) to a given item:: int @@ -461,19 +461,19 @@ sets all items of a list (actually, any mutable sequence) to a given item:: .. index:: single: set_all() -The situation is slightly different for function return values. While passing -a reference to most functions does not change your ownership responsibilities -for that reference, many functions that return a reference to an object give +The situation is slightly different for function return values. While passing +a reference to most functions does not change your ownership responsibilities +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 :c:func:`PyObject_GetItem` and :c:func:`PySequence_GetItem`, +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 :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 +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 :c:func:`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 :c:func:`PySequence_GetItem` (which happens to take exactly the same arguments), you do own a reference to the returned object. @@ -483,7 +483,7 @@ arguments), you do own a reference to the returned object. single: PySequence_GetItem (C function) 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 :c:func:`PyList_GetItem`, and once +the items in a list of integers; once using :c:func:`PyList_GetItem`, and once using :c:func:`PySequence_GetItem`. :: long @@ -548,12 +548,12 @@ using :c:func:`PySequence_GetItem`. :: Types ----- -There are few other data types that play a significant role in the Python/C -API; most are simple C types such as :c:expr:`int`, :c:expr:`long`, -:c:expr:`double` and :c:expr:`char*`. A few structure types are used to -describe static tables used to list the functions exported by a module or the +There are few other data types that play a significant role in the Python/C +API; most are simple C types such as :c:expr:`int`, :c:expr:`long`, +:c:expr:`double` and :c:expr:`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 +of a complex number. These will be discussed together with the functions that use them. .. c:type:: Py_ssize_t @@ -569,75 +569,75 @@ use them. Exceptions ========== -The Python programmer only needs to deal with exceptions if specific error -handling is required; unhandled exceptions are automatically propagated to the +The Python programmer only needs to deal with exceptions if specific error +handling is required; unhandled exceptions are automatically propagated to the caller, then to the caller's caller, and so on, until they reach the top-level -interpreter, where they are reported to the user accompanied by a stack +interpreter, where they are reported to the user accompanied by a stack traceback. .. index:: single: PyErr_Occurred (C function) -For C programmers, however, error checking always has to be explicit. All +For C programmers, however, error checking always has to be explicit. All functions in the Python/C API can raise exceptions, unless an explicit claim is -made otherwise in a function's documentation. In general, when a function +made otherwise in a function's documentation. In general, when a function encounters an error, it sets an exception, discards any object references that -it owns, and returns an error indicator. If not documented otherwise, this +it owns, and returns an error indicator. If not documented otherwise, this 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 +error. Very few functions return no explicit error indicator or have an ambiguous return value, and require explicit testing for errors with -:c:func:`PyErr_Occurred`. These exceptions are always explicitly documented. +:c:func:`PyErr_Occurred`. These exceptions are always explicitly documented. .. index:: single: PyErr_SetString (C function) single: PyErr_Clear (C function) -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 +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 :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: +``NULL`` otherwise. There are a number of functions to set the exception state: :c:func:`PyErr_SetString` is the most common (though not the most general) function to set the exception state, and :c:func:`PyErr_Clear` clears the exception state. -The full exception state consists of three objects (all of which can be -``NULL``): the exception type, the corresponding exception value, and the -traceback. These have the same meanings as the Python result of +The full exception state consists of three objects (all of which can be +``NULL``): the exception type, the corresponding exception value, and the +traceback. These have the same meanings as the Python result of ``sys.exc_info()``; however, they are not the same: the Python objects represent -the last exception being handled by a Python :keyword:`try` ... +the last exception being handled by a Python :keyword:`try` ... :keyword:`except` statement, while the C level exception state only exists while an exception is being passed on between C functions until it reaches the Python -bytecode interpreter's main loop, which takes care of transferring it to +bytecode interpreter's main loop, which takes care of transferring it to ``sys.exc_info()`` and friends. .. index:: single: exc_info (in module sys) Note that starting with Python 1.5, the preferred, thread-safe way to access the exception state from Python code is to call the function :func:`sys.exc_info`, -which returns the per-thread exception state for Python code. Also, the +which returns the per-thread exception state for Python code. Also, the semantics of both ways to access the exception state have changed so that a function which catches an exception will save and restore its thread's exception -state so as to preserve the exception state of its caller. This prevents common +state so as to preserve the exception state of its caller. This prevents common bugs in exception handling code caused by an innocent-looking function overwriting the exception being handled; it also reduces the often unwanted lifetime extension for objects that are referenced by the stack frames in the traceback. -As a general principle, a function that calls another function to perform some -task should check whether the called function raised an exception, and if so, -pass the exception state on to its caller. It should discard any object -references that it owns, and return an error indicator, but it should *not* set +As a general principle, a function that calls another function to perform some +task should check whether the called function raised an exception, and if so, +pass the exception state on to its caller. It should discard any object +references that it owns, and return an error indicator, but it should *not* set another exception --- that would overwrite the exception that was just raised, 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 -:c:func:`!sum_sequence` example above. It so happens that this 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 +:c:func:`!sum_sequence` example above. It so happens that this 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:: def incr_item(dict, key): @@ -701,12 +701,12 @@ Here is the corresponding C code, in all its glory:: single: PyErr_Clear (C function) single: Py_XDECREF (C function) -This example represents an endorsed use of the ``goto`` statement in C! +This example represents an endorsed use of the ``goto`` statement in C! 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 +``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 the final call made is successful. @@ -719,7 +719,7 @@ Embedding Python The one important task that only embedders (as opposed to extension writers) of the Python interpreter have to worry about is the initialization, and possibly -the finalization, of the Python interpreter. Most functionality of the +the finalization, of the Python interpreter. Most functionality of the interpreter can only be used after the interpreter has been initialized. .. index:: @@ -732,10 +732,10 @@ interpreter can only be used after the interpreter has been initialized. The basic initialization function is :c:func:`Py_Initialize`. This initializes the table of loaded modules, and creates the fundamental modules -:mod:`builtins`, :mod:`__main__`, and :mod:`sys`. It also +:mod:`builtins`, :mod:`__main__`, and :mod:`sys`. It also initializes the module search path (``sys.path``). -:c:func:`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, setting :c:member:`PyConfig.argv` and :c:member:`PyConfig.parse_argv` must be set: see :ref:`Python Initialization Configuration `. @@ -744,16 +744,16 @@ On most systems (in particular, on Unix and Windows, although the details are 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 +relative to the Python interpreter executable. In particular, it looks for a directory named :file:`lib/python{X.Y}` relative to the parent directory where the executable named :file:`python` is found on the shell command search path (the environment variable :envvar:`PATH`). For instance, if the Python executable is found in :file:`/usr/local/bin/python`, it will assume that the libraries are in -:file:`/usr/local/lib/python{X.Y}`. (In fact, this particular path is also +:file:`/usr/local/lib/python{X.Y}`. (In fact, this particular path is also the "fallback" location, used when no executable file named :file:`python` is -found along :envvar:`PATH`.) The user can override this behavior by setting the +found along :envvar:`PATH`.) The user can override this behavior by setting the environment variable :envvar:`PYTHONHOME`, or insert additional directories in front of the standard path by setting :envvar:`PYTHONPATH`. @@ -765,12 +765,12 @@ inserted in front of the standard path. .. index:: single: Py_IsInitialized (C function) -Sometimes, it is desirable to "uninitialize" Python. For instance, the +Sometimes, it is desirable to "uninitialize" Python. For instance, the application may want to start over (make another call to -: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 :c:func:`Py_FinalizeEx`. The function :c:func:`Py_IsInitialized` returns -true if Python is currently in the initialized state. More information about +: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 :c:func:`Py_FinalizeEx`. 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 :c:func:`Py_FinalizeEx` does *not* free all memory allocated by the Python interpreter, e.g. memory allocated by extension modules currently cannot be released. @@ -782,13 +782,13 @@ Debugging Builds ================ Python can be built with several macros to enable extra checks of the -interpreter and extension modules. These checks tend to add a large amount of +interpreter and extension modules. These checks tend to add a large amount of overhead to the runtime so they are not enabled by default. A full list of the various types of debugging builds is in the file :file:`Misc/SpecialBuilds.txt` in the Python source distribution. Builds are available that support tracing of reference counts, debugging the memory -allocator, or low-level profiling of the main interpreter loop. Only the most +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. .. c:macro:: Py_DEBUG @@ -810,8 +810,8 @@ performed. See :ref:`Python Debug Build ` for more details. Defining :c:macro:`Py_TRACE_REFS` enables reference tracing (see the :option:`configure --with-trace-refs option <--with-trace-refs>`). When defined, a circular doubly linked list of active objects is maintained by adding two extra -fields to every :c:type:`PyObject`. Total allocations are tracked as well. Upon -exit, all existing references are printed. (In interactive mode this happens +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.) Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution diff --git a/Doc/c-api/iter.rst b/Doc/c-api/iter.rst index bf9df62c6f1706..d3627cf8925961 100644 --- a/Doc/c-api/iter.rst +++ b/Doc/c-api/iter.rst @@ -16,7 +16,7 @@ There are two functions specifically for working with iterators. .. c:function:: int PyAIter_Check(PyObject *o) Return non-zero if the object *o* provides the :class:`AsyncIterator` - protocol, and ``0`` otherwise. This function always succeeds. + protocol, and ``0`` otherwise. This function always succeeds. .. versionadded:: 3.10 @@ -35,7 +35,7 @@ There are two functions specifically for working with iterators. which is retained for backwards compatibility. Prefer :c:func:`PyIter_NextItem`. - Return the next value from the iterator *o*. The object must be an iterator + Return the next value from the iterator *o*. The object must be an iterator according to :c:func:`PyIter_Check` (it is up to the caller to check this). If there are no remaining values, returns ``NULL`` with no exception set. If an error occurs while retrieving the item, returns ``NULL`` and passes diff --git a/Doc/c-api/iterator.rst b/Doc/c-api/iterator.rst index 6b7ba8c9979163..aaa55b05fd4eb8 100644 --- a/Doc/c-api/iterator.rst +++ b/Doc/c-api/iterator.rst @@ -5,9 +5,9 @@ Iterator Objects ---------------- -Python provides two general-purpose iterator objects. The first, a sequence +Python provides two general-purpose iterator objects. The first, a sequence iterator, works with an arbitrary sequence supporting the :meth:`~object.__getitem__` -method. The second works with a callable object and a sentinel value, calling +method. The second works with a callable object and a sentinel value, calling the callable for each item in the sequence, and ending the iteration when the sentinel value is returned. @@ -21,13 +21,13 @@ sentinel value is returned. .. c:function:: int PySeqIter_Check(PyObject *op) - Return true if the type of *op* is :c:data:`PySeqIter_Type`. This function + Return true if the type of *op* is :c:data:`PySeqIter_Type`. This function always succeeds. .. c:function:: PyObject* PySeqIter_New(PyObject *seq) - Return an iterator that works with a general sequence object, *seq*. The + Return an iterator that works with a general sequence object, *seq*. The iteration ends when the sequence raises :exc:`IndexError` for the subscripting operation. @@ -40,13 +40,13 @@ sentinel value is returned. .. c:function:: int PyCallIter_Check(PyObject *op) - Return true if the type of *op* is :c:data:`PyCallIter_Type`. This + Return true if the type of *op* is :c:data:`PyCallIter_Type`. This function always succeeds. .. c:function:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel) - Return a new iterator. The first parameter, *callable*, can be any Python + 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 - return the next item in the iteration. When *callable* returns a value equal to + return the next item in the iteration. When *callable* returns a value equal to *sentinel*, the iteration will be terminated. diff --git a/Doc/c-api/lifecycle.rst b/Doc/c-api/lifecycle.rst index 5a170862a26f44..5ad9a33d50c02d 100644 --- a/Doc/c-api/lifecycle.rst +++ b/Doc/c-api/lifecycle.rst @@ -6,7 +6,7 @@ Object Life Cycle ================= This section explains how a type's slots relate to each other throughout the -life of an object. It is not intended to be a complete canonical reference for +life of an object. It is not intended to be a complete canonical reference for the slots; instead, refer to the slot-specific documentation in :ref:`type-structs` for details about a particular slot. @@ -15,7 +15,7 @@ Life Events ----------- The figure below illustrates the order of events that can occur throughout an -object's life. An arrow from *A* to *B* indicates that event *B* can occur +object's life. An arrow from *A* to *B* indicates that event *B* can occur after event *A* has occurred, with the arrow's label indicating the condition that must be true for *B* to occur after *A*. @@ -55,14 +55,14 @@ that must be true for *B* to occur after *A*. .. image:: lifecycle.dot.svg :align: center :class: invert-in-dark-mode - :alt: Diagram showing events in an object's life. Explained in detail below. + :alt: Diagram showing events in an object's life. Explained in detail below. .. only:: latex .. image:: lifecycle.dot.pdf :align: center :class: invert-in-dark-mode - :alt: Diagram showing events in an object's life. Explained in detail below. + :alt: Diagram showing events in an object's life. Explained in detail below. .. container:: :name: life-events-graph-description @@ -85,13 +85,13 @@ that must be true for *B* to occur after *A*. #. If an object is not marked as *finalized*, it might be finalized by marking it as *finalized* and calling its - :c:member:`~PyTypeObject.tp_finalize` function. Python does + :c:member:`~PyTypeObject.tp_finalize` function. Python does *not* finalize an object when the last reference to it is deleted; use :c:func:`PyObject_CallFinalizerFromDealloc` to ensure that :c:member:`~PyTypeObject.tp_finalize` is always called. #. If the object is marked as finalized, :c:member:`~PyTypeObject.tp_clear` might be called by the garbage collector - to clear references held by the object. It is *not* called when the + to clear references held by the object. It is *not* called when the object's reference count reaches zero. #. :c:member:`~PyTypeObject.tp_dealloc` is called to destroy the object. To avoid code duplication, :c:member:`~PyTypeObject.tp_dealloc` typically @@ -103,13 +103,13 @@ that must be true for *B* to occur after *A*. appropriate for the type) to deallocate the memory. * The :c:member:`~PyTypeObject.tp_finalize` function is permitted to add a - reference to the object if desired. If it does, the object is - *resurrected*, preventing its pending destruction. (Only + reference to the object if desired. If it does, the object is + *resurrected*, preventing its pending destruction. (Only :c:member:`!tp_finalize` is allowed to resurrect an object; :c:member:`~PyTypeObject.tp_clear` and :c:member:`~PyTypeObject.tp_dealloc` cannot without calling into - :c:member:`!tp_finalize`.) Resurrecting an object may - or may not cause the object's *finalized* mark to be removed. Currently, + :c:member:`!tp_finalize`.) Resurrecting an object may + or may not cause the object's *finalized* mark to be removed. Currently, Python does not remove the *finalized* mark from a resurrected object if it supports garbage collection (i.e., the :c:macro:`Py_TPFLAGS_HAVE_GC` flag is set) but does remove the mark if the object does not support @@ -118,16 +118,16 @@ that must be true for *B* to occur after *A*. * :c:member:`~PyTypeObject.tp_dealloc` can optionally call :c:member:`~PyTypeObject.tp_finalize` via :c:func:`PyObject_CallFinalizerFromDealloc` if it wishes to reuse that - code to help with object destruction. This is recommended because it + code to help with object destruction. This is recommended because it guarantees that :c:member:`!tp_finalize` is always called before - destruction. See the :c:member:`~PyTypeObject.tp_dealloc` documentation + destruction. See the :c:member:`~PyTypeObject.tp_dealloc` documentation for example code. * If the object is a member of a :term:`cyclic isolate` and either :c:member:`~PyTypeObject.tp_clear` fails to break the reference cycle or the cyclic isolate is not detected (perhaps :func:`gc.disable` was called, or the :c:macro:`Py_TPFLAGS_HAVE_GC` flag was erroneously omitted in one of the involved types), the objects remain indefinitely uncollectable - (they "leak"). See :data:`gc.garbage`. + (they "leak"). See :data:`gc.garbage`. If the object is marked as supporting garbage collection (the :c:macro:`Py_TPFLAGS_HAVE_GC` flag is set in @@ -142,7 +142,7 @@ that must be true for *B* to occur after *A*. This repeats until the cyclic isolate doesn't exist or all of the objects have been finalized. * :c:member:`~PyTypeObject.tp_finalize` is permitted to resurrect the object - by adding a reference from outside the :term:`cyclic isolate`. The new + by adding a reference from outside the :term:`cyclic isolate`. The new reference causes the group of objects to no longer form a cyclic isolate (the reference cycle may still exist, but if it does the objects are no longer isolated). @@ -150,7 +150,7 @@ that must be true for *B* to occur after *A*. the objects in the group have already been marked as *finalized*, the garbage collector clears one or more of the uncleared objects in the group (possibly concurrently) by calling each's - :c:member:`~PyTypeObject.tp_clear` function. This repeats as long as the + :c:member:`~PyTypeObject.tp_clear` function. This repeats as long as the cyclic isolate still exists and not all of the objects have been cleared. @@ -158,26 +158,26 @@ Cyclic Isolate Destruction -------------------------- Listed below are the stages of life of a hypothetical :term:`cyclic isolate` -that continues to exist after each member object is finalized or cleared. It +that continues to exist after each member object is finalized or cleared. It is a memory leak if a cyclic isolate progresses through all of these stages; it should -vanish once all objects are cleared, if not sooner. A cyclic isolate can +vanish once all objects are cleared, if not sooner. A cyclic isolate can vanish either because the reference cycle is broken or because the objects are no longer isolated due to finalizer resurrection (see :c:member:`~PyTypeObject.tp_finalize`). 0. **Reachable** (not yet a cyclic isolate): All objects are in their normal, - reachable state. A reference cycle could exist, but an external reference + reachable state. A reference cycle could exist, but an external reference means the objects are not yet isolated. #. **Unreachable but consistent:** The final reference from outside the cyclic group of objects has been removed, causing the objects to become isolated - (thus a cyclic isolate is born). None of the group's objects have been - finalized or cleared yet. The cyclic isolate remains at this stage until + (thus a cyclic isolate is born). None of the group's objects have been + finalized or cleared yet. The cyclic isolate remains at this stage until some future run of the garbage collector (not necessarily the next run because the next run might not scan every object). #. **Mix of finalized and not finalized:** Objects in a cyclic isolate are finalized one at a time, which means that there is a period of time when the cyclic isolate is composed of a mix of finalized and non-finalized objects. - Finalization order is unspecified, so it can appear random. A finalized + Finalization order is unspecified, so it can appear random. A finalized object must behave in a sane manner when non-finalized objects interact with it, and a non-finalized object must be able to tolerate the finalization of an arbitrary subset of its referents. @@ -185,27 +185,27 @@ no longer isolated due to finalizer resurrection (see of them are cleared. #. **Mix of finalized and cleared:** The objects can be cleared serially or concurrently (but with the :term:`GIL` held); either way, some will finish - before others. A finalized object must be able to tolerate the clearing of - a subset of its referents. :pep:`442` calls this stage "cyclic trash". + before others. A finalized object must be able to tolerate the clearing of + a subset of its referents. :pep:`442` calls this stage "cyclic trash". #. **Leaked:** If a cyclic isolate still exists after all objects in the group have been finalized and cleared, then the objects remain indefinitely - uncollectable (see :data:`gc.garbage`). It is a bug if a cyclic isolate + uncollectable (see :data:`gc.garbage`). It is a bug if a cyclic isolate reaches this stage---it means the :c:member:`~PyTypeObject.tp_clear` methods of the participating objects have failed to break the reference cycle as required. If :c:member:`~PyTypeObject.tp_clear` did not exist, then Python would have no -way to safely break a reference cycle. Simply destroying an object in a cyclic +way to safely break a reference cycle. Simply destroying an object in a cyclic isolate would result in a dangling pointer, triggering undefined behavior when -an object referencing the destroyed object is itself destroyed. The clearing +an object referencing the destroyed object is itself destroyed. The clearing step makes object destruction a two-phase process: first :c:member:`~PyTypeObject.tp_clear` is called to partially destroy the objects enough to detangle them from each other, then :c:member:`~PyTypeObject.tp_dealloc` is called to complete the destruction. -Unlike clearing, finalization is not a phase of destruction. A finalized +Unlike clearing, finalization is not a phase of destruction. A finalized object must still behave properly by continuing to fulfill its design -contracts. An object's finalizer is allowed to execute arbitrary Python code, +contracts. An object's finalizer is allowed to execute arbitrary Python code, and is even allowed to prevent the impending destruction by adding a reference. The finalizer is only related to destruction by call order---if it runs, it runs before destruction, which starts with :c:member:`~PyTypeObject.tp_clear` (if @@ -213,10 +213,10 @@ called) and concludes with :c:member:`~PyTypeObject.tp_dealloc`. The finalization step is not necessary to safely reclaim the objects in a cyclic isolate, but its existence makes it easier to design types that behave -in a sane manner when objects are cleared. Clearing an object might +in a sane manner when objects are cleared. Clearing an object might necessarily leave it in a broken, partially destroyed state---it might be unsafe to call any of the cleared object's methods or access any of its -attributes. With finalization, only finalized objects can possibly interact +attributes. With finalization, only finalized objects can possibly interact with cleared objects; non-finalized objects are guaranteed to interact with only non-cleared (but potentially finalized) objects. @@ -231,11 +231,11 @@ To summarize the possible interactions: Without any reference cycles, an object can be simply destroyed once its last reference is deleted; the finalization and clearing steps are not necessary to -safely reclaim unused objects. However, it can be useful to automatically call +safely reclaim unused objects. However, it can be useful to automatically call :c:member:`~PyTypeObject.tp_finalize` and :c:member:`~PyTypeObject.tp_clear` before destruction anyway because type design is simplified when all objects always experience the same series of events regardless of whether they -participated in a cyclic isolate. Python currently only calls +participated in a cyclic isolate. Python currently only calls :c:member:`~PyTypeObject.tp_finalize` and :c:member:`~PyTypeObject.tp_clear` as needed to destroy a cyclic isolate; this may change in a future version. @@ -261,9 +261,9 @@ To allocate and free memory, see :ref:`allocating-objects`. Same as :c:func:`PyObject_CallFinalizer` but meant to be called at the beginning of the object's destructor (:c:member:`~PyTypeObject.tp_dealloc`). - There must not be any references to the object. If the object's finalizer + There must not be any references to the object. If the object's finalizer resurrects the object, this function returns -1; no further destruction - should happen. Otherwise, this function returns 0 and destruction can + should happen. Otherwise, this function returns 0 and destruction can continue normally. .. seealso:: diff --git a/Doc/c-api/list.rst b/Doc/c-api/list.rst index 758415a76e5cb4..debeb60ddfb3a7 100644 --- a/Doc/c-api/list.rst +++ b/Doc/c-api/list.rst @@ -22,13 +22,13 @@ List Objects .. 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. This function always succeeds. + type. This function always succeeds. .. 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. This function always succeeds. + the list type. This function always succeeds. .. c:function:: PyObject* PyList_New(Py_ssize_t len) @@ -61,9 +61,9 @@ List Objects .. c:function:: PyObject* PyList_GetItemRef(PyObject *list, Py_ssize_t index) - Return the object at position *index* in the list pointed to by *list*. The + Return the object at position *index* in the list pointed to by *list*. The position must be non-negative; indexing from the end of the list is not - supported. If *index* is out of bounds (:code:`<0 or >=len(list)`), + supported. If *index* is out of bounds (:code:`<0 or >=len(list)`), return ``NULL`` and set an :exc:`IndexError` exception. .. versionadded:: 3.13 @@ -82,7 +82,7 @@ List Objects .. 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. + Set the item at index *index* in list to *item*. Return ``0`` on success. If *index* is out of bounds, return ``-1`` and set an :exc:`IndexError` exception. @@ -111,7 +111,7 @@ List Objects .. 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 + 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)``. @@ -119,29 +119,29 @@ List Objects .. 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 + successful; return ``-1`` and set an exception if unsuccessful. Analogous to ``list.append(item)``. .. 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 - to ``list[low:high]``. Indexing from the end of the list is not supported. + and *high*. Return ``NULL`` and set an exception if unsuccessful. Analogous + to ``list[low:high]``. Indexing from the end of the list is not supported. .. 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 + *itemlist*. Analogous to ``list[low:high] = itemlist``. The *itemlist* may be ``NULL``, indicating the assignment of an empty list (slice deletion). - Return ``0`` on success, ``-1`` on failure. Indexing from the end of the + Return ``0`` on success, ``-1`` on failure. Indexing from the end of the list is not supported. .. c:function:: int PyList_Extend(PyObject *list, PyObject *iterable) - Extend *list* with the contents of *iterable*. This is the same as + Extend *list* with the contents of *iterable*. This is the same as ``PyList_SetSlice(list, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, iterable)`` and analogous to ``list.extend(iterable)`` or ``list += iterable``. @@ -153,26 +153,26 @@ List Objects .. c:function:: int PyList_Clear(PyObject *list) - Remove all items from *list*. This is the same as + Remove all items from *list*. This is the same as ``PyList_SetSlice(list, 0, PY_SSIZE_T_MAX, NULL)`` and analogous to ``list.clear()`` or ``del list[:]``. Raise an exception and return ``-1`` if *list* is not a :class:`list` - object. Return 0 on success. + object. Return 0 on success. .. versionadded:: 3.13 .. 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()``. + Sort the items of *list* in place. Return ``0`` on success, ``-1`` on + failure. This is equivalent to ``list.sort()``. .. 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()``. + Reverse the items of *list* in place. Return ``0`` on success, ``-1`` on + failure. This is the equivalent of ``list.reverse()``. .. c:function:: PyObject* PyList_AsTuple(PyObject *list) diff --git a/Doc/c-api/long.rst b/Doc/c-api/long.rst index 2d0bda76697e81..8fb136e6518e10 100644 --- a/Doc/c-api/long.rst +++ b/Doc/c-api/long.rst @@ -11,7 +11,7 @@ Integer Objects All integers are implemented as "long" integer objects of arbitrary size. On error, most ``PyLong_As*`` APIs return ``(return type)-1`` which cannot be -distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. +distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:type:: PyLongObject @@ -27,13 +27,13 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: int PyLong_Check(PyObject *p) Return true if its argument is a :c:type:`PyLongObject` or a subtype of - :c:type:`PyLongObject`. This function always succeeds. + :c:type:`PyLongObject`. This function always succeeds. .. c:function:: int PyLong_CheckExact(PyObject *p) Return true if its argument is a :c:type:`PyLongObject`, but not a subtype of - :c:type:`PyLongObject`. This function always succeeds. + :c:type:`PyLongObject`. This function always succeeds. .. c:function:: PyObject* PyLong_FromLong(long v) @@ -104,14 +104,14 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: PyObject* PyLong_FromString(const char *str, char **pend, int base) Return a new :c:type:`PyLongObject` based on the string value in *str*, which - is interpreted according to the radix in *base*, or ``NULL`` on failure. If + is interpreted according to the radix in *base*, or ``NULL`` on failure. If *pend* is non-``NULL``, *\*pend* will point to the end of *str* on success or - to the first character that could not be processed on error. If *base* is ``0``, + to the first character that could not be processed on error. If *base* is ``0``, *str* is interpreted using the :ref:`integers` definition; in this case, leading - zeros in a non-zero decimal number raises a :exc:`ValueError`. If *base* is not - ``0``, it must be between ``2`` and ``36``, inclusive. Leading and trailing + zeros in a non-zero decimal number raises a :exc:`ValueError`. If *base* is not + ``0``, it must be between ``2`` and ``36``, inclusive. Leading and trailing whitespace and single underscores after a base specifier and between digits are - ignored. If there are no digits or *str* is not NULL-terminated following the + ignored. If there are no digits or *str* is not NULL-terminated following the digits and trailing whitespace, :exc:`ValueError` will be raised. .. seealso:: :c:func:`PyLong_AsNativeBytes()` and @@ -165,14 +165,14 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. single: LONG_MAX (C macro) single: OverflowError (built-in exception) - Return a C :c:expr:`long` representation of *obj*. If *obj* is not an + Return a C :c:expr:`long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *obj* is out of range for a :c:expr:`long`. - Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. @@ -201,16 +201,16 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow) - Return a C :c:expr:`long` representation of *obj*. If *obj* is not an + Return a C :c:expr:`long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is greater than :c:macro:`LONG_MAX` or less than :c:macro:`LONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and - return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception + return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception occurs set *\*overflow* to ``0`` and return ``-1`` as usual. - Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. @@ -224,14 +224,14 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. index:: single: OverflowError (built-in exception) - Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an + Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *obj* is out of range for a :c:expr:`long long`. - Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 Use :meth:`~object.__index__` if available. @@ -242,16 +242,16 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow) - Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an + Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is greater than :c:macro:`LLONG_MAX` or less than :c:macro:`LLONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, - and return ``-1``; otherwise, set *\*overflow* to ``0``. If any other + and return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception occurs set *\*overflow* to ``0`` and return ``-1`` as usual. - Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionadded:: 3.2 @@ -268,13 +268,13 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. single: PY_SSIZE_T_MAX (C macro) single: OverflowError (built-in exception) - Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must + Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:type:`Py_ssize_t`. - Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong) @@ -283,7 +283,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. single: ULONG_MAX (C macro) single: OverflowError (built-in exception) - Return a C :c:expr:`unsigned long` representation of *pylong*. *pylong* + Return a C :c:expr:`unsigned long` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a @@ -299,7 +299,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. single: SIZE_MAX (C macro) single: OverflowError (built-in exception) - Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be + Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a @@ -314,7 +314,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. index:: single: OverflowError (built-in exception) - Return a C :c:expr:`unsigned long long` representation of *pylong*. *pylong* + Return a C :c:expr:`unsigned long long` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for an @@ -329,14 +329,14 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: unsigned long PyLong_AsUnsignedLongMask(PyObject *obj) - Return a C :c:expr:`unsigned long` representation of *obj*. If *obj* is not + Return a C :c:expr:`unsigned long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. If the value of *obj* is out of range for an :c:expr:`unsigned long`, return the reduction of that value modulo ``ULONG_MAX + 1``. - Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to + Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 @@ -348,7 +348,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj) - Return a C :c:expr:`unsigned long long` representation of *obj*. If *obj* + Return a C :c:expr:`unsigned long long` representation of *obj*. If *obj* is not an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method (if present) to convert it to a :c:type:`PyLongObject`. @@ -356,7 +356,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. If the value of *obj* is out of range for an :c:expr:`unsigned long long`, return the reduction of that value modulo ``ULLONG_MAX + 1``. - Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` + Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. versionchanged:: 3.8 @@ -405,23 +405,23 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: double PyLong_AsDouble(PyObject *pylong) - Return a C :c:expr:`double` representation of *pylong*. *pylong* must be + Return a C :c:expr:`double` representation of *pylong*. *pylong* must be an instance of :c:type:`PyLongObject`. Raise :exc:`OverflowError` if the value of *pylong* is out of range for a :c:expr:`double`. - Returns ``-1.0`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + Returns ``-1.0`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: void* PyLong_AsVoidPtr(PyObject *pylong) Convert a Python integer *pylong* to a C :c:expr:`void` pointer. - If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This + If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This is only assured to produce a usable :c:expr:`void` pointer for values created with :c:func:`PyLong_FromVoidPtr`. - Returns ``NULL`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. + Returns ``NULL`` on error. Use :c:func:`PyErr_Occurred` to disambiguate. .. c:function:: Py_ssize_t PyLong_AsNativeBytes(PyObject *pylong, void* buffer, Py_ssize_t n_bytes, int flags) @@ -430,7 +430,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. *n_bytes*. The *flags* can be set to ``-1`` to behave similarly to a C cast, or to values documented below to control the behavior. - Returns ``-1`` with an exception raised on error. This may happen if + Returns ``-1`` with an exception raised on error. This may happen if *pylong* cannot be interpreted as an integer, or if *pylong* was negative and the ``Py_ASNATIVEBYTES_REJECT_NEGATIVE`` flag was set. @@ -488,7 +488,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. // Failed. A Python exception was set with the reason. return NULL; } - assert(expected != 0); // Impossible per the API definition. + assert(expected != 0); // Impossible per the API definition. uint8_t *bignum = malloc(expected); if (!bignum) { PyErr_SetString(PyExc_MemoryError, "bignum malloc failed."); @@ -496,11 +496,11 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. } // Safely get the entire value. Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, bignum, expected, -1); - if (bytes < 0) { // Exception has been set. + if (bytes < 0) { // Exception has been set. free(bignum); return NULL; } - else if (bytes > expected) { // This should not be possible. + else if (bytes > expected) { // This should not be possible. PyErr_SetString(PyExc_RuntimeError, "Unexpected bignum truncation after a size check."); free(bignum); @@ -560,7 +560,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. .. note:: - With the default *flags* (``-1``, or *UNSIGNED_BUFFER* without + With the default *flags* (``-1``, or *UNSIGNED_BUFFER* without *REJECT_NEGATIVE*), multiple Python integers can map to a single value without overflow. For example, both ``255`` and ``-1`` fit a single-byte buffer and set all its bits. @@ -573,10 +573,10 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. Get the sign of the integer object *obj*. - On success, set *\*sign* to the integer sign (0, -1 or +1 for zero, negative or + On success, set *\*sign* to the integer sign (0, -1 or +1 for zero, negative or positive integer, respectively) and return 0. - On failure, return -1 with an exception set. This function always succeeds + On failure, return -1 with an exception set. This function always succeeds if *obj* is a :c:type:`PyLongObject` or its subtype. .. versionadded:: 3.14 @@ -587,7 +587,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. Check if the integer object *obj* is positive (``obj > 0``). If *obj* is an instance of :c:type:`PyLongObject` or its subtype, - return ``1`` when it's positive and ``0`` otherwise. Else set an + return ``1`` when it's positive and ``0`` otherwise. Else set an exception and return ``-1``. .. versionadded:: 3.14 @@ -598,7 +598,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. Check if the integer object *obj* is negative (``obj < 0``). If *obj* is an instance of :c:type:`PyLongObject` or its subtype, - return ``1`` when it's negative and ``0`` otherwise. Else set an + return ``1`` when it's negative and ``0`` otherwise. Else set an exception and return ``-1``. .. versionadded:: 3.14 @@ -609,7 +609,7 @@ distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate. Check if the integer object *obj* is zero. If *obj* is an instance of :c:type:`PyLongObject` or its subtype, - return ``1`` when it's zero and ``0`` otherwise. Else set an + return ``1`` when it's zero and ``0`` otherwise. Else set an exception and return ``-1``. .. versionadded:: 3.14 diff --git a/Doc/c-api/mapping.rst b/Doc/c-api/mapping.rst index 1f55c0aa955c75..f7f6c481d5ca61 100644 --- a/Doc/c-api/mapping.rst +++ b/Doc/c-api/mapping.rst @@ -12,7 +12,7 @@ See also :c:func:`PyObject_GetItem`, :c:func:`PyObject_SetItem` and .. c:function:: int PyMapping_Check(PyObject *o) Return ``1`` if the object provides the mapping protocol or supports slicing, - and ``0`` otherwise. Note that it returns ``1`` for Python classes with + and ``0`` otherwise. Note that it returns ``1`` for Python classes with a :meth:`~object.__getitem__` method, since in general it is impossible to determine what type of keys the class supports. This function always succeeds. @@ -126,7 +126,7 @@ See also :c:func:`PyObject_GetItem`, :c:func:`PyObject_SetItem` and .. c:function:: PyObject* PyMapping_Keys(PyObject *o) - On success, return a list of the keys in object *o*. On failure, return + On success, return a list of the keys in object *o*. On failure, return ``NULL``. .. versionchanged:: 3.7 @@ -135,7 +135,7 @@ See also :c:func:`PyObject_GetItem`, :c:func:`PyObject_SetItem` and .. c:function:: PyObject* PyMapping_Values(PyObject *o) - On success, return a list of the values in object *o*. On failure, return + On success, return a list of the values in object *o*. On failure, return ``NULL``. .. versionchanged:: 3.7 @@ -145,7 +145,7 @@ See also :c:func:`PyObject_GetItem`, :c:func:`PyObject_SetItem` and .. 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``. + tuple containing a key-value pair. On failure, return ``NULL``. .. versionchanged:: 3.7 Previously, the function returned a list or a tuple. diff --git a/Doc/c-api/marshal.rst b/Doc/c-api/marshal.rst index 61218a1bf6f171..b2294eac0ed994 100644 --- a/Doc/c-api/marshal.rst +++ b/Doc/c-api/marshal.rst @@ -6,9 +6,9 @@ Data marshalling support ======================== These routines allow C code to work with serialized objects using the same -data format as the :mod:`marshal` module. There are functions to write data +data format as the :mod:`marshal` module. There are functions to write data into the serialization format, and additional functions that can be used to -read the data back. Files used to store marshalled data must be opened in +read the data back. Files used to store marshalled data must be opened in binary mode. Numeric values are stored with the least significant byte first. @@ -22,9 +22,9 @@ the :py:mod:`Python module documentation ` for details. .. c:function:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version) - Marshal a :c:expr:`long` integer, *value*, to *file*. This will only write + Marshal a :c:expr:`long` integer, *value*, to *file*. This will only write the least-significant 32 bits of *value*; regardless of the size of the - native :c:expr:`long` type. *version* indicates the file format. + native :c:expr:`long` type. *version* indicates the file format. This function can fail, in which case it sets the error indicator. Use :c:func:`PyErr_Occurred` to check for that. @@ -49,7 +49,7 @@ The following functions allow marshalled values to be read back in. .. c:function:: long PyMarshal_ReadLongFromFile(FILE *file) Return a C :c:expr:`long` from the data stream in a :c:expr:`FILE*` opened - for reading. Only a 32-bit value can be read in using this function, + for reading. Only a 32-bit value can be read in using this function, regardless of the native size of :c:expr:`long`. On error, sets the appropriate exception (:exc:`EOFError`) and returns @@ -59,7 +59,7 @@ The following functions allow marshalled values to be read back in. .. c:function:: int PyMarshal_ReadShortFromFile(FILE *file) Return a C :c:expr:`short` from the data stream in a :c:expr:`FILE*` opened - for reading. Only a 16-bit value can be read in using this function, + for reading. Only a 16-bit value can be read in using this function, regardless of the native size of :c:expr:`short`. On error, sets the appropriate exception (:exc:`EOFError`) and returns @@ -78,11 +78,11 @@ The following functions allow marshalled values to be read back in. .. c:function:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file) Return a Python object from the data stream in a :c:expr:`FILE*` opened for - reading. Unlike :c:func:`PyMarshal_ReadObjectFromFile`, this function + 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 - file. Only use these variant if you are certain that you won't be reading + file. Only use these variant if you are certain that you won't be reading anything else from the file. On error, sets the appropriate exception (:exc:`EOFError`, :exc:`ValueError` diff --git a/Doc/c-api/memory.rst b/Doc/c-api/memory.rst index 61fa49f8681cce..36c3fc37b51405 100644 --- a/Doc/c-api/memory.rst +++ b/Doc/c-api/memory.rst @@ -18,7 +18,7 @@ Overview Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured -internally by the *Python memory manager*. The Python memory manager has +internally by the *Python memory manager*. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching. @@ -36,7 +36,7 @@ operate within the bounds of the private heap. It is important to understand that the management of the Python heap is performed by the interpreter itself and that the user has no control over it, even if they regularly manipulate object pointers to memory blocks inside that -heap. The allocation of heap space for Python objects and other internal +heap. The allocation of heap space for Python objects and other internal buffers is performed on demand by the Python memory manager through the Python/C API functions listed in this document. @@ -48,10 +48,10 @@ API functions listed in this document. To avoid memory corruption, extension writers should never try to operate on 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 +: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 +different heaps. However, one may safely allocate and release memory blocks with the C library allocator for individual purposes, as shown in the following example:: @@ -193,7 +193,7 @@ zero bytes. Frees the memory block pointed to by *p*, which must have been returned by a previous call to :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or - :c:func:`PyMem_RawCalloc`. Otherwise, or if ``PyMem_RawFree(p)`` has been + :c:func:`PyMem_RawCalloc`. Otherwise, or if ``PyMem_RawFree(p)`` has been called before, undefined behavior occurs. If *p* is ``NULL``, no operation is performed. @@ -262,30 +262,30 @@ The :ref:`default memory allocator ` uses the Frees the memory block pointed to by *p*, which must have been returned by a previous call to :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or - :c:func:`PyMem_Calloc`. Otherwise, or if ``PyMem_Free(p)`` has been called + :c:func:`PyMem_Calloc`. Otherwise, or if ``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 +The following type-oriented macros are provided for convenience. Note that *TYPE* refers to any C type. .. c:macro:: PyMem_New(TYPE, n) Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of - memory. Returns a pointer cast to ``TYPE*``. The memory will not have + memory. Returns a pointer cast to ``TYPE*``. The memory will not have been initialized in any way. .. c:macro:: PyMem_Resize(p, TYPE, n) Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n * - sizeof(TYPE))`` bytes. Returns a pointer cast to ``TYPE*``. On return, + sizeof(TYPE))`` bytes. Returns a pointer cast to ``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 + This is a C preprocessor macro; *p* is always reassigned. Save the original value of *p* to avoid losing memory when handling errors. @@ -371,7 +371,7 @@ The :ref:`default object allocator ` uses the Frees the memory block pointed to by *p*, which must have been returned by a previous call to :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or - :c:func:`PyObject_Calloc`. Otherwise, or if ``PyObject_Free(p)`` has been called + :c:func:`PyObject_Calloc`. Otherwise, or if ``PyObject_Free(p)`` has been called before, undefined behavior occurs. If *p* is ``NULL``, no operation is performed. @@ -417,7 +417,7 @@ Legend: * ``malloc``: system allocators from the standard C library, C functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`. * ``pymalloc``: :ref:`pymalloc memory allocator `. -* ``mimalloc``: :ref:`mimalloc memory allocator `. The pymalloc +* ``mimalloc``: :ref:`mimalloc memory allocator `. The pymalloc allocator will be used if mimalloc support isn't available. * "+ debug": with :ref:`debug hooks on the Python memory allocators `. @@ -582,13 +582,13 @@ if :mod:`tracemalloc` is tracing Python memory allocations and the memory block was traced. Let *S* = ``sizeof(size_t)``. ``2*S`` bytes are added at each end of each block -of *N* bytes requested. The memory layout is like so, where p represents the +of *N* bytes requested. The memory layout is like so, where p represents the address returned by a malloc-like or realloc-like function (``p[i:j]`` means the slice of bytes from ``*(p+i)`` inclusive up to ``*(p+j)`` exclusive; note that the treatment of negative indices differs from a Python slice): ``p[-2*S:-S]`` - Number of bytes originally asked for. This is a size_t, big-endian (easier + Number of bytes originally asked for. This is a size_t, big-endian (easier to read in a memory dump). ``p[-S]`` API identifier (ASCII character): @@ -598,43 +598,43 @@ that the treatment of negative indices differs from a Python slice): * ``'o'`` for :c:macro:`PYMEM_DOMAIN_OBJ`. ``p[-S+1:0]`` - Copies of PYMEM_FORBIDDENBYTE. Used to catch under- writes and reads. + Copies of PYMEM_FORBIDDENBYTE. Used to catch under- writes and reads. ``p[0:N]`` The requested memory, filled with copies of PYMEM_CLEANBYTE, used to catch - reference to uninitialized memory. When a realloc-like function is called + reference to uninitialized memory. When a realloc-like function is called requesting a larger memory block, the new excess bytes are also filled with - PYMEM_CLEANBYTE. When a free-like function is called, these are - overwritten with PYMEM_DEADBYTE, to catch reference to freed memory. When + PYMEM_CLEANBYTE. When a free-like function is called, these are + overwritten with PYMEM_DEADBYTE, to catch reference to freed memory. When a realloc- like function is called requesting a smaller memory block, the excess old bytes are also filled with PYMEM_DEADBYTE. ``p[N:N+S]`` - Copies of PYMEM_FORBIDDENBYTE. Used to catch over- writes and reads. + Copies of PYMEM_FORBIDDENBYTE. Used to catch over- writes and reads. ``p[N+S:N+2*S]`` Only used if the ``PYMEM_DEBUG_SERIALNO`` macro is defined (not defined by default). A serial number, incremented by 1 on each call to a malloc-like or - realloc-like function. Big-endian :c:type:`size_t`. If "bad memory" is detected + realloc-like function. Big-endian :c:type:`size_t`. If "bad memory" is detected later, the serial number gives an excellent way to set a breakpoint on the - next run, to capture the instant at which this block was passed out. The + next run, to capture the instant at which this block was passed out. The static function bumpserialno() in obmalloc.c is the only place the serial number is incremented, and exists so you can set such a breakpoint easily. A realloc-like or free-like function first checks that the PYMEM_FORBIDDENBYTE -bytes at each end are intact. If they've been altered, diagnostic output is -written to stderr, and the program is aborted via Py_FatalError(). The other +bytes at each end are intact. If they've been altered, diagnostic output is +written to stderr, and the program is aborted via Py_FatalError(). The other main failure mode is provoking a memory error when a program reads up one of -the special bit patterns and tries to use it as an address. If you get in a +the special bit patterns and tries to use it as an address. If you get in a debugger then and look at the object, you're likely to see that it's entirely filled with PYMEM_DEADBYTE (meaning freed memory is getting used) or PYMEM_CLEANBYTE (meaning uninitialized memory is getting used). .. versionchanged:: 3.6 The :c:func:`PyMem_SetupDebugHooks` function now also works on Python - compiled in release mode. On error, the debug hooks now use + compiled in release mode. On error, the debug hooks now use :mod:`tracemalloc` to get the traceback where a memory block was allocated. The debug hooks now also check if there is an :term:`attached thread state` when functions of :c:macro:`PYMEM_DOMAIN_OBJ` and :c:macro:`PYMEM_DOMAIN_MEM` domains are @@ -776,7 +776,7 @@ allocators operating on different heaps. :: ... PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */ free(buf2); /* Right -- allocated via malloc() */ - free(buf1); /* Fatal -- should be PyMem_Free() */ + free(buf1); /* Fatal -- should be PyMem_Free() */ In addition to the functions aimed at handling raw memory blocks from the Python heap, objects in Python are allocated and released with :c:macro:`PyObject_New`, diff --git a/Doc/c-api/memoryview.rst b/Doc/c-api/memoryview.rst index f6038032805259..ba7dd2b0956a75 100644 --- a/Doc/c-api/memoryview.rst +++ b/Doc/c-api/memoryview.rst @@ -57,8 +57,8 @@ any other object. .. 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`. This + Return true if the object *obj* is a memoryview object. It is not + currently allowed to create subclasses of :class:`memoryview`. This function always succeeds. diff --git a/Doc/c-api/method.rst b/Doc/c-api/method.rst index 0d75ab8e1af111..90c671a2ef7acb 100644 --- a/Doc/c-api/method.rst +++ b/Doc/c-api/method.rst @@ -21,7 +21,7 @@ to bind a :c:type:`PyCFunction` to a class object. It replaces the former call .. c:function:: int PyInstanceMethod_Check(PyObject *o) Return true if *o* is an instance method object (has type - :c:data:`PyInstanceMethod_Type`). The parameter must not be ``NULL``. + :c:data:`PyInstanceMethod_Type`). The parameter must not be ``NULL``. This function always succeeds. @@ -58,14 +58,14 @@ no longer available. .. index:: single: MethodType (in module types) - This instance of :c:type:`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``. .. c:function:: int PyMethod_Check(PyObject *o) - Return true if *o* is a method object (has type :c:data:`PyMethod_Type`). The - parameter must not be ``NULL``. This function always succeeds. + Return true if *o* is a method object (has type :c:data:`PyMethod_Type`). The + parameter must not be ``NULL``. This function always succeeds. .. c:function:: PyObject* PyMethod_New(PyObject *func, PyObject *self) diff --git a/Doc/c-api/module.rst b/Doc/c-api/module.rst index c8edcecc5b419f..14b85a310ac907 100644 --- a/Doc/c-api/module.rst +++ b/Doc/c-api/module.rst @@ -12,7 +12,7 @@ Module Objects .. index:: single: ModuleType (in module types) - This instance of :c:type:`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``. @@ -25,7 +25,7 @@ Module Objects .. c:function:: int PyModule_CheckExact(PyObject *p) Return true if *p* is a module object, but not a subtype of - :c:data:`PyModule_Type`. This function always succeeds. + :c:data:`PyModule_Type`. This function always succeeds. .. c:function:: PyObject* PyModule_NewObject(PyObject *name) @@ -78,7 +78,7 @@ Module Objects single: __name__ (module attribute) single: SystemError (built-in exception) - Return *module*'s :attr:`~module.__name__` value. If the module does not + Return *module*'s :attr:`~module.__name__` value. If the module does not provide one, or if it is not a string, :exc:`SystemError` is raised and ``NULL`` is returned. @@ -93,7 +93,7 @@ Module Objects .. c:function:: void* PyModule_GetState(PyObject *module) Return the "state" of the module, that is, a pointer to the block of memory - allocated at module creation time, or ``NULL``. See + allocated at module creation time, or ``NULL``. See :c:member:`PyModuleDef.m_size`. @@ -110,7 +110,7 @@ Module Objects single: SystemError (built-in exception) Return the name of the file from which *module* was loaded using *module*'s - :attr:`~module.__file__` attribute. If this is not defined, or if it is not a + :attr:`~module.__file__` attribute. If this is not defined, or if it is not a string, raise :exc:`SystemError` and return ``NULL``; otherwise return a reference to a Unicode object. @@ -196,7 +196,7 @@ data stored in module state. .. c:member:: PyMethodDef* m_methods A pointer to a table of module-level functions, described by - :c:type:`PyMethodDef` values. Can be ``NULL`` if no functions are present. + :c:type:`PyMethodDef` values. Can be ``NULL`` if no functions are present. .. c:member:: PyModuleDef_Slot* m_slots @@ -377,7 +377,7 @@ The available slot types are: The module is safe to run without an active GIL. This slot is ignored by Python builds not configured with - :option:`--disable-gil`. Otherwise, it determines whether or not importing + :option:`--disable-gil`. Otherwise, it determines whether or not importing this module will cause the GIL to be automatically enabled. See :ref:`whatsnew313-free-threaded-cpython` for more detail. @@ -410,7 +410,7 @@ They are also used in .. c:function:: PyObject* PyModule_Create2(PyModuleDef *def, int module_api_version) Create a new module object, given the definition in *def*, assuming the - API version *module_api_version*. If that version does not match the version + API version *module_api_version*. If that version does not match the version of the running interpreter, a :exc:`RuntimeWarning` is emitted. Return ``NULL`` with an exception set on error. @@ -485,7 +485,7 @@ or code that creates modules dynamically. .. c:function:: int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value) - Add an object to *module* as *name*. This is a convenience function which + Add an object to *module* as *name*. This is a convenience function which can be used from the module's initialization function. On success, return ``0``. On error, raise an exception and return ``-1``. @@ -588,7 +588,7 @@ or code that creates modules dynamically. .. 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 + Add an integer constant to *module* as *name*. This convenience function can be used from the module's initialization function. Return ``-1`` with an exception set on error, ``0`` on success. @@ -598,8 +598,8 @@ or code that creates modules dynamically. .. 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 + Add a string constant to *module* as *name*. This convenience function can be + used from the module's initialization function. The string *value* must be ``NULL``-terminated. Return ``-1`` with an exception set on error, ``0`` on success. diff --git a/Doc/c-api/none.rst b/Doc/c-api/none.rst index f1941fc4bc4e85..4a9bbc01e9dcd5 100644 --- a/Doc/c-api/none.rst +++ b/Doc/c-api/none.rst @@ -8,14 +8,14 @@ The ``None`` Object .. index:: pair: object; None 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 +Python/C API. Since ``None`` is a singleton, testing for object identity (using ``==`` in C) is sufficient. There is no :c:func:`!PyNone_Check` function for the same reason. .. c:var:: PyObject* Py_None - The Python ``None`` object, denoting lack of value. This object has no methods + The Python ``None`` object, denoting lack of value. This object has no methods and is :term:`immortal`. .. versionchanged:: 3.12 diff --git a/Doc/c-api/number.rst b/Doc/c-api/number.rst index ad8b5935258fa7..0c03329c4a9170 100644 --- a/Doc/c-api/number.rst +++ b/Doc/c-api/number.rst @@ -17,48 +17,48 @@ Number Protocol .. c:function:: PyObject* PyNumber_Add(PyObject *o1, PyObject *o2) - Returns the result of adding *o1* and *o2*, or ``NULL`` on failure. This is the + Returns the result of adding *o1* and *o2*, or ``NULL`` on failure. This is the equivalent of the Python expression ``o1 + o2``. .. c:function:: PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2) - Returns the result of subtracting *o2* from *o1*, or ``NULL`` on failure. This is + Returns the result of subtracting *o2* from *o1*, or ``NULL`` on failure. This is the equivalent of the Python expression ``o1 - o2``. .. c:function:: PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2) - Returns the result of multiplying *o1* and *o2*, or ``NULL`` on failure. This is + Returns the result of multiplying *o1* and *o2*, or ``NULL`` on failure. This is the equivalent of the Python expression ``o1 * o2``. .. c:function:: PyObject* PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2) Returns the result of matrix multiplication on *o1* and *o2*, or ``NULL`` on - failure. This is the equivalent of the Python expression ``o1 @ o2``. + failure. This is the equivalent of the Python expression ``o1 @ o2``. .. versionadded:: 3.5 .. c:function:: PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2) - Return the floor of *o1* divided by *o2*, or ``NULL`` on failure. This is + Return the floor of *o1* divided by *o2*, or ``NULL`` on failure. This is the equivalent of the Python expression ``o1 // 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 + *o2*, or ``NULL`` on failure. The return value is "approximate" because binary floating-point numbers are approximate; it is not possible to represent all real - numbers in base two. This function can return a floating-point value when - passed two integers. This is the equivalent of the Python expression ``o1 / o2``. + numbers in base two. This function can return a floating-point value when + passed two integers. This is the equivalent of the Python expression ``o1 / o2``. .. c:function:: PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2) - Returns the remainder of dividing *o1* by *o2*, or ``NULL`` on failure. This is + Returns the remainder of dividing *o1* by *o2*, or ``NULL`` on failure. This is the equivalent of the Python expression ``o1 % o2``. @@ -66,7 +66,7 @@ Number Protocol .. index:: pair: built-in function; divmod - See the built-in function :func:`divmod`. Returns ``NULL`` on failure. This is + See the built-in function :func:`divmod`. Returns ``NULL`` on failure. This is the equivalent of the Python expression ``divmod(o1, o2)``. @@ -74,7 +74,7 @@ Number Protocol .. index:: pair: built-in function; pow - See the built-in function :func:`pow`. Returns ``NULL`` on failure. This is the + 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 :c:data:`Py_None` in its place (passing ``NULL`` for *o3* would cause an illegal memory access). @@ -88,7 +88,7 @@ Number Protocol .. c:function:: PyObject* PyNumber_Positive(PyObject *o) - Returns *o* on success, or ``NULL`` on failure. This is the equivalent of the + Returns *o* on success, or ``NULL`` on failure. This is the equivalent of the Python expression ``+o``. @@ -96,26 +96,26 @@ Number Protocol .. index:: pair: built-in function; abs - Returns the absolute value of *o*, or ``NULL`` on failure. This is the equivalent + Returns the absolute value of *o*, or ``NULL`` on failure. This is the equivalent of the Python expression ``abs(o)``. .. c:function:: PyObject* PyNumber_Invert(PyObject *o) - Returns the bitwise negation of *o* on success, or ``NULL`` on failure. This is + Returns the bitwise negation of *o* on success, or ``NULL`` on failure. This is the equivalent of the Python expression ``~o``. .. 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``. + failure. This is the equivalent of the Python expression ``o1 << 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``. + failure. This is the equivalent of the Python expression ``o1 >> o2``. .. c:function:: PyObject* PyNumber_And(PyObject *o1, PyObject *o2) @@ -127,7 +127,7 @@ Number Protocol .. 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``. + failure. This is the equivalent of the Python expression ``o1 ^ o2``. .. c:function:: PyObject* PyNumber_Or(PyObject *o1, PyObject *o2) @@ -138,29 +138,29 @@ Number Protocol .. 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 + 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``. .. 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 + 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``. .. 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 + 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``. .. c:function:: PyObject* PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2) Returns the result of matrix multiplication on *o1* and *o2*, or ``NULL`` on - failure. The operation is done *in-place* when *o1* supports it. This is + failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 @= o2``. .. versionadded:: 3.5 @@ -169,24 +169,24 @@ Number Protocol .. 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 + The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 //= 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 + *o2*, or ``NULL`` on failure. The return value is "approximate" because binary floating-point numbers are approximate; it is not possible to represent all real - numbers in base two. This function can return a floating-point value when - passed two integers. The operation is done *in-place* when *o1* supports it. + numbers in base two. This function can return a floating-point value when + passed two integers. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 /= 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 + 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``. @@ -194,8 +194,8 @@ Number Protocol .. index:: pair: built-in function; 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 + 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 :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). @@ -204,35 +204,35 @@ Number Protocol .. 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 + failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 <<= 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 + failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 >>= 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 + operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 &= 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 + failure. The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 ^= 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 + 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``. @@ -241,7 +241,7 @@ Number Protocol .. index:: pair: built-in function; int Returns the *o* converted to an integer object on success, or ``NULL`` on - failure. This is the equivalent of the Python expression ``int(o)``. + failure. This is the equivalent of the Python expression ``int(o)``. .. c:function:: PyObject* PyNumber_Float(PyObject *o) @@ -258,28 +258,28 @@ Number Protocol :exc:`TypeError` exception raised on failure. .. versionchanged:: 3.10 - The result always has exact type :class:`int`. Previously, the result + The result always has exact type :class:`int`. Previously, the result could have been an instance of a subclass of ``int``. .. c:function:: PyObject* PyNumber_ToBase(PyObject *n, int base) - Returns the integer *n* converted to base *base* as a string. The *base* - argument must be one of 2, 8, 10, or 16. For base 2, 8, or 16, the + Returns the integer *n* converted to base *base* as a string. The *base* + argument must be one of 2, 8, 10, or 16. For base 2, 8, or 16, the returned string is prefixed with a base marker of ``'0b'``, ``'0o'``, or - ``'0x'``, respectively. If *n* is not a Python int, it is converted with + ``'0x'``, respectively. If *n* is not a Python int, it is converted with :c:func:`PyNumber_Index` first. .. c:function:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc) Returns *o* converted to a :c:type:`Py_ssize_t` value if *o* can be interpreted as an - integer. If the call fails, an exception is raised and ``-1`` is returned. + integer. If the call fails, an exception is raised and ``-1`` is returned. If *o* can be converted to a Python int but the attempt to convert to a :c:type:`Py_ssize_t` value would raise an :exc:`OverflowError`, then the *exc* argument is the type of exception that will be raised (usually - :exc:`IndexError` or :exc:`OverflowError`). If *exc* is ``NULL``, then the + :exc:`IndexError` or :exc:`OverflowError`). If *exc* is ``NULL``, then the exception is cleared and the value is clipped to ``PY_SSIZE_T_MIN`` for a negative integer or ``PY_SSIZE_T_MAX`` for a positive integer. diff --git a/Doc/c-api/object.rst b/Doc/c-api/object.rst index 55f0d0f9fb7ff8..c0ebb237711078 100644 --- a/Doc/c-api/object.rst +++ b/Doc/c-api/object.rst @@ -79,8 +79,8 @@ Object Protocol .. 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 + 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 is :c:macro:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written instead of the :func:`repr`. @@ -136,7 +136,7 @@ Object Protocol .. 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 + value on success, or ``NULL`` on failure. This is the equivalent of the Python expression ``o.attr_name``. If the missing attribute should not be treated as a failure, you can use @@ -179,18 +179,18 @@ Object Protocol .. 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 + object's ``tp_getattro`` slot. It looks for a descriptor in the dictionary of classes in the object's MRO as well as an attribute in the object's - :attr:`~object.__dict__` (if present). As outlined in :ref:`descriptors`, + :attr:`~object.__dict__` (if present). As outlined in :ref:`descriptors`, data descriptors take preference over instance attributes, while non-data - descriptors don't. Otherwise, an :exc:`AttributeError` is raised. + descriptors don't. Otherwise, an :exc:`AttributeError` is raised. .. 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*. Raise an exception and return ``-1`` on failure; - return ``0`` on success. This is the equivalent of the Python statement + return ``0`` on success. This is the equivalent of the Python statement ``o.attr_name = v``. If *v* is ``NULL``, the attribute is deleted. This behaviour is deprecated @@ -234,7 +234,7 @@ Object Protocol Generic attribute setter and deleter function that is meant to be put into a type object's :c:member:`~PyTypeObject.tp_setattro` - slot. It looks for a data descriptor in the + slot. It looks for a data descriptor in the dictionary of classes in the object's MRO, and if found it takes preference over setting or deleting the attribute in the instance dictionary. Otherwise, the attribute is set or deleted in the object's :attr:`~object.__dict__` (if present). @@ -330,9 +330,9 @@ Object Protocol .. index:: pair: built-in function; repr - Compute a string representation of object *o*. Returns the string - representation on success, ``NULL`` on failure. This is the equivalent of the - Python expression ``repr(o)``. Called by the :func:`repr` built-in function. + Compute a string representation of object *o*. Returns the string + representation on success, ``NULL`` on failure. This is the equivalent of the + Python expression ``repr(o)``. Called by the :func:`repr` built-in function. .. versionchanged:: 3.4 This function now includes a debug assertion to help ensure that it @@ -344,7 +344,7 @@ Object Protocol As :c:func:`PyObject_Repr`, compute a string representation of object *o*, but escape the non-ASCII characters in the string returned by - :c:func:`PyObject_Repr` with ``\x``, ``\u`` or ``\U`` escapes. This generates + :c:func:`PyObject_Repr` with ``\x``, ``\u`` or ``\U`` escapes. This generates a string similar to that returned by :c:func:`PyObject_Repr` in Python 2. Called by the :func:`ascii` built-in function. @@ -353,9 +353,9 @@ Object Protocol .. c:function:: PyObject* PyObject_Str(PyObject *o) - Compute a string representation of object *o*. Returns the string - representation on success, ``NULL`` on failure. This is the equivalent of the - Python expression ``str(o)``. Called by the :func:`str` built-in function + Compute a string representation of object *o*. Returns the string + representation on success, ``NULL`` on failure. This is the equivalent of the + Python expression ``str(o)``. Called by the :func:`str` built-in function and, therefore, by the :func:`print` function. .. versionchanged:: 3.4 @@ -367,9 +367,9 @@ Object Protocol .. index:: pair: built-in function; bytes - Compute a bytes representation of object *o*. ``NULL`` is returned on - failure and a bytes object on success. This is equivalent to the Python - expression ``bytes(o)``, when *o* is not an integer. Unlike ``bytes(o)``, + Compute a bytes representation of object *o*. ``NULL`` is returned on + failure and a bytes object on success. This is equivalent to the Python + expression ``bytes(o)``, when *o* is not an integer. Unlike ``bytes(o)``, a TypeError is raised when *o* is an integer instead of a zero-initialized bytes object. @@ -377,33 +377,33 @@ Object Protocol .. c:function:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls) Return ``1`` if the class *derived* is identical to or derived from the class - *cls*, otherwise return ``0``. In case of an error, return ``-1``. + *cls*, otherwise return ``0``. In case of an error, return ``-1``. 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 *cls* has a :meth:`~type.__subclasscheck__` method, it will be called to - determine the subclass status as described in :pep:`3119`. Otherwise, + determine the subclass status as described in :pep:`3119`. Otherwise, *derived* is a subclass of *cls* if it is a direct or indirect subclass, i.e. contained in :attr:`cls.__mro__ `. Normally only class objects, i.e. instances of :class:`type` or a derived - class, are considered classes. However, objects can override this by having + class, are considered classes. However, objects can override this by having a :attr:`~type.__bases__` attribute (which must be a tuple of base classes). .. c:function:: int PyObject_IsInstance(PyObject *inst, PyObject *cls) Return ``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. + *cls*, or ``0`` if not. On error, returns ``-1`` and sets an exception. 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 *cls* has a :meth:`~type.__instancecheck__` method, it will be called to - determine the subclass status as described in :pep:`3119`. Otherwise, *inst* + determine the subclass status as described in :pep:`3119`. Otherwise, *inst* is an instance of *cls* if its class is a subclass of *cls*. An instance *inst* can override what is considered its class by having a @@ -418,11 +418,11 @@ Object Protocol .. index:: pair: built-in function; hash - Compute and return the hash value of an object *o*. On failure, return ``-1``. + Compute and return the hash value of an object *o*. On failure, return ``-1``. This is the equivalent of the Python expression ``hash(o)``. .. versionchanged:: 3.2 - The return type is now Py_hash_t. This is a signed integer the same size + The return type is now Py_hash_t. This is a signed integer the same size as :c:type:`Py_ssize_t`. @@ -437,14 +437,14 @@ Object Protocol .. 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 + This is equivalent to the Python expression ``not not o``. On failure, return ``-1``. .. 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 + This is equivalent to the Python expression ``not o``. On failure, return ``-1``. @@ -453,7 +453,7 @@ Object Protocol .. index:: pair: built-in function; type When *o* is non-``NULL``, returns a type object corresponding to the object type - of object *o*. On failure, raises :exc:`SystemError` and returns ``NULL``. This + of object *o*. On failure, raises :exc:`SystemError` and returns ``NULL``. This is equivalent to the Python expression ``type(o)``. This function creates a new :term:`strong reference` to the return value. There's really no reason to use this @@ -465,7 +465,7 @@ Object Protocol .. c:function:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type) Return non-zero if the object *o* is of type *type* or a subtype of *type*, and - ``0`` otherwise. Both parameters must be non-``NULL``. + ``0`` otherwise. Both parameters must be non-``NULL``. .. c:function:: Py_ssize_t PyObject_Size(PyObject *o) @@ -473,9 +473,9 @@ Object Protocol .. index:: pair: built-in function; len - Return the length of object *o*. If the object *o* provides either the sequence - and mapping protocols, the sequence length is returned. On error, ``-1`` is - returned. This is the equivalent to the Python expression ``len(o)``. + Return the length of object *o*. If the object *o* provides either the sequence + and mapping protocols, the sequence length is returned. On error, ``-1`` is + returned. This is the equivalent to the Python expression ``len(o)``. .. c:function:: Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue) @@ -496,16 +496,16 @@ Object Protocol .. c:function:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v) - Map the object *key* to the value *v*. Raise an exception and - return ``-1`` on failure; return ``0`` on success. This is the - equivalent of the Python statement ``o[key] = v``. This function *does + Map the object *key* to the value *v*. Raise an exception and + return ``-1`` on failure; return ``0`` on success. This is the + equivalent of the Python statement ``o[key] = v``. This function *does not* steal a reference to *v*. .. c:function:: int PyObject_DelItem(PyObject *o, PyObject *key) - Remove the mapping for the object *key* from the object *o*. Return ``-1`` - on failure. This is equivalent to the Python statement ``del o[key]``. + Remove the mapping for the object *key* from the object *o*. Return ``-1`` + on failure. This is equivalent to the Python statement ``del o[key]``. .. c:function:: int PyObject_DelItemString(PyObject *o, const char *key) @@ -519,7 +519,7 @@ Object Protocol 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()``, + 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 :c:func:`PyErr_Occurred` will return false. @@ -527,8 +527,8 @@ Object Protocol .. 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 - an iterator. Raises :exc:`TypeError` and returns ``NULL`` if the object cannot be + iterator for the object argument, or the object itself if the object is already + an iterator. Raises :exc:`TypeError` and returns ``NULL`` if the object cannot be iterated. @@ -608,9 +608,9 @@ Object Protocol .. c:function:: int PyUnstable_Object_EnableDeferredRefcount(PyObject *obj) Enable `deferred reference counting `_ on *obj*, - if supported by the runtime. In the :term:`free-threaded ` build, + if supported by the runtime. In the :term:`free-threaded ` build, this allows the interpreter to avoid reference count adjustments to *obj*, - which may improve multi-threaded performance. The tradeoff is + which may improve multi-threaded performance. The tradeoff is that *obj* will only be deallocated by the tracing garbage collector, and not when the interpreter no longer has any references to it. @@ -634,7 +634,7 @@ Object Protocol Check if *obj* is a unique temporary object. Returns ``1`` if *obj* is known to be a unique temporary object, - and ``0`` otherwise. This function cannot fail, but the check is + and ``0`` otherwise. This function cannot fail, but the check is conservative, and may return ``0`` in some cases even if *obj* is a unique temporary object. @@ -676,7 +676,7 @@ Object Protocol .. c:function:: int PyUnstable_TryIncRef(PyObject *obj) - Increments the reference count of *obj* if it is not zero. Returns ``1`` + Increments the reference count of *obj* if it is not zero. Returns ``1`` if the object's reference count was successfully incremented. Otherwise, this function returns ``0``. @@ -750,7 +750,7 @@ Object Protocol .. c:function:: void PyUnstable_EnableTryIncRef(PyObject *obj) - Enables subsequent uses of :c:func:`PyUnstable_TryIncRef` on *obj*. The + Enables subsequent uses of :c:func:`PyUnstable_TryIncRef` on *obj*. The caller must hold a :term:`strong reference` to *obj* when calling this. .. versionadded:: 3.14 diff --git a/Doc/c-api/refcounting.rst b/Doc/c-api/refcounting.rst index 57a0728d4e9af4..a52f08a03939f5 100644 --- a/Doc/c-api/refcounting.rst +++ b/Doc/c-api/refcounting.rst @@ -16,9 +16,9 @@ of Python objects. Get the reference count of the Python object *o*. Note that the returned value may not actually reflect how many - references to the object are actually held. For example, some + references to the object are actually held. For example, some objects are :term:`immortal` and have a very high refcount that does not - reflect the actual number of references. Consequently, do not rely + reflect the actual number of references. Consequently, do not rely on the returned value to be accurate, other than a value of 0 or 1. Use the :c:func:`Py_SET_REFCNT()` function to set an object reference count. @@ -145,11 +145,11 @@ of Python objects. .. warning:: The deallocation function can cause arbitrary Python code to be invoked (e.g. - when a class instance with a :meth:`~object.__del__` method is deallocated). While + when a class instance with a :meth:`~object.__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 + all Python global variables. This means that any object that is reachable from 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 + 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 :c:func:`Py_DECREF` for the temporary variable. @@ -169,7 +169,7 @@ of Python objects. Release a :term:`strong reference` for object *o*. The object may be ``NULL``, in which case the macro has no effect; otherwise the effect is the same as for - :c:func:`Py_DECREF`, except that the argument is also set to ``NULL``. The warning + :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 releasing the reference. diff --git a/Doc/c-api/reflection.rst b/Doc/c-api/reflection.rst index 54fd5a064aa2ac..615c79319d57e0 100644 --- a/Doc/c-api/reflection.rst +++ b/Doc/c-api/reflection.rst @@ -101,6 +101,6 @@ Reflection 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 + " instance", and " object". Concatenated with the result of :c:func:`PyEval_GetFuncName`, the result will be a description of *func*. diff --git a/Doc/c-api/sequence.rst b/Doc/c-api/sequence.rst index df5bf6b64a93a0..08d06b2c19427c 100644 --- a/Doc/c-api/sequence.rst +++ b/Doc/c-api/sequence.rst @@ -11,7 +11,7 @@ Sequence Protocol Return ``1`` if the object provides the sequence protocol, and ``0`` otherwise. Note that it returns ``1`` for Python classes with a :meth:`~object.__getitem__` method, unless they are :class:`dict` subclasses, since in general it - is impossible to determine what type of keys the class supports. This + is impossible to determine what type of keys the class supports. This function always succeeds. @@ -21,7 +21,7 @@ Sequence Protocol .. index:: pair: built-in function; len Returns the number of objects in sequence *o* on success, and ``-1`` on - failure. This is equivalent to the Python expression ``len(o)``. + failure. This is equivalent to the Python expression ``len(o)``. .. c:function:: PyObject* PySequence_Concat(PyObject *o1, PyObject *o2) @@ -33,20 +33,20 @@ Sequence Protocol .. 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``. + failure. This is the equivalent of the Python expression ``o * count``. .. 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 + The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python expression ``o1 += o2``. .. 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 + failure. The operation is done *in-place* when *o* supports it. This is the equivalent of the Python expression ``o *= count``. @@ -64,9 +64,9 @@ Sequence Protocol .. c:function:: int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v) - Assign object *v* to the *i*\ th element of *o*. Raise an exception - and return ``-1`` on failure; return ``0`` on success. This - is the equivalent of the Python statement ``o[i] = v``. This function *does + Assign object *v* to the *i*\ th element of *o*. Raise an exception + and return ``-1`` on failure; return ``0`` on success. This + is the equivalent of the Python statement ``o[i] = v``. This function *does not* steal a reference to *v*. If *v* is ``NULL``, the element is deleted, but this feature is @@ -75,33 +75,33 @@ Sequence Protocol .. 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 + Delete the *i*\ th element of object *o*. Returns ``-1`` on failure. This is the equivalent of the Python statement ``del o[i]``. .. 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``. + *i2*. This is the equivalent of the Python statement ``o[i1:i2] = v``. .. 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]``. + 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]``. .. 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 + of keys for which ``o[key] == value``. On failure, return ``-1``. This is equivalent to the Python expression ``o.count(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 + 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``. @@ -116,14 +116,14 @@ Sequence Protocol .. 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)``. + Return the first index *i* for which ``o[i] == value``. On error, return + ``-1``. This is equivalent to the Python expression ``o.index(value)``. .. c:function:: PyObject* PySequence_List(PyObject *o) Return a list object with the same contents as the sequence or iterable *o*, - or ``NULL`` on failure. The returned list is guaranteed to be new. This is + or ``NULL`` on failure. The returned list is guaranteed to be new. This is equivalent to the Python expression ``list(o)``. @@ -132,8 +132,8 @@ Sequence Protocol .. index:: pair: built-in function; tuple Return a tuple object with the same contents as the sequence or iterable *o*, - or ``NULL`` on failure. If *o* is a tuple, a new reference will be returned, - otherwise a tuple will be constructed with the appropriate contents. This is + or ``NULL`` on failure. If *o* is a tuple, a new reference will be returned, + otherwise a tuple will be constructed with the appropriate contents. This is equivalent to the Python expression ``tuple(o)``. @@ -155,7 +155,7 @@ Sequence Protocol .. c:function:: Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o) Returns the length of *o*, assuming that *o* was returned by - :c:func:`PySequence_Fast` and that *o* is not ``NULL``. The size can also be + :c:func:`PySequence_Fast` and that *o* is not ``NULL``. The size can also be retrieved 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. @@ -169,7 +169,7 @@ Sequence Protocol .. c:function:: PyObject** PySequence_Fast_ITEMS(PyObject *o) - Return the underlying array of PyObject pointers. Assumes that *o* was returned + Return the underlying array of PyObject pointers. Assumes that *o* was returned by :c:func:`PySequence_Fast` and *o* is not ``NULL``. Note, if a list gets resized, the reallocation may relocate the items array. diff --git a/Doc/c-api/set.rst b/Doc/c-api/set.rst index cba823aa027bd6..2c29573e76858c 100644 --- a/Doc/c-api/set.rst +++ b/Doc/c-api/set.rst @@ -13,7 +13,7 @@ Set Objects pair: object; frozenset This section details the public API for :class:`set` and :class:`frozenset` -objects. Any functionality not listed below is best accessed using either +objects. Any functionality not listed below is best accessed using either 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 @@ -27,11 +27,11 @@ the abstract object protocol (including :c:func:`PyObject_CallMethod`, .. c:type:: PySetObject 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` + :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 - considered public and all are subject to change. All access should be done through + considered public and all are subject to change. All access should be done through the documented API rather than by manipulating the values in the structure. @@ -58,46 +58,46 @@ the constructor functions work with any iterable Python object. .. c:function:: int PyFrozenSet_Check(PyObject *p) Return true if *p* is a :class:`frozenset` object or an instance of a - subtype. This function always succeeds. + subtype. This function always succeeds. .. 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. This function always succeeds. + instance of a subtype. This function always succeeds. .. c:function:: int PySet_CheckExact(PyObject *p) Return true if *p* is a :class:`set` object but not an instance of a - subtype. This function always succeeds. + subtype. This function always succeeds. .. versionadded:: 3.10 .. 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. This function always succeeds. + not an instance of a subtype. This function always succeeds. .. c:function:: int PyFrozenSet_CheckExact(PyObject *p) Return true if *p* is a :class:`frozenset` object but not an instance of a - subtype. This function always succeeds. + subtype. This function always succeeds. .. 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 - success or ``NULL`` on failure. Raise :exc:`TypeError` if *iterable* is not - actually iterable. The constructor is also useful for copying a set + 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 + success or ``NULL`` on failure. Raise :exc:`TypeError` if *iterable* is not + actually iterable. The constructor is also useful for copying a set (``c=set(s)``). .. 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 - set on success or ``NULL`` on failure. Raise :exc:`TypeError` if *iterable* is + The *iterable* may be ``NULL`` to create a new empty frozenset. Return the new + set on success or ``NULL`` on failure. Raise :exc:`TypeError` if *iterable* is not actually iterable. @@ -110,7 +110,7 @@ or :class:`frozenset` or instances of their subtypes. .. index:: pair: built-in function; len Return the length of a :class:`set` or :class:`frozenset` object. Equivalent to - ``len(anyset)``. Raises a :exc:`SystemError` if *anyset* is not a + ``len(anyset)``. Raises a :exc:`SystemError` if *anyset* is not a :class:`set`, :class:`frozenset`, or an instance of a subtype. @@ -121,20 +121,20 @@ or :class:`frozenset` or instances of their subtypes. .. 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 + Return ``1`` if found, ``0`` if not found, and ``-1`` if an error is encountered. Unlike the Python :meth:`~object.__contains__` method, this function does not automatically - convert unhashable sets into temporary frozensets. Raise a :exc:`TypeError` if + convert unhashable sets into temporary frozensets. Raise a :exc:`TypeError` if the *key* is unhashable. Raise :exc:`SystemError` if *anyset* is not a :class:`set`, :class:`frozenset`, or an instance of a subtype. .. c:function:: int PySet_Add(PyObject *set, PyObject *key) - Add *key* to a :class:`set` instance. Also works with :class:`frozenset` + Add *key* to a :class:`set` instance. Also works with :class:`frozenset` instances (like :c:func:`PyTuple_SetItem` it can be used to fill in the values - of brand new frozensets before they are exposed to other code). Return ``0`` on + of brand new frozensets before they are exposed to other code). Return ``0`` on success or ``-1`` on failure. Raise a :exc:`TypeError` if the *key* is - unhashable. Raise a :exc:`MemoryError` if there is no room to grow. Raise a + unhashable. Raise a :exc:`MemoryError` if there is no room to grow. Raise a :exc:`SystemError` if *set* is not an instance of :class:`set` or its subtype. @@ -146,8 +146,8 @@ subtypes but not for instances of :class:`frozenset` or its subtypes. .. 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 - :exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`~frozenset.discard` + error is encountered. Does not raise :exc:`KeyError` for missing keys. Raise a + :exc:`TypeError` if the *key* is unhashable. Unlike the Python :meth:`~frozenset.discard` method, this function does not automatically convert unhashable sets into temporary frozensets. Raise :exc:`SystemError` if *set* is not an instance of :class:`set` or its subtype. @@ -156,7 +156,7 @@ subtypes but not for instances of :class:`frozenset` or its subtypes. .. 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 + object from the *set*. Return ``NULL`` on failure. Raise :exc:`KeyError` if the set is empty. Raise a :exc:`SystemError` if *set* is not an instance of :class:`set` or its subtype. diff --git a/Doc/c-api/slice.rst b/Doc/c-api/slice.rst index c6d761fe7fd1c9..8ff9995dcc6fcf 100644 --- a/Doc/c-api/slice.rst +++ b/Doc/c-api/slice.rst @@ -8,21 +8,21 @@ Slice Objects .. c:var:: PyTypeObject PySlice_Type - The type object for slice objects. This is the same as :class:`slice` in the + The type object for slice objects. This is the same as :class:`slice` in the Python layer. .. c:function:: int PySlice_Check(PyObject *ob) - Return true if *ob* is a slice object; *ob* must not be ``NULL``. This + Return true if *ob* is a slice object; *ob* must not be ``NULL``. This function always succeeds. .. c:function:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step) - Return a new slice object with the given values. The *start*, *stop*, and + 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 - the same names. Any of the values may be ``NULL``, in which case the + the same names. Any of the values may be ``NULL``, in which case the ``None`` will be used for the corresponding attribute. Return ``NULL`` with an exception set if @@ -48,9 +48,9 @@ Slice Objects .. c:function:: int PySlice_GetIndicesEx(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) - Usable replacement for :c:func:`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 + 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 normal slices. @@ -92,7 +92,7 @@ Slice Objects .. c:function:: int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) Extract the start, stop and step data members from a slice object as - C integers. Silently reduce values larger than ``PY_SSIZE_T_MAX`` to + C integers. Silently reduce values larger than ``PY_SSIZE_T_MAX`` to ``PY_SSIZE_T_MAX``, silently boost the start and stop values less than ``PY_SSIZE_T_MIN`` to ``PY_SSIZE_T_MIN``, and silently boost the step values less than ``-PY_SSIZE_T_MAX`` to ``-PY_SSIZE_T_MAX``. @@ -108,7 +108,7 @@ Slice Objects Out of bounds indices are clipped in a manner consistent with the handling of normal slices. - Return the length of the slice. Always successful. Doesn't call Python + Return the length of the slice. Always successful. Doesn't call Python code. .. versionadded:: 3.6.1 @@ -120,13 +120,13 @@ Ellipsis Object .. c:var:: PyTypeObject PyEllipsis_Type - The type of Python :const:`Ellipsis` object. Same as :class:`types.EllipsisType` + The type of Python :const:`Ellipsis` object. Same as :class:`types.EllipsisType` in the Python layer. .. c:var:: PyObject *Py_Ellipsis - The Python ``Ellipsis`` object. This object has no methods. Like + The Python ``Ellipsis`` object. This object has no methods. Like :c:data:`Py_None`, it is an :term:`immortal` singleton object. .. versionchanged:: 3.12 diff --git a/Doc/c-api/structures.rst b/Doc/c-api/structures.rst index 58dd915e04f619..0f80bf38ad6856 100644 --- a/Doc/c-api/structures.rst +++ b/Doc/c-api/structures.rst @@ -6,7 +6,7 @@ Common Object Structures ======================== There are a large number of structures which are used in the definition of -object types for Python. This section describes these structures and how they +object types for Python. This section describes these structures and how they are used. @@ -14,18 +14,18 @@ Base object types and macros ---------------------------- 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 +of the object's representation in memory. These are represented by the :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. Additional macros can be found +the definition of all other Python objects. Additional macros can be found under :ref:`reference counting `. .. c:type:: PyObject - All object types are extensions of this type. This is a type which + 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 - object. In a normal "release" build, it contains only the object's + object. In a normal "release" build, it contains only the object's reference count and a pointer to the corresponding type object. Nothing is actually declared to be a :c:type:`PyObject`, but every pointer to a Python object can be cast to a :c:expr:`PyObject*`. @@ -79,7 +79,7 @@ under :ref:`reference counting `. .. c:macro:: PyObject_HEAD This is a macro used when declaring new types which represent objects - without a varying length. The PyObject_HEAD macro expands to:: + without a varying length. The PyObject_HEAD macro expands to:: PyObject ob_base; @@ -191,7 +191,7 @@ under :ref:`reference counting `. .. c:macro:: PyObject_HEAD_INIT(type) This is a macro which expands to initialization values for a new - :c:type:`PyObject` type. This macro expands to:: + :c:type:`PyObject` type. This macro expands to:: _PyObject_EXTRA_INIT 1, type, @@ -214,9 +214,9 @@ Implementing functions and methods Type of the functions used to implement most Python callables in C. Functions of this type take two :c:expr:`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 + 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. The function signature is:: @@ -273,7 +273,7 @@ Implementing functions and methods .. c:type:: PyMethodDef - Structure used to describe a method of an extension type. This structure has + Structure used to describe a method of an extension type. This structure has four fields: .. c:member:: const char *ml_name @@ -294,7 +294,7 @@ Implementing functions and methods The :c:member:`~PyMethodDef.ml_meth` is a C function pointer. The functions may be of different -types, but they always return :c:expr:`PyObject*`. If the function is not of +types, but they always return :c:expr:`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:expr:`PyObject*`, it is common that the method implementation uses the @@ -312,7 +312,7 @@ There are these calling conventions: This is the typical calling convention, where the methods have the type :c:type:`PyCFunction`. The function expects two :c:expr:`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 + the module object. The second parameter (often called *args*) is a tuple object representing all arguments. This parameter is typically processed using :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_UnpackTuple`. @@ -331,7 +331,7 @@ There are these calling conventions: Methods with these flags must be of type :c:type:`PyCFunctionWithKeywords`. The function expects three parameters: *self*, *args*, *kwargs* where *kwargs* is a dictionary of all the keyword arguments or possibly ``NULL`` - if there are no keyword arguments. The parameters are typically processed + if there are no keyword arguments. The parameters are typically processed using :c:func:`PyArg_ParseTupleAndKeywords`. @@ -360,7 +360,7 @@ There are these calling conventions: there is an additional fourth :c:expr:`PyObject*` parameter which is a tuple representing the names of the keyword arguments (which are guaranteed to be strings) - or possibly ``NULL`` if there are no keywords. The values of the keyword + or possibly ``NULL`` if there are no keywords. The values of the keyword arguments are stored in the *args* array, after the positional arguments. .. versionadded:: 3.7 @@ -390,9 +390,9 @@ There are these calling conventions: .. c:macro:: METH_NOARGS Methods without parameters don't need to check whether arguments are given if - they are listed with the :c:macro:`METH_NOARGS` flag. They need to be of type - :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 + they are listed with the :c:macro:`METH_NOARGS` flag. They need to be of type + :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``. The function must have 2 parameters. Since the second parameter is unused, @@ -408,8 +408,8 @@ There are these calling conventions: These two constants are not used to indicate the calling convention but the -binding when use with methods of classes. These may not be used for functions -defined for modules. At most one of these flags may be set for any given +binding when use with methods of classes. These may not be used for functions +defined for modules. At most one of these flags may be set for any given method. @@ -418,7 +418,7 @@ method. .. index:: pair: built-in function; classmethod The method will be passed the type object as the first parameter rather - than an instance of the type. This is used to create *class methods*, + than an instance of the type. This is used to create *class methods*, similar to what is created when using the :func:`classmethod` built-in function. @@ -428,7 +428,7 @@ method. .. index:: pair: built-in function; staticmethod The method will be passed ``NULL`` as the first parameter rather than an - instance of the type. This is used to create *static methods*, similar to + instance of the type. This is used to create *static methods*, similar to what is created when using the :func:`staticmethod` built-in function. One other constant controls whether a method is loaded in place of another @@ -437,14 +437,14 @@ definition with the same method name. .. c:macro:: METH_COEXIST - The method will be loaded in place of existing definitions. Without - *METH_COEXIST*, the default is to skip repeated definitions. Since slot + The method will be loaded in place of existing definitions. Without + *METH_COEXIST*, the default is to skip repeated definitions. Since slot wrappers are loaded before the method table, the existence of a *sq_contains* slot, for example, would generate a wrapped method named :meth:`~object.__contains__` and preclude the loading of a corresponding - PyCFunction with the same name. With the flag defined, the PyCFunction + PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in place of the wrapper object and will co-exist with the - slot. This is helpful because calls to PyCFunctions are optimized more + slot. This is helpful because calls to PyCFunctions are optimized more than wrapper object calls. .. c:function:: PyObject * PyCMethod_New(PyMethodDef *ml, PyObject *self, PyObject *module, PyTypeObject *cls) @@ -539,7 +539,7 @@ Accessing attributes of extension types static PyMemberDef spam_type_members[] = { {"__vectorcalloffset__", Py_T_PYSSIZET, offsetof(Spam_object, vectorcall), Py_READONLY}, - {NULL} /* Sentinel */ + {NULL} /* Sentinel */ }; (You may need to ``#include `` for :c:func:`!offsetof`.) @@ -563,8 +563,8 @@ Accessing attributes of extension types .. c:function:: PyObject* PyMember_GetOne(const char *obj_addr, struct PyMemberDef *m) - Get an attribute belonging to the object at address *obj_addr*. The - attribute is described by ``PyMemberDef`` *m*. Returns ``NULL`` + Get an attribute belonging to the object at address *obj_addr*. The + attribute is described by ``PyMemberDef`` *m*. Returns ``NULL`` on error. .. versionchanged:: 3.12 @@ -575,7 +575,7 @@ Accessing attributes of extension types .. c:function:: int PyMember_SetOne(char *obj_addr, struct PyMemberDef *m, PyObject *o) Set an attribute belonging to the object at address *obj_addr* to object *o*. - The attribute to set is described by ``PyMemberDef`` *m*. Returns ``0`` + The attribute to set is described by ``PyMemberDef`` *m*. Returns ``0`` if successful and a negative value on failure. .. versionchanged:: 3.12 diff --git a/Doc/c-api/sys.rst b/Doc/c-api/sys.rst index b34936dd55e94c..d05a34bb82b2e3 100644 --- a/Doc/c-api/sys.rst +++ b/Doc/c-api/sys.rst @@ -22,8 +22,8 @@ Operating System Utilities .. 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 :c:member:`PyConfig.interactive` is non-zero, this function + deemed interactive. This is the case for files for which ``isatty(fileno(fp))`` + is true. If the :c:member:`PyConfig.interactive` is non-zero, this function also returns true if the *filename* pointer is ``NULL`` or if the name is equal to one of the strings ``''`` or ``'???'``. @@ -32,7 +32,7 @@ Operating System Utilities .. c:function:: void PyOS_BeforeFork() - Function to prepare some internal state before a process fork. This + Function to prepare some internal state before a process fork. This should be called before calling :c:func:`fork` or any similar function that clones the current process. Only available on systems where :c:func:`fork` is defined. @@ -40,7 +40,7 @@ Operating System Utilities .. warning:: The C :c:func:`fork` call should only be made from the :ref:`"main" thread ` (of the - :ref:`"main" interpreter `). The same is + :ref:`"main" interpreter `). The same is true for ``PyOS_BeforeFork()``. .. versionadded:: 3.7 @@ -48,7 +48,7 @@ Operating System Utilities .. c:function:: void PyOS_AfterFork_Parent() - Function to update some internal state after a process fork. This + Function to update some internal state after a process fork. This should be called from the parent process after calling :c:func:`fork` or any similar function that clones the current process, regardless of whether process cloning was successful. @@ -57,7 +57,7 @@ Operating System Utilities .. warning:: The C :c:func:`fork` call should only be made from the :ref:`"main" thread ` (of the - :ref:`"main" interpreter `). The same is + :ref:`"main" interpreter `). The same is true for ``PyOS_AfterFork_Parent()``. .. versionadded:: 3.7 @@ -74,7 +74,7 @@ Operating System Utilities .. warning:: The C :c:func:`fork` call should only be made from the :ref:`"main" thread ` (of the - :ref:`"main" interpreter `). The same is + :ref:`"main" interpreter `). The same is true for ``PyOS_AfterFork_Child()``. .. versionadded:: 3.7 @@ -82,7 +82,7 @@ Operating System Utilities .. seealso:: :func:`os.register_at_fork` allows registering custom Python functions to be called by :c:func:`PyOS_BeforeFork()`, - :c:func:`PyOS_AfterFork_Parent` and :c:func:`PyOS_AfterFork_Child`. + :c:func:`PyOS_AfterFork_Parent` and :c:func:`PyOS_AfterFork_Child`. .. c:function:: void PyOS_AfterFork() @@ -100,27 +100,27 @@ Operating System Utilities .. index:: single: USE_STACKCHECK (C macro) - Return true when the interpreter runs out of stack space. This is a reliable + Return true when the interpreter runs out of stack space. This is a reliable check, but is only available when :c:macro:`!USE_STACKCHECK` is defined (currently on certain versions of Windows using the Microsoft Visual C++ compiler). :c:macro:`!USE_STACKCHECK` will be defined automatically; you should never change the definition in your own code. -.. c:type:: void (*PyOS_sighandler_t)(int) +.. c:type:: void (*PyOS_sighandler_t)(int) .. c:function:: PyOS_sighandler_t PyOS_getsig(int i) - Return the current signal handler for signal *i*. This is a thin wrapper around - either :c:func:`!sigaction` or :c:func:`!signal`. Do not call those functions + Return the current signal handler for signal *i*. This is a thin wrapper around + either :c:func:`!sigaction` or :c:func:`!signal`. Do not call those functions directly! .. 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 :c:func:`!sigaction` or :c:func:`!signal`. Do + This is a thin wrapper around either :c:func:`!sigaction` or :c:func:`!signal`. Do not call those functions directly! .. c:function:: wchar_t* Py_DecodeLocale(const char* arg, size_t *size) @@ -187,7 +187,7 @@ Operating System Utilities error. If error_pos is not ``NULL``, ``*error_pos`` is set to ``(size_t)-1`` on - success, or set to the index of the invalid character on encoding error. + success, or set to the index of the invalid character on encoding error. The :term:`filesystem encoding and error handler` are selected by :c:func:`PyConfig_Read`: see :c:member:`~PyConfig.filesystem_encoding` and @@ -255,7 +255,7 @@ System Functions ================ 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 +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. .. c:function:: PyObject *PySys_GetAttr(PyObject *name) @@ -326,7 +326,7 @@ accessible to C code. They all work with the current interpreter thread's .. c:function:: void PySys_WriteStdout(const char *format, ...) - Write the output string described by *format* to :data:`sys.stdout`. No + Write the output string described by *format* to :data:`sys.stdout`. No exceptions are raised, even if truncation occurs (see below). *format* should limit the total size of the formatted output string to @@ -334,7 +334,7 @@ accessible to C code. They all work with the current interpreter thread's In particular, this means that no unrestricted "%s" formats should occur; these should be limited using "%.s" where is a decimal number calculated so that plus the maximum size of other formatted text does not - exceed 1000 bytes. Also watch out for "%f", which can print hundreds of + exceed 1000 bytes. Also watch out for "%f", which can print hundreds of digits for very large numbers. If a problem occurs, or :data:`sys.stdout` is unset, the formatted message @@ -363,7 +363,7 @@ accessible to C code. They all work with the current interpreter thread's .. c:function:: PyObject *PySys_GetXOptions() Return the current dictionary of :option:`-X` options, similarly to - :data:`sys._xoptions`. On error, ``NULL`` is returned and an exception is + :data:`sys._xoptions`. On error, ``NULL`` is returned and an exception is set. .. versionadded:: 3.2 @@ -428,7 +428,7 @@ accessible to C code. They all work with the current interpreter thread's The hook function is always called with an :term:`attached thread state` by the Python interpreter that raised the event. - See :pep:`578` for a detailed description of auditing. Functions in the + See :pep:`578` for a detailed description of auditing. Functions in the runtime and standard library that raise events are listed in the :ref:`audit events table `. Details are in each function's documentation. @@ -463,10 +463,10 @@ Process Control .. index:: single: abort (C function) - Print a fatal error message and kill the process. No cleanup is performed. + Print a fatal error message and kill the process. No cleanup is performed. 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 + object administration appears to be corrupted. On Unix, the standard C library function :c:func:`!abort` is called which will attempt to produce a :file:`core` file. @@ -484,8 +484,8 @@ Process Control single: Py_FinalizeEx (C function) single: exit (C function) - Exit the current process. This calls :c:func:`Py_FinalizeEx` and then calls the - standard C library function ``exit(status)``. If :c:func:`Py_FinalizeEx` + Exit the current process. This calls :c:func:`Py_FinalizeEx` and then calls the + standard C library function ``exit(status)``. If :c:func:`Py_FinalizeEx` indicates an error, the exit status is set to 120. .. versionchanged:: 3.6 @@ -498,12 +498,12 @@ Process Control single: Py_FinalizeEx (C function) single: cleanup functions - Register a cleanup function to be called by :c:func:`Py_FinalizeEx`. 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, - :c:func:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup + Register a cleanup function to be called by :c:func:`Py_FinalizeEx`. 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, + :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 + at most once. Since Python's internal finalization will have completed before the cleanup function, no Python APIs should be called by *func*. .. seealso:: diff --git a/Doc/c-api/tuple.rst b/Doc/c-api/tuple.rst index 815afddad19df1..9c6af322c58e94 100644 --- a/Doc/c-api/tuple.rst +++ b/Doc/c-api/tuple.rst @@ -22,13 +22,13 @@ Tuple Objects .. 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. This function always succeeds. + tuple type. This function always succeeds. .. 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. This function always succeeds. + tuple type. This function always succeeds. .. c:function:: PyObject* PyTuple_New(Py_ssize_t len) @@ -58,7 +58,7 @@ Tuple Objects .. 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 + Return the object at position *pos* in the tuple pointed to by *p*. If *pos* is negative or out of bounds, return ``NULL`` and set an :exc:`IndexError` exception. The returned reference is borrowed from the tuple *p* @@ -85,7 +85,7 @@ Tuple Objects .. 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. If *pos* is out of bounds, return ``-1`` + *p*. Return ``0`` on success. If *pos* is out of bounds, return ``-1`` and set an :exc:`IndexError` exception. .. note:: @@ -118,15 +118,15 @@ Tuple Objects .. 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. + 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 - is only one reference to the object. Do *not* use this if the tuple may already - be known to some other part of the code. The tuple will always grow or shrink - at the end. Think of this as destroying the old tuple and creating a new one, - only more efficiently. Returns ``0`` on success. Client code should never + is only one reference to the object. Do *not* use this if the tuple may already + be known to some other part of the code. The tuple will always grow or shrink + at the end. Think of this as destroying the old tuple and creating a new one, + only more efficiently. Returns ``0`` on success. Client code should never assume that the resulting value of ``*p`` will be the same as before calling this function. If the object referenced by ``*p`` is replaced, the original - ``*p`` is destroyed. On failure, returns ``-1`` and sets ``*p`` to ``NULL``, and + ``*p`` is destroyed. On failure, returns ``-1`` and sets ``*p`` to ``NULL``, and raises :exc:`MemoryError` or :exc:`SystemError`. @@ -186,7 +186,7 @@ type. .. c:type:: PyStructSequence_Field Describes a field of a struct sequence. As a struct sequence is modeled as a - tuple, all fields are typed as :c:expr:`PyObject*`. The index in the + tuple, all fields are typed as :c:expr:`PyObject*`. The index in the :c:member:`~PyStructSequence_Desc.fields` array of the :c:type:`PyStructSequence_Desc` determines which field of the struct sequence is described. @@ -235,7 +235,7 @@ type. .. c:function:: void PyStructSequence_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o) - Sets the field at index *pos* of the struct sequence *p* to value *o*. Like + Sets the field at index *pos* of the struct sequence *p* to value *o*. Like :c:func:`PyTuple_SET_ITEM`, this should only be used to fill in brand new instances. diff --git a/Doc/c-api/type.rst b/Doc/c-api/type.rst index 5bdbff4e0ad990..b7c9b6ce3bf1f7 100644 --- a/Doc/c-api/type.rst +++ b/Doc/c-api/type.rst @@ -22,14 +22,14 @@ Type Objects .. c:function:: int PyType_Check(PyObject *o) Return non-zero if the object *o* is a type object, including instances of - types derived from the standard type object. Return 0 in all other cases. + types derived from the standard type object. Return 0 in all other cases. This function always succeeds. .. c:function:: int PyType_CheckExact(PyObject *o) Return non-zero if the object *o* is a type object, but not a subtype of - the standard type object. Return 0 in all other cases. This function + the standard type object. Return 0 in all other cases. This function always succeeds. @@ -71,7 +71,7 @@ Type Objects .. 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 + subtypes. This function must be called after any manual modification of the attributes or base classes of the type. @@ -144,7 +144,7 @@ Type Objects Return true if *a* is a subtype of *b*. This function only checks for actual subtypes, which means that - :meth:`~type.__subclasscheck__` is not called on *b*. Call + :meth:`~type.__subclasscheck__` is not called on *b*. Call :c:func:`PyObject_IsSubclass` to do the same check that :func:`issubclass` would do. @@ -152,7 +152,7 @@ Type Objects .. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) Generic handler for the :c:member:`~PyTypeObject.tp_alloc` slot of a type - object. Uses Python's default memory allocation mechanism to allocate memory + object. Uses Python's default memory allocation mechanism to allocate memory for a new instance, zeros the memory, then initializes the memory as if by calling :c:func:`PyObject_Init` or :c:func:`PyObject_InitVar`. @@ -172,14 +172,14 @@ Type Objects .. c:function:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) Generic handler for the :c:member:`~PyTypeObject.tp_new` slot of a type - object. Creates a new instance using the type's + object. Creates a new instance using the type's :c:member:`~PyTypeObject.tp_alloc` slot and returns the resulting object. .. 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 - from a type's base class. Return ``0`` on success, or return ``-1`` and sets an + Finalize a type object. This should be called on all type objects to finish + their initialization. This function is responsible for adding inherited slots + from a type's base class. Return ``0`` on success, or return ``-1`` and sets an exception on error. .. note:: @@ -378,7 +378,7 @@ The following functions and structs are used to create .. versionchanged:: 3.12 The function now finds and uses a metaclass corresponding to the provided - base classes. Previously, only :class:`type` instances were returned. + base classes. Previously, only :class:`type` instances were returned. The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*. which may result in incomplete initialization. @@ -399,7 +399,7 @@ The following functions and structs are used to create .. versionchanged:: 3.12 The function now finds and uses a metaclass corresponding to the provided - base classes. Previously, only :class:`type` instances were returned. + base classes. Previously, only :class:`type` instances were returned. The :c:member:`~PyTypeObject.tp_new` of the metaclass is *ignored*. which may result in incomplete initialization. @@ -588,7 +588,7 @@ The following functions and structs are used to create .. versionchanged:: 3.14 The field :c:member:`~PyTypeObject.tp_vectorcall` can now set - using ``Py_tp_vectorcall``. See the field's documentation + using ``Py_tp_vectorcall``. See the field's documentation for details. .. c:member:: void *pfunc diff --git a/Doc/c-api/typehints.rst b/Doc/c-api/typehints.rst index 98fe68737deb81..55f2390b1d5b8b 100644 --- a/Doc/c-api/typehints.rst +++ b/Doc/c-api/typehints.rst @@ -5,24 +5,24 @@ Objects for Type Hinting ------------------------ -Various built-in types for type hinting are provided. Currently, +Various built-in types for type hinting are provided. Currently, two types exist -- :ref:`GenericAlias ` and -:ref:`Union `. Only ``GenericAlias`` is exposed to C. +:ref:`Union `. Only ``GenericAlias`` is exposed to C. .. c:function:: PyObject* Py_GenericAlias(PyObject *origin, PyObject *args) Create a :ref:`GenericAlias ` object. Equivalent to calling the Python class - :class:`types.GenericAlias`. The *origin* and *args* arguments set the + :class:`types.GenericAlias`. The *origin* and *args* arguments set the ``GenericAlias``\ 's ``__origin__`` and ``__args__`` attributes respectively. *origin* should be a :c:expr:`PyTypeObject*`, and *args* can be a - :c:expr:`PyTupleObject*` or any ``PyObject*``. If *args* passed is + :c:expr:`PyTupleObject*` or any ``PyObject*``. If *args* passed is not a tuple, a 1-tuple is automatically constructed and ``__args__`` is set to ``(args,)``. Minimal checking is done for the arguments, so the function will succeed even if *origin* is not a type. The ``GenericAlias``\ 's ``__parameters__`` attribute is constructed lazily - from ``__args__``. On failure, an exception is raised and ``NULL`` is + from ``__args__``. On failure, an exception is raised and ``NULL`` is returned. Here's an example of how to make an extension type generic:: diff --git a/Doc/c-api/typeobj.rst b/Doc/c-api/typeobj.rst index 060d6f60174b41..590603f9a1a227 100644 --- a/Doc/c-api/typeobj.rst +++ b/Doc/c-api/typeobj.rst @@ -6,7 +6,7 @@ Type Object Structures ====================== Perhaps one of the most important structures of the Python object system is the -structure that defines a new type: the :c:type:`PyTypeObject` structure. Type +structure that defines a new type: the :c:type:`PyTypeObject` structure. Type objects can be handled using any of the ``PyObject_*`` or ``PyType_*`` functions, but do not offer much that's interesting to most Python applications. These objects are fundamental to how objects behave, so @@ -16,8 +16,8 @@ that implements new types. Type objects are fairly large compared to most of the standard types. The reason for the size is that each type object stores a large number of values, mostly C function pointers, each of which implements a small part of the type's -functionality. The fields of the type object are examined in detail in this -section. The fields will be described in the order in which they occur in the +functionality. The fields of the type object are examined in detail in this +section. The fields will be described in the order in which they occur in the structure. In addition to the following quick reference, the :ref:`typedef-examples` @@ -163,11 +163,11 @@ Quick Reference .. [#cols] Columns: - **"O"**: set on :c:data:`PyBaseObject_Type` + **"O"**: set on :c:data:`PyBaseObject_Type` - **"T"**: set on :c:data:`PyType_Type` + **"T"**: set on :c:data:`PyType_Type` - **"D"**: default (if slot is set to ``NULL``) + **"D"**: default (if slot is set to ``NULL``) .. code-block:: none @@ -177,7 +177,7 @@ Quick Reference Also see the inheritance column ("I"). - **"I"**: inheritance + **"I"**: inheritance .. code-block:: none @@ -474,7 +474,7 @@ PyTypeObject Definition ----------------------- The structure definition for :c:type:`PyTypeObject` can be found in -:file:`Include/cpython/object.h`. For convenience of reference, this repeats the +:file:`Include/cpython/object.h`. For convenience of reference, this repeats the definition found there: .. XXX Drop this? @@ -495,9 +495,9 @@ type objects) *must* have the :c:member:`~PyVarObject.ob_size` field. :c:member:`PyObject.ob_refcnt` The type object's reference count is initialized to ``1`` by the - ``PyObject_HEAD_INIT`` macro. Note that for :ref:`statically allocated type + ``PyObject_HEAD_INIT`` macro. Note that for :ref:`statically allocated type objects `, the type's instances (objects whose :c:member:`~PyObject.ob_type` - points back to the type) do *not* count as references. But for + points back to the type) do *not* count as references. But for :ref:`dynamically allocated type objects `, the instances *do* count as references. @@ -508,13 +508,13 @@ type objects) *must* have the :c:member:`~PyVarObject.ob_size` field. :c:member:`PyObject.ob_type` - This is the type's type, in other words its metatype. It is initialized by the + 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 - ``&PyType_Type``. However, for dynamically loadable extension modules that must + ``&PyType_Type``. However, for dynamically loadable extension modules that must be usable on Windows (at least), the compiler complains that this is not a valid - initializer. Therefore, the convention is to pass ``NULL`` to the + initializer. Therefore, the convention is to pass ``NULL`` to the ``PyObject_HEAD_INIT`` macro and to initialize this field explicitly at the - start of the module's initialization function, before doing anything else. This + start of the module's initialization function, before doing anything else. This is typically done like this:: Foo_Type.ob_type = &PyType_Type; @@ -548,9 +548,9 @@ PyVarObject Slots PyTypeObject Slots ------------------ -Each slot has a section describing inheritance. If :c:func:`PyType_Ready` +Each slot has a section describing inheritance. If :c:func:`PyType_Ready` may set a value when the field is set to ``NULL`` then there will also be -a "Default" section. (Note that many fields set on :c:data:`PyBaseObject_Type` +a "Default" section. (Note that many fields set on :c:data:`PyBaseObject_Type` and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: const char* PyTypeObject.tp_name @@ -558,8 +558,8 @@ and :c:data:`PyType_Type` effectively act as defaults.) 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 name, followed by a dot, followed by the type name; for built-in types, it - should be just the type name. If the module is a submodule of a package, the - full package name is part of the full module name. For example, a type named + should be just the type name. If the module is a submodule of a package, the + full package name is part of the full module name. For example, a type named :class:`!T` defined in module :mod:`!M` in subpackage :mod:`!Q` in package :mod:`!P` should have the :c:member:`~PyTypeObject.tp_name` initializer ``"P.Q.M.T"``. @@ -576,11 +576,11 @@ and :c:data:`PyType_Type` effectively act as defaults.) If no dot is present, the entire :c:member:`~PyTypeObject.tp_name` field is made accessible as the :attr:`~type.__name__` attribute, and the :attr:`~type.__module__` attribute is undefined - (unless explicitly set in the dictionary, as explained above). This means your - type will be impossible to pickle. Additionally, it will not be listed in + (unless explicitly set in the dictionary, as explained above). This means your + type will be impossible to pickle. Additionally, it will not be listed in module documentations created with pydoc. - This field must not be ``NULL``. It is the only required field + This field must not be ``NULL``. It is the only required field in :c:func:`PyTypeObject` (other than potentially :c:member:`~PyTypeObject.tp_itemsize`). @@ -596,7 +596,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) There are two kinds of types: types with fixed-length instances have a zero :c:member:`!tp_itemsize` field, types with variable-length instances have a non-zero - :c:member:`!tp_itemsize` field. For a type with fixed-length instances, all + :c:member:`!tp_itemsize` field. For a type with fixed-length instances, all instances have the same size, given in :c:member:`!tp_basicsize`. (Exceptions to this rule can be made using :c:func:`PyUnstable_Object_GC_NewWithExtraData`.) @@ -630,7 +630,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) :c:member:`~PyTypeObject.tp_base`, plus any extra data needed by each instance. - The correct way to set :c:member:`!tp_basicsize` is to use the + The correct way to set :c:member:`!tp_basicsize` is to use the ``sizeof`` operator on the struct used to declare the instance layout. This struct must include the struct used to declare the base type. In other words, :c:member:`!tp_basicsize` must be greater than or equal @@ -676,7 +676,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: destructor PyTypeObject.tp_dealloc - A pointer to the instance destructor function. The function signature is:: + A pointer to the instance destructor function. The function signature is:: void tp_dealloc(PyObject *self); @@ -729,12 +729,12 @@ and :c:data:`PyType_Type` effectively act as defaults.) It is permissible to call :c:member:`~PyTypeObject.tp_clear` from :c:member:`!tp_dealloc` to reduce code duplication and to guarantee that the - object is always cleared before destruction. Beware that + object is always cleared before destruction. Beware that :c:member:`!tp_clear` might have already been called. If the type is heap allocated (:c:macro:`Py_TPFLAGS_HEAPTYPE`), the deallocator should release the owned reference to its type object (via - :c:func:`Py_DECREF`) after calling the type deallocator. See the example + :c:func:`Py_DECREF`) after calling the type deallocator. See the example code below.:: static void @@ -746,7 +746,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) Py_TYPE(self)->tp_free(self); } - :c:member:`!tp_dealloc` must leave the exception status unchanged. If it + :c:member:`!tp_dealloc` must leave the exception status unchanged. If it needs to call something that might raise an exception, the exception state must be backed up first and restored later (after logging any exceptions with :c:func:`PyErr_WriteUnraisable`). @@ -777,7 +777,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) // Any additional destruction goes here. tp->tp_free(self); - self = NULL; // In case PyErr_WriteUnraisable() is called below. + self = NULL; // In case PyErr_WriteUnraisable() is called below. if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE) { Py_CLEAR(tp); @@ -795,9 +795,9 @@ and :c:data:`PyType_Type` effectively act as defaults.) :c:member:`!tp_dealloc` may be called from any Python thread, not just the thread which created the object (if the object becomes part of a refcount cycle, that cycle might be collected by - a garbage collection on any thread). This is not a problem for Python + a garbage collection on any thread). This is not a problem for Python API calls, since the thread on which :c:member:`!tp_dealloc` is called - with an :term:`attached thread state`. However, if the object being + with an :term:`attached thread state`. However, if the object being destroyed in turn destroys objects from some other C library, care should be taken to ensure that destroying those objects on the thread which called :c:member:`!tp_dealloc` will not violate any assumptions of @@ -862,7 +862,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) An optional pointer to the get-attribute-string function. - This field is deprecated. When it is defined, it should point to a function + This field is deprecated. When it is defined, it should point to a function that acts the same as the :c:member:`~PyTypeObject.tp_getattro` function, but taking a C string instead of a Python string object to give the attribute name. @@ -879,7 +879,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) An optional pointer to the function for setting and deleting attributes. - This field is deprecated. When it is defined, it should point to a function + This field is deprecated. When it is defined, it should point to a function that acts the same as the :c:member:`~PyTypeObject.tp_setattro` function, but taking a C string instead of a Python string object to give the attribute name. @@ -896,7 +896,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) Pointer to an additional structure that contains fields relevant only to objects which implement :term:`awaitable` and :term:`asynchronous iterator` - protocols at the C-level. See :ref:`async-structs` for details. + protocols at the C-level. See :ref:`async-structs` for details. .. versionadded:: 3.5 Formerly known as ``tp_compare`` and ``tp_reserved``. @@ -918,10 +918,10 @@ and :c:data:`PyType_Type` effectively act as defaults.) PyObject *tp_repr(PyObject *self); - The function must return a string or a Unicode object. Ideally, + The function 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 + same value. If this is not feasible, it should return a string starting with ``'<'`` and ending with ``'>'`` from which both the type and the value of the object can be deduced. @@ -939,7 +939,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: PyNumberMethods* PyTypeObject.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 + objects which implement the number protocol. These fields are documented in :ref:`number-structs`. **Inheritance:** @@ -951,7 +951,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: PySequenceMethods* PyTypeObject.tp_as_sequence Pointer to an additional structure that contains fields relevant only to - objects which implement the sequence protocol. These fields are documented + objects which implement the sequence protocol. These fields are documented in :ref:`sequence-structs`. **Inheritance:** @@ -963,7 +963,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: PyMappingMethods* PyTypeObject.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 + objects which implement the mapping protocol. These fields are documented in :ref:`mapping-structs`. **Inheritance:** @@ -1015,8 +1015,8 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. 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 + 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 :c:func:`PyObject_Call`:: PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs); @@ -1029,15 +1029,15 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. 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 :c:func:`PyObject_Str` to do + :func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls the + 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 :c:func:`PyObject_Str`:: PyObject *tp_str(PyObject *self); - The function must return a string or a Unicode object. It should be a "friendly" string + The function must return a string or a Unicode object. It should be a "friendly" string representation of the object, as this is the representation that will be used, among other things, by the :func:`print` function. @@ -1084,7 +1084,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) int tp_setattro(PyObject *self, PyObject *attr, PyObject *value); In addition, setting *value* to ``NULL`` to delete an attribute must be - supported. It is usually convenient to set this field to + supported. It is usually convenient to set this field to :c:func:`PyObject_GenericSetAttr`, which implements the normal way of setting object attributes. @@ -1104,7 +1104,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. 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 + which implement the buffer interface. These fields are documented in :ref:`buffer-structs`. **Inheritance:** @@ -1115,7 +1115,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: unsigned long PyTypeObject.tp_flags - This field is a bit mask of various flags. Some flags indicate variant + This field is a bit mask of various flags. Some flags indicate variant semantics for certain situations; others are used to indicate that certain fields in the type object (or in the extension structures referenced via :c:member:`~PyTypeObject.tp_as_number`, :c:member:`~PyTypeObject.tp_as_sequence`, :c:member:`~PyTypeObject.tp_as_mapping`, and @@ -1125,12 +1125,12 @@ and :c:data:`PyType_Type` effectively act as defaults.) **Inheritance:** - Inheritance of this field is complicated. Most flag bits are inherited + Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag bit set, the subtype inherits - this flag bit. The flag bits that pertain to extension structures are strictly + this flag bit. The flag bits that pertain to extension structures are strictly inherited if the extension structure is inherited, i.e. the base type's value of the flag bit is copied into the subtype together with a pointer to the extension - structure. The :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with + structure. The :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields, i.e. if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is clear in the subtype and the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields in the subtype exist and have @@ -1148,14 +1148,14 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:namespace:: NULL The following bit masks are currently defined; these can be ORed together using - the ``|`` operator to form the value of the :c:member:`~PyTypeObject.tp_flags` field. The macro + the ``|`` operator to form the value of the :c:member:`~PyTypeObject.tp_flags` field. The macro :c:func:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and checks whether ``tp->tp_flags & f`` is non-zero. .. c:macro:: Py_TPFLAGS_HEAPTYPE This bit is set when the type object itself is allocated on the heap, for - example, types created dynamically using :c:func:`PyType_FromSpec`. In this + example, types created dynamically using :c:func:`PyType_FromSpec`. In this case, the :c:member:`~PyObject.ob_type` field of its instances is considered a reference to the type, and the type object is INCREF'ed when a new instance is created, and DECREF'ed when an instance is destroyed (this does not apply to instances of @@ -1170,7 +1170,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:macro:: Py_TPFLAGS_BASETYPE - This bit is set when the type can be used as the base type of another type. If + This bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to a "final" class in Java). @@ -1201,11 +1201,11 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:macro:: Py_TPFLAGS_HAVE_GC - This bit is set when the object supports garbage collection. If this bit + This bit is set when the object supports garbage collection. If this bit is set, memory for new instances (see :c:member:`~PyTypeObject.tp_alloc`) must be allocated using :c:macro:`PyObject_GC_New` or :c:func:`PyType_GenericAlloc` and deallocated (see - :c:member:`~PyTypeObject.tp_free`) using :c:func:`PyObject_GC_Del`. More + :c:member:`~PyTypeObject.tp_free`) using :c:func:`PyObject_GC_Del`. More information in section :ref:`supporting-cycle-detection`. **Inheritance:** @@ -1214,7 +1214,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) The :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` - fields, i.e. if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is + fields, i.e. if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is clear in the subtype and the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields in the subtype exist and have ``NULL`` values. @@ -1252,7 +1252,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) **Inheritance:** This flag is never inherited by types without the - :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` flag set. For extension types, it is + :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` flag set. For extension types, it is inherited whenever :c:member:`~PyTypeObject.tp_descr_get` is inherited. .. c:macro:: Py_TPFLAGS_MANAGED_DICT @@ -1461,7 +1461,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: const 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:`~type.__doc__` attribute on the + type object. This is exposed as the :attr:`~type.__doc__` attribute on the type and instances of the type. **Inheritance:** @@ -1471,8 +1471,8 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: traverseproc PyTypeObject.tp_traverse - An optional pointer to a traversal function for the garbage collector. This is - only used if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is set. The signature is:: + An optional pointer to a traversal function for the garbage collector. This is + only used if the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit is set. The signature is:: int tp_traverse(PyObject *self, visitproc visit, void *arg); @@ -1496,7 +1496,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) } 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 + 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. On the other hand, even if you know a member can never be part of a cycle, as a @@ -1551,7 +1551,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. versionchanged:: 3.9 Heap-allocated types are expected to visit ``Py_TYPE(self)`` in - ``tp_traverse``. In earlier versions of Python, due to + ``tp_traverse``. In earlier versions of Python, due to `bug 40217 `_, doing this may lead to crashes in subclasses. @@ -1567,20 +1567,20 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: inquiry PyTypeObject.tp_clear - An optional pointer to a clear function. The signature is:: + An optional pointer to a clear function. The signature is:: int tp_clear(PyObject *); The purpose of this function is to break reference cycles that are causing a - :term:`cyclic isolate` so that the objects can be safely destroyed. A + :term:`cyclic isolate` so that the objects can be safely destroyed. A cleared object is a partially destroyed object; the object is not obligated to satisfy design invariants held during normal use. :c:member:`!tp_clear` does not need to delete references to objects that can't participate in reference cycles, such as Python strings or Python - integers. However, it may be convenient to clear all references, and write + integers. However, it may be convenient to clear all references, and write the type's :c:member:`~PyTypeObject.tp_dealloc` function to invoke - :c:member:`!tp_clear` to avoid code duplication. (Beware that + :c:member:`!tp_clear` to avoid code duplication. (Beware that :c:member:`!tp_clear` might have already been called. Prefer calling idempotent functions like :c:func:`Py_CLEAR`.) @@ -1591,7 +1591,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) If :c:member:`!tp_clear` fails to break a reference cycle then the objects in the :term:`cyclic isolate` may remain indefinitely - uncollectable ("leak"). See :data:`gc.garbage`. + uncollectable ("leak"). See :data:`gc.garbage`. .. note:: @@ -1612,18 +1612,18 @@ and :c:data:`PyType_Type` effectively act as defaults.) (:c:member:`~PyTypeObject.tp_dealloc`) in the following ways: * The purpose of clearing an object is to remove references to other objects - that might participate in a reference cycle. The purpose of the + that might participate in a reference cycle. The purpose of the destructor, on the other hand, is a superset: it must release *all* resources it owns, including references to objects that cannot participate in a reference cycle (e.g., integers) as well as the object's own memory (by calling :c:member:`~PyTypeObject.tp_free`). * When :c:member:`!tp_clear` is called, other objects might still hold - references to the object being cleared. Because of this, + references to the object being cleared. Because of this, :c:member:`!tp_clear` must not deallocate the object's own memory - (:c:member:`~PyTypeObject.tp_free`). The destructor, on the other hand, + (:c:member:`~PyTypeObject.tp_free`). The destructor, on the other hand, is only called when no (strong) references exist, and as such, must safely destroy the object itself by deallocating it. - * :c:member:`!tp_clear` might never be automatically called. An object's + * :c:member:`!tp_clear` might never be automatically called. An object's destructor, on the other hand, will be automatically called some time after the object becomes unreachable (i.e., either there are no references to the object or the object is a member of a :term:`cyclic isolate`). @@ -1635,14 +1635,14 @@ and :c:data:`PyType_Type` effectively act as defaults.) there is a reference to it and it is not a member of a :term:`cyclic isolate`. * Python will not automatically clear an object if it has not been - automatically finalized (see :c:member:`~PyTypeObject.tp_finalize`). (If + automatically finalized (see :c:member:`~PyTypeObject.tp_finalize`). (If the finalizer resurrected the object, the object may or may not be automatically finalized again before it is cleared.) * If an object is a member of a :term:`cyclic isolate`, Python will not automatically clear it if any member of the cyclic isolate has not yet been automatically finalized (:c:member:`~PyTypeObject.tp_finalize`). * Python will not destroy an object until after any automatic calls to its - :c:member:`!tp_clear` function have returned. This ensures that the act + :c:member:`!tp_clear` function have returned. This ensures that the act of breaking a reference cycle does not invalidate the ``self`` pointer while :c:member:`!tp_clear` is still executing. * Python will not automatically call :c:member:`!tp_clear` multiple times @@ -1653,13 +1653,13 @@ and :c:data:`PyType_Type` effectively act as defaults.) clear objects regularly before their destruction. Taken together, all :c:member:`~PyTypeObject.tp_clear` functions in the - system must combine to break all reference cycles. This is subtle, and if - in any doubt supply a :c:member:`~PyTypeObject.tp_clear` function. For + system must combine to break all reference cycles. This is subtle, and if + in any doubt supply a :c:member:`~PyTypeObject.tp_clear` function. For example, the tuple type does not implement a :c:member:`~PyTypeObject.tp_clear` function, because it's possible to prove - that no reference cycle can be composed entirely of tuples. Therefore the + that no reference cycle can be composed entirely of tuples. Therefore the :c:member:`~PyTypeObject.tp_clear` functions of other types are responsible - for breaking any cycle containing a tuple. This isn't immediately obvious, + for breaking any cycle containing a tuple. This isn't immediately obvious, and there's rarely a good reason to avoid implementing :c:member:`~PyTypeObject.tp_clear`. @@ -1679,15 +1679,15 @@ and :c:data:`PyType_Type` effectively act as defaults.) } The :c:func:`Py_CLEAR` macro should be used, because clearing references is - delicate: the reference to the contained object must not be released + delicate: the reference to the contained object must not be released (via :c:func:`Py_DECREF`) until - after the pointer to the contained object is set to ``NULL``. This is because + after the pointer to the contained object is set to ``NULL``. This is because releasing the reference may cause the contained object to become trash, triggering a chain of reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks, associated with 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 + so that *self* knows the contained object can no longer be used. The :c:func:`Py_CLEAR` macro performs the operations in a safe order. If the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit is set in the @@ -1723,7 +1723,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) that is defined by :c:type:`PyTypeObject`. The function should return the result of the comparison (usually ``Py_True`` - or ``Py_False``). If the comparison is undefined, it must return + or ``Py_False``). If the comparison is undefined, it must return ``Py_NotImplemented``, if another error occurred it must return ``NULL`` and set an exception condition. @@ -1776,7 +1776,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) **Default:** :c:data:`PyBaseObject_Type` provides a :c:member:`~PyTypeObject.tp_richcompare` - implementation, which may be inherited. However, if only + implementation, which may be inherited. However, if only :c:member:`~PyTypeObject.tp_hash` is defined, not even the inherited function is used and instances of the type will not be able to participate in any comparisons. @@ -1790,7 +1790,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) 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 - :c:func:`PyObject_ClearWeakRefs` and the ``PyWeakref_*`` functions. The + :c:func:`PyObject_ClearWeakRefs` and the ``PyWeakref_*`` functions. The instance structure needs to include a field of type :c:expr:`PyObject*` which is initialized to ``NULL``. @@ -1804,7 +1804,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means that the subtype uses a different weak - reference list head than the base type. Since the list head is always found via + reference list head than the base type. Since the list head is always found via :c:member:`~PyTypeObject.tp_weaklistoffset`, this should not be a problem. **Default:** @@ -1818,7 +1818,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: getiterfunc PyTypeObject.tp_iter An optional pointer to a function that returns an :term:`iterator` for the - object. Its presence normally signals that the instances of this type are + object. Its presence normally signals that the instances of this type are :term:`iterable` (although sequences may be iterable without this function). This function has the same signature as :c:func:`PyObject_GetIter`:: @@ -1838,8 +1838,8 @@ and :c:data:`PyType_Type` effectively act as defaults.) PyObject *tp_iternext(PyObject *self); When the iterator is exhausted, it must return ``NULL``; a :exc:`StopIteration` - exception may or may not be set. When another error occurs, it must return - ``NULL`` too. Its presence signals that the instances of this type are + exception may or may not be set. When another error occurs, it must return + ``NULL`` too. Its presence signals that the instances of this type are iterators. Iterator types should also define the :c:member:`~PyTypeObject.tp_iter` function, and that @@ -1898,7 +1898,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: PyTypeObject* PyTypeObject.tp_base - An optional pointer to a base type from which type properties are inherited. At + An optional pointer to a base type from which type properties are inherited. At this level, only single inheritance is supported; multiple inheritance require dynamically creating a type object by calling the metatype. @@ -1907,13 +1907,13 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. from Modules/xxmodule.c Slot initialization is subject to the rules of initializing globals. - C99 requires the initializers to be "address constants". Function + C99 requires the initializers to be "address constants". Function designators like :c:func:`PyType_GenericNew`, with implicit conversion to a pointer, are valid C99 address constants. However, the unary '&' operator applied to a non-static variable like :c:data:`PyBaseObject_Type` is not required to produce an address - constant. Compilers may support this (gcc does), MSVC does not. + constant. Compilers may support this (gcc does), MSVC does not. Both compilers are strictly standard conforming in this particular behavior. @@ -1936,9 +1936,9 @@ and :c:data:`PyType_Type` effectively act as defaults.) 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 :c:func:`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:`~object.__add__`). Once + correspond to overloaded operations (like :meth:`~object.__add__`). Once initialization for the type has finished, this field should be treated as read-only. @@ -2034,7 +2034,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) **Default:** - This slot has no default. For :ref:`static types `, if the + This slot has no default. For :ref:`static types `, if the field is ``NULL`` then no :attr:`~object.__dict__` gets created for instances. If the :c:macro:`Py_TPFLAGS_MANAGED_DICT` bit is set in the @@ -2047,7 +2047,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) An optional pointer to an instance initialization function. - This function corresponds to the :meth:`~object.__init__` method of classes. Like + This function corresponds to the :meth:`~object.__init__` method of classes. Like :meth:`!__init__`, it is possible to create an instance without calling :meth:`!__init__`, and it is possible to reinitialize an instance by calling its :meth:`!__init__` method again. @@ -2062,7 +2062,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) The :c:member:`~PyTypeObject.tp_init` function, if not ``NULL``, is called when an instance is created normally by calling its type, after the type's :c:member:`~PyTypeObject.tp_new` function - has returned an instance of the type. If the :c:member:`~PyTypeObject.tp_new` function returns an + has returned an instance of the type. If the :c:member:`~PyTypeObject.tp_new` function returns an instance of some other type that is not a subtype of the original type, no :c:member:`~PyTypeObject.tp_init` function is called; if :c:member:`~PyTypeObject.tp_new` returns an instance of a subtype of the original type, the subtype's :c:member:`~PyTypeObject.tp_init` is called. @@ -2111,14 +2111,14 @@ and :c:data:`PyType_Type` effectively act as defaults.) The *subtype* argument is the type of the object being created; the *args* and *kwds* arguments represent positional and keyword arguments of the call to the - type. Note that *subtype* doesn't have to equal the type whose :c:member:`~PyTypeObject.tp_new` + type. Note that *subtype* doesn't have to equal the type whose :c:member:`~PyTypeObject.tp_new` function is called; it may be a subtype of that type (but not an unrelated type). The :c:member:`~PyTypeObject.tp_new` function should call ``subtype->tp_alloc(subtype, nitems)`` to allocate space for the object, and then do only as much further - initialization as is absolutely necessary. Initialization that can safely be - ignored or repeated should be placed in the :c:member:`~PyTypeObject.tp_init` handler. A good + initialization as is absolutely necessary. Initialization that can safely be + ignored or repeated should be placed in the :c:member:`~PyTypeObject.tp_init` handler. A good rule of thumb is that for immutable types, all initialization should take place in :c:member:`~PyTypeObject.tp_new`, while for mutable types, most initialization should be deferred to :c:member:`~PyTypeObject.tp_init`. @@ -2142,7 +2142,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: freefunc PyTypeObject.tp_free - An optional pointer to an instance deallocation function. Its signature is:: + An optional pointer to an instance deallocation function. Its signature is:: void tp_free(void *self); @@ -2152,7 +2152,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) **Inheritance:** Static subtypes inherit this slot, which will be :c:func:`PyObject_Free` if - inherited from :class:`object`. Exception: If the type supports garbage + inherited from :class:`object`. Exception: If the type supports garbage collection (i.e., the :c:macro:`Py_TPFLAGS_HAVE_GC` flag is set in :c:member:`~PyTypeObject.tp_flags`) and it would inherit :c:func:`PyObject_Free`, then this slot is not inherited but instead defaults @@ -2174,16 +2174,16 @@ and :c:data:`PyType_Type` effectively act as defaults.) An optional pointer to a function called by the garbage collector. The garbage collector needs to know whether a particular object is collectible - or not. Normally, it is sufficient to look at the object's type's - :c:member:`~PyTypeObject.tp_flags` field, and check the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit. But + or not. Normally, it is sufficient to look at the object's type's + :c:member:`~PyTypeObject.tp_flags` field, and check the :c:macro:`Py_TPFLAGS_HAVE_GC` flag bit. But some types have a mixture of statically and dynamically allocated instances, and - the statically allocated instances are not collectible. Such types should + the statically allocated instances are not collectible. Such types should define this function; it should return ``1`` for a collectible instance, and ``0`` for a non-collectible instance. The signature is:: int tp_is_gc(PyObject *self); - (The only example of this are types themselves. The metatype, + (The only example of this are types themselves. The metatype, :c:data:`PyType_Type`, defines this function to distinguish between statically and :ref:`dynamically allocated types `.) @@ -2193,7 +2193,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) **Default:** - This slot has no default. If this field is ``NULL``, + This slot has no default. If this field is ``NULL``, :c:macro:`Py_TPFLAGS_HAVE_GC` is used as the functional equivalent. @@ -2236,7 +2236,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: PyObject* PyTypeObject.tp_cache - Unused. Internal use only. + Unused. Internal use only. **Inheritance:** @@ -2245,7 +2245,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: void* PyTypeObject.tp_subclasses - A collection of subclasses. Internal use only. May be an invalid pointer. + A collection of subclasses. Internal use only. May be an invalid pointer. To get a list of subclasses, call the Python method :py:meth:`~type.__subclasses__`. @@ -2262,14 +2262,14 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: PyObject* PyTypeObject.tp_weaklist - Weak reference list head, for weak references to this type object. Not - inherited. Internal use only. + Weak reference list head, for weak references to this type object. Not + inherited. Internal use only. .. versionchanged:: 3.12 Internals detail: For the static builtin types this is always ``NULL``, - even if weakrefs are added. Instead, the weakrefs for each are stored - on ``PyInterpreterState``. Use the public C-API or the internal + even if weakrefs are added. Instead, the weakrefs for each are stored + on ``PyInterpreterState``. Use the public C-API or the internal ``_PyObject_GET_WEAKREFS_LISTPTR()`` macro to avoid the distinction. **Inheritance:** @@ -2279,12 +2279,12 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: destructor PyTypeObject.tp_del - This field is deprecated. Use :c:member:`~PyTypeObject.tp_finalize` instead. + This field is deprecated. Use :c:member:`~PyTypeObject.tp_finalize` instead. .. c:member:: unsigned int PyTypeObject.tp_version_tag - Used to index into the method cache. Internal use only. + Used to index into the method cache. Internal use only. **Inheritance:** @@ -2293,8 +2293,8 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. c:member:: destructor PyTypeObject.tp_finalize - An optional pointer to an instance finalization function. This is the C - implementation of the :meth:`~object.__del__` special method. Its signature + An optional pointer to an instance finalization function. This is the C + implementation of the :meth:`~object.__del__` special method. Its signature is:: void tp_finalize(PyObject *self); @@ -2302,7 +2302,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) The primary purpose of finalization is to perform any non-trivial cleanup that must be performed before the object is destroyed, while the object and any other objects it directly or indirectly references are still in a - consistent state. The finalizer is allowed to execute + consistent state. The finalizer is allowed to execute arbitrary Python code. Before Python automatically finalizes an object, some of the object's direct @@ -2318,14 +2318,14 @@ and :c:data:`PyType_Type` effectively act as defaults.) After Python automatically finalizes an object, Python might start automatically clearing (:c:member:`~PyTypeObject.tp_clear`) the object - and its referents (direct and indirect). Cleared objects are not + and its referents (direct and indirect). Cleared objects are not guaranteed to be in a consistent state; a finalized object must be able to tolerate cleared referents. .. note:: An object is not guaranteed to be automatically finalized before its - destructor (:c:member:`~PyTypeObject.tp_dealloc`) is called. It is + destructor (:c:member:`~PyTypeObject.tp_dealloc`) is called. It is recommended to call :c:func:`PyObject_CallFinalizerFromDealloc` at the beginning of :c:member:`!tp_dealloc` to guarantee that the object is always finalized before destruction. @@ -2338,12 +2338,12 @@ and :c:data:`PyType_Type` effectively act as defaults.) .. note:: The :c:member:`!tp_finalize` function can be called during shutdown, - after some global variables have been deleted. See the documentation of + after some global variables have been deleted. See the documentation of the :meth:`~object.__del__` method for details. When Python finalizes an object, it behaves like the following algorithm: - #. Python might mark the object as *finalized*. Currently, Python always + #. Python might mark the object as *finalized*. Currently, Python always marks objects whose type supports garbage collection (i.e., the :c:macro:`Py_TPFLAGS_HAVE_GC` flag is set in :c:member:`~PyTypeObject.tp_flags`) and never marks other types of @@ -2354,27 +2354,27 @@ and :c:data:`PyType_Type` effectively act as defaults.) #. If the finalizer function was called and the finalizer made the object reachable (i.e., there is a reference to the object and it is not a member of a :term:`cyclic isolate`), then the finalizer is said to have - *resurrected* the object. It is unspecified whether the finalizer can + *resurrected* the object. It is unspecified whether the finalizer can also resurrect the object by adding a new reference to the object that does not make it reachable, i.e., the object is (still) a member of a cyclic isolate. #. If the finalizer resurrected the object, the object's pending destruction is canceled and the object's *finalized* mark might be removed if - present. Currently, Python never removes the *finalized* mark; this + present. Currently, Python never removes the *finalized* mark; this might change in a future version. *Automatic finalization* refers to any finalization performed by Python except via calls to :c:func:`PyObject_CallFinalizer` or - :c:func:`PyObject_CallFinalizerFromDealloc`. No guarantees are made about + :c:func:`PyObject_CallFinalizerFromDealloc`. No guarantees are made about when, if, or how often an object is automatically finalized, except: * Python will not automatically finalize an object if it is reachable, i.e., there is a reference to it and it is not a member of a :term:`cyclic isolate`. * Python will not automatically finalize an object if finalizing it would - not mark the object as *finalized*. Currently, this applies to objects + not mark the object as *finalized*. Currently, this applies to objects whose type does not support garbage collection, i.e., the - :c:macro:`Py_TPFLAGS_HAVE_GC` flag is not set. Such objects can still be + :c:macro:`Py_TPFLAGS_HAVE_GC` flag is not set. Such objects can still be manually finalized by calling :c:func:`PyObject_CallFinalizer` or :c:func:`PyObject_CallFinalizerFromDealloc`. * Python will not automatically finalize any two members of a :term:`cyclic @@ -2400,12 +2400,12 @@ and :c:data:`PyType_Type` effectively act as defaults.) :c:func:`PyObject_CallFinalizerFromDealloc` instead. :c:member:`~PyTypeObject.tp_finalize` should leave the current exception - status unchanged. The recommended way to write a non-trivial finalizer is + status unchanged. The recommended way to write a non-trivial finalizer is to back up the exception at the beginning by calling :c:func:`PyErr_GetRaisedException` and restore the exception at the end by - calling :c:func:`PyErr_SetRaisedException`. If an exception is encountered + calling :c:func:`PyErr_SetRaisedException`. If an exception is encountered in the middle of the finalizer, log and clear it with - :c:func:`PyErr_WriteUnraisable` or :c:func:`PyErr_FormatUnraisable`. For + :c:func:`PyErr_WriteUnraisable` or :c:func:`PyErr_FormatUnraisable`. For example:: static void @@ -2422,7 +2422,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) } done: - // Restore the saved exception. This silently discards any exception + // Restore the saved exception. This silently discards any exception // raised above, so be sure to call PyErr_WriteUnraisable first if // necessary. PyErr_SetRaisedException(exc); @@ -2438,7 +2438,7 @@ and :c:data:`PyType_Type` effectively act as defaults.) Before version 3.8 it was necessary to set the :c:macro:`Py_TPFLAGS_HAVE_FINALIZE` flags bit in order for this field to be - used. This is no longer required. + used. This is no longer required. .. seealso:: @@ -2550,7 +2550,7 @@ Number Object Structures .. c:type:: PyNumberMethods This structure holds pointers to the functions which an object uses to - implement the number protocol. Each function is used by the function of + implement the number protocol. Each function is used by the function of similar name documented in the :ref:`number` section. .. XXX Drop the definition? @@ -2604,14 +2604,14 @@ Number Object Structures Binary and ternary functions must check the type of all their operands, and implement the necessary conversions (at least one of the operands is - an instance of the defined type). If the operation is not defined for the + an instance of the defined type). If the operation is not defined for the given operands, binary and ternary functions must return ``Py_NotImplemented``, if another error occurred they must return ``NULL`` and set an exception. .. note:: - The :c:member:`~PyNumberMethods.nb_reserved` field should always be ``NULL``. It + The :c:member:`~PyNumberMethods.nb_reserved` field should always be ``NULL``. It was previously called :c:member:`!nb_long`, and was renamed in Python 3.0.1. @@ -2664,19 +2664,19 @@ Mapping Object Structures .. c:type:: PyMappingMethods This structure holds pointers to the functions which an object uses to - implement the mapping protocol. It has three members: + implement the mapping protocol. It has three members: .. c:member:: lenfunc PyMappingMethods.mp_length This function is used by :c:func:`PyMapping_Size` and - :c:func:`PyObject_Size`, and has the same signature. This slot may be set to + :c:func:`PyObject_Size`, and has the same signature. This slot may be set to ``NULL`` if the object has no defined length. .. c:member:: binaryfunc PyMappingMethods.mp_subscript This function is used by :c:func:`PyObject_GetItem` and :c:func:`PySequence_GetSlice`, and has the same signature as - :c:func:`!PyObject_GetItem`. This slot must be filled for the + :c:func:`!PyObject_GetItem`. This slot must be filled for the :c:func:`PyMapping_Check` function to return ``1``, it can be ``NULL`` otherwise. @@ -2684,9 +2684,9 @@ Mapping Object Structures This function is used by :c:func:`PyObject_SetItem`, :c:func:`PyObject_DelItem`, :c:func:`PySequence_SetSlice` and - :c:func:`PySequence_DelSlice`. It has the same signature as + :c:func:`PySequence_DelSlice`. It has the same signature as :c:func:`!PyObject_SetItem`, but *v* can also be set to ``NULL`` to delete - an item. If this slot is ``NULL``, the object does not support item + an item. If this slot is ``NULL``, the object does not support item assignment and deletion. @@ -2706,39 +2706,39 @@ Sequence Object Structures .. c:member:: lenfunc PySequenceMethods.sq_length This function is used by :c:func:`PySequence_Size` and - :c:func:`PyObject_Size`, and has the same signature. It is also used for + :c:func:`PyObject_Size`, and has the same signature. It is also used for handling negative indices via the :c:member:`~PySequenceMethods.sq_item` and the :c:member:`~PySequenceMethods.sq_ass_item` slots. .. c:member:: binaryfunc PySequenceMethods.sq_concat 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 + signature. It is also used by the ``+`` operator, after trying the numeric addition via the :c:member:`~PyNumberMethods.nb_add` slot. .. c:member:: ssizeargfunc PySequenceMethods.sq_repeat This function is used by :c:func:`PySequence_Repeat` and has the same - signature. It is also used by the ``*`` operator, after trying numeric + signature. It is also used by the ``*`` operator, after trying numeric multiplication via the :c:member:`~PyNumberMethods.nb_multiply` slot. .. c:member:: ssizeargfunc PySequenceMethods.sq_item This function is used by :c:func:`PySequence_GetItem` and has the same - signature. It is also used by :c:func:`PyObject_GetItem`, after trying + signature. It is also used by :c:func:`PyObject_GetItem`, after trying the subscription via the :c:member:`~PyMappingMethods.mp_subscript` slot. 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 :c:member:`~PySequenceMethods.sq_length` slot is filled, it is called and the sequence length is used to compute a positive - index which is passed to :c:member:`~PySequenceMethods.sq_item`. If :c:member:`!sq_length` is ``NULL``, + index which is passed to :c:member:`~PySequenceMethods.sq_item`. If :c:member:`!sq_length` is ``NULL``, the index is passed as is to the function. .. c:member:: ssizeobjargproc PySequenceMethods.sq_ass_item This function is used by :c:func:`PySequence_SetItem` and has the same - signature. It is also used by :c:func:`PyObject_SetItem` and + signature. It is also used by :c:func:`PyObject_SetItem` and :c:func:`PyObject_DelItem`, after trying the item assignment and deletion via the :c:member:`~PyMappingMethods.mp_ass_subscript` slot. This slot may be left to ``NULL`` if the object does not support @@ -2747,25 +2747,25 @@ Sequence Object Structures .. c:member:: objobjproc PySequenceMethods.sq_contains 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 + signature. This slot may be left to ``NULL``, in this case :c:func:`!PySequence_Contains` simply traverses the sequence until it finds a match. .. c:member:: binaryfunc PySequenceMethods.sq_inplace_concat This function is used by :c:func:`PySequence_InPlaceConcat` and has the same - signature. It should modify its first operand, and return it. This slot + signature. It should modify its first operand, and return it. This slot may be left to ``NULL``, in this case :c:func:`!PySequence_InPlaceConcat` - will fall back to :c:func:`PySequence_Concat`. It is also used by the + will fall back to :c:func:`PySequence_Concat`. It is also used by the augmented assignment ``+=``, after trying numeric in-place addition via the :c:member:`~PyNumberMethods.nb_inplace_add` slot. .. c:member:: ssizeargfunc PySequenceMethods.sq_inplace_repeat This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same - signature. It should modify its first operand, and return it. This slot + signature. It should modify its first operand, and return it. This slot may be left to ``NULL``, in this case :c:func:`!PySequence_InPlaceRepeat` - will fall back to :c:func:`PySequence_Repeat`. It is also used by the + will fall back to :c:func:`PySequence_Repeat`. It is also used by the augmented assignment ``*=``, after trying numeric in-place multiplication via the :c:member:`~PyNumberMethods.nb_inplace_multiply` slot. @@ -2941,9 +2941,9 @@ Slot Type typedefs .. c:type:: PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems) The purpose of this function is to separate memory allocation from memory - initialization. It should return a pointer to a block of memory of adequate + initialization. It should return a pointer to a block of memory of adequate length for the instance, suitably aligned, and initialized to zeros, but with - :c:member:`~PyObject.ob_refcnt` set to ``1`` and :c:member:`~PyObject.ob_type` set to the type argument. If + :c:member:`~PyObject.ob_refcnt` set to ``1`` and :c:member:`~PyObject.ob_type` set to the type argument. If the type's :c:member:`~PyTypeObject.tp_itemsize` is non-zero, the object's :c:member:`~PyVarObject.ob_size` field should be initialized to *nitems* and the length of the allocated memory block should be ``tp_basicsize + nitems*tp_itemsize``, rounded up to a multiple of @@ -3047,9 +3047,9 @@ Slot Type typedefs Examples -------- -The following are simple examples of Python type definitions. They -include common usage you may encounter. Some demonstrate tricky corner -cases. For more examples, practical info, and a tutorial, see +The following are simple examples of Python type definitions. They +include common usage you may encounter. Some demonstrate tricky corner +cases. For more examples, practical info, and a tutorial, see :ref:`defining-new-types` and :ref:`new-types-topics`. A basic :ref:`static type `:: diff --git a/Doc/c-api/unicode.rst b/Doc/c-api/unicode.rst index 84fee05cb4ce20..32e2697d51e1a3 100644 --- a/Doc/c-api/unicode.rst +++ b/Doc/c-api/unicode.rst @@ -13,7 +13,7 @@ Unicode Objects Since the implementation of :pep:`393` in Python 3.3, Unicode objects internally use a variety of representations, in order to allow handling the complete range -of Unicode characters while staying memory efficient. There are special cases +of Unicode characters while staying memory efficient. There are special cases for strings where all code points are below 128, 256, or 65536; otherwise, code points must be below 1114112 (which is the full Unicode range). @@ -48,7 +48,7 @@ Python: Py_UCS1 These types are typedefs for unsigned integer types wide enough to contain - characters of 32 bits, 16 bits and 8 bits, respectively. When dealing with + characters of 32 bits, 16 bits and 8 bits, respectively. When dealing with single Unicode characters, use :c:type:`Py_UCS4`. .. versionadded:: 3.3 @@ -58,7 +58,7 @@ Python: PyCompactUnicodeObject PyUnicodeObject - These subtypes of :c:type:`PyObject` represent a Python Unicode object. In + These subtypes of :c:type:`PyObject` represent a Python Unicode object. In almost all cases, they shouldn't be used directly, since all API functions that deal with Unicode objects take and return :c:type:`PyObject` pointers. @@ -71,18 +71,18 @@ access to internal read-only data of Unicode objects: .. c:function:: int PyUnicode_Check(PyObject *obj) Return true if the object *obj* is a Unicode object or an instance of a Unicode - subtype. This function always succeeds. + subtype. This function always succeeds. .. c:function:: int PyUnicode_CheckExact(PyObject *obj) Return true if the object *obj* is a Unicode object, but not an instance of a - subtype. This function always succeeds. + subtype. This function always succeeds. .. c:function:: Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode) - Return the length of the Unicode string, in code points. *unicode* has to be a + Return the length of the Unicode string, in code points. *unicode* has to be a Unicode object in the "canonical" representation (not checked). .. versionadded:: 3.3 @@ -93,7 +93,7 @@ access to internal read-only data of Unicode objects: Py_UCS4* PyUnicode_4BYTE_DATA(PyObject *unicode) Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 - integer types for direct character access. No checks are performed if the + integer types for direct character access. No checks are performed if the canonical representation has the correct character size; use :c:func:`PyUnicode_KIND` to select the right function. @@ -115,7 +115,7 @@ access to internal read-only data of Unicode objects: .. c:function:: int PyUnicode_KIND(PyObject *unicode) Return one of the PyUnicode kind constants (see above) that indicate how many - bytes per character this Unicode object uses to store its data. *unicode* has to + bytes per character this Unicode object uses to store its data. *unicode* has to be a Unicode object in the "canonical" representation (not checked). .. versionadded:: 3.3 @@ -123,7 +123,7 @@ access to internal read-only data of Unicode objects: .. c:function:: void* PyUnicode_DATA(PyObject *unicode) - Return a void pointer to the raw Unicode buffer. *unicode* has to be a Unicode + Return a void pointer to the raw Unicode buffer. *unicode* has to be a Unicode object in the "canonical" representation (not checked). .. versionadded:: 3.3 @@ -150,7 +150,7 @@ access to internal read-only data of Unicode objects: Py_ssize_t index) Read a code point from a canonical representation *data* (as obtained with - :c:func:`PyUnicode_DATA`). No checks or ready calls are performed. + :c:func:`PyUnicode_DATA`). No checks or ready calls are performed. .. versionadded:: 3.3 @@ -158,7 +158,7 @@ access to internal read-only data of Unicode objects: .. c:function:: Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index) Read a character from a Unicode object *unicode*, which must be in the "canonical" - representation. This is less efficient than :c:func:`PyUnicode_READ` if you + representation. This is less efficient than :c:func:`PyUnicode_READ` if you do multiple consecutive reads. .. versionadded:: 3.3 @@ -167,7 +167,7 @@ access to internal read-only data of Unicode objects: .. c:function:: Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *unicode) Return the maximum code point that is suitable for creating another string - based on *unicode*, which must be in the "canonical" representation. This is + based on *unicode*, which must be in the "canonical" representation. This is always an approximation but more efficient than iterating over the string. .. versionadded:: 3.3 @@ -291,20 +291,20 @@ These APIs can be used for fast direct character conversions: .. c:function:: int Py_UNICODE_TODECIMAL(Py_UCS4 ch) - Return the character *ch* converted to a decimal positive integer. Return - ``-1`` if this is not possible. This function does not raise exceptions. + Return the character *ch* converted to a decimal positive integer. Return + ``-1`` if this is not possible. This function does not raise exceptions. .. c:function:: int Py_UNICODE_TODIGIT(Py_UCS4 ch) Return the character *ch* converted to a single digit integer. Return ``-1`` if - this is not possible. This function does not raise exceptions. + this is not possible. This function does not raise exceptions. .. c:function:: double Py_UNICODE_TONUMERIC(Py_UCS4 ch) Return the character *ch* converted to a double. Return ``-1.0`` if this is not - possible. This function does not raise exceptions. + possible. This function does not raise exceptions. These APIs can be used to work with surrogates: @@ -337,8 +337,8 @@ APIs: .. c:function:: PyObject* PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar) - Create a new Unicode object. *maxchar* should be the true maximum code point - to be placed in the string. As an approximation, it can be rounded up to the + Create a new Unicode object. *maxchar* should be the true maximum code point + to be placed in the string. As an approximation, it can be rounded up to the nearest value in the sequence 127, 255, 65535, 1114111. On error, set an exception and return ``NULL``. @@ -372,11 +372,11 @@ APIs: Create a new Unicode object with the given *kind* (possible values are :c:macro:`PyUnicode_1BYTE_KIND` etc., as returned by - :c:func:`PyUnicode_KIND`). The *buffer* must point to an array of *size* + :c:func:`PyUnicode_KIND`). The *buffer* must point to an array of *size* units of 1, 2 or 4 bytes per character, as given by the kind. If necessary, the input *buffer* is copied and transformed into the - canonical representation. For example, if the *buffer* is a UCS4 string + canonical representation. For example, if the *buffer* is a UCS4 string (:c:macro:`PyUnicode_4BYTE_KIND`) and it consists only of codepoints in the UCS1 range, it will be transformed into UCS1 (:c:macro:`PyUnicode_1BYTE_KIND`). @@ -386,8 +386,8 @@ APIs: .. c:function:: PyObject* PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size) - Create a Unicode object from the char buffer *str*. The bytes will be - interpreted as being UTF-8 encoded. The buffer is copied into the new + Create a Unicode object from the char buffer *str*. The bytes will be + interpreted as being UTF-8 encoded. The buffer is copied into the new object. The return value might be a shared object, i.e. modification of the data is not allowed. @@ -411,7 +411,7 @@ APIs: 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 + 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* ASCII-encoded string. @@ -517,7 +517,7 @@ APIs: * - ``p`` - :c:expr:`const void*` - - The hex representation of a C pointer. + - The hex representation of a C pointer. Mostly equivalent to ``printf("%p")`` except that it is guaranteed to start with the literal ``0x`` regardless of what the platform's ``printf`` yields. @@ -640,7 +640,7 @@ APIs: All other objects, including Unicode objects, cause a :exc:`TypeError` to be set. - The API returns ``NULL`` if there was an error. The caller is responsible for + The API returns ``NULL`` if there was an error. The caller is responsible for decref'ing the returned objects. @@ -696,9 +696,9 @@ APIs: Py_ssize_t from_start, \ Py_ssize_t how_many) - Copy characters from one Unicode object into another. This function performs + Copy characters from one Unicode object into another. This function performs character conversion when necessary and falls back to :c:func:`!memcpy` if - possible. Returns ``-1`` and sets an exception on error, otherwise returns + possible. Returns ``-1`` and sets an exception on error, otherwise returns the number of copied characters. The string must not have been “used” yet. @@ -759,7 +759,7 @@ APIs: .. c:function:: Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index) - Read a character from a string. This function checks that *unicode* is a + Read a character from a string. This function checks that *unicode* is a Unicode object and the index is not out of bounds, in contrast to :c:func:`PyUnicode_READ_CHAR`, which performs no error checking. @@ -772,7 +772,7 @@ APIs: Py_ssize_t end) Return a substring of *unicode*, from character index *start* (included) to - character index *end* (excluded). Negative indices are not supported. + character index *end* (excluded). Negative indices are not supported. On error, set an exception and return ``NULL``. .. versionadded:: 3.3 @@ -782,9 +782,9 @@ APIs: Py_ssize_t buflen, int copy_null) Copy the string *unicode* into a UCS4 buffer, including a null character, if - *copy_null* is set. Returns ``NULL`` and sets an exception on error (in + *copy_null* is set. Returns ``NULL`` and sets an exception on error (in particular, a :exc:`SystemError` if *buflen* is smaller than the length of - *unicode*). *buffer* is returned on success. + *unicode*). *buffer* is returned on success. .. versionadded:: 3.3 @@ -792,8 +792,8 @@ APIs: .. c:function:: Py_UCS4* PyUnicode_AsUCS4Copy(PyObject *unicode) Copy the string *unicode* into a new UCS4 buffer that is allocated using - :c:func:`PyMem_Malloc`. If this fails, ``NULL`` is returned with a - :exc:`MemoryError` set. The returned buffer always has an extra + :c:func:`PyMem_Malloc`. If this fails, ``NULL`` is returned with a + :exc:`MemoryError` set. The returned buffer always has an extra null code point appended. .. versionadded:: 3.3 @@ -813,7 +813,7 @@ system. locale encoding on other platforms. The supported error handlers are ``"strict"`` and ``"surrogateescape"`` (:pep:`383`). The decoder uses ``"strict"`` error handler if - *errors* is ``NULL``. *str* must end with a null character but + *errors* is ``NULL``. *str* must end with a null character but cannot contain embedded null characters. Use :c:func:`PyUnicode_DecodeFSDefaultAndSize` to decode a string from @@ -993,16 +993,16 @@ wchar_t Support .. c:function:: Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *wstr, Py_ssize_t size) - Copy the Unicode object contents into the :c:type:`wchar_t` buffer *wstr*. At most + Copy the Unicode object contents into the :c:type:`wchar_t` buffer *wstr*. At most *size* :c:type:`wchar_t` characters are copied (excluding a possibly trailing - null termination character). Return the number of :c:type:`wchar_t` characters + null termination character). Return the number of :c:type:`wchar_t` characters copied or ``-1`` in case of an error. When *wstr* is ``NULL``, instead return the *size* that would be required to store all of *unicode* including a terminating null. Note that the resulting :c:expr:`wchar_t*` - string may or may not be null-terminated. It is the responsibility of the caller + string may or may not be null-terminated. It is the responsibility of the caller to make sure that the :c:expr:`wchar_t*` string is null-terminated in case this is required by the application. Also, note that the :c:expr:`wchar_t*` string might contain null characters, which would cause the string to be truncated @@ -1044,15 +1044,15 @@ have the same semantics as the ones of the built-in :func:`str` string object constructor. Setting encoding to ``NULL`` causes the default encoding to be used -which is UTF-8. The file system calls should use +which is UTF-8. The file system calls should use :c:func:`PyUnicode_FSConverter` for encoding file names. This uses the :term:`filesystem encoding and error handler` internally. Error handling is set by errors which may also be set to ``NULL`` meaning to use -the default handling defined for the codec. Default error handling for all +the default handling defined for the codec. Default error handling for all built-in codecs is "strict" (:exc:`ValueError` is raised). -The codecs all use a similar interface. Only deviations from the following +The codecs all use a similar interface. Only deviations from the following generic ones are documented for simplicity. @@ -1078,8 +1078,8 @@ These are the generic codec APIs: Create a Unicode object by decoding *size* bytes of the encoded string *str*. *encoding* and *errors* have the same meaning as the parameters of the same name - in the :func:`str` built-in function. The codec to be used is looked up - using the Python codec registry. Return ``NULL`` if an exception was raised by + in the :func:`str` built-in function. The codec to be used is looked up + using the Python codec registry. Return ``NULL`` if an exception was raised by the codec. @@ -1117,7 +1117,7 @@ These are the UTF-8 codec APIs: .. c:function:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode) Encode a Unicode object using UTF-8 and return the result as Python bytes - object. Error handling is "strict". Return ``NULL`` if an exception was + object. Error handling is "strict". Return ``NULL`` if an exception was raised by the codec. The function fails if the string contains surrogate code points @@ -1127,8 +1127,8 @@ These are the UTF-8 codec APIs: .. c:function:: const char* PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size) Return a pointer to the UTF-8 encoding of the Unicode object, and - store the size of the encoded representation (in bytes) in *size*. The - *size* argument can be ``NULL``; in this case no size will be stored. The + store the size of the encoded representation (in bytes) in *size*. The + *size* argument can be ``NULL``; in this case no size will be stored. The returned buffer always has an extra null byte appended (not included in *size*), regardless of whether there are any other null code points. @@ -1139,7 +1139,7 @@ These are the UTF-8 codec APIs: (``U+D800`` - ``U+DFFF``). This caches the UTF-8 representation of the string in the Unicode object, and - subsequent calls will return a pointer to the same buffer. The caller is not + subsequent calls will return a pointer to the same buffer. The caller is not responsible for deallocating the buffer. The buffer is deallocated and pointers to it become invalid when the Unicode object is garbage collected. @@ -1181,19 +1181,19 @@ These are the UTF-32 codec APIs: 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 + corresponding Unicode object. *errors* (if non-``NULL``) defines the error handling. It defaults to "strict". If *byteorder* is non-``NULL``, the decoder starts decoding using the given byte order:: *byteorder == -1: little endian - *byteorder == 0: native order - *byteorder == 1: big endian + *byteorder == 0: native order + *byteorder == 1: big endian If ``*byteorder`` is zero, and the first four bytes of the input data are a byte order mark (BOM), the decoder switches to this byte order and the BOM is - not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or + not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or ``1``, any byte order mark is copied to the output. After completion, *\*byteorder* is set to the current byte order at the end @@ -1217,7 +1217,7 @@ These are the UTF-32 codec APIs: .. c:function:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode) Return a Python byte string using the UTF-32 encoding in native byte - order. The string always starts with a BOM mark. Error handling is "strict". + order. The string always starts with a BOM mark. Error handling is "strict". Return ``NULL`` if an exception was raised by the codec. @@ -1231,19 +1231,19 @@ These are the UTF-16 codec APIs: 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 + corresponding Unicode object. *errors* (if non-``NULL``) defines the error handling. It defaults to "strict". If *byteorder* is non-``NULL``, the decoder starts decoding using the given byte order:: *byteorder == -1: little endian - *byteorder == 0: native order - *byteorder == 1: big endian + *byteorder == 0: native order + *byteorder == 1: big endian If ``*byteorder`` is zero, and the first two bytes of the input data are a byte order mark (BOM), the decoder switches to this byte order and the BOM is - not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or + not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or ``1``, any byte order mark is copied to the output (where it will result in either a ``\ufeff`` or a ``\ufffe`` character). @@ -1268,7 +1268,7 @@ These are the UTF-16 codec APIs: .. c:function:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode) Return a Python byte string using the UTF-16 encoding in native byte - order. The string always starts with a BOM mark. Error handling is "strict". + order. The string always starts with a BOM mark. Error handling is "strict". Return ``NULL`` if an exception was raised by the codec. @@ -1281,15 +1281,15 @@ These are the UTF-7 codec APIs: .. c:function:: PyObject* PyUnicode_DecodeUTF7(const char *str, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string - *str*. Return ``NULL`` if an exception was raised by the codec. + *str*. Return ``NULL`` if an exception was raised by the codec. .. c:function:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *str, Py_ssize_t size, \ const char *errors, Py_ssize_t *consumed) - If *consumed* is ``NULL``, behave like :c:func:`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 + 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*. @@ -1303,13 +1303,13 @@ These are the "Unicode Escape" codec APIs: Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded - string *str*. Return ``NULL`` if an exception was raised by the codec. + string *str*. Return ``NULL`` if an exception was raised by the codec. .. c:function:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode) Encode a Unicode object using Unicode-Escape and return the result as a - bytes object. Error handling is "strict". Return ``NULL`` if an exception was + bytes object. Error handling is "strict". Return ``NULL`` if an exception was raised by the codec. @@ -1323,13 +1323,13 @@ These are the "Raw Unicode Escape" codec APIs: Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape - encoded string *str*. Return ``NULL`` if an exception was raised by the codec. + encoded string *str*. Return ``NULL`` if an exception was raised by the codec. .. c:function:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode) Encode a Unicode object using Raw-Unicode-Escape and return the result as - a bytes object. Error handling is "strict". Return ``NULL`` if an exception + a bytes object. Error handling is "strict". Return ``NULL`` if an exception was raised by the codec. @@ -1343,33 +1343,33 @@ ordinals and only these are accepted by the codecs during encoding. .. c:function:: PyObject* PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string - *str*. Return ``NULL`` if an exception was raised by the codec. + *str*. Return ``NULL`` if an exception was raised by the codec. .. c:function:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode) Encode a Unicode object using Latin-1 and return the result as Python bytes - object. Error handling is "strict". Return ``NULL`` if an exception was + object. Error handling is "strict". Return ``NULL`` if an exception was raised by the codec. ASCII Codecs """""""""""" -These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other +These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors. .. c:function:: PyObject* PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors) Create a Unicode object by decoding *size* bytes of the ASCII encoded string - *str*. Return ``NULL`` if an exception was raised by the codec. + *str*. Return ``NULL`` if an exception was raised by the codec. .. c:function:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode) Encode a Unicode object using ASCII and return the result as Python bytes - object. Error handling is "strict". Return ``NULL`` if an exception was + object. Error handling is "strict". Return ``NULL`` if an exception was raised by the codec. @@ -1379,7 +1379,7 @@ Character Map Codecs This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs included in the :mod:`!encodings` package). The codec uses mappings to encode and -decode characters. The mapping objects provided must support the +decode characters. The mapping objects provided must support the :meth:`~object.__getitem__` mapping interface; dictionaries and sequences work well. These are the mapping codec APIs: @@ -1388,13 +1388,13 @@ These are the mapping codec APIs: PyObject *mapping, const char *errors) Create a Unicode object by decoding *size* bytes of the encoded string *str* - using the given *mapping* object. Return ``NULL`` if an exception was raised + using the given *mapping* object. Return ``NULL`` if an exception was raised by the codec. - If *mapping* is ``NULL``, Latin-1 decoding will be applied. Else + If *mapping* is ``NULL``, Latin-1 decoding will be applied. Else *mapping* must map bytes ordinals (integers in the range from 0 to 255) to Unicode strings, integers (which are then interpreted as Unicode - ordinals) or ``None``. Unmapped data bytes -- ones which cause a + ordinals) or ``None``. Unmapped data bytes -- ones which cause a :exc:`LookupError`, as well as ones which get mapped to ``None``, ``0xFFFE`` or ``'\ufffe'``, are treated as undefined mappings and cause an error. @@ -1403,11 +1403,11 @@ These are the mapping codec APIs: .. c:function:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping) Encode a Unicode object using the given *mapping* object and return the - result as a bytes object. Error handling is "strict". Return ``NULL`` if an + result as a bytes object. Error handling is "strict". Return ``NULL`` if an exception was raised by the codec. The *mapping* object must map Unicode ordinal integers to bytes objects, - integers in the range from 0 to 255 or ``None``. Unmapped character + integers in the range from 0 to 255 or ``None``. Unmapped character ordinals (ones which cause a :exc:`LookupError`) as well as mapped to ``None`` are treated as "undefined mapping" and cause an error. @@ -1424,7 +1424,7 @@ The following codec API is special in that maps Unicode to Unicode. or ``None`` (causing deletion of the character). Mapping tables need only provide the :meth:`~object.__getitem__` interface; dictionaries - and sequences work well. Unmapped character ordinals (ones which cause a + and sequences work well. Unmapped character ordinals (ones which cause a :exc:`LookupError`) are left untouched and are copied as-is. *errors* has the usual meaning for codecs. It may be ``NULL`` which indicates to @@ -1435,8 +1435,8 @@ MBCS codecs for Windows """"""""""""""""""""""" These are the MBCS codec APIs. They are currently only available on Windows and -use the Win32 MBCS converters to implement the conversions. Note that MBCS (or -DBCS) is a class of encodings, not just one. The target encoding is defined by +use the Win32 MBCS converters to implement the conversions. Note that MBCS (or +DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec. .. c:function:: PyObject* PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors) @@ -1464,14 +1464,14 @@ the user settings on the machine running the codec. .. c:function:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode) Encode a Unicode object using MBCS and return the result as Python bytes - object. Error handling is "strict". Return ``NULL`` if an exception was + object. Error handling is "strict". Return ``NULL`` if an exception was raised by the codec. .. c:function:: PyObject* PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors) Encode the Unicode object using the specified code page and return a Python - bytes object. Return ``NULL`` if an exception was raised by the codec. Use + bytes object. Return ``NULL`` if an exception was raised by the codec. Use :c:macro:`!CP_ACP` code page to get the MBCS encoder. .. versionadded:: 3.3 @@ -1496,10 +1496,10 @@ They all return ``NULL`` or ``-1`` if an exception occurs. .. c:function:: PyObject* PyUnicode_Split(PyObject *unicode, 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 - separator. At most *maxsplit* splits will be done. If negative, no limit is - set. Separators are not included in the resulting list. + 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 + separator. At most *maxsplit* splits will be done. If negative, no limit is + set. Separators are not included in the resulting list. On error, return ``NULL`` with an exception set. @@ -1519,7 +1519,7 @@ They all return ``NULL`` or ``-1`` if an exception occurs. .. c:function:: PyObject* PyUnicode_Splitlines(PyObject *unicode, int keepends) Split a Unicode string at line breaks, returning a list of Unicode strings. - CRLF is considered to be one line break. If *keepends* is ``0``, the Line break + CRLF is considered to be one line break. If *keepends* is ``0``, the Line break characters are not included in the resulting strings. @@ -1569,7 +1569,7 @@ They all return ``NULL`` or ``-1`` if an exception occurs. Return the first position of *substr* in ``unicode[start:end]`` using the given *direction* (*direction* == ``1`` means to do a forward search, *direction* == ``-1`` a - backward search). The return value is the index of the first match; a value of + backward search). The return value is the index of the first match; a value of ``-1`` indicates that no match was found, and ``-2`` indicates that an error occurred and an exception has been set. @@ -1579,7 +1579,7 @@ They all return ``NULL`` or ``-1`` if an exception occurs. Return the first position of the character *ch* in ``unicode[start:end]`` using the given *direction* (*direction* == ``1`` means to do a forward search, - *direction* == ``-1`` a backward search). The return value is the index of the + *direction* == ``-1`` a backward search). The return value is the index of the first match; a value of ``-1`` indicates that no match was found, and ``-2`` indicates that an error occurred and an exception has been set. @@ -1593,7 +1593,7 @@ They all return ``NULL`` or ``-1`` if an exception occurs. Py_ssize_t start, Py_ssize_t end) Return the number of non-overlapping occurrences of *substr* in - ``unicode[start:end]``. Return ``-1`` if an error occurred. + ``unicode[start:end]``. Return ``-1`` if an error occurred. .. c:function:: PyObject* PyUnicode_Replace(PyObject *unicode, PyObject *substr, \ @@ -1671,7 +1671,7 @@ They all return ``NULL`` or ``-1`` if an exception occurs. This function does not raise exceptions. -.. c:function:: PyObject* PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) +.. c:function:: PyObject* PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) Rich compare two Unicode strings and return one of the following: @@ -1700,8 +1700,8 @@ They all return ``NULL`` or ``-1`` if an exception occurs. .. c:function:: void PyUnicode_InternInPlace(PyObject **p_unicode) - Intern the argument :c:expr:`*p_unicode` in place. The argument must be the address of a - pointer variable pointing to a Python Unicode string object. If there is an + Intern the argument :c:expr:`*p_unicode` in place. The argument must be the address of a + pointer variable pointing to a Python Unicode string object. If there is an existing interned string that is the same as :c:expr:`*p_unicode`, it sets :c:expr:`*p_unicode` to it (releasing the reference to the old string object and creating a new :term:`strong reference` to the interned string object), otherwise it leaves diff --git a/Doc/c-api/veryhigh.rst b/Doc/c-api/veryhigh.rst index fb07fec7effce8..616b6d6db861f9 100644 --- a/Doc/c-api/veryhigh.rst +++ b/Doc/c-api/veryhigh.rst @@ -12,13 +12,13 @@ file or a buffer, but they will not let you interact in a more detailed way with the interpreter. Several of these functions accept a start symbol from the grammar as a -parameter. The available start symbols are :c:data:`Py_eval_input`, -:c:data:`Py_file_input`, and :c:data:`Py_single_input`. These are described +parameter. The available start symbols are :c:data:`Py_eval_input`, +:c:data:`Py_file_input`, and :c:data:`Py_single_input`. These are described following the functions which accept them as parameters. -Note also that several of these functions take :c:expr:`FILE*` parameters. One +Note also that several of these functions take :c:expr:`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 +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 :c:expr:`FILE*` parameters are only passed to these functions if it is certain that they were created by @@ -48,8 +48,8 @@ the same library that the Python runtime is using. If *fp* refers to a file associated with an interactive device (console or terminal input or Unix pseudo-terminal), return the value of :c:func:`PyRun_InteractiveLoop`, otherwise return the result of - :c:func:`PyRun_SimpleFile`. *filename* is decoded from the filesystem - encoding (:func:`sys.getfilesystemencoding`). If *filename* is ``NULL``, this + :c:func:`PyRun_SimpleFile`. *filename* is decoded from the filesystem + encoding (:func:`sys.getfilesystemencoding`). If *filename* is ``NULL``, this function uses ``"???"`` as the filename. If *closeit* is true, the file is closed before ``PyRun_SimpleFileExFlags()`` returns. @@ -65,7 +65,7 @@ the same library that the Python runtime is using. 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 - is created. Returns ``0`` on success or ``-1`` if an exception was raised. If + is created. Returns ``0`` on success or ``-1`` if an exception was raised. If there was an error, there is no way to get the exception information. For the meaning of *flags*, see below. @@ -108,14 +108,14 @@ the same library that the Python runtime is using. .. 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 - prompted using ``sys.ps1`` and ``sys.ps2``. *filename* is decoded from the + interactive device according to the *flags* argument. The user will be + prompted using ``sys.ps1`` and ``sys.ps2``. *filename* is decoded from the :term:`filesystem encoding and error handler`. Returns ``0`` when the input was executed successfully, ``-1`` if there was an exception, or an error code from the :file:`errcode.h` include file distributed as part of Python if - there was a parse error. (Note that :file:`errcode.h` is not included by + there was a parse error. (Note that :file:`errcode.h` is not included by :file:`Python.h`, so must be included specifically if needed.) @@ -128,17 +128,17 @@ the same library that the Python runtime is using. .. 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``. *filename* is decoded from the :term:`filesystem encoding and - error handler`. Returns ``0`` at EOF or a negative number upon failure. + until EOF is reached. The user will be prompted using ``sys.ps1`` and + ``sys.ps2``. *filename* is decoded from the :term:`filesystem encoding and + error handler`. Returns ``0`` at EOF or a negative number upon failure. .. c:var:: int (*PyOS_InputHook)(void) Can be set to point to a function with the prototype - ``int func(void)``. The function will be called when Python's + ``int func(void)``. The function will be called when Python's interpreter prompt is about to become idle and wait for user input - from the terminal. The return value is ignored. Overriding this + from the terminal. The return value is ignored. Overriding this hook can be used to integrate the interpreter's prompt with other event loops, as done in the :file:`Modules/_tkinter.c` in the Python source code. @@ -153,10 +153,10 @@ the same library that the Python runtime is using. Can be set to point to a function with the prototype ``char *func(FILE *stdin, FILE *stdout, char *prompt)``, overriding the default function used to read a single line of input - at the interpreter's prompt. The function is expected to output + at the interpreter's prompt. The function is expected to output the string *prompt* if it's not ``NULL``, and then read a line of input from the provided standard input file, returning the - resulting string. For example, The :mod:`readline` module sets + resulting string. For example, The :mod:`readline` module sets this hook to provide line-editing and tab-completion features. The result must be a string allocated by :c:func:`PyMem_RawMalloc` or @@ -181,8 +181,8 @@ the same library that the Python runtime is using. Execute Python source code from *str* in the context specified by the objects *globals* and *locals* with the compiler flags specified by - *flags*. *globals* must be a dictionary; *locals* can be any object - that implements the mapping protocol. The parameter *start* specifies + *flags*. *globals* must be a dictionary; *locals* can be any object + that implements the mapping protocol. The parameter *start* specifies the start token that should be used to parse the source code. Returns the result of executing the code as a Python object, or ``NULL`` if an @@ -231,16 +231,16 @@ the same library that the Python runtime is using. .. c:function:: PyObject* Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int optimize) 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 + object. The start token is given by *start*; this can be used to constrain the code which can be compiled and should be :c:data:`Py_eval_input`, - :c:data:`Py_file_input`, or :c:data:`Py_single_input`. The filename specified by + :c:data:`Py_file_input`, or :c:data:`Py_single_input`. The filename specified by *filename* is used to construct the code object and may appear in tracebacks or - :exc:`SyntaxError` exception messages. This returns ``NULL`` if the code + :exc:`SyntaxError` exception messages. This returns ``NULL`` if the code cannot be parsed or compiled. The integer *optimize* specifies the optimization level of the compiler; a value of ``-1`` selects the optimization level of the interpreter as given by - :option:`-O` options. Explicit levels are ``0`` (no optimization; + :option:`-O` options. Explicit levels are ``0`` (no optimization; ``__debug__`` is true), ``1`` (asserts are removed, ``__debug__`` is false) or ``2`` (docstrings are removed too). @@ -257,14 +257,14 @@ the same library that the Python runtime is using. .. c:function:: PyObject* PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals) This is a simplified interface to :c:func:`PyEval_EvalCodeEx`, with just - the code object, and global and local variables. The other arguments are + the code object, and global and local variables. The other arguments are set to ``NULL``. .. c:function:: PyObject* PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int defcount, PyObject *kwdefs, PyObject *closure) Evaluate a precompiled code object, given a particular environment for its - evaluation. This environment consists of a dictionary of global variables, + evaluation. This environment consists of a dictionary of global variables, a mapping object of local variables, arrays of arguments, keywords and defaults, a dictionary of default values for :ref:`keyword-only ` arguments and a closure tuple of cells. @@ -272,15 +272,15 @@ the same library that the Python runtime is using. .. c:function:: PyObject* PyEval_EvalFrame(PyFrameObject *f) - Evaluate an execution frame. This is a simplified interface to + Evaluate an execution frame. This is a simplified interface to :c:func:`PyEval_EvalFrameEx`, for backward compatibility. .. c:function:: PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) - This is the main, unvarnished function of Python interpretation. The code + This is the main, unvarnished function of Python interpretation. The code object associated with the execution frame *f* is executed, interpreting - bytecode and executing calls as needed. The additional *throwflag* + bytecode and executing calls as needed. The additional *throwflag* parameter can mostly be ignored - if true, then it causes an exception to immediately be thrown; this is used for the :meth:`~generator.throw` methods of generator objects. @@ -309,7 +309,7 @@ the same library that the Python runtime is using. .. index:: single: Py_CompileString (C function) The start symbol from the Python grammar for sequences of statements as read - from a file or other source; for use with :c:func:`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. @@ -324,9 +324,9 @@ the same library that the Python runtime is using. .. c:struct:: PyCompilerFlags - This is the structure used to hold compiler flags. In cases where code is only + 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 - executed, it is passed as ``PyCompilerFlags *flags``. In this case, ``from + executed, it is passed as ``PyCompilerFlags *flags``. In this case, ``from __future__ import`` can modify *flags*. Whenever ``PyCompilerFlags *flags`` is ``NULL``, :c:member:`~PyCompilerFlags.cf_flags` is treated as diff --git a/Doc/c-api/weakref.rst b/Doc/c-api/weakref.rst index c3c6cf413dcef5..0081294ba13130 100644 --- a/Doc/c-api/weakref.rst +++ b/Doc/c-api/weakref.rst @@ -5,48 +5,48 @@ Weak Reference Objects ---------------------- -Python supports *weak references* as first-class objects. There are two -specific object types which directly implement weak references. The first is a +Python supports *weak references* as first-class objects. There are two +specific object types which directly implement weak references. The first is a simple reference object, and the second acts as a proxy for the original object as much as it can. .. c:function:: int PyWeakref_Check(PyObject *ob) - Return non-zero if *ob* is either a reference or proxy object. This function + Return non-zero if *ob* is either a reference or proxy object. This function always succeeds. .. c:function:: int PyWeakref_CheckRef(PyObject *ob) - Return non-zero if *ob* is a reference object. This function always succeeds. + Return non-zero if *ob* is a reference object. This function always succeeds. .. c:function:: int PyWeakref_CheckProxy(PyObject *ob) - Return non-zero if *ob* is a proxy object. This function always succeeds. + Return non-zero if *ob* is a proxy object. This function always succeeds. .. c:function:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback) - Return a weak reference object for the object *ob*. This will always return + 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 - reference object may be returned. The second parameter, *callback*, can be a + reference object may be returned. The second parameter, *callback*, can be a callable object that receives notification when *ob* is garbage collected; it should accept a single parameter, which will be the weak reference object - itself. *callback* may also be ``None`` or ``NULL``. If *ob* is not a + itself. *callback* may also be ``None`` or ``NULL``. If *ob* is not a weakly referenceable object, or if *callback* is not callable, ``None``, or ``NULL``, this will return ``NULL`` and raise :exc:`TypeError`. .. c:function:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback) - Return a weak reference proxy object for the object *ob*. This will always + 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 - existing proxy object may be returned. The second parameter, *callback*, can + existing proxy object may be returned. The second parameter, *callback*, can be a callable object that receives notification when *ob* is garbage collected; it should accept a single parameter, which will be the weak - reference object itself. *callback* may also be ``None`` or ``NULL``. If *ob* + reference object itself. *callback* may also be ``None`` or ``NULL``. If *ob* is not a weakly referenceable object, or if *callback* is not callable, ``None``, or ``NULL``, this will return ``NULL`` and raise :exc:`TypeError`. @@ -67,7 +67,7 @@ as much as it can. .. c:function:: PyObject* PyWeakref_GetObject(PyObject *ref) Return a :term:`borrowed reference` to the referenced object from a weak - reference, *ref*. If the referent is no longer live, returns ``Py_None``. + reference, *ref*. If the referent is no longer live, returns ``Py_None``. .. note:: @@ -112,7 +112,7 @@ as much as it can. Clears the weakrefs for *object* without calling the callbacks. This function is called by the :c:member:`~PyTypeObject.tp_dealloc` handler - for types with finalizers (i.e., :meth:`~object.__del__`). The handler for + for types with finalizers (i.e., :meth:`~object.__del__`). The handler for those objects first calls :c:func:`PyObject_ClearWeakRefs` to clear weakrefs and call their callbacks, then the finalizer, and finally this function to clear any weakrefs that may have been created by the finalizer. pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy