gh-107298: Fix more Sphinx warnings in the C API doc (#107329)

Declare the following functions as macros, since they are actually
macros. It avoids a warning on "TYPE" or "macro" argument.

* PyMem_New()
* PyMem_Resize()
* PyModule_AddIntMacro()
* PyModule_AddStringMacro()
* PyObject_GC_New()
* PyObject_GC_NewVar()
* PyObject_New()
* PyObject_NewVar()

Add C standard C types to nitpick_ignore in Doc/conf.py:

* int64_t
* uint64_t
* uintptr_t

No longer ignore non existing "__int" type in nitpick_ignore.

Update Doc/tools/.nitignore
This commit is contained in:
Victor Stinner 2023-07-27 02:52:40 +02:00 committed by GitHub
parent 391e03fa05
commit 8d61a71f9c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 122 additions and 119 deletions

View File

@ -27,22 +27,25 @@ Allocating Objects on the Heap
length information for a variable-size object. length information for a variable-size object.
.. c:function:: TYPE* PyObject_New(TYPE, PyTypeObject *type) .. c:macro:: PyObject_New(TYPE, typeobj)
Allocate a new Python object using the C structure type *TYPE* and the Allocate a new Python object using the C structure type *TYPE* and the
Python type object *type*. Fields not defined by the Python object header Python type object *typeobj* (``PyTypeObject*``).
Fields not defined by the Python object header
are not initialized; the object's reference count will be one. The size of are not initialized; the object's reference count will be one. The size of
the memory allocation is determined from the :c:member:`~PyTypeObject.tp_basicsize` field of the memory allocation is determined from the :c:member:`~PyTypeObject.tp_basicsize` field of
the type object. the type object.
.. c:function:: TYPE* PyObject_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) .. c:macro:: PyObject_NewVar(TYPE, typeobj, size)
Allocate a new Python object using the C structure type *TYPE* and the Allocate a new Python object using the C structure type *TYPE* and the
Python type object *type*. Fields not defined by the Python object header Python type object *typeobj* (``PyTypeObject*``).
Fields not defined by the Python object header
are not initialized. The allocated memory allows for the *TYPE* structure are not initialized. The allocated memory allows for the *TYPE* structure
plus *size* fields of the size given by the :c:member:`~PyTypeObject.tp_itemsize` field of plus *size* (``Py_ssize_t``) fields of the size
*type*. This is useful for implementing objects like tuples, which are given by the :c:member:`~PyTypeObject.tp_itemsize` field of
*typeobj*. This is useful for implementing objects like tuples, which are
able to determine their size at construction time. Embedding the array of able to determine their size at construction time. Embedding the array of
fields into the same allocation decreases the number of allocations, fields into the same allocation decreases the number of allocations,
improving the memory management efficiency. improving the memory management efficiency.
@ -50,8 +53,8 @@ Allocating Objects on the Heap
.. c:function:: void PyObject_Del(void *op) .. c:function:: void PyObject_Del(void *op)
Releases memory allocated to an object using :c:func:`PyObject_New` or Releases memory allocated to an object using :c:macro:`PyObject_New` or
:c:func:`PyObject_NewVar`. This is normally called from the :c:macro:`PyObject_NewVar`. This is normally called from the
:c:member:`~PyTypeObject.tp_dealloc` handler specified in the object's type. The fields of :c:member:`~PyTypeObject.tp_dealloc` handler specified in the object's type. The fields of
the object should not be accessed after this call as the memory is no the object should not be accessed after this call as the memory is no
longer a valid Python object. longer a valid Python object.

View File

@ -64,7 +64,7 @@ Refer to :ref:`using-capsules` for more information on using these objects.
The *name* parameter must compare exactly to the name stored in the capsule. 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 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. names.

View File

@ -64,7 +64,7 @@ pointers. This is consistent throughout the API.
representation. representation.
If *divisor* is null, this method returns zero and sets If *divisor* is null, this method returns zero and sets
:c:data:`errno` to :c:macro:`EDOM`. :c:data:`errno` to :c:macro:`!EDOM`.
.. c:function:: Py_complex _Py_c_pow(Py_complex num, Py_complex exp) .. c:function:: Py_complex _Py_c_pow(Py_complex num, Py_complex exp)
@ -73,7 +73,7 @@ pointers. This is consistent throughout the API.
representation. representation.
If *num* is null and *exp* is not a positive real number, If *num* is null and *exp* is not a positive real number,
this method returns zero and sets :c:data:`errno` to :c:macro:`EDOM`. this method returns zero and sets :c:data:`errno` to :c:macro:`!EDOM`.
Complex Numbers as Python Objects Complex Numbers as Python Objects

View File

@ -119,10 +119,10 @@ The following functions provide locale-independent string to number conversions.
.. c:function:: int PyOS_stricmp(const char *s1, const char *s2) .. c:function:: int PyOS_stricmp(const char *s1, const char *s2)
Case insensitive comparison of strings. The function works almost Case insensitive comparison of strings. The function works almost
identically to :c:func:`strcmp` except that it ignores the case. 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 Case insensitive comparison of strings. The function works almost
identically to :c:func:`strncmp` except that it ignores the case. identically to :c:func:`!strncmp` except that it ignores the case.

View File

