Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

Location:
python/vendor/current/Doc/extending
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Doc/extending/building.rst

    r2 r388  
    5959driver script. In the example above, the\ ``ext_modules`` argument to
    6060:func:`setup` is a list of extension modules, each of which is an instance of
    61 the :class:`Extension`. In the example, the instance defines an extension named
    62 ``demo`` which is build by compiling a single source file, :file:`demo.c`.
     61the :class:`~distutils.extension.Extension`. In the example, the instance
     62defines an extension named ``demo`` which is build by compiling a single source
     63file, :file:`demo.c`.
    6364
    6465In many cases, building an extension is more complex, since additional
  • python/vendor/current/Doc/extending/embedding.rst

    r2 r388  
    2626So if you are embedding Python, you are providing your own main program.  One of
    2727the things this main program has to do is initialize the Python interpreter.  At
    28 the very least, you have to call the function :cfunc:`Py_Initialize`.  There are
     28the very least, you have to call the function :c:func:`Py_Initialize`.  There are
    2929optional calls to pass command line arguments to Python.  Then later you can
    3030call the interpreter from any part of the application.
    3131
    3232There are several different ways to call the interpreter: you can pass a string
    33 containing Python statements to :cfunc:`PyRun_SimpleString`, or you can pass a
     33containing Python statements to :c:func:`PyRun_SimpleString`, or you can pass a
    3434stdio file pointer and a file name (for identification in error messages only)
    35 to :cfunc:`PyRun_SimpleFile`.  You can also call the lower-level operations
     35to :c:func:`PyRun_SimpleFile`.  You can also call the lower-level operations
    3636described in the previous chapters to construct and use Python objects.
    3737
     
    6262   main(int argc, char *argv[])
    6363   {
     64     Py_SetProgramName(argv[0]);  /* optional but recommended */
    6465     Py_Initialize();
    6566     PyRun_SimpleString("from time import time,ctime\n"
     
    6970   }
    7071
    71 The above code first initializes the Python interpreter with
    72 :cfunc:`Py_Initialize`, followed by the execution of a hard-coded Python script
    73 that print the date and time.  Afterwards, the :cfunc:`Py_Finalize` call shuts
     72The :c:func:`Py_SetProgramName` function should be called before
     73:c:func:`Py_Initialize` to inform the interpreter about paths to Python run-time
     74libraries.  Next, the Python interpreter is initialized with
     75:c:func:`Py_Initialize`, followed by the execution of a hard-coded Python script
     76that prints the date and time.  Afterwards, the :c:func:`Py_Finalize` call shuts
    7477the interpreter down, followed by the end of the program.  In a real program,
    7578you may want to get the Python script from another source, perhaps a text-editor
    7679routine, a file, or a database.  Getting the Python code from a file can better
    77 be done by using the :cfunc:`PyRun_SimpleFile` function, which saves you the
     80be done by using the :c:func:`PyRun_SimpleFile` function, which saves you the
    7881trouble of allocating memory space and loading the file contents.
    7982
     
    138141in ``argv[2]``.  Its integer arguments are the other values of the ``argv``
    139142array.  If you compile and link this program (let's call the finished executable
    140 :program:`call`), and use it to execute a Python script, such as::
     143:program:`call`), and use it to execute a Python script, such as:
     144
     145.. code-block:: python
    141146
    142147   def multiply(a,b):
     
    163168
    164169After initializing the interpreter, the script is loaded using
    165 :cfunc:`PyImport_Import`.  This routine needs a Python string as its argument,
    166 which is constructed using the :cfunc:`PyString_FromString` data conversion
     170:c:func:`PyImport_Import`.  This routine needs a Python string as its argument,
     171which is constructed using the :c:func:`PyString_FromString` data conversion
    167172routine. ::
    168173
     
    176181
    177182Once the script is loaded, the name we're looking for is retrieved using
    178 :cfunc:`PyObject_GetAttrString`.  If the name exists, and the object returned is
     183:c:func:`PyObject_GetAttrString`.  If the name exists, and the object returned is
    179184callable, you can safely assume that it is a function.  The program then
    180185proceeds by constructing a tuple of arguments as normal.  The call to the Python
     
    219224   };
    220225
    221 Insert the above code just above the :cfunc:`main` function. Also, insert the
    222 following two statements directly after :cfunc:`Py_Initialize`::
     226Insert the above code just above the :c:func:`main` function. Also, insert the
     227following two statements directly after :c:func:`Py_Initialize`::
    223228
    224229   numargs = argc;
     
    227232These two lines initialize the ``numargs`` variable, and make the
    228233:func:`emb.numargs` function accessible to the embedded Python interpreter.
    229 With these extensions, the Python script can do things like ::
     234With these extensions, the Python script can do things like
     235
     236.. code-block:: python
    230237
    231238   import emb
     
    252259.. _link-reqs:
    253260
    254 Linking Requirements
    255 ====================
    256 
    257 While the :program:`configure` script shipped with the Python sources will
    258 correctly build Python to export the symbols needed by dynamically linked
    259 extensions, this is not automatically inherited by applications which embed the
    260 Python library statically, at least on Unix.  This is an issue when the
    261 application is linked to the static runtime library (:file:`libpython.a`) and
    262 needs to load dynamic extensions (implemented as :file:`.so` files).
    263 
    264 The problem is that some entry points are defined by the Python runtime solely
    265 for extension modules to use.  If the embedding application does not use any of
    266 these entry points, some linkers will not include those entries in the symbol
    267 table of the finished executable.  Some additional options are needed to inform
    268 the linker not to remove these symbols.
    269 
    270 Determining the right options to use for any given platform can be quite
    271 difficult, but fortunately the Python configuration already has those values.
    272 To retrieve them from an installed Python interpreter, start an interactive
    273 interpreter and have a short session like this::
    274 
    275    >>> import distutils.sysconfig
    276    >>> distutils.sysconfig.get_config_var('LINKFORSHARED')
     261Compiling and Linking under Unix-like systems
     262=============================================
     263
     264It is not necessarily trivial to find the right flags to pass to your
     265compiler (and linker) in order to embed the Python interpreter into your
     266application, particularly because Python needs to load library modules
     267implemented as C dynamic extensions (:file:`.so` files) linked against
     268it.
     269
     270To find out the required compiler and linker flags, you can execute the
     271:file:`python{X.Y}-config` script which is generated as part of the
     272installation process (a :file:`python-config` script may also be
     273available).  This script has several options, of which the following will
     274be directly useful to you:
     275
     276* ``pythonX.Y-config --cflags`` will give you the recommended flags when
     277  compiling::
     278
     279   $ /opt/bin/python2.7-config --cflags
     280   -I/opt/include/python2.7 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
     281
     282* ``pythonX.Y-config --ldflags`` will give you the recommended flags when
     283  linking::
     284
     285   $ /opt/bin/python2.7-config --ldflags
     286   -L/opt/lib/python2.7/config -lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic
     287
     288.. note::
     289   To avoid confusion between several Python installations (and especially
     290   between the system Python and your own compiled Python), it is recommended
     291   that you use the absolute path to :file:`python{X.Y}-config`, as in the above
     292   example.
     293
     294If this procedure doesn't work for you (it is not guaranteed to work for
     295all Unix-like platforms; however, we welcome :ref:`bug reports <reporting-bugs>`)
     296you will have to read your system's documentation about dynamic linking and/or
     297examine Python's :file:`Makefile` (use :func:`sysconfig.get_makefile_filename`
     298to find its location) and compilation
     299options.  In this case, the :mod:`sysconfig` module is a useful tool to
     300programmatically extract the configuration values that you will want to
     301combine together.  For example:
     302
     303.. code-block:: python
     304
     305   >>> import sysconfig
     306   >>> sysconfig.get_config_var('LIBS')
     307   '-lpthread -ldl  -lutil'
     308   >>> sysconfig.get_config_var('LINKFORSHARED')
    277309   '-Xlinker -export-dynamic'
    278310
    279 .. index:: module: distutils.sysconfig
    280 
    281 The contents of the string presented will be the options that should be used.
    282 If the string is empty, there's no need to add any additional options.  The
    283 :const:`LINKFORSHARED` definition corresponds to the variable of the same name
    284 in Python's top-level :file:`Makefile`.
    285 
     311
     312.. XXX similar documentation for Windows missing
  • python/vendor/current/Doc/extending/extending.rst

    r2 r388  
    3636Let's create an extension module called ``spam`` (the favorite food of Monty
    3737Python fans...) and let's say we want to create a Python interface to the C
    38 library function :cfunc:`system`. [#]_ This function takes a null-terminated
     38library function :c:func:`system`. [#]_ This function takes a null-terminated
    3939character string as argument and returns an integer.  We want this function to
    4040be callable from Python as follows::
     
    6666includes a few standard header files: ``<stdio.h>``, ``<string.h>``,
    6767``<errno.h>``, and ``<stdlib.h>``.  If the latter header file does not exist on
    68 your system, it declares the functions :cfunc:`malloc`, :cfunc:`free` and
    69 :cfunc:`realloc` directly.
     68your system, it declares the functions :c:func:`malloc`, :c:func:`free` and
     69:c:func:`realloc` directly.
    7070
    7171The next thing we add to our module file is the C function that will be called
     
    9090and *args*.
    9191
    92 The *self* argument is only used when the C function implements a built-in
    93 method, not a function. In the example, *self* will always be a *NULL* pointer,
    94 since we are defining a function, not a method.  (This is done so that the
    95 interpreter doesn't have to understand two different types of C functions.)
     92The *self* argument points to the module object for module-level functions;
     93for a method it would point to the object instance.
    9694
    9795The *args* argument will be a pointer to a Python tuple object containing the
     
    9997argument list.  The arguments are Python objects --- in order to do anything
    10098with them in our C function we have to convert them to C values.  The function
    101 :cfunc:`PyArg_ParseTuple` in the Python API checks the argument types and
     99:c:func:`PyArg_ParseTuple` in the Python API checks the argument types and
    102100converts them to C values.  It uses a template string to determine the required
    103101types of the arguments as well as the types of the C variables into which to
    104102store the converted values.  More about this later.
    105103
    106 :cfunc:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right
     104:c:func:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right
    107105type and its components have been stored in the variables whose addresses are
    108106passed.  It returns false (zero) if an invalid argument list was passed.  In the
     
    130128The Python API defines a number of functions to set various types of exceptions.
    131129
    132 The most common one is :cfunc:`PyErr_SetString`.  Its arguments are an exception
     130The most common one is :c:func:`PyErr_SetString`.  Its arguments are an exception
    133131object and a C string.  The exception object is usually a predefined object like
    134 :cdata:`PyExc_ZeroDivisionError`.  The C string indicates the cause of the error
     132:c:data:`PyExc_ZeroDivisionError`.  The C string indicates the cause of the error
    135133and is converted to a Python string object and stored as the "associated value"
    136134of the exception.
    137135
    138 Another useful function is :cfunc:`PyErr_SetFromErrno`, which only takes an
     136Another useful function is :c:func:`PyErr_SetFromErrno`, which only takes an
    139137exception argument and constructs the associated value by inspection of the
    140 global variable :cdata:`errno`.  The most general function is
    141 :cfunc:`PyErr_SetObject`, which takes two object arguments, the exception and
    142 its associated value.  You don't need to :cfunc:`Py_INCREF` the objects passed
     138global variable :c:data:`errno`.  The most general function is
     139:c:func:`PyErr_SetObject`, which takes two object arguments, the exception and
     140its associated value.  You don't need to :c:func:`Py_INCREF` the objects passed
    143141to any of these functions.
    144142
    145143You can test non-destructively whether an exception has been set with
    146 :cfunc:`PyErr_Occurred`.  This returns the current exception object, or *NULL*
     144:c:func:`PyErr_Occurred`.  This returns the current exception object, or *NULL*
    147145if no exception has occurred.  You normally don't need to call
    148 :cfunc:`PyErr_Occurred` to see whether an error occurred in a function call,
     146:c:func:`PyErr_Occurred` to see whether an error occurred in a function call,
    149147since you should be able to tell from the return value.
    150148
    151149When a function *f* that calls another function *g* detects that the latter
    152150fails, *f* should itself return an error value (usually *NULL* or ``-1``).  It
    153 should *not* call one of the :cfunc:`PyErr_\*` functions --- one has already
     151should *not* call one of the :c:func:`PyErr_\*` functions --- one has already
    154152been called by *g*. *f*'s caller is then supposed to also return an error
    155 indication to *its* caller, again *without* calling :cfunc:`PyErr_\*`, and so on
     153indication to *its* caller, again *without* calling :c:func:`PyErr_\*`, and so on
    156154--- the most detailed cause of the error was already reported by the function
    157155that first detected it.  Once the error reaches the Python interpreter's main
     
    160158
    161159(There are situations where a module can actually give a more detailed error
    162 message by calling another :cfunc:`PyErr_\*` function, and in such cases it is
     160message by calling another :c:func:`PyErr_\*` function, and in such cases it is
    163161fine to do so.  As a general rule, however, this is not necessary, and can cause
    164162information about the cause of the error to be lost: most operations can fail
     
    166164
    167165To ignore an exception set by a function call that failed, the exception
    168 condition must be cleared explicitly by calling :cfunc:`PyErr_Clear`.  The only
    169 time C code should call :cfunc:`PyErr_Clear` is if it doesn't want to pass the
     166condition must be cleared explicitly by calling :c:func:`PyErr_Clear`.  The only
     167time C code should call :c:func:`PyErr_Clear` is if it doesn't want to pass the
    170168error on to the interpreter but wants to handle it completely by itself
    171169(possibly by trying something else, or pretending nothing went wrong).
    172170
    173 Every failing :cfunc:`malloc` call must be turned into an exception --- the
    174 direct caller of :cfunc:`malloc` (or :cfunc:`realloc`) must call
    175 :cfunc:`PyErr_NoMemory` and return a failure indicator itself.  All the
    176 object-creating functions (for example, :cfunc:`PyInt_FromLong`) already do
    177 this, so this note is only relevant to those who call :cfunc:`malloc` directly.
    178 
    179 Also note that, with the important exception of :cfunc:`PyArg_ParseTuple` and
     171Every failing :c:func:`malloc` call must be turned into an exception --- the
     172direct caller of :c:func:`malloc` (or :c:func:`realloc`) must call
     173:c:func:`PyErr_NoMemory` and return a failure indicator itself.  All the
     174object-creating functions (for example, :c:func:`PyInt_FromLong`) already do
     175this, so this note is only relevant to those who call :c:func:`malloc` directly.
     176
     177Also note that, with the important exception of :c:func:`PyArg_ParseTuple` and
    180178friends, functions that return an integer status usually return a positive value
    181179or zero for success and ``-1`` for failure, like Unix system calls.
    182180
    183 Finally, be careful to clean up garbage (by making :cfunc:`Py_XDECREF` or
    184 :cfunc:`Py_DECREF` calls for objects you have already created) when you return
     181Finally, be careful to clean up garbage (by making :c:func:`Py_XDECREF` or
     182:c:func:`Py_DECREF` calls for objects you have already created) when you return
    185183an error indicator!
    186184
    187185The choice of which exception to raise is entirely yours.  There are predeclared
    188186C objects corresponding to all built-in Python exceptions, such as
    189 :cdata:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you
    190 should choose exceptions wisely --- don't use :cdata:`PyExc_TypeError` to mean
    191 that a file couldn't be opened (that should probably be :cdata:`PyExc_IOError`).
    192 If something's wrong with the argument list, the :cfunc:`PyArg_ParseTuple`
    193 function usually raises :cdata:`PyExc_TypeError`.  If you have an argument whose
     187:c:data:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you
     188should choose exceptions wisely --- don't use :c:data:`PyExc_TypeError` to mean
     189that a file couldn't be opened (that should probably be :c:data:`PyExc_IOError`).
     190If something's wrong with the argument list, the :c:func:`PyArg_ParseTuple`
     191function usually raises :c:data:`PyExc_TypeError`.  If you have an argument whose
    194192value must be in a particular range or must satisfy other conditions,
    195 :cdata:`PyExc_ValueError` is appropriate.
     193:c:data:`PyExc_ValueError` is appropriate.
    196194
    197195You can also define a new exception that is unique to your module. For this, you
     
    200198   static PyObject *SpamError;
    201199
    202 and initialize it in your module's initialization function (:cfunc:`initspam`)
     200and initialize it in your module's initialization function (:c:func:`initspam`)
    203201with an exception object (leaving out the error checking for now)::
    204202
     
    218216
    219217Note that the Python name for the exception object is :exc:`spam.error`.  The
    220 :cfunc:`PyErr_NewException` function may create a class with the base class
     218:c:func:`PyErr_NewException` function may create a class with the base class
    221219being :exc:`Exception` (unless another class is passed in instead of *NULL*),
    222220described in :ref:`bltin-exceptions`.
    223221
    224 Note also that the :cdata:`SpamError` variable retains a reference to the newly
     222Note also that the :c:data:`SpamError` variable retains a reference to the newly
    225223created exception class; this is intentional!  Since the exception could be
    226224removed from the module by external code, an owned reference to the class is
    227 needed to ensure that it will not be discarded, causing :cdata:`SpamError` to
     225needed to ensure that it will not be discarded, causing :c:data:`SpamError` to
    228226become a dangling pointer. Should it become a dangling pointer, C code which
    229227raises the exception could cause a core dump or other unintended side effects.
    230228
    231 We discuss the use of PyMODINIT_FUNC as a function return type later in this
     229We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this
    232230sample.
     231
     232The :exc:`spam.error` exception can be raised in your extension module using a
     233call to :c:func:`PyErr_SetString` as shown below::
     234
     235   static PyObject *
     236   spam_system(PyObject *self, PyObject *args)
     237   {
     238       const char *command;
     239       int sts;
     240
     241       if (!PyArg_ParseTuple(args, "s", &command))
     242           return NULL;
     243       sts = system(command);
     244       if (sts < 0) {
     245           PyErr_SetString(SpamError, "System command failed");
     246           return NULL;
     247       }
     248       return PyLong_FromLong(sts);
     249   }
    233250
    234251
     
    246263It returns *NULL* (the error indicator for functions returning object pointers)
    247264if an error is detected in the argument list, relying on the exception set by
    248 :cfunc:`PyArg_ParseTuple`.  Otherwise the string value of the argument has been
    249 copied to the local variable :cdata:`command`.  This is a pointer assignment and
     265:c:func:`PyArg_ParseTuple`.  Otherwise the string value of the argument has been
     266copied to the local variable :c:data:`command`.  This is a pointer assignment and
    250267you are not supposed to modify the string to which it points (so in Standard C,
    251 the variable :cdata:`command` should properly be declared as ``const char
     268the variable :c:data:`command` should properly be declared as ``const char
    252269*command``).
    253270
    254 The next statement is a call to the Unix function :cfunc:`system`, passing it
    255 the string we just got from :cfunc:`PyArg_ParseTuple`::
     271The next statement is a call to the Unix function :c:func:`system`, passing it
     272the string we just got from :c:func:`PyArg_ParseTuple`::
    256273
    257274   sts = system(command);
    258275
    259 Our :func:`spam.system` function must return the value of :cdata:`sts` as a
    260 Python object.  This is done using the function :cfunc:`Py_BuildValue`, which is
    261 something like the inverse of :cfunc:`PyArg_ParseTuple`: it takes a format
     276Our :func:`spam.system` function must return the value of :c:data:`sts` as a
     277Python object.  This is done using the function :c:func:`Py_BuildValue`, which is
     278something like the inverse of :c:func:`PyArg_ParseTuple`: it takes a format
    262279string and an arbitrary number of C values, and returns a new Python object.
    263 More info on :cfunc:`Py_BuildValue` is given later. ::
     280More info on :c:func:`Py_BuildValue` is given later. ::
    264281
    265282   return Py_BuildValue("i", sts);
     
    269286
    270287If you have a C function that returns no useful argument (a function returning
    271 :ctype:`void`), the corresponding Python function must return ``None``.   You
    272 need this idiom to do so (which is implemented by the :cmacro:`Py_RETURN_NONE`
     288:c:type:`void`), the corresponding Python function must return ``None``.   You
     289need this idiom to do so (which is implemented by the :c:macro:`Py_RETURN_NONE`
    273290macro)::
    274291
     
    276293   return Py_None;
    277294
    278 :cdata:`Py_None` is the C name for the special Python object ``None``.  It is a
     295:c:data:`Py_None` is the C name for the special Python object ``None``.  It is a
    279296genuine Python object rather than a *NULL* pointer, which means "error" in most
    280297contexts, as we have seen.
     
    286303=====================================================
    287304
    288 I promised to show how :cfunc:`spam_system` is called from Python programs.
     305I promised to show how :c:func:`spam_system` is called from Python programs.
    289306First, we need to list its name and address in a "method table"::
    290307
     
    300317the calling convention to be used for the C function.  It should normally always
    301318be ``METH_VARARGS`` or ``METH_VARARGS | METH_KEYWORDS``; a value of ``0`` means
    302 that an obsolete variant of :cfunc:`PyArg_ParseTuple` is used.
     319that an obsolete variant of :c:func:`PyArg_ParseTuple` is used.
    303320
    304321When using only ``METH_VARARGS``, the function should expect the Python-level
    305322parameters to be passed in as a tuple acceptable for parsing via
    306 :cfunc:`PyArg_ParseTuple`; more information on this function is provided below.
     323:c:func:`PyArg_ParseTuple`; more information on this function is provided below.
    307324
    308325The :const:`METH_KEYWORDS` bit may be set in the third field if keyword
    309326arguments should be passed to the function.  In this case, the C function should
    310327accept a third ``PyObject *`` parameter which will be a dictionary of keywords.
    311 Use :cfunc:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a
     328Use :c:func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a
    312329function.
    313330
    314331The method table must be passed to the interpreter in the module's
    315332initialization function.  The initialization function must be named
    316 :cfunc:`initname`, where *name* is the name of the module, and should be the
     333:c:func:`initname`, where *name* is the name of the module, and should be the
    317334only non-\ ``static`` item defined in the module file::
    318335
     
    328345
    329346When the Python program imports module :mod:`spam` for the first time,
    330 :cfunc:`initspam` is called. (See below for comments about embedding Python.)
    331 It calls :cfunc:`Py_InitModule`, which creates a "module object" (which is
     347:c:func:`initspam` is called. (See below for comments about embedding Python.)
     348It calls :c:func:`Py_InitModule`, which creates a "module object" (which is
    332349inserted in the dictionary ``sys.modules`` under the key ``"spam"``), and
    333350inserts built-in function objects into the newly created module based upon the
    334 table (an array of :ctype:`PyMethodDef` structures) that was passed as its
    335 second argument. :cfunc:`Py_InitModule` returns a pointer to the module object
     351table (an array of :c:type:`PyMethodDef` structures) that was passed as its
     352second argument. :c:func:`Py_InitModule` returns a pointer to the module object
    336353that it creates (which is unused here).  It may abort with a fatal error for
    337354certain errors, or return *NULL* if the module could not be initialized
    338355satisfactorily.
    339356
    340 When embedding Python, the :cfunc:`initspam` function is not called
    341 automatically unless there's an entry in the :cdata:`_PyImport_Inittab` table.
     357When embedding Python, the :c:func:`initspam` function is not called
     358automatically unless there's an entry in the :c:data:`_PyImport_Inittab` table.
    342359The easiest way to handle this is to statically initialize your
    343 statically-linked modules by directly calling :cfunc:`initspam` after the call
    344 to :cfunc:`Py_Initialize`::
     360statically-linked modules by directly calling :c:func:`initspam` after the call
     361to :c:func:`Py_Initialize`::
    345362
    346363   int
     
    356373       initspam();
    357374
     375       ...
     376
    358377An example may be found in the file :file:`Demo/embed/demo.c` in the Python
    359378source distribution.
     
    362381
    363382   Removing entries from ``sys.modules`` or importing compiled modules into
    364    multiple interpreters within a process (or following a :cfunc:`fork` without an
    365    intervening :cfunc:`exec`) can create problems for some extension modules.
     383   multiple interpreters within a process (or following a :c:func:`fork` without an
     384   intervening :c:func:`exec`) can create problems for some extension modules.
    366385   Extension module authors should exercise caution when initializing internal data
    367386   structures. Note also that the :func:`reload` function can be used with
    368387   extension modules, and will call the module initialization function
    369    (:cfunc:`initspam` in the example), but will not load the module again if it was
     388   (:c:func:`initspam` in the example), but will not load the module again if it was
    370389   loaded from a dynamically loadable object file (:file:`.so` on Unix,
    371390   :file:`.dll` on Windows).
     
    373392A more substantial example module is included in the Python source distribution
    374393as :file:`Modules/xxmodule.c`.  This file may be used as a  template or simply
    375 read as an example.  The :program:`modulator.py` script included in the source
    376 distribution or Windows install provides  a simple graphical user interface for
    377 declaring the functions and objects which a module should implement, and can
    378 generate a template which can be filled in.  The script lives in the
    379 :file:`Tools/modulator/` directory; see the :file:`README` file there for more
    380 information.
     394read as an example.
    381395
    382396
     
    436450you the Python function object.  You should provide a function (or some other
    437451interface) to do this.  When this function is called, save a pointer to the
    438 Python function object (be careful to :cfunc:`Py_INCREF` it!) in a global
     452Python function object (be careful to :c:func:`Py_INCREF` it!) in a global
    439453variable --- or wherever you see fit. For example, the following function might
    440454be part of a module definition::
     
    465479This function must be registered with the interpreter using the
    466480:const:`METH_VARARGS` flag; this is described in section :ref:`methodtable`.  The
    467 :cfunc:`PyArg_ParseTuple` function and its arguments are documented in section
     481:c:func:`PyArg_ParseTuple` function and its arguments are documented in section
    468482:ref:`parsetuple`.
    469483
    470 The macros :cfunc:`Py_XINCREF` and :cfunc:`Py_XDECREF` increment/decrement the
     484The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement the
    471485reference count of an object and are safe in the presence of *NULL* pointers
    472486(but note that *temp* will not be  *NULL* in this context).  More info on them
     
    476490
    477491Later, when it is time to call the function, you call the C function
    478 :cfunc:`PyObject_CallObject`.  This function has two arguments, both pointers to
     492:c:func:`PyObject_CallObject`.  This function has two arguments, both pointers to
    479493arbitrary Python objects: the Python function, and the argument list.  The
    480494argument list must always be a tuple object, whose length is the number of
    481495arguments.  To call the Python function with no arguments, pass in NULL, or
    482496an empty tuple; to call it with one argument, pass a singleton tuple.
    483 :cfunc:`Py_BuildValue` returns a tuple when its format string consists of zero
     497:c:func:`Py_BuildValue` returns a tuple when its format string consists of zero
    484498or more format codes between parentheses.  For example::
    485499
     
    495509   Py_DECREF(arglist);
    496510
    497 :cfunc:`PyObject_CallObject` returns a Python object pointer: this is the return
    498 value of the Python function.  :cfunc:`PyObject_CallObject` is
     511:c:func:`PyObject_CallObject` returns a Python object pointer: this is the return
     512value of the Python function.  :c:func:`PyObject_CallObject` is
    499513"reference-count-neutral" with respect to its arguments.  In the example a new
    500 tuple was created to serve as the argument list, which is :cfunc:`Py_DECREF`\
    501 -ed immediately after the call.
    502 
    503 The return value of :cfunc:`PyObject_CallObject` is "new": either it is a brand
     514tuple was created to serve as the argument list, which is :c:func:`Py_DECREF`\
     515-ed immediately after the :c:func:`PyObject_CallObject` call.
     516
     517The return value of :c:func:`PyObject_CallObject` is "new": either it is a brand
    504518new object, or it is an existing object whose reference count has been
    505519incremented.  So, unless you want to save it in a global variable, you should
    506 somehow :cfunc:`Py_DECREF` the result, even (especially!) if you are not
     520somehow :c:func:`Py_DECREF` the result, even (especially!) if you are not
    507521interested in its value.
    508522
    509523Before you do this, however, it is important to check that the return value
    510524isn't *NULL*.  If it is, the Python function terminated by raising an exception.
    511 If the C code that called :cfunc:`PyObject_CallObject` is called from Python, it
     525If the C code that called :c:func:`PyObject_CallObject` is called from Python, it
    512526should now return an error indication to its Python caller, so the interpreter
    513527can print a stack trace, or the calling Python code can handle the exception.
    514528If this is not possible or desirable, the exception should be cleared by calling
    515 :cfunc:`PyErr_Clear`.  For example::
     529:c:func:`PyErr_Clear`.  For example::
    516530
    517531   if (result == NULL)
     
    521535
    522536Depending on the desired interface to the Python callback function, you may also
    523 have to provide an argument list to :cfunc:`PyObject_CallObject`.  In some cases
     537have to provide an argument list to :c:func:`PyObject_CallObject`.  In some cases
    524538the argument list is also provided by the Python program, through the same
    525539interface that specified the callback function.  It can then be saved and used
    526540in the same manner as the function object.  In other cases, you may have to
    527541construct a new tuple to pass as the argument list.  The simplest way to do this
    528 is to call :cfunc:`Py_BuildValue`.  For example, if you want to pass an integral
     542is to call :c:func:`Py_BuildValue`.  For example, if you want to pass an integral
    529543event code, you might use the following code::
    530544
     
    541555Note the placement of ``Py_DECREF(arglist)`` immediately after the call, before
    542556the error check!  Also note that strictly speaking this code is not complete:
    543 :cfunc:`Py_BuildValue` may run out of memory, and this should be checked.
     557:c:func:`Py_BuildValue` may run out of memory, and this should be checked.
    544558
    545559You may also call a function with keyword arguments by using
    546 :cfunc:`PyObject_Call`, which supports arguments and keyword arguments.  As in
    547 the above example, we use :cfunc:`Py_BuildValue` to construct the dictionary. ::
     560:c:func:`PyObject_Call`, which supports arguments and keyword arguments.  As in
     561the above example, we use :c:func:`Py_BuildValue` to construct the dictionary. ::
    548562
    549563   PyObject *dict;
     
    565579.. index:: single: PyArg_ParseTuple()
    566580
    567 The :cfunc:`PyArg_ParseTuple` function is declared as follows::
     581The :c:func:`PyArg_ParseTuple` function is declared as follows::
    568582
    569583   int PyArg_ParseTuple(PyObject *arg, char *format, ...);
     
    575589determined by the format string.
    576590
    577 Note that while :cfunc:`PyArg_ParseTuple` checks that the Python arguments have
     591Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments have
    578592the required types, it cannot check the validity of the addresses of C variables
    579593passed to the call: if you make mistakes there, your code will probably crash or
     
    652666.. index:: single: PyArg_ParseTupleAndKeywords()
    653667
    654 The :cfunc:`PyArg_ParseTupleAndKeywords` function is declared as follows::
     668The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::
    655669
    656670   int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
     
    658672
    659673The *arg* and *format* parameters are identical to those of the
    660 :cfunc:`PyArg_ParseTuple` function.  The *kwdict* parameter is the dictionary of
     674:c:func:`PyArg_ParseTuple` function.  The *kwdict* parameter is the dictionary of
    661675keywords received as the third parameter from the Python runtime.  The *kwlist*
    662676parameter is a *NULL*-terminated list of strings which identify the parameters;
    663677the names are matched with the type information from *format* from left to
    664 right.  On success, :cfunc:`PyArg_ParseTupleAndKeywords` returns true, otherwise
     678right.  On success, :c:func:`PyArg_ParseTupleAndKeywords` returns true, otherwise
    665679it returns false and raises an appropriate exception.
    666680
     
    726740=========================
    727741
    728 This function is the counterpart to :cfunc:`PyArg_ParseTuple`.  It is declared
     742This function is the counterpart to :c:func:`PyArg_ParseTuple`.  It is declared
    729743as follows::
    730744
     
    732746
    733747It recognizes a set of format units similar to the ones recognized by
    734 :cfunc:`PyArg_ParseTuple`, but the arguments (which are input to the function,
     748:c:func:`PyArg_ParseTuple`, but the arguments (which are input to the function,
    735749not output) must not be pointers, just values.  It returns a new Python object,
    736750suitable for returning from a C function called from Python.
    737751
    738 One difference with :cfunc:`PyArg_ParseTuple`: while the latter requires its
     752One difference with :c:func:`PyArg_ParseTuple`: while the latter requires its
    739753first argument to be a tuple (since Python argument lists are always represented
    740 as tuples internally), :cfunc:`Py_BuildValue` does not always build a tuple.  It
     754as tuples internally), :c:func:`Py_BuildValue` does not always build a tuple.  It
    741755builds a tuple only if its format string contains two or more format units. If
    742756the format string is empty, it returns ``None``; if it contains exactly one
     
    770784In languages like C or C++, the programmer is responsible for dynamic allocation
    771785and deallocation of memory on the heap.  In C, this is done using the functions
    772 :cfunc:`malloc` and :cfunc:`free`.  In C++, the operators ``new`` and
     786:c:func:`malloc` and :c:func:`free`.  In C++, the operators ``new`` and
    773787``delete`` are used with essentially the same meaning and we'll restrict
    774788the following discussion to the C case.
    775789
    776 Every block of memory allocated with :cfunc:`malloc` should eventually be
    777 returned to the pool of available memory by exactly one call to :cfunc:`free`.
    778 It is important to call :cfunc:`free` at the right time.  If a block's address
    779 is forgotten but :cfunc:`free` is not called for it, the memory it occupies
     790Every block of memory allocated with :c:func:`malloc` should eventually be
     791returned to the pool of available memory by exactly one call to :c:func:`free`.
     792It is important to call :c:func:`free` at the right time.  If a block's address
     793is forgotten but :c:func:`free` is not called for it, the memory it occupies
    780794cannot be reused until the program terminates.  This is called a :dfn:`memory
    781 leak`.  On the other hand, if a program calls :cfunc:`free` for a block and then
     795leak`.  On the other hand, if a program calls :c:func:`free` for a block and then
    782796continues to use the block, it creates a conflict with re-use of the block
    783 through another :cfunc:`malloc` call.  This is called :dfn:`using freed memory`.
     797through another :c:func:`malloc` call.  This is called :dfn:`using freed memory`.
    784798It has the same bad consequences as referencing uninitialized data --- core
    785799dumps, wrong results, mysterious crashes.
     
    798812strategy that minimizes this kind of errors.
    799813
    800 Since Python makes heavy use of :cfunc:`malloc` and :cfunc:`free`, it needs a
     814Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it needs a
    801815strategy to avoid memory leaks as well as the use of freed memory.  The chosen
    802816method is called :dfn:`reference counting`.  The principle is simple: every
     
    810824strategy, hence my use of "automatic" to distinguish the two.)  The big
    811825advantage of automatic garbage collection is that the user doesn't need to call
    812 :cfunc:`free` explicitly.  (Another claimed advantage is an improvement in speed
     826:c:func:`free` explicitly.  (Another claimed advantage is an improvement in speed
    813827or memory usage --- this is no hard fact however.)  The disadvantage is that for
    814828C, there is no truly portable automatic garbage collector, while reference
    815 counting can be implemented portably (as long as the functions :cfunc:`malloc`
    816 and :cfunc:`free` are available --- which the C Standard guarantees). Maybe some
     829counting can be implemented portably (as long as the functions :c:func:`malloc`
     830and :c:func:`free` are available --- which the C Standard guarantees). Maybe some
    817831day a sufficiently portable automatic garbage collector will be available for C.
    818832Until then, we'll have to live with reference counts.
     
    832846as there are no finalizers implemented in Python (:meth:`__del__` methods).
    833847When there are such finalizers, the detector exposes the cycles through the
    834 :mod:`gc` module (specifically, the
    835 ``garbage`` variable in that module).  The :mod:`gc` module also exposes a way
    836 to run the detector (the :func:`collect` function), as well as configuration
     848:mod:`gc` module (specifically, the :attr:`~gc.garbage` variable in that module).
     849The :mod:`gc` module also exposes a way to run the detector (the
     850:func:`~gc.collect` function), as well as configuration
    837851interfaces and the ability to disable the detector at runtime.  The cycle
    838852detector is considered an optional component; though it is included by default,
     
    850864
    851865There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle the
    852 incrementing and decrementing of the reference count. :cfunc:`Py_DECREF` also
     866incrementing and decrementing of the reference count. :c:func:`Py_DECREF` also
    853867frees the object when the count reaches zero. For flexibility, it doesn't call
    854 :cfunc:`free` directly --- rather, it makes a call through a function pointer in
     868:c:func:`free` directly --- rather, it makes a call through a function pointer in
    855869the object's :dfn:`type object`.  For this purpose (and others), every object
    856870also contains a pointer to its type object.
     
    860874:dfn:`own a reference` to an object.  An object's reference count is now defined
    861875as the number of owned references to it.  The owner of a reference is
    862 responsible for calling :cfunc:`Py_DECREF` when the reference is no longer
     876responsible for calling :c:func:`Py_DECREF` when the reference is no longer
    863877needed.  Ownership of a reference can be transferred.  There are three ways to
    864 dispose of an owned reference: pass it on, store it, or call :cfunc:`Py_DECREF`.
     878dispose of an owned reference: pass it on, store it, or call :c:func:`Py_DECREF`.
    865879Forgetting to dispose of an owned reference creates a memory leak.
    866880
    867881It is also possible to :dfn:`borrow` [#]_ a reference to an object.  The
    868 borrower of a reference should not call :cfunc:`Py_DECREF`.  The borrower must
     882borrower of a reference should not call :c:func:`Py_DECREF`.  The borrower must
    869883not hold on to the object longer than the owner from which it was borrowed.
    870884Using a borrowed reference after the owner has disposed of it risks using freed
     
    880894
    881895A borrowed reference can be changed into an owned reference by calling
    882 :cfunc:`Py_INCREF`.  This does not affect the status of the owner from which the
     896:c:func:`Py_INCREF`.  This does not affect the status of the owner from which the
    883897reference was borrowed --- it creates a new owned reference, and gives full
    884898owner responsibilities (the new owner must dispose of the reference properly, as
     
    897911Most functions that return a reference to an object pass on ownership with the
    898912reference.  In particular, all functions whose function it is to create a new
    899 object, such as :cfunc:`PyInt_FromLong` and :cfunc:`Py_BuildValue`, pass
     913object, such as :c:func:`PyInt_FromLong` and :c:func:`Py_BuildValue`, pass
    900914ownership to the receiver.  Even if the object is not actually new, you still
    901915receive ownership of a new reference to that object.  For instance,
    902 :cfunc:`PyInt_FromLong` maintains a cache of popular values and can return a
     916:c:func:`PyInt_FromLong` maintains a cache of popular values and can return a
    903917reference to a cached item.
    904918
    905919Many functions that extract objects from other objects also transfer ownership
    906 with the reference, for instance :cfunc:`PyObject_GetAttrString`.  The picture
     920with the reference, for instance :c:func:`PyObject_GetAttrString`.  The picture
    907921is less clear, here, however, since a few common routines are exceptions:
    908 :cfunc:`PyTuple_GetItem`, :cfunc:`PyList_GetItem`, :cfunc:`PyDict_GetItem`, and
    909 :cfunc:`PyDict_GetItemString` all return references that you borrow from the
     922:c:func:`PyTuple_GetItem`, :c:func:`PyList_GetItem`, :c:func:`PyDict_GetItem`, and
     923:c:func:`PyDict_GetItemString` all return references that you borrow from the
    910924tuple, list or dictionary.
    911925
    912 The function :cfunc:`PyImport_AddModule` also returns a borrowed reference, even
     926The function :c:func:`PyImport_AddModule` also returns a borrowed reference, even
    913927though it may actually create the object it returns: this is possible because an
    914928owned reference to the object is stored in ``sys.modules``.
     
    916930When you pass an object reference into another function, in general, the
    917931function borrows the reference from you --- if it needs to store it, it will use
    918 :cfunc:`Py_INCREF` to become an independent owner.  There are exactly two
    919 important exceptions to this rule: :cfunc:`PyTuple_SetItem` and
    920 :cfunc:`PyList_SetItem`.  These functions take over ownership of the item passed
    921 to them --- even if they fail!  (Note that :cfunc:`PyDict_SetItem` and friends
     932:c:func:`Py_INCREF` to become an independent owner.  There are exactly two
     933important exceptions to this rule: :c:func:`PyTuple_SetItem` and
     934:c:func:`PyList_SetItem`.  These functions take over ownership of the item passed
     935to them --- even if they fail!  (Note that :c:func:`PyDict_SetItem` and friends
    922936don't take over ownership --- they are "normal.")
    923937
     
    926940reference's lifetime is guaranteed until the function returns.  Only when such a
    927941borrowed reference must be stored or passed on, it must be turned into an owned
    928 reference by calling :cfunc:`Py_INCREF`.
     942reference by calling :c:func:`Py_INCREF`.
    929943
    930944The object reference returned from a C function that is called from Python must
     
    942956interpreter, which can cause the owner of a reference to dispose of it.
    943957
    944 The first and most important case to know about is using :cfunc:`Py_DECREF` on
     958The first and most important case to know about is using :c:func:`Py_DECREF` on
    945959an unrelated object while borrowing a reference to a list item.  For instance::
    946960
     
    958972Looks harmless, right?  But it's not!
    959973
    960 Let's follow the control flow into :cfunc:`PyList_SetItem`.  The list owns
     974Let's follow the control flow into :c:func:`PyList_SetItem`.  The list owns
    961975references to all its items, so when item 1 is replaced, it has to dispose of
    962976the original item 1.  Now let's suppose the original item 1 was an instance of a
     
    967981Since it is written in Python, the :meth:`__del__` method can execute arbitrary
    968982Python code.  Could it perhaps do something to invalidate the reference to
    969 ``item`` in :cfunc:`bug`?  You bet!  Assuming that the list passed into
    970 :cfunc:`bug` is accessible to the :meth:`__del__` method, it could execute a
     983``item`` in :c:func:`bug`?  You bet!  Assuming that the list passed into
     984:c:func:`bug` is accessible to the :meth:`__del__` method, it could execute a
    971985statement to the effect of ``del list[0]``, and assuming this was the last
    972986reference to that object, it would free the memory associated with it, thereby
     
    9951009other's way, because there is a global lock protecting Python's entire object
    9961010space.  However, it is possible to temporarily release this lock using the macro
    997 :cmacro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using
    998 :cmacro:`Py_END_ALLOW_THREADS`.  This is common around blocking I/O calls, to
     1011:c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using
     1012:c:macro:`Py_END_ALLOW_THREADS`.  This is common around blocking I/O calls, to
    9991013let other threads use the processor while waiting for the I/O to complete.
    10001014Obviously, the following function has the same problem as the previous one::
     
    10251039
    10261040It is better to test for *NULL* only at the "source:" when a pointer that may be
    1027 *NULL* is received, for example, from :cfunc:`malloc` or from a function that
     1041*NULL* is received, for example, from :c:func:`malloc` or from a function that
    10281042may raise an exception.
    10291043
    1030 The macros :cfunc:`Py_INCREF` and :cfunc:`Py_DECREF` do not check for *NULL*
    1031 pointers --- however, their variants :cfunc:`Py_XINCREF` and :cfunc:`Py_XDECREF`
     1044The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for *NULL*
     1045pointers --- however, their variants :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF`
    10321046do.
    10331047
     
    10661080
    10671081
    1068 .. _using-cobjects:
     1082.. _using-capsules:
    10691083
    10701084Providing a C API for an Extension Module
     
    11021116
    11031117Python provides a special mechanism to pass C-level information (pointers) from
    1104 one extension module to another one: CObjects. A CObject is a Python data type
    1105 which stores a pointer (:ctype:`void \*`).  CObjects can only be created and
     1118one extension module to another one: Capsules. A Capsule is a Python data type
     1119which stores a pointer (:c:type:`void \*`).  Capsules can only be created and
    11061120accessed via their C API, but they can be passed around like any other Python
    11071121object. In particular,  they can be assigned to a name in an extension module's
    11081122namespace. Other extension modules can then import this module, retrieve the
    1109 value of this name, and then retrieve the pointer from the CObject.
    1110 
    1111 There are many ways in which CObjects can be used to export the C API of an
    1112 extension module. Each name could get its own CObject, or all C API pointers
    1113 could be stored in an array whose address is published in a CObject. And the
     1123value of this name, and then retrieve the pointer from the Capsule.
     1124
     1125There are many ways in which Capsules can be used to export the C API of an
     1126extension module. Each function could get its own Capsule, or all C API pointers
     1127could be stored in an array whose address is published in a Capsule. And the
    11141128various tasks of storing and retrieving the pointers can be distributed in
    11151129different ways between the module providing the code and the client modules.
     1130
     1131Whichever method you choose, it's important to name your Capsules properly.
     1132The function :c:func:`PyCapsule_New` takes a name parameter
     1133(:c:type:`const char \*`); you're permitted to pass in a *NULL* name, but
     1134we strongly encourage you to specify a name.  Properly named Capsules provide
     1135a degree of runtime type-safety; there is no feasible way to tell one unnamed
     1136Capsule from another.
     1137
     1138In particular, Capsules used to expose C APIs should be given a name following
     1139this convention::
     1140
     1141    modulename.attributename
     1142
     1143The convenience function :c:func:`PyCapsule_Import` makes it easy to
     1144load a C API provided via a Capsule, but only if the Capsule's name
     1145matches this convention.  This behavior gives C API users a high degree
     1146of certainty that the Capsule they load contains the correct C API.
    11161147
    11171148The following example demonstrates an approach that puts most of the burden on
    11181149the writer of the exporting module, which is appropriate for commonly used
    11191150library modules. It stores all C API pointers (just one in the example!) in an
    1120 array of :ctype:`void` pointers which becomes the value of a CObject. The header
     1151array of :c:type:`void` pointers which becomes the value of a Capsule. The header
    11211152file corresponding to the module provides a macro that takes care of importing
    11221153the module and retrieving its C API pointers; client modules only have to call
     
    11251156The exporting module is a modification of the :mod:`spam` module from section
    11261157:ref:`extending-simpleexample`. The function :func:`spam.system` does not call
    1127 the C library function :cfunc:`system` directly, but a function
    1128 :cfunc:`PySpam_System`, which would of course do something more complicated in
     1158the C library function :c:func:`system` directly, but a function
     1159:c:func:`PySpam_System`, which would of course do something more complicated in
    11291160reality (such as adding "spam" to every command). This function
    1130 :cfunc:`PySpam_System` is also exported to other extension modules.
    1131 
    1132 The function :cfunc:`PySpam_System` is a plain C function, declared
     1161:c:func:`PySpam_System` is also exported to other extension modules.
     1162
     1163The function :c:func:`PySpam_System` is a plain C function, declared
    11331164``static`` like everything else::
    11341165
     
    11391170   }
    11401171
    1141 The function :cfunc:`spam_system` is modified in a trivial way::
     1172The function :c:func:`spam_system` is modified in a trivial way::
    11421173
    11431174   static PyObject *
     
    11801211       PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
    11811212
    1182        /* Create a CObject containing the API pointer array's address */
    1183        c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);
     1213       /* Create a Capsule containing the API pointer array's address */
     1214       c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL);
    11841215
    11851216       if (c_api_object != NULL)
     
    12231254    (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
    12241255
    1225    /* Return -1 and set exception on error, 0 on success. */
     1256   /* Return -1 on error, 0 on success.
     1257    * PyCapsule_Import will set an exception if there's an error.
     1258    */
    12261259   static int
    12271260   import_spam(void)
    12281261   {
    1229        PyObject *c_api_object;
    1230        PyObject *module;
    1231 
    1232        module = PyImport_ImportModule("spam");
    1233        if (module == NULL)
    1234            return -1;
    1235 
    1236        c_api_object = PyObject_GetAttrString(module, "_C_API");
    1237        if (c_api_object == NULL) {
    1238            Py_DECREF(module);
    1239            return -1;
    1240        }
    1241        if (PyCObject_Check(c_api_object))
    1242            PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object);
    1243 
    1244        Py_DECREF(c_api_object);
    1245        Py_DECREF(module);
    1246        return 0;
     1262       PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0);
     1263       return (PySpam_API != NULL) ? 0 : -1;
    12471264   }
    12481265
     
    12561273
    12571274All that a client module must do in order to have access to the function
    1258 :cfunc:`PySpam_System` is to call the function (or rather macro)
    1259 :cfunc:`import_spam` in its initialization function::
     1275:c:func:`PySpam_System` is to call the function (or rather macro)
     1276:c:func:`import_spam` in its initialization function::
    12601277
    12611278   PyMODINIT_FUNC
     
    12761293that is exported, so it has to be learned only once.
    12771294
    1278 Finally it should be mentioned that CObjects offer additional functionality,
     1295Finally it should be mentioned that Capsules offer additional functionality,
    12791296which is especially useful for memory allocation and deallocation of the pointer
    1280 stored in a CObject. The details are described in the Python/C API Reference
    1281 Manual in the section :ref:`cobjects` and in the implementation of CObjects (files
    1282 :file:`Include/cobject.h` and :file:`Objects/cobject.c` in the Python source
     1297stored in a Capsule. The details are described in the Python/C API Reference
     1298Manual in the section :ref:`capsules` and in the implementation of Capsules (files
     1299:file:`Include/pycapsule.h` and :file:`Objects/pycapsule.c` in the Python source
    12831300code distribution).
    12841301
  • python/vendor/current/Doc/extending/index.rst

    r2 r388  
    55##################################################
    66
    7 :Release: |version|
    8 :Date: |today|
    9 
    107This document describes how to write modules in C or C++ to extend the Python
    11 interpreter with new modules.  Those modules can define new functions but also
    12 new object types and their methods.  The document also describes how to embed
    13 the Python interpreter in another application, for use as an extension language.
    14 Finally, it shows how to compile and link extension modules so that they can be
    15 loaded dynamically (at run time) into the interpreter, if the underlying
    16 operating system supports this feature.
     8interpreter with new modules.  Those modules can not only define new functions
     9but also new object types and their methods.  The document also describes how
     10to embed the Python interpreter in another application, for use as an extension
     11language.  Finally, it shows how to compile and link extension modules so that
     12they can be loaded dynamically (at run time) into the interpreter, if the
     13underlying operating system supports this feature.
    1714
    1815This document assumes basic knowledge about Python.  For an informal
  • python/vendor/current/Doc/extending/newtypes.rst

    r2 r388  
    3535
    3636The Python runtime sees all Python objects as variables of type
    37 :ctype:`PyObject\*`.  A :ctype:`PyObject` is not a very magnificent object - it
     37:c:type:`PyObject\*`.  A :c:type:`PyObject` is not a very magnificent object - it
    3838just contains the refcount and a pointer to the object's "type object".  This is
    3939where the action is; the type object determines which (C) functions get called
    4040when, for instance, an attribute gets looked up on an object or it is multiplied
    41 by another object.  These C functions are called "type methods" to distinguish
    42 them from things like ``[].append`` (which we call "object methods").
     41by another object.  These C functions are called "type methods".
    4342
    4443So, if you want to define a new object type, you need to create a new type
     
    105104   };
    106105
    107 Now if you go and look up the definition of :ctype:`PyTypeObject` in
     106Now if you go and look up the definition of :c:type:`PyTypeObject` in
    108107:file:`object.h` you'll see that it has many more fields that the definition
    109108above.  The remaining fields will be filled with zeros by the C compiler, and
     
    121120as the type of a type object is "type", but this isn't strictly conforming C and
    122121some compilers complain.  Fortunately, this member will be filled in for us by
    123 :cfunc:`PyType_Ready`. ::
     122:c:func:`PyType_Ready`. ::
    124123
    125124   0,                          /* ob_size */
     
    147146
    148147This is so that Python knows how much memory to allocate when you call
    149 :cfunc:`PyObject_New`.
     148:c:func:`PyObject_New`.
    150149
    151150.. note::
    152151
    153152   If you want your type to be subclassable from Python, and your type has the same
    154    :attr:`tp_basicsize` as its base type, you may have problems with multiple
     153   :c:member:`~PyTypeObject.tp_basicsize` as its base type, you may have problems with multiple
    155154   inheritance.  A Python subclass of your type will have to list your type first
    156    in its :attr:`__bases__`, or else it will not be able to call your type's
     155   in its :attr:`~class.__bases__`, or else it will not be able to call your type's
    157156   :meth:`__new__` method without getting an error.  You can avoid this problem by
    158    ensuring that your type has a larger value for :attr:`tp_basicsize` than its
     157   ensuring that your type has a larger value for :c:member:`~PyTypeObject.tp_basicsize` than its
    159158   base type does.  Most of the time, this will be true anyway, because either your
    160159   base type will be :class:`object`, or else you will be adding data members to
     
    176175members defined by the current version of Python.
    177176
    178 We provide a doc string for the type in :attr:`tp_doc`. ::
     177We provide a doc string for the type in :c:member:`~PyTypeObject.tp_doc`. ::
    179178
    180179   "Noddy objects",           /* tp_doc */
     
    185184
    186185For now, all we want to be able to do is to create new :class:`Noddy` objects.
    187 To enable object creation, we have to provide a :attr:`tp_new` implementation.
     186To enable object creation, we have to provide a :c:member:`~PyTypeObject.tp_new` implementation.
    188187In this case, we can just use the default implementation provided by the API
    189 function :cfunc:`PyType_GenericNew`.  We'd like to just assign this to the
    190 :attr:`tp_new` slot, but we can't, for portability sake, On some platforms or
     188function :c:func:`PyType_GenericNew`.  We'd like to just assign this to the
     189:c:member:`~PyTypeObject.tp_new` slot, but we can't, for portability sake, On some platforms or
    191190compilers, we can't statically initialize a structure member with a function
    192 defined in another C module, so, instead, we'll assign the :attr:`tp_new` slot
     191defined in another C module, so, instead, we'll assign the :c:member:`~PyTypeObject.tp_new` slot
    193192in the module initialization function just before calling
    194 :cfunc:`PyType_Ready`::
     193:c:func:`PyType_Ready`::
    195194
    196195   noddy_NoddyType.tp_new = PyType_GenericNew;
     
    202201
    203202Everything else in the file should be familiar, except for some code in
    204 :cfunc:`initnoddy`::
     203:c:func:`initnoddy`::
    205204
    206205   if (PyType_Ready(&noddy_NoddyType) < 0)
     
    253252We've added an extra include::
    254253
    255    #include "structmember.h"
     254   #include <structmember.h>
    256255
    257256This include provides declarations that we use to handle attributes, as
     
    285284   }
    286285
    287 which is assigned to the :attr:`tp_dealloc` member::
     286which is assigned to the :c:member:`~PyTypeObject.tp_dealloc` member::
    288287
    289288   (destructor)Noddy_dealloc, /*tp_dealloc*/
    290289
    291290This method decrements the reference counts of the two Python attributes. We use
    292 :cfunc:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members
    293 could be *NULL*.  It then calls the :attr:`tp_free` member of the object's type
     291:c:func:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members
     292could be *NULL*.  It then calls the :c:member:`~PyTypeObject.tp_free` member of the object's type
    294293to free the object's memory.  Note that the object's type might not be
    295294:class:`NoddyType`, because the object may be an instance of a subclass.
     
    325324   }
    326325
    327 and install it in the :attr:`tp_new` member::
     326and install it in the :c:member:`~PyTypeObject.tp_new` member::
    328327
    329328   Noddy_new,                 /* tp_new */
     
    336335to make sure that the initial values of the members :attr:`first` and
    337336:attr:`last` are not *NULL*. If we didn't care whether the initial values were
    338 *NULL*, we could have used :cfunc:`PyType_GenericNew` as our new method, as we
    339 did before.  :cfunc:`PyType_GenericNew` initializes all of the instance variable
     337*NULL*, we could have used :c:func:`PyType_GenericNew` as our new method, as we
     338did before.  :c:func:`PyType_GenericNew` initializes all of the instance variable
    340339members to *NULL*.
    341340
     
    346345methods. Note that if the type supports subclassing, the type passed may not be
    347346the type being defined.  The new method calls the tp_alloc slot to allocate
    348 memory. We don't fill the :attr:`tp_alloc` slot ourselves. Rather
    349 :cfunc:`PyType_Ready` fills it for us by inheriting it from our base class,
     347memory. We don't fill the :c:member:`~PyTypeObject.tp_alloc` slot ourselves. Rather
     348:c:func:`PyType_Ready` fills it for us by inheriting it from our base class,
    350349which is :class:`object` by default.  Most types use the default allocation.
    351350
    352351.. note::
    353352
    354    If you are creating a co-operative :attr:`tp_new` (one that calls a base type's
    355    :attr:`tp_new` or :meth:`__new__`), you must *not* try to determine what method
     353   If you are creating a co-operative :c:member:`~PyTypeObject.tp_new` (one that calls a base type's
     354   :c:member:`~PyTypeObject.tp_new` or :meth:`__new__`), you must *not* try to determine what method
    356355   to call using method resolution order at runtime.  Always statically determine
    357    what type you are going to call, and call its :attr:`tp_new` directly, or via
     356   what type you are going to call, and call its :c:member:`~PyTypeObject.tp_new` directly, or via
    358357   ``type->tp_base->tp_new``.  If you do not do this, Python subclasses of your
    359358   type that also inherit from other Python-defined classes may not work correctly.
     
    392391   }
    393392
    394 by filling the :attr:`tp_init` slot. ::
     393by filling the :c:member:`~PyTypeObject.tp_init` slot. ::
    395394
    396395   (initproc)Noddy_init,         /* tp_init */
    397396
    398 The :attr:`tp_init` slot is exposed in Python as the :meth:`__init__` method. It
     397The :c:member:`~PyTypeObject.tp_init` slot is exposed in Python as the :meth:`__init__` method. It
    399398is used to initialize an object after it's created. Unlike the new method, we
    400399can't guarantee that the initializer is called.  The initializer isn't called
     
    426425  back into our type's code
    427426
    428 * when decrementing a reference count in a :attr:`tp_dealloc` handler when
     427* when decrementing a reference count in a :c:member:`~PyTypeObject.tp_dealloc` handler when
    429428  garbage-collections is not supported [#]_
    430429
     
    442441   };
    443442
    444 and put the definitions in the :attr:`tp_members` slot::
     443and put the definitions in the :c:member:`~PyTypeObject.tp_members` slot::
    445444
    446445   Noddy_members,             /* tp_members */
    447446
    448447Each member definition has a member name, type, offset, access flags and
    449 documentation string. See the "Generic Attribute Management" section below for
     448documentation string. See the :ref:`Generic-Attribute-Management` section below for
    450449details.
    451450
     
    518517   };
    519518
    520 and assign them to the :attr:`tp_methods` slot::
     519and assign them to the :c:member:`~PyTypeObject.tp_methods` slot::
    521520
    522521   Noddy_methods,             /* tp_methods */
     
    532531   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
    533532
    534 We rename :cfunc:`initnoddy` to :cfunc:`initnoddy2` and update the module name
    535 passed to :cfunc:`Py_InitModule3`.
     533We rename :c:func:`initnoddy` to :c:func:`initnoddy2` and update the module name
     534passed to :c:func:`Py_InitModule3`.
    536535
    537536Finally, we update our :file:`setup.py` file to build the new module::
     
    599598attribute value is not a string.
    600599
    601 We create an array of :ctype:`PyGetSetDef` structures::
     600We create an array of :c:type:`PyGetSetDef` structures::
    602601
    603602   static PyGetSetDef Noddy_getseters[] = {
     
    613612   };
    614613
    615 and register it in the :attr:`tp_getset` slot::
     614and register it in the :c:member:`~PyTypeObject.tp_getset` slot::
    616615
    617616   Noddy_getseters,           /* tp_getset */
     
    619618to register our attribute getters and setters.
    620619
    621 The last item in a :ctype:`PyGetSetDef` structure is the closure mentioned
     620The last item in a :c:type:`PyGetSetDef` structure is the closure mentioned
    622621above. In this case, we aren't using the closure, so we just pass *NULL*.
    623622
     
    630629   };
    631630
    632 We also need to update the :attr:`tp_init` handler to only allow strings [#]_ to
     631We also need to update the :c:member:`~PyTypeObject.tp_init` handler to only allow strings [#]_ to
    633632be passed::
    634633
     
    664663With these changes, we can assure that the :attr:`first` and :attr:`last`
    665664members are never *NULL* so we can remove checks for *NULL* values in almost all
    666 cases. This means that most of the :cfunc:`Py_XDECREF` calls can be converted to
    667 :cfunc:`Py_DECREF` calls. The only place we can't change these calls is in the
     665cases. This means that most of the :c:func:`Py_XDECREF` calls can be converted to
     666:c:func:`Py_DECREF` calls. The only place we can't change these calls is in the
    668667deallocator, where there is the possibility that the initialization of these
    669668members failed in the constructor.
     
    730729
    731730For each subobject that can participate in cycles, we need to call the
    732 :cfunc:`visit` function, which is passed to the traversal method. The
    733 :cfunc:`visit` function takes as arguments the subobject and the extra argument
     731:c:func:`visit` function, which is passed to the traversal method. The
     732:c:func:`visit` function takes as arguments the subobject and the extra argument
    734733*arg* passed to the traversal method.  It returns an integer value that must be
    735734returned if it is non-zero.
    736735
    737 Python 2.4 and higher provide a :cfunc:`Py_VISIT` macro that automates calling
    738 visit functions.  With :cfunc:`Py_VISIT`, :cfunc:`Noddy_traverse` can be
     736Python 2.4 and higher provide a :c:func:`Py_VISIT` macro that automates calling
     737visit functions.  With :c:func:`Py_VISIT`, :c:func:`Noddy_traverse` can be
    739738simplified::
    740739
     
    749748.. note::
    750749
    751    Note that the :attr:`tp_traverse` implementation must name its arguments exactly
    752    *visit* and *arg* in order to use :cfunc:`Py_VISIT`.  This is to encourage
     750   Note that the :c:member:`~PyTypeObject.tp_traverse` implementation must name its arguments exactly
     751   *visit* and *arg* in order to use :c:func:`Py_VISIT`.  This is to encourage
    753752   uniformity across these boring implementations.
    754753
     
    780779   }
    781780
    782 Notice the use of a temporary variable in :cfunc:`Noddy_clear`. We use the
     781Notice the use of a temporary variable in :c:func:`Noddy_clear`. We use the
    783782temporary variable so that we can set each member to *NULL* before decrementing
    784783its reference count.  We do this because, as was discussed earlier, if the
     
    786785the object.  In addition, because we now support garbage collection, we also
    787786have to worry about code being run that triggers garbage collection.  If garbage
    788 collection is run, our :attr:`tp_traverse` handler could get called. We can't
    789 take a chance of having :cfunc:`Noddy_traverse` called when a member's reference
     787collection is run, our :c:member:`~PyTypeObject.tp_traverse` handler could get called. We can't
     788take a chance of having :c:func:`Noddy_traverse` called when a member's reference
    790789count has dropped to zero and its value hasn't been set to *NULL*.
    791790
    792 Python 2.4 and higher provide a :cfunc:`Py_CLEAR` that automates the careful
    793 decrementing of reference counts.  With :cfunc:`Py_CLEAR`, the
    794 :cfunc:`Noddy_clear` function can be simplified::
     791Python 2.4 and higher provide a :c:func:`Py_CLEAR` that automates the careful
     792decrementing of reference counts.  With :c:func:`Py_CLEAR`, the
     793:c:func:`Noddy_clear` function can be simplified::
    795794
    796795   static int
     
    806805   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
    807806
    808 That's pretty much it.  If we had written custom :attr:`tp_alloc` or
    809 :attr:`tp_free` slots, we'd need to modify them for cyclic-garbage collection.
     807That's pretty much it.  If we had written custom :c:member:`~PyTypeObject.tp_alloc` or
     808:c:member:`~PyTypeObject.tp_free` slots, we'd need to modify them for cyclic-garbage collection.
    810809Most extensions will use the versions automatically provided.
    811810
     
    847846The primary difference for derived type objects is that the base type's object
    848847structure must be the first value. The base type will already include the
    849 :cfunc:`PyObject_HEAD` at the beginning of its structure.
     848:c:func:`PyObject_HEAD` at the beginning of its structure.
    850849
    851850When a Python object is a :class:`Shoddy` instance, its *PyObject\** pointer can
     
    866865This pattern is important when writing a type with custom :attr:`new` and
    867866:attr:`dealloc` methods. The :attr:`new` method should not actually create the
    868 memory for the object with :attr:`tp_alloc`, that will be handled by the base
    869 class when calling its :attr:`tp_new`.
    870 
    871 When filling out the :cfunc:`PyTypeObject` for the :class:`Shoddy` type, you see
    872 a slot for :cfunc:`tp_base`. Due to cross platform compiler issues, you can't
    873 fill that field directly with the :cfunc:`PyList_Type`; it can be done later in
    874 the module's :cfunc:`init` function. ::
     867memory for the object with :c:member:`~PyTypeObject.tp_alloc`, that will be handled by the base
     868class when calling its :c:member:`~PyTypeObject.tp_new`.
     869
     870When filling out the :c:func:`PyTypeObject` for the :class:`Shoddy` type, you see
     871a slot for :c:func:`tp_base`. Due to cross platform compiler issues, you can't
     872fill that field directly with the :c:func:`PyList_Type`; it can be done later in
     873the module's :c:func:`init` function. ::
    875874
    876875   PyMODINIT_FUNC
     
    891890   }
    892891
    893 Before calling :cfunc:`PyType_Ready`, the type structure must have the
    894 :attr:`tp_base` slot filled in. When we are deriving a new type, it is not
    895 necessary to fill out the :attr:`tp_alloc` slot with :cfunc:`PyType_GenericNew`
     892Before calling :c:func:`PyType_Ready`, the type structure must have the
     893:c:member:`~PyTypeObject.tp_base` slot filled in. When we are deriving a new type, it is not
     894necessary to fill out the :c:member:`~PyTypeObject.tp_alloc` slot with :c:func:`PyType_GenericNew`
    896895-- the allocate function from the base type will be inherited.
    897896
    898 After that, calling :cfunc:`PyType_Ready` and adding the type object to the
     897After that, calling :c:func:`PyType_Ready` and adding the type object to the
    899898module is the same as with the basic :class:`Noddy` examples.
    900899
     
    908907implement and what they do.
    909908
    910 Here is the definition of :ctype:`PyTypeObject`, with some fields only used in
     909Here is the definition of :c:type:`PyTypeObject`, with some fields only used in
    911910debug builds omitted:
    912911
     
    936935These fields tell the runtime how much memory to allocate when new objects of
    937936this type are created.  Python has some built-in support for variable length
    938 structures (think: strings, lists) which is where the :attr:`tp_itemsize` field
     937structures (think: strings, lists) which is where the :c:member:`~PyTypeObject.tp_itemsize` field
    939938comes in.  This will be dealt with later. ::
    940939
     
    986985errors from the interpreter.  The proper way to protect against this is to save
    987986a pending exception before performing the unsafe action, and restoring it when
    988 done.  This can be done using the :cfunc:`PyErr_Fetch` and
    989 :cfunc:`PyErr_Restore` functions::
     987done.  This can be done using the :c:func:`PyErr_Fetch` and
     988:c:func:`PyErr_Restore` functions::
    990989
    991990   static void
     
    10281027:func:`str` function, and the :keyword:`print` statement.  For most objects, the
    10291028:keyword:`print` statement is equivalent to the :func:`str` function, but it is
    1030 possible to special-case printing to a :ctype:`FILE\*` if necessary; this should
     1029possible to special-case printing to a :c:type:`FILE\*` if necessary; this should
    10311030only be done if efficiency is identified as a problem and profiling suggests
    10321031that creating a temporary string object to be written to a file is too
     
    10341033
    10351034These handlers are all optional, and most types at most need to implement the
    1036 :attr:`tp_str` and :attr:`tp_repr` handlers. ::
     1035:c:member:`~PyTypeObject.tp_str` and :c:member:`~PyTypeObject.tp_repr` handlers. ::
    10371036
    10381037   reprfunc tp_repr;
     
    10401039   printfunc tp_print;
    10411040
    1042 The :attr:`tp_repr` handler should return a string object containing a
     1041The :c:member:`~PyTypeObject.tp_repr` handler should return a string object containing a
    10431042representation of the instance for which it is called.  Here is a simple
    10441043example::
     
    10511050   }
    10521051
    1053 If no :attr:`tp_repr` handler is specified, the interpreter will supply a
    1054 representation that uses the type's :attr:`tp_name` and a uniquely-identifying
     1052If no :c:member:`~PyTypeObject.tp_repr` handler is specified, the interpreter will supply a
     1053representation that uses the type's :c:member:`~PyTypeObject.tp_name` and a uniquely-identifying
    10551054value for the object.
    10561055
    1057 The :attr:`tp_str` handler is to :func:`str` what the :attr:`tp_repr` handler
     1056The :c:member:`~PyTypeObject.tp_str` handler is to :func:`str` what the :c:member:`~PyTypeObject.tp_repr` handler
    10581057described above is to :func:`repr`; that is, it is called when Python code calls
    10591058:func:`str` on an instance of your object.  Its implementation is very similar
    1060 to the :attr:`tp_repr` function, but the resulting string is intended for human
    1061 consumption.  If :attr:`tp_str` is not specified, the :attr:`tp_repr` handler is
     1059to the :c:member:`~PyTypeObject.tp_repr` function, but the resulting string is intended for human
     1060consumption.  If :c:member:`~PyTypeObject.tp_str` is not specified, the :c:member:`~PyTypeObject.tp_repr` handler is
    10621061used instead.
    10631062
     
    11121111Python supports two pairs of attribute handlers; a type that supports attributes
    11131112only needs to implement the functions for one pair.  The difference is that one
    1114 pair takes the name of the attribute as a :ctype:`char\*`, while the other
    1115 accepts a :ctype:`PyObject\*`.  Each type can use whichever pair makes more
     1113pair takes the name of the attribute as a :c:type:`char\*`, while the other
     1114accepts a :c:type:`PyObject\*`.  Each type can use whichever pair makes more
    11161115sense for the implementation's convenience. ::
    11171116
     
    11241123If accessing attributes of an object is always a simple operation (this will be
    11251124explained shortly), there are generic implementations which can be used to
    1126 provide the :ctype:`PyObject\*` version of the attribute management functions.
     1125provide the :c:type:`PyObject\*` version of the attribute management functions.
    11271126The actual need for type-specific attribute handlers almost completely
    11281127disappeared starting with Python 2.2, though there are many examples which have
     
    11301129
    11311130
     1131.. _generic-attribute-management:
     1132
    11321133Generic Attribute Management
    11331134^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     
    11381139attributes simple?  There are only a couple of conditions that must be met:
    11391140
    1140 #. The name of the attributes must be known when :cfunc:`PyType_Ready` is
     1141#. The name of the attributes must be known when :c:func:`PyType_Ready` is
    11411142   called.
    11421143
     
    11471148attributes, when the values are computed, or how relevant data is stored.
    11481149
    1149 When :cfunc:`PyType_Ready` is called, it uses three tables referenced by the
     1150When :c:func:`PyType_Ready` is called, it uses three tables referenced by the
    11501151type object to create :term:`descriptor`\s which are placed in the dictionary of the
    11511152type object.  Each descriptor controls access to one attribute of the instance
    11521153object.  Each of the tables is optional; if all three are *NULL*, instances of
    11531154the type will only have attributes that are inherited from their base type, and
    1154 should leave the :attr:`tp_getattro` and :attr:`tp_setattro` fields *NULL* as
     1155should leave the :c:member:`~PyTypeObject.tp_getattro` and :c:member:`~PyTypeObject.tp_setattro` fields *NULL* as
    11551156well, allowing the base type to handle attributes.
    11561157
     
    11611162   struct PyGetSetDef *tp_getset;
    11621163
    1163 If :attr:`tp_methods` is not *NULL*, it must refer to an array of
    1164 :ctype:`PyMethodDef` structures.  Each entry in the table is an instance of this
     1164If :c:member:`~PyTypeObject.tp_methods` is not *NULL*, it must refer to an array of
     1165:c:type:`PyMethodDef` structures.  Each entry in the table is an instance of this
    11651166structure::
    11661167
     
    12251226   single: RESTRICTED
    12261227
    1227 An interesting advantage of using the :attr:`tp_members` table to build
     1228An interesting advantage of using the :c:member:`~PyTypeObject.tp_members` table to build
    12281229descriptors that are used at runtime is that any attribute defined this way can
    12291230have an associated doc string simply by providing the text in the table.  An
     
    12311232class object, and get the doc string using its :attr:`__doc__` attribute.
    12321233
    1233 As with the :attr:`tp_methods` table, a sentinel entry with a :attr:`name` value
     1234As with the :c:member:`~PyTypeObject.tp_methods` table, a sentinel entry with a :attr:`name` value
    12341235of *NULL* is required.
    12351236
     
    12471248^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    12481249
    1249 For simplicity, only the :ctype:`char\*` version will be demonstrated here; the
    1250 type of the name parameter is the only difference between the :ctype:`char\*`
    1251 and :ctype:`PyObject\*` flavors of the interface. This example effectively does
     1250For simplicity, only the :c:type:`char\*` version will be demonstrated here; the
     1251type of the name parameter is the only difference between the :c:type:`char\*`
     1252and :c:type:`PyObject\*` flavors of the interface. This example effectively does
    12521253the same thing as the generic example above, but does not use the generic
    12531254support added in Python 2.2.  The value in showing this is two-fold: it
     
    12571258what needs to be done.
    12581259
    1259 The :attr:`tp_getattr` handler is called when the object requires an attribute
     1260The :c:member:`~PyTypeObject.tp_getattr` handler is called when the object requires an attribute
    12601261look-up.  It is called in the same situations where the :meth:`__getattr__`
    12611262method of a class would be called.
    12621263
    12631264A likely way to handle this is (1) to implement a set of functions (such as
    1264 :cfunc:`newdatatype_getSize` and :cfunc:`newdatatype_setSize` in the example
     1265:c:func:`newdatatype_getSize` and :c:func:`newdatatype_setSize` in the example
    12651266below), (2) provide a method table listing these functions, and (3) provide a
    12661267getattr function that returns the result of a lookup in that table.  The method
    1267 table uses the same structure as the :attr:`tp_methods` field of the type
     1268table uses the same structure as the :c:member:`~PyTypeObject.tp_methods` field of the type
    12681269object.
    12691270
     
    12841285   }
    12851286
    1286 The :attr:`tp_setattr` handler is called when the :meth:`__setattr__` or
     1287The :c:member:`~PyTypeObject.tp_setattr` handler is called when the :meth:`__setattr__` or
    12871288:meth:`__delattr__` method of a class instance would be called.  When an
    12881289attribute should be deleted, the third parameter will be *NULL*.  Here is an
    12891290example that simply raises an exception; if this were really all you wanted, the
    1290 :attr:`tp_setattr` handler should be set to *NULL*. ::
     1291:c:member:`~PyTypeObject.tp_setattr` handler should be set to *NULL*. ::
    12911292
    12921293   static int
     
    13051306   cmpfunc tp_compare;
    13061307
    1307 The :attr:`tp_compare` handler is called when comparisons are needed and the
     1308The :c:member:`~PyTypeObject.tp_compare` handler is called when comparisons are needed and the
    13081309object does not implement the specific rich comparison method which matches the
    13091310requested comparison.  (It is always used if defined and the
    1310 :cfunc:`PyObject_Compare` or :cfunc:`PyObject_Cmp` functions are used, or if
     1311:c:func:`PyObject_Compare` or :c:func:`PyObject_Cmp` functions are used, or if
    13111312:func:`cmp` is used from Python.) It is analogous to the :meth:`__cmp__` method.
    13121313This function should return ``-1`` if *obj1* is less than *obj2*, ``0`` if they
     
    13161317future, other return values may be assigned a different meaning.)
    13171318
    1318 A :attr:`tp_compare` handler may raise an exception.  In this case it should
     1319A :c:member:`~PyTypeObject.tp_compare` handler may raise an exception.  In this case it should
    13191320return a negative value.  The caller has to test for the exception using
    1320 :cfunc:`PyErr_Occurred`.
     1321:c:func:`PyErr_Occurred`.
    13211322
    13221323Here is a sample implementation::
     
    13601361to indicate the presence of a slot, but a slot may still be unfilled.) ::
    13611362
    1362    PyNumberMethods   tp_as_number;
    1363    PySequenceMethods tp_as_sequence;
    1364    PyMappingMethods  tp_as_mapping;
     1363   PyNumberMethods   *tp_as_number;
     1364   PySequenceMethods *tp_as_sequence;
     1365   PyMappingMethods  *tp_as_mapping;
    13651366
    13661367If you wish your object to be able to act like a number, a sequence, or a
    13671368mapping object, then you place the address of a structure that implements the C
    1368 type :ctype:`PyNumberMethods`, :ctype:`PySequenceMethods`, or
    1369 :ctype:`PyMappingMethods`, respectively. It is up to you to fill in this
     1369type :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, or
     1370:c:type:`PyMappingMethods`, respectively. It is up to you to fill in this
    13701371structure with appropriate values. You can find examples of the use of each of
    13711372these in the :file:`Objects` directory of the Python source distribution. ::
     
    13911392This function is called when an instance of your data type is "called", for
    13921393example, if ``obj1`` is an instance of your data type and the Python script
    1393 contains ``obj1('hello')``, the :attr:`tp_call` handler is invoked.
     1394contains ``obj1('hello')``, the :c:member:`~PyTypeObject.tp_call` handler is invoked.
    13941395
    13951396This function takes three arguments:
     
    13991400
    14001401#. *arg2* is a tuple containing the arguments to the call.  You can use
    1401    :cfunc:`PyArg_ParseTuple` to extract the arguments.
     1402   :c:func:`PyArg_ParseTuple` to extract the arguments.
    14021403
    14031404#. *arg3* is a dictionary of keyword arguments that were passed. If this is
    14041405   non-*NULL* and you support keyword arguments, use
    1405    :cfunc:`PyArg_ParseTupleAndKeywords` to extract the arguments.  If you do not
     1406   :c:func:`PyArg_ParseTupleAndKeywords` to extract the arguments.  If you do not
    14061407   want to support keyword arguments and this is non-*NULL*, raise a
    14071408   :exc:`TypeError` with a message saying that keyword arguments are not supported.
     
    14781479
    14791480For an object to be weakly referencable, the extension must include a
    1480 :ctype:`PyObject\*` field in the instance structure for the use of the weak
     1481:c:type:`PyObject\*` field in the instance structure for the use of the weak
    14811482reference mechanism; it must be initialized to *NULL* by the object's
    1482 constructor.  It must also set the :attr:`tp_weaklistoffset` field of the
     1483constructor.  It must also set the :c:member:`~PyTypeObject.tp_weaklistoffset` field of the
    14831484corresponding type object to the offset of the field. For example, the instance
    14841485type is defined with the following structure::
     
    15211522
    15221523The only further addition is that the destructor needs to call the weak
    1523 reference manager to clear any weak references.  This should be done before any
    1524 other parts of the destruction have occurred, but is only required if the weak
    1525 reference list is non-*NULL*::
     1524reference manager to clear any weak references.  This is only required if the
     1525weak reference list is non-*NULL*::
    15261526
    15271527   static void
     
    15541554
    15551555When you need to verify that an object is an instance of the type you are
    1556 implementing, use the :cfunc:`PyObject_TypeCheck` function. A sample of its use
     1556implementing, use the :c:func:`PyObject_TypeCheck` function. A sample of its use
    15571557might be something like the following::
    15581558
     
    15671567   float.
    15681568
    1569 .. [#] We relied on this in the :attr:`tp_dealloc` handler in this example, because our
     1569.. [#] We relied on this in the :c:member:`~PyTypeObject.tp_dealloc` handler in this example, because our
    15701570   type doesn't support garbage collection. Even if a type supports garbage
    15711571   collection, there are calls that can be made to "untrack" the object from
  • python/vendor/current/Doc/extending/windows.rst

    r2 r388  
    9999   not necessarily have to match the module name, but the name of the
    100100   initialization function should match the module name --- you can only import a
    101    module :mod:`spam` if its initialization function is called :cfunc:`initspam`,
    102    and it should call :cfunc:`Py_InitModule` with the string ``"spam"`` as its
     101   module :mod:`spam` if its initialization function is called :c:func:`initspam`,
     102   and it should call :c:func:`Py_InitModule` with the string ``"spam"`` as its
    103103   first argument (use the minimal :file:`example.c` in this directory as a guide).
    104104   By convention, it lives in a file called :file:`spam.c` or :file:`spammodule.c`.
     
    115115
    116116#. Copy :file:`example.sln` and :file:`example.vcproj`, rename them to
    117       :file:`spam.\*`, and edit them by hand, or
     117   :file:`spam.\*`, and edit them by hand, or
    118118
    119119#. Create a brand new project; instructions are below.
     
    176176   PyObject_HEAD_INIT(&PyType_Type)
    177177
    178 Change it to::
     178Static type object initializers in extension modules may cause
     179compiles to fail with an error message like "initializer not a
     180constant".  This shows up when building DLL under MSVC.  Change it to::
    179181
    180182   PyObject_HEAD_INIT(NULL)
     
    182184and add the following to the module initialization function::
    183185
    184    MyObject_Type.ob_type = &PyType_Type;
    185 
    186 Refer to section 3 of the `Python FAQ <http://www.python.org/doc/faq>`_ for
    187 details on why you must do this.
     186   if (PyType_Ready(&MyObject_Type) < 0)
     187        return NULL;
    188188
    189189
     
    264264The first command created three files: :file:`spam.obj`, :file:`spam.dll` and
    265265:file:`spam.lib`.  :file:`Spam.dll` does not contain any Python functions (such
    266 as :cfunc:`PyArg_ParseTuple`), but it does know how to find the Python code
     266as :c:func:`PyArg_ParseTuple`), but it does know how to find the Python code
    267267thanks to :file:`pythonXY.lib`.
    268268
Note: See TracChangeset for help on using the changeset viewer.