@ -83,7 +83,7 @@ Printing and clearing
This utility function prints a warning message to ``sys.stderr`` when an 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 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:`__del__` method. :meth:`~object.__del__` method.
The function is called with a single argument *obj* that identifies the context The function is called with a single argument *obj* that identifies the context
in which the unraisable exception occurred. If possible, in which the unraisable exception occurred. If possible,
@ -165,7 +165,7 @@ For convenience, some of these functions will always return a
tuple object whose first item is the integer :c:data:`errno` value and whose 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`), 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, :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, 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);`` function around a system call can write ``return PyErr_SetFromErrno(type);``
@ -177,7 +177,7 @@ For convenience, some of these functions will always return a
Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if 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 *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 this is used to define the :attr:`!filename` attribute of the
exception instance. exception instance.
@ -200,12 +200,12 @@ For convenience, some of these functions will always return a
.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr) .. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr)
This is a convenience function to raise :exc:`WindowsError`. If called with This is a convenience function to raise :exc:`WindowsError`. If called with
*ierr* of ``0``, the error code returned by a call to :c:func:`GetLastError` *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`, the Windows description of error code given by *ierr* or :c:func:`!GetLastError`,
then it constructs a tuple object whose first item is the *ierr* value and whose then it constructs a tuple object whose first item is the *ierr* value and whose
second item is the corresponding error message (gotten from second item is the corresponding error message (gotten from
:c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError, :c:func:`!FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError,
object)``. This function always returns ``NULL``. object)``. This function always returns ``NULL``.
.. availability:: Windows. .. availability:: Windows.
@ -631,7 +631,7 @@ Signal Handling
be interruptible by user requests (such as by pressing Ctrl-C). be interruptible by user requests (such as by pressing Ctrl-C).
.. note:: .. note::
The default Python signal handler for :c:macro:`SIGINT` raises the The default Python signal handler for :c:macro:`!SIGINT` raises the
:exc:`KeyboardInterrupt` exception. :exc:`KeyboardInterrupt` exception.
@ -642,7 +642,7 @@ Signal Handling
single: SIGINT single: SIGINT
single: KeyboardInterrupt (built-in exception) single: KeyboardInterrupt (built-in exception)
Simulate the effect of a :c:macro:`SIGINT` signal arriving. Simulate the effect of a :c:macro:`!SIGINT` signal arriving.
This is equivalent to ``PyErr_SetInterruptEx(SIGINT)``. This is equivalent to ``PyErr_SetInterruptEx(SIGINT)``.
.. note:: .. note::

View File

@ -25,8 +25,8 @@ include the :c:macro:`Py_TPFLAGS_HAVE_GC` and provide an implementation of the
Constructors for container types must conform to two rules: Constructors for container types must conform to two rules:
#. The memory for the object must be allocated using :c:func:`PyObject_GC_New` #. The memory for the object must be allocated using :c:macro:`PyObject_GC_New`
or :c:func:`PyObject_GC_NewVar`. or :c:macro:`PyObject_GC_NewVar`.
#. Once all the fields which may contain references to other containers are #. Once all the fields which may contain references to other containers are
initialized, it must call :c:func:`PyObject_GC_Track`. initialized, it must call :c:func:`PyObject_GC_Track`.
@ -52,19 +52,19 @@ rules:
class that implements the garbage collector protocol and the child class class that implements the garbage collector protocol and the child class
does *not* include the :c:macro:`Py_TPFLAGS_HAVE_GC` flag. does *not* include the :c:macro:`Py_TPFLAGS_HAVE_GC` flag.
.. c:function:: TYPE* PyObject_GC_New(TYPE, PyTypeObject *type) .. c:macro:: PyObject_GC_New(TYPE, typeobj)
Analogous to :c:func:`PyObject_New` but for container objects with the Analogous to :c:macro:`PyObject_New` but for container objects with the
:c:macro:`Py_TPFLAGS_HAVE_GC` flag set. :c:macro:`Py_TPFLAGS_HAVE_GC` flag set.
.. c:function:: TYPE* PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) .. c:macro:: PyObject_GC_NewVar(TYPE, typeobj, size)
Analogous to :c:func:`PyObject_NewVar` but for container objects with the Analogous to :c:macro:`PyObject_NewVar` but for container objects with the
:c:macro:`Py_TPFLAGS_HAVE_GC` flag set. :c:macro:`Py_TPFLAGS_HAVE_GC` flag set.
.. c:function:: PyObject* PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *type, size_t extra_size) .. c:function:: PyObject* PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *type, size_t extra_size)
Analogous to :c:func:`PyObject_GC_New` but allocates *extra_size* Analogous to :c:macro:`PyObject_GC_New` but allocates *extra_size*
bytes at the end of the object (at offset bytes at the end of the object (at offset
:c:member:`~PyTypeObject.tp_basicsize`). :c:member:`~PyTypeObject.tp_basicsize`).
The allocated memory is initialized to zeros, The allocated memory is initialized to zeros,
@ -85,7 +85,7 @@ rules:
.. c:function:: TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize) .. c:function:: TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize)
Resize an object allocated by :c:func:`PyObject_NewVar`. Returns the Resize an object allocated by :c:macro:`PyObject_NewVar`. Returns the
resized object or ``NULL`` on failure. *op* must not be tracked by the collector yet. resized object or ``NULL`` on failure. *op* must not be tracked by the collector yet.
@ -128,8 +128,8 @@ rules:
.. c:function:: void PyObject_GC_Del(void *op) .. c:function:: void PyObject_GC_Del(void *op)
Releases memory allocated to an object using :c:func:`PyObject_GC_New` or Releases memory allocated to an object using :c:macro:`PyObject_GC_New` or
:c:func:`PyObject_GC_NewVar`. :c:macro:`PyObject_GC_NewVar`.
.. c:function:: void PyObject_GC_UnTrack(void *op) .. c:function:: void PyObject_GC_UnTrack(void *op)

View File

@ -151,10 +151,10 @@ Importing Modules
The module's :attr:`__spec__` and :attr:`__loader__` will be set, if The module's :attr:`__spec__` and :attr:`__loader__` will be set, if
not set already, with the appropriate values. The spec's loader will not set already, with the appropriate values. The spec's loader will
be set to the module's ``__loader__`` (if set) and to an instance of be set to the module's ``__loader__`` (if set) and to an instance of
:class:`SourceFileLoader` otherwise. :class:`~importlib.machinery.SourceFileLoader` otherwise.
The module's :attr:`__file__` attribute will be set to the code object's The module's :attr:`__file__` attribute will be set to the code object's
:attr:`co_filename`. If applicable, :attr:`__cached__` will also :attr:`!co_filename`. If applicable, :attr:`__cached__` will also
be set. 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
@ -241,7 +241,7 @@ Importing Modules
.. c:function:: PyObject* PyImport_GetImporter(PyObject *path) .. c:function:: PyObject* PyImport_GetImporter(PyObject *path)
Return a finder object for a :data:`sys.path`/:attr:`pkg.__path__` item 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` *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 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; is found that can handle the path item. Return ``None`` if no hook could;

View File

@ -25,7 +25,7 @@ The following functions can be safely called before Python is initialized:
* :c:func:`PyImport_AppendInittab` * :c:func:`PyImport_AppendInittab`
* :c:func:`PyImport_ExtendInittab` * :c:func:`PyImport_ExtendInittab`
* :c:func:`PyInitFrozenExtensions` * :c:func:`!PyInitFrozenExtensions`
* :c:func:`PyMem_SetAllocator` * :c:func:`PyMem_SetAllocator`
* :c:func:`PyMem_SetupDebugHooks` * :c:func:`PyMem_SetupDebugHooks`
* :c:func:`PyObject_SetArenaAllocator` * :c:func:`PyObject_SetArenaAllocator`
@ -151,7 +151,7 @@ to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2.
:c:member:`PyConfig.use_environment` should be used instead, see :c:member:`PyConfig.use_environment` should be used instead, see
:ref:`Python Initialization Configuration <init-config>`. :ref:`Python Initialization Configuration <init-config>`.
Ignore all :envvar:`PYTHON*` environment variables, e.g. Ignore all :envvar:`!PYTHON*` environment variables, e.g.
:envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set. :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.
Set by the :option:`-E` and :option:`-I` options. Set by the :option:`-E` and :option:`-I` options.
@ -224,7 +224,7 @@ to 1 and ``-bb`` sets :c:data:`Py_BytesWarningFlag` to 2.
:ref:`Python Initialization Configuration <init-config>`. :ref:`Python Initialization Configuration <init-config>`.
If the flag is non-zero, use :class:`io.FileIO` instead of If the flag is non-zero, use :class:`io.FileIO` instead of
:class:`WindowsConsoleIO` for :mod:`sys` standard streams. :class:`!io._WindowsConsoleIO` for :mod:`sys` standard streams.
Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment
variable is set to a non-empty string. variable is set to a non-empty string.
@ -393,7 +393,7 @@ Initializing and finalizing the interpreter
the application. the application.
**Bugs and caveats:** The destruction of modules and objects in modules is done **Bugs and caveats:** The destruction of modules and objects in modules is done
in random order; this may cause destructors (:meth:`__del__` methods) to fail in random order; this may cause destructors (:meth:`~object.__del__` methods) to fail
when they depend on other objects (even functions) or modules. Dynamically when they depend on other objects (even functions) or modules. Dynamically
loaded extension modules loaded by Python are not unloaded. Small amounts of 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, memory allocated by the Python interpreter may not be freed (if you find a leak,
@ -417,7 +417,7 @@ Process-wide parameters
======================= =======================
.. c:function:: wchar* Py_GetProgramName() .. c:function:: wchar_t* Py_GetProgramName()
Return the program name set with :c:member:`PyConfig.program_name`, or the default. Return the program name set with :c:member:`PyConfig.program_name`, or the default.
The returned string points into static storage; the caller should not modify its The returned string points into static storage; the caller should not modify its
@ -785,7 +785,7 @@ the fork, and releasing them afterwards. In addition, it resets any
:ref:`lock-objects` in the child. When extending or embedding Python, there :ref:`lock-objects` in the child. When extending or embedding Python, there
is no way to inform Python of additional (non-Python) locks that need to be is no way to inform Python of additional (non-Python) locks that need to be
acquired before or reset after a fork. OS facilities such as acquired before or reset after a fork. OS facilities such as
:c:func:`pthread_atfork` would need to be used to accomplish the same thing. :c:func:`!pthread_atfork` would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling :c:func:`fork` Additionally, when extending or embedding Python, calling :c:func:`fork`
directly rather than through :func:`os.fork` (and returning to or calling directly rather than through :func:`os.fork` (and returning to or calling
into Python) may result in a deadlock by one of Python's internal locks into Python) may result in a deadlock by one of Python's internal locks
@ -849,7 +849,7 @@ code, or when embedding the Python interpreter:
.. note:: .. note::
Calling this function from a thread when the runtime is finalizing Calling this function from a thread when the runtime is finalizing
will terminate the thread, even if the thread was not created by Python. will terminate the thread, even if the thread was not created by Python.
You can use :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to You can use :c:func:`!_Py_IsFinalizing` or :func:`sys.is_finalizing` to
check if the interpreter is in process of being finalized before calling check if the interpreter is in process of being finalized before calling
this function to avoid unwanted termination. this function to avoid unwanted termination.
@ -895,7 +895,7 @@ with sub-interpreters:
.. note:: .. note::
Calling this function from a thread when the runtime is finalizing Calling this function from a thread when the runtime is finalizing
will terminate the thread, even if the thread was not created by Python. will terminate the thread, even if the thread was not created by Python.
You can use :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to You can use :c:func:`!_Py_IsFinalizing` or :func:`sys.is_finalizing` to
check if the interpreter is in process of being finalized before calling check if the interpreter is in process of being finalized before calling
this function to avoid unwanted termination. this function to avoid unwanted termination.
@ -1177,7 +1177,7 @@ All of the following functions must be called after :c:func:`Py_Initialize`.
.. note:: .. note::
Calling this function from a thread when the runtime is finalizing Calling this function from a thread when the runtime is finalizing
will terminate the thread, even if the thread was not created by Python. will terminate the thread, even if the thread was not created by Python.
You can use :c:func:`_Py_IsFinalizing` or :func:`sys.is_finalizing` to You can use :c:func:`!_Py_IsFinalizing` or :func:`sys.is_finalizing` to
check if the interpreter is in process of being finalized before calling check if the interpreter is in process of being finalized before calling
this function to avoid unwanted termination. this function to avoid unwanted termination.

View File

@ -889,7 +889,7 @@ PyConfig
.. c:member:: int legacy_windows_stdio .. c:member:: int legacy_windows_stdio
If non-zero, use :class:`io.FileIO` instead of If non-zero, use :class:`io.FileIO` instead of
:class:`io.WindowsConsoleIO` for :data:`sys.stdin`, :data:`sys.stdout` :class:`!io._WindowsConsoleIO` for :data:`sys.stdin`, :data:`sys.stdout`
and :data:`sys.stderr`. and :data:`sys.stderr`.
Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment Set to ``1`` if the :envvar:`PYTHONLEGACYWINDOWSSTDIO` environment
@ -1139,7 +1139,7 @@ PyConfig
Set to ``0`` by the :option:`-S` command line option. Set to ``0`` by the :option:`-S` command line option.
:data:`sys.flags.no_site` is set to the inverted value of :data:`sys.flags.no_site <sys.flags>` is set to the inverted value of
:c:member:`~PyConfig.site_import`. :c:member:`~PyConfig.site_import`.
Default: ``1``. Default: ``1``.

View File

@ -136,7 +136,7 @@ need to be held.
The :ref:`default raw memory allocator <default-memory-allocators>` uses The :ref:`default raw memory allocator <default-memory-allocators>` uses
the following functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` the following functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc`
and :c:func:`free`; call ``malloc(1)`` (or ``calloc(1, 1)``) when requesting and :c:func:`!free`; call ``malloc(1)`` (or ``calloc(1, 1)``) when requesting
zero bytes. zero bytes.
.. versionadded:: 3.4 .. versionadded:: 3.4
@ -264,14 +264,14 @@ The following type-oriented macros are provided for convenience. Note that
*TYPE* refers to any C type. *TYPE* refers to any C type.
.. c:function:: TYPE* PyMem_New(TYPE, size_t n) .. c:macro:: PyMem_New(TYPE, n)
Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of
memory. Returns a pointer cast to :c:expr:`TYPE*`. The memory will not have memory. Returns a pointer cast to :c:expr:`TYPE*`. The memory will not have
been initialized in any way. been initialized in any way.
.. c:function:: TYPE* PyMem_Resize(void *p, TYPE, size_t n) .. c:macro:: PyMem_Resize(p, TYPE, n)
Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n * Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n *
sizeof(TYPE))`` bytes. Returns a pointer cast to :c:expr:`TYPE*`. On return, sizeof(TYPE))`` bytes. Returns a pointer cast to :c:expr:`TYPE*`. On return,
@ -423,7 +423,7 @@ Customize Memory Allocators
+----------------------------------------------------------+---------------------------------------+ +----------------------------------------------------------+---------------------------------------+
.. versionchanged:: 3.5 .. versionchanged:: 3.5
The :c:type:`PyMemAllocator` structure was renamed to The :c:type:`!PyMemAllocator` structure was renamed to
:c:type:`PyMemAllocatorEx` and a new ``calloc`` field was added. :c:type:`PyMemAllocatorEx` and a new ``calloc`` field was added.
@ -627,8 +627,8 @@ with a fixed size of 256 KiB. It falls back to :c:func:`PyMem_RawMalloc` and
The arena allocator uses the following functions: The arena allocator uses the following functions:
* :c:func:`VirtualAlloc` and :c:func:`VirtualFree` on Windows, * :c:func:`!VirtualAlloc` and :c:func:`!VirtualFree` on Windows,
* :c:func:`mmap` and :c:func:`munmap` if available, * :c:func:`!mmap` and :c:func:`!munmap` if available,
* :c:func:`malloc` and :c:func:`free` otherwise. * :c:func:`malloc` and :c:func:`free` otherwise.
This allocator is disabled if Python is configured with the This allocator is disabled if Python is configured with the
@ -732,8 +732,8 @@ allocators operating on different heaps. ::
free(buf1); /* Fatal -- should be PyMem_Del() */ free(buf1); /* Fatal -- should be PyMem_Del() */
In addition to the functions aimed at handling raw memory blocks from the Python In addition to the functions aimed at handling raw memory blocks from the Python
heap, objects in Python are allocated and released with :c:func:`PyObject_New`, heap, objects in Python are allocated and released with :c:macro:`PyObject_New`,
:c:func:`PyObject_NewVar` and :c:func:`PyObject_Del`. :c:macro:`PyObject_NewVar` and :c:func:`PyObject_Del`.
These will be explained in the next chapter on defining and implementing new These will be explained in the next chapter on defining and implementing new
object types in C. object types in C.

View File

@ -282,7 +282,7 @@ An alternate way to specify extensions is to request "multi-phase initialization
Extension modules created this way behave more like Python modules: the Extension modules created this way behave more like Python modules: the
initialization is split between the *creation phase*, when the module object initialization is split between the *creation phase*, when the module object
is created, and the *execution phase*, when it is populated. is created, and the *execution phase*, when it is populated.
The distinction is similar to the :py:meth:`__new__` and :py:meth:`__init__` methods The distinction is similar to the :py:meth:`!__new__` and :py:meth:`!__init__` methods
of classes. of classes.
Unlike modules created using single-phase initialization, these modules are not Unlike modules created using single-phase initialization, these modules are not
@ -293,7 +293,7 @@ By default, multiple modules created from the same definition should be
independent: changes to one should not affect the others. independent: changes to one should not affect the others.
This means that all state should be specific to the module object (using e.g. This means that all state should be specific to the module object (using e.g.
using :c:func:`PyModule_GetState`), or its contents (such as the module's using :c:func:`PyModule_GetState`), or its contents (such as the module's
:attr:`__dict__` or individual classes created with :c:func:`PyType_FromSpec`). :attr:`~object.__dict__` or individual classes created with :c:func:`PyType_FromSpec`).
All modules created using multi-phase initialization are expected to support All modules created using multi-phase initialization are expected to support
:ref:`sub-interpreters <sub-interpreter-support>`. Making sure multiple modules :ref:`sub-interpreters <sub-interpreter-support>`. Making sure multiple modules
@ -552,7 +552,7 @@ state:
``NULL``-terminated. Return ``-1`` on error, ``0`` on success. ``NULL``-terminated. Return ``-1`` on error, ``0`` on success.
.. c:function:: int PyModule_AddIntMacro(PyObject *module, macro) .. c:macro:: PyModule_AddIntMacro(module, macro)
Add an int constant to *module*. The name and the value are taken from Add an int constant to *module*. The name and the value are taken from
*macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int *macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int
@ -560,7 +560,7 @@ state:
Return ``-1`` on error, ``0`` on success. Return ``-1`` on error, ``0`` on success.
.. c:function:: int PyModule_AddStringMacro(PyObject *module, macro) .. c:macro:: PyModule_AddStringMacro(module, macro)
Add a string constant to *module*. Add a string constant to *module*.

View File

@ -122,7 +122,7 @@ or :class:`frozenset` or instances of their subtypes.
.. c:function:: int PySet_Contains(PyObject *anyset, PyObject *key) .. c:function:: int PySet_Contains(PyObject *anyset, PyObject *key)
Return ``1`` if found, ``0`` if not found, and ``-1`` if an error is encountered. Unlike Return ``1`` if found, ``0`` if not found, and ``-1`` if an error is encountered. Unlike
the Python :meth:`__contains__` method, this function does not automatically 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:`PyExc_SystemError` if *anyset* is not a the *key* is unhashable. Raise :exc:`PyExc_SystemError` if *anyset* is not a
:class:`set`, :class:`frozenset`, or an instance of a subtype. :class:`set`, :class:`frozenset`, or an instance of a subtype.

View File

@ -393,7 +393,7 @@ definition with the same method name.
*METH_COEXIST*, the default is to skip repeated definitions. Since slot *METH_COEXIST*, the default is to skip repeated definitions. Since slot
wrappers are loaded before the method table, the existence of a wrappers are loaded before the method table, the existence of a
*sq_contains* slot, for example, would generate a wrapped method named *sq_contains* slot, for example, would generate a wrapped method named
:meth:`__contains__` and preclude the loading of a corresponding :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 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

View File

@ -363,7 +363,7 @@ Process Control
This function should only be invoked when a condition is detected that would 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 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` function :c:func:`!abort` is called which will attempt to produce a :file:`core`
file. file.
The ``Py_FatalError()`` function is replaced with a macro which logs The ``Py_FatalError()`` function is replaced with a macro which logs

View File

@ -579,7 +579,7 @@ and :c:data:`PyType_Type` effectively act as defaults.)
name, followed by a dot, followed by the type name; for built-in types, it 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 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 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` :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"``. should have the :c:member:`~PyTypeObject.tp_name` initializer ``"P.Q.M.T"``.
For :ref:`dynamically allocated type objects <heap-types>`, For :ref:`dynamically allocated type objects <heap-types>`,
@ -673,9 +673,9 @@ and :c:data:`PyType_Type` effectively act as defaults.)
permissible to call the object deallocator directly instead of via permissible to call the object deallocator directly instead of via
:c:member:`~PyTypeObject.tp_free`. The object deallocator should be the one used to allocate the :c:member:`~PyTypeObject.tp_free`. The object deallocator should be the one used to allocate the
instance; this is normally :c:func:`PyObject_Del` if the instance was allocated instance; this is normally :c:func:`PyObject_Del` if the instance was allocated
using :c:func:`PyObject_New` or :c:func:`PyObject_VarNew`, or using :c:macro:`PyObject_New` or :c:macro:`PyObject_NewVar`, or
:c:func:`PyObject_GC_Del` if the instance was allocated using :c:func:`PyObject_GC_Del` if the instance was allocated using
:c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`. :c:macro:`PyObject_GC_New` or :c:macro:`PyObject_GC_NewVar`.
If the type supports garbage collection (has the :c:macro:`Py_TPFLAGS_HAVE_GC` If the type supports garbage collection (has the :c:macro:`Py_TPFLAGS_HAVE_GC`
flag bit set), the destructor should call :c:func:`PyObject_GC_UnTrack` flag bit set), the destructor should call :c:func:`PyObject_GC_UnTrack`
@ -1092,7 +1092,7 @@ and :c:data:`PyType_Type` effectively act as defaults.)
.. c:macro:: Py_TPFLAGS_HAVE_GC .. 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, instances must be created using :c:func:`PyObject_GC_New` and is set, instances must be created using :c:macro:`PyObject_GC_New` and
destroyed using :c:func:`PyObject_GC_Del`. More information in section destroyed using :c:func:`PyObject_GC_Del`. More information in section
:ref:`supporting-cycle-detection`. This bit also implies that the :ref:`supporting-cycle-detection`. This bit also implies that the
GC-related fields :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` are present in GC-related fields :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` are present in
@ -1180,7 +1180,7 @@ and :c:data:`PyType_Type` effectively act as defaults.)
Indicates that the variable-sized portion of an instance of this type is Indicates that the variable-sized portion of an instance of this type is
at the end of the instance's memory area, at an offset of at the end of the instance's memory area, at an offset of
:c:expr:`Py_TYPE(obj)->tp_basicsize` (which may be different in each ``Py_TYPE(obj)->tp_basicsize`` (which may be different in each
subclass). subclass).
When setting this flag, be sure that all superclasses either When setting this flag, be sure that all superclasses either

View File

@ -601,7 +601,7 @@ APIs:
Py_ssize_t how_many) 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 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 number of copied characters.
@ -714,7 +714,7 @@ system.
.. c:function:: PyObject* PyUnicode_DecodeLocale(const char *str, const char *errors) .. c:function:: PyObject* PyUnicode_DecodeLocale(const char *str, const char *errors)
Similar to :c:func:`PyUnicode_DecodeLocaleAndSize`, but compute the string Similar to :c:func:`PyUnicode_DecodeLocaleAndSize`, but compute the string
length using :c:func:`strlen`. length using :c:func:`!strlen`.
.. versionadded:: 3.3 .. versionadded:: 3.3
@ -872,7 +872,7 @@ wchar_t Support
most C functions. If *size* is ``NULL`` and the :c:expr:`wchar_t*` string most C functions. If *size* is ``NULL`` and the :c:expr:`wchar_t*` string
contains null characters a :exc:`ValueError` is raised. contains null characters a :exc:`ValueError` is raised.
Returns a buffer allocated by :c:func:`PyMem_New` (use Returns a buffer allocated by :c:macro:`PyMem_New` (use
:c:func:`PyMem_Free` to free it) on success. On error, returns ``NULL`` :c:func:`PyMem_Free` to free it) on success. On error, returns ``NULL``
and *\*size* is undefined. Raises a :exc:`MemoryError` if memory allocation and *\*size* is undefined. Raises a :exc:`MemoryError` if memory allocation
is failed. is failed.

View File

@ -97,7 +97,7 @@ nitpick_ignore = [
('c:func', 'vsnprintf'), ('c:func', 'vsnprintf'),
# Standard C types # Standard C types
('c:type', 'FILE'), ('c:type', 'FILE'),
('c:type', '__int'), ('c:type', 'int64_t'),
('c:type', 'intmax_t'), ('c:type', 'intmax_t'),
('c:type', 'off_t'), ('c:type', 'off_t'),
('c:type', 'ptrdiff_t'), ('c:type', 'ptrdiff_t'),
@ -105,9 +105,12 @@ nitpick_ignore = [
('c:type', 'size_t'), ('c:type', 'size_t'),
('c:type', 'ssize_t'), ('c:type', 'ssize_t'),
('c:type', 'time_t'), ('c:type', 'time_t'),
('c:type', 'uint64_t'),
('c:type', 'uintmax_t'), ('c:type', 'uintmax_t'),
('c:type', 'uintptr_t'),
('c:type', 'va_list'), ('c:type', 'va_list'),
('c:type', 'wchar_t'), ('c:type', 'wchar_t'),
# Standard C structures
('c:struct', 'in6_addr'), ('c:struct', 'in6_addr'),
('c:struct', 'in_addr'), ('c:struct', 'in_addr'),
('c:struct', 'stat'), ('c:struct', 'stat'),

View File

@ -230,7 +230,7 @@ with an exception object::
return m; return m;
} }
Note that the Python name for the exception object is :exc:`spam.error`. The Note that the Python name for the exception object is :exc:`!spam.error`. The
:c:func:`PyErr_NewException` function may create a class with the base class :c:func:`PyErr_NewException` function may create a class with the base class
being :exc:`Exception` (unless another class is passed in instead of ``NULL``), being :exc:`Exception` (unless another class is passed in instead of ``NULL``),
described in :ref:`bltin-exceptions`. described in :ref:`bltin-exceptions`.
@ -245,7 +245,7 @@ raises the exception could cause a core dump or other unintended side effects.
We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this
sample. sample.
The :exc:`spam.error` exception can be raised in your extension module using a The :exc:`!spam.error` exception can be raised in your extension module using a
call to :c:func:`PyErr_SetString` as shown below:: call to :c:func:`PyErr_SetString` as shown below::
static PyObject * static PyObject *
@ -315,7 +315,7 @@ contexts, as we have seen.
The Module's Method Table and Initialization Function The Module's Method Table and Initialization Function
===================================================== =====================================================
I promised to show how :c:func:`spam_system` is called from Python programs. I promised to show how :c:func:`!spam_system` is called from Python programs.
First, we need to list its name and address in a "method table":: First, we need to list its name and address in a "method table"::
static PyMethodDef SpamMethods[] = { static PyMethodDef SpamMethods[] = {
@ -1041,13 +1041,13 @@ Let's follow the control flow into :c:func:`PyList_SetItem`. The list owns
references to all its items, so when item 1 is replaced, it has to dispose of references to all its items, so when item 1 is replaced, it has to dispose of
the original item 1. Now let's suppose the original item 1 was an instance of a the original item 1. Now let's suppose the original item 1 was an instance of a
user-defined class, and let's further suppose that the class defined a user-defined class, and let's further suppose that the class defined a
:meth:`__del__` method. If this class instance has a reference count of 1, :meth:`!__del__` method. If this class instance has a reference count of 1,
disposing of it will call its :meth:`__del__` method. disposing of it will call its :meth:`!__del__` method.
Since it is written in Python, the :meth:`__del__` method can execute arbitrary Since it is written in Python, the :meth:`!__del__` method can execute arbitrary
Python code. Could it perhaps do something to invalidate the reference to Python code. Could it perhaps do something to invalidate the reference to
``item`` in :c:func:`bug`? You bet! Assuming that the list passed into ``item`` in :c:func:`!bug`? You bet! Assuming that the list passed into
:c:func:`bug` is accessible to the :meth:`__del__` method, it could execute a :c:func:`!bug` is accessible to the :meth:`!__del__` method, it could execute a
statement to the effect of ``del list[0]``, and assuming this was the last statement to the effect of ``del list[0]``, and assuming this was the last
reference to that object, it would free the memory associated with it, thereby reference to that object, it would free the memory associated with it, thereby
invalidating ``item``. invalidating ``item``.
@ -1068,7 +1068,7 @@ increment the reference count. The correct version of the function reads::
This is a true story. An older version of Python contained variants of this bug This is a true story. An older version of Python contained variants of this bug
and someone spent a considerable amount of time in a C debugger to figure out and someone spent a considerable amount of time in a C debugger to figure out
why his :meth:`__del__` methods would fail... why his :meth:`!__del__` methods would fail...
The second case of problems with a borrowed reference is a variant involving The second case of problems with a borrowed reference is a variant involving
threads. Normally, multiple threads in the Python interpreter can't get in each threads. Normally, multiple threads in the Python interpreter can't get in each
@ -1235,7 +1235,7 @@ The function :c:func:`PySpam_System` is a plain C function, declared
return system(command); return system(command);
} }
The function :c:func:`spam_system` is modified in a trivial way:: The function :c:func:`!spam_system` is modified in a trivial way::
static PyObject * static PyObject *
spam_system(PyObject *self, PyObject *args) spam_system(PyObject *self, PyObject *args)

View File

@ -36,7 +36,7 @@ So, if you want to define a new extension type, you need to create a new type
object. object.
This sort of thing can only be explained by example, so here's a minimal, but This sort of thing can only be explained by example, so here's a minimal, but
complete, module that defines a new type named :class:`Custom` inside a C complete, module that defines a new type named :class:`!Custom` inside a C
extension module :mod:`!custom`: extension module :mod:`!custom`:
.. note:: .. note::
@ -50,9 +50,9 @@ extension module :mod:`!custom`:
Now that's quite a bit to take in at once, but hopefully bits will seem familiar Now that's quite a bit to take in at once, but hopefully bits will seem familiar
from the previous chapter. This file defines three things: from the previous chapter. This file defines three things:
#. What a :class:`Custom` **object** contains: this is the ``CustomObject`` #. What a :class:`!Custom` **object** contains: this is the ``CustomObject``
struct, which is allocated once for each :class:`Custom` instance. struct, which is allocated once for each :class:`!Custom` instance.
#. How the :class:`Custom` **type** behaves: this is the ``CustomType`` struct, #. How the :class:`!Custom` **type** behaves: this is the ``CustomType`` struct,
which defines a set of flags and function pointers that the interpreter which defines a set of flags and function pointers that the interpreter
inspects when specific operations are requested. inspects when specific operations are requested.
#. How to initialize the :mod:`!custom` module: this is the ``PyInit_custom`` #. How to initialize the :mod:`!custom` module: this is the ``PyInit_custom``
@ -128,7 +128,7 @@ our objects and in some error messages, for example:
Note that the name is a dotted name that includes both the module name and the Note that the name is a dotted name that includes both the module name and the
name of the type within the module. The module in this case is :mod:`!custom` and name of the type within the module. The module in this case is :mod:`!custom` and
the type is :class:`Custom`, so we set the type name to :class:`custom.Custom`. the type is :class:`!Custom`, so we set the type name to :class:`!custom.Custom`.
Using the real dotted import path is important to make your type compatible Using the real dotted import path is important to make your type compatible
with the :mod:`pydoc` and :mod:`pickle` modules. :: with the :mod:`pydoc` and :mod:`pickle` modules. ::
@ -136,7 +136,7 @@ with the :mod:`pydoc` and :mod:`pickle` modules. ::
.tp_itemsize = 0, .tp_itemsize = 0,
This is so that Python knows how much memory to allocate when creating This is so that Python knows how much memory to allocate when creating
new :class:`Custom` instances. :c:member:`~PyTypeObject.tp_itemsize` is new :class:`!Custom` instances. :c:member:`~PyTypeObject.tp_itemsize` is
only used for variable-sized objects and should otherwise be zero. only used for variable-sized objects and should otherwise be zero.
.. note:: .. note::
@ -176,7 +176,7 @@ Everything else in the file should be familiar, except for some code in
if (PyType_Ready(&CustomType) < 0) if (PyType_Ready(&CustomType) < 0)
return; return;
This initializes the :class:`Custom` type, filling in a number of members This initializes the :class:`!Custom` type, filling in a number of members
to the appropriate default values, including :attr:`ob_type` that we initially to the appropriate default values, including :attr:`ob_type` that we initially
set to ``NULL``. :: set to ``NULL``. ::
@ -186,7 +186,7 @@ set to ``NULL``. ::
} }
This adds the type to the module dictionary. This allows us to create This adds the type to the module dictionary. This allows us to create
:class:`Custom` instances by calling the :class:`Custom` class: :class:`!Custom` instances by calling the :class:`!Custom` class:
.. code-block:: pycon .. code-block:: pycon
@ -237,7 +237,7 @@ adds these capabilities:
This version of the module has a number of changes. This version of the module has a number of changes.
The :class:`Custom` type now has three data attributes in its C struct, The :class:`!Custom` type now has three data attributes in its C struct,
*first*, *last*, and *number*. The *first* and *last* variables are Python *first*, *last*, and *number*. The *first* and *last* variables are Python
strings containing first and last names. The *number* attribute is a C integer. strings containing first and last names. The *number* attribute is a C integer.
@ -312,7 +312,7 @@ The ``tp_new`` handler is responsible for creating (as opposed to initializing)
objects of the type. It is exposed in Python as the :meth:`__new__` method. objects of the type. It is exposed in Python as the :meth:`__new__` method.
It is not required to define a ``tp_new`` member, and indeed many extension It is not required to define a ``tp_new`` member, and indeed many extension
types will simply reuse :c:func:`PyType_GenericNew` as done in the first types will simply reuse :c:func:`PyType_GenericNew` as done in the first
version of the ``Custom`` type above. In this case, we use the ``tp_new`` version of the :class:`!Custom` type above. In this case, we use the ``tp_new``
handler to initialize the ``first`` and ``last`` attributes to non-``NULL`` handler to initialize the ``first`` and ``last`` attributes to non-``NULL``
default values. default values.
@ -451,7 +451,7 @@ Further, the attributes can be deleted, setting the C pointers to ``NULL``. Eve
though we can make sure the members are initialized to non-``NULL`` values, the though we can make sure the members are initialized to non-``NULL`` values, the
members can be set to ``NULL`` if the attributes are deleted. members can be set to ``NULL`` if the attributes are deleted.
We define a single method, :meth:`Custom.name()`, that outputs the objects name as the We define a single method, :meth:`!Custom.name()`, that outputs the objects name as the
concatenation of the first and last names. :: concatenation of the first and last names. ::
static PyObject * static PyObject *
@ -468,8 +468,8 @@ concatenation of the first and last names. ::
return PyUnicode_FromFormat("%S %S", self->first, self->last); return PyUnicode_FromFormat("%S %S", self->first, self->last);
} }
The method is implemented as a C function that takes a :class:`Custom` (or The method is implemented as a C function that takes a :class:`!Custom` (or
:class:`Custom` subclass) instance as the first argument. Methods always take an :class:`!Custom` subclass) instance as the first argument. Methods always take an
instance as the first argument. Methods often take positional and keyword instance as the first argument. Methods often take positional and keyword
arguments as well, but in this case we don't take any and don't need to accept arguments as well, but in this case we don't take any and don't need to accept
a positional argument tuple or keyword argument dictionary. This method is a positional argument tuple or keyword argument dictionary. This method is
@ -480,8 +480,8 @@ equivalent to the Python method:
def name(self): def name(self):
return "%s %s" % (self.first, self.last) return "%s %s" % (self.first, self.last)
Note that we have to check for the possibility that our :attr:`first` and Note that we have to check for the possibility that our :attr:`!first` and
:attr:`last` members are ``NULL``. This is because they can be deleted, in which :attr:`!last` members are ``NULL``. This is because they can be deleted, in which
case they are set to ``NULL``. It would be better to prevent deletion of these case they are set to ``NULL``. It would be better to prevent deletion of these
attributes and to restrict the attribute values to be strings. We'll see how to attributes and to restrict the attribute values to be strings. We'll see how to
do that in the next section. do that in the next section.
@ -510,7 +510,7 @@ to add the :c:macro:`Py_TPFLAGS_BASETYPE` to our class flag definition::
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
We rename :c:func:`PyInit_custom` to :c:func:`PyInit_custom2`, update the We rename :c:func:`!PyInit_custom` to :c:func:`!PyInit_custom2`, update the
module name in the :c:type:`PyModuleDef` struct, and update the full class module name in the :c:type:`PyModuleDef` struct, and update the full class
name in the :c:type:`PyTypeObject` struct. name in the :c:type:`PyTypeObject` struct.
@ -529,18 +529,18 @@ Finally, we update our :file:`setup.py` file to build the new module:
Providing finer control over data attributes Providing finer control over data attributes
============================================ ============================================
In this section, we'll provide finer control over how the :attr:`first` and In this section, we'll provide finer control over how the :attr:`!first` and
:attr:`last` attributes are set in the :class:`Custom` example. In the previous :attr:`!last` attributes are set in the :class:`!Custom` example. In the previous
version of our module, the instance variables :attr:`first` and :attr:`last` version of our module, the instance variables :attr:`!first` and :attr:`!last`
could be set to non-string values or even deleted. We want to make sure that could be set to non-string values or even deleted. We want to make sure that
these attributes always contain strings. these attributes always contain strings.
.. literalinclude:: ../includes/custom3.c .. literalinclude:: ../includes/custom3.c
To provide greater control, over the :attr:`first` and :attr:`last` attributes, To provide greater control, over the :attr:`!first` and :attr:`!last` attributes,
we'll use custom getter and setter functions. Here are the functions for we'll use custom getter and setter functions. Here are the functions for
getting and setting the :attr:`first` attribute:: getting and setting the :attr:`!first` attribute::
static PyObject * static PyObject *
Custom_getfirst(CustomObject *self, void *closure) Custom_getfirst(CustomObject *self, void *closure)
@ -569,13 +569,13 @@ getting and setting the :attr:`first` attribute::
return 0; return 0;
} }
The getter function is passed a :class:`Custom` object and a "closure", which is The getter function is passed a :class:`!Custom` object and a "closure", which is
a void pointer. In this case, the closure is ignored. (The closure supports an a void pointer. In this case, the closure is ignored. (The closure supports an
advanced usage in which definition data is passed to the getter and setter. This advanced usage in which definition data is passed to the getter and setter. This
could, for example, be used to allow a single set of getter and setter functions could, for example, be used to allow a single set of getter and setter functions
that decide the attribute to get or set based on data in the closure.) that decide the attribute to get or set based on data in the closure.)
The setter function is passed the :class:`Custom` object, the new value, and the The setter function is passed the :class:`!Custom` object, the new value, and the
closure. The new value may be ``NULL``, in which case the attribute is being closure. The new value may be ``NULL``, in which case the attribute is being
deleted. In our setter, we raise an error if the attribute is deleted or if its deleted. In our setter, we raise an error if the attribute is deleted or if its
new value is not a string. new value is not a string.
@ -664,11 +664,11 @@ still has a reference from itself. Its reference count doesn't drop to zero.
Fortunately, Python's cyclic garbage collector will eventually figure out that Fortunately, Python's cyclic garbage collector will eventually figure out that
the list is garbage and free it. the list is garbage and free it.
In the second version of the :class:`Custom` example, we allowed any kind of In the second version of the :class:`!Custom` example, we allowed any kind of
object to be stored in the :attr:`first` or :attr:`last` attributes [#]_. object to be stored in the :attr:`!first` or :attr:`!last` attributes [#]_.
Besides, in the second and third versions, we allowed subclassing Besides, in the second and third versions, we allowed subclassing
:class:`Custom`, and subclasses may add arbitrary attributes. For any of :class:`!Custom`, and subclasses may add arbitrary attributes. For any of
those two reasons, :class:`Custom` objects can participate in cycles: those two reasons, :class:`!Custom` objects can participate in cycles:
.. code-block:: pycon .. code-block:: pycon
@ -678,8 +678,8 @@ those two reasons, :class:`Custom` objects can participate in cycles:
>>> n = Derived() >>> n = Derived()
>>> n.some_attribute = n >>> n.some_attribute = n
To allow a :class:`Custom` instance participating in a reference cycle to To allow a :class:`!Custom` instance participating in a reference cycle to
be properly detected and collected by the cyclic GC, our :class:`Custom` type be properly detected and collected by the cyclic GC, our :class:`!Custom` type
needs to fill two additional slots and to enable a flag that enables these slots: needs to fill two additional slots and to enable a flag that enables these slots:
.. literalinclude:: ../includes/custom4.c .. literalinclude:: ../includes/custom4.c
@ -809,7 +809,7 @@ increases an internal counter:
.. literalinclude:: ../includes/sublist.c .. literalinclude:: ../includes/sublist.c
As you can see, the source code closely resembles the :class:`Custom` examples in As you can see, the source code closely resembles the :class:`!Custom` examples in
previous sections. We will break down the main differences between them. :: previous sections. We will break down the main differences between them. ::
typedef struct { typedef struct {
@ -875,7 +875,7 @@ slot with :c:func:`PyType_GenericNew` -- the allocation function from the base
type will be inherited. type will be inherited.
After that, calling :c:func:`PyType_Ready` and adding the type object to the After that, calling :c:func:`PyType_Ready` and adding the type object to the
module is the same as with the basic :class:`Custom` examples. module is the same as with the basic :class:`!Custom` examples.
.. rubric:: Footnotes .. rubric:: Footnotes

View File

@ -2,12 +2,9 @@
# as tested on the CI via check-warnings.py in reusable-docs.yml. # as tested on the CI via check-warnings.py in reusable-docs.yml.
# Keep lines sorted lexicographically to help avoid merge conflicts. # Keep lines sorted lexicographically to help avoid merge conflicts.
Doc/c-api/allocation.rst
Doc/c-api/bool.rst Doc/c-api/bool.rst
Doc/c-api/buffer.rst Doc/c-api/buffer.rst
Doc/c-api/capsule.rst Doc/c-api/capsule.rst
Doc/c-api/complex.rst
Doc/c-api/conversion.rst
Doc/c-api/datetime.rst Doc/c-api/datetime.rst
Doc/c-api/descriptor.rst Doc/c-api/descriptor.rst
Doc/c-api/exceptions.rst Doc/c-api/exceptions.rst

View File

@ -1847,7 +1847,7 @@ specifically for allocating Python objects.
:c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc`, and :c:func:`PyObject_Free`. :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc`, and :c:func:`PyObject_Free`.
* To allocate and free Python objects, use the "object" family * To allocate and free Python objects, use the "object" family
:c:func:`PyObject_New`, :c:func:`PyObject_NewVar`, and :c:func:`PyObject_Del`. :c:macro:`PyObject_New`, :c:macro:`PyObject_NewVar`, and :c:func:`PyObject_Del`.
Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging
features to catch memory overwrites and doubled frees in both extension modules features to catch memory overwrites and doubled frees in both extension modules

View File

@ -2061,8 +2061,8 @@ Changes in the C API
* Remove :c:macro:`Py_INCREF` on the type object after allocating an * Remove :c:macro:`Py_INCREF` on the type object after allocating an
instance - if any. instance - if any.
This may happen after calling :c:func:`PyObject_New`, This may happen after calling :c:macro:`PyObject_New`,
:c:func:`PyObject_NewVar`, :c:func:`PyObject_GC_New`, :c:macro:`PyObject_NewVar`, :c:func:`PyObject_GC_New`,
:c:func:`PyObject_GC_NewVar`, or any other custom allocator that uses :c:func:`PyObject_GC_NewVar`, or any other custom allocator that uses
:c:func:`PyObject_Init` or :c:func:`PyObject_INIT`. :c:func:`PyObject_Init` or :c:func:`PyObject_INIT`.

View File

@ -1389,8 +1389,8 @@ Porting to Python 3.9
* :c:func:`PyObject_IS_GC` macro was converted to a function. * :c:func:`PyObject_IS_GC` macro was converted to a function.
* The :c:func:`PyObject_NEW` macro becomes an alias to the * The :c:func:`PyObject_NEW` macro becomes an alias to the
:c:func:`PyObject_New` macro, and the :c:func:`PyObject_NEW_VAR` macro :c:macro:`PyObject_New` macro, and the :c:func:`PyObject_NEW_VAR` macro
becomes an alias to the :c:func:`PyObject_NewVar` macro. They no longer becomes an alias to the :c:macro:`PyObject_NewVar` macro. They no longer
access directly the :c:member:`PyTypeObject.tp_basicsize` member. access directly the :c:member:`PyTypeObject.tp_basicsize` member.
* :c:func:`PyObject_GET_WEAKREFS_LISTPTR` macro was converted to a function: * :c:func:`PyObject_GET_WEAKREFS_LISTPTR` macro was converted to a function: