Changeset 391 for python/trunk/Doc/c-api/intro.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/c-api/intro.rst
r2 r391 42 42 43 43 This implies inclusion of the following standard headers: ``<stdio.h>``, 44 ``<string.h>``, ``<errno.h>``, ``<limits.h>``, and ``<stdlib.h>`` (if45 available).44 ``<string.h>``, ``<errno.h>``, ``<limits.h>``, ``<assert.h>`` and ``<stdlib.h>`` 45 (if available). 46 46 47 47 .. note:: … … 89 89 90 90 Most Python/C API functions have one or more arguments as well as a return value 91 of type :c type:`PyObject\*`. This type is a pointer to an opaque data type91 of type :c:type:`PyObject\*`. This type is a pointer to an opaque data type 92 92 representing an arbitrary Python object. Since all Python object types are 93 93 treated the same way by the Python language in most situations (e.g., … … 95 95 should be represented by a single C type. Almost all Python objects live on the 96 96 heap: you never declare an automatic or static variable of type 97 :c type:`PyObject`, only pointer variables of type :ctype:`PyObject\*` can be97 :c:type:`PyObject`, only pointer variables of type :c:type:`PyObject\*` can be 98 98 declared. The sole exception are the type objects; since these must never be 99 deallocated, they are typically static :c type:`PyTypeObject` objects.99 deallocated, they are typically static :c:type:`PyTypeObject` objects. 100 100 101 101 All Python objects (even Python integers) have a :dfn:`type` and a … … 128 128 129 129 Reference counts are always manipulated explicitly. The normal way is to use 130 the macro :c func:`Py_INCREF` to increment an object's reference count by one,131 and :c func:`Py_DECREF` to decrement it by one. The :cfunc:`Py_DECREF` macro130 the macro :c:func:`Py_INCREF` to increment an object's reference count by one, 131 and :c:func:`Py_DECREF` to decrement it by one. The :c:func:`Py_DECREF` macro 132 132 is considerably more complex than the incref one, since it must check whether 133 133 the reference count becomes zero and then cause the object's deallocator to be … … 160 160 and possible deallocating it. The real danger is that innocent-looking 161 161 operations may invoke arbitrary Python code which could do this; there is a code 162 path which allows control to flow back to the user from a :c func:`Py_DECREF`, so162 path which allows control to flow back to the user from a :c:func:`Py_DECREF`, so 163 163 almost any operation is potentially dangerous. 164 164 … … 166 166 begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``). 167 167 These operations always increment the reference count of the object they return. 168 This leaves the caller with the responsibility to call :c func:`Py_DECREF` when168 This leaves the caller with the responsibility to call :c:func:`Py_DECREF` when 169 169 they are done with the result; this soon becomes second nature. 170 170 … … 181 181 reference is no longer needed. Ownership can also be transferred, meaning that 182 182 the code that receives ownership of the reference then becomes responsible for 183 eventually decref'ing it by calling :c func:`Py_DECREF` or :cfunc:`Py_XDECREF`183 eventually decref'ing it by calling :c:func:`Py_DECREF` or :c:func:`Py_XDECREF` 184 184 when it's no longer needed---or passing on this responsibility (usually to its 185 185 caller). When a function passes ownership of a reference on to its caller, the … … 199 199 200 200 Few functions steal references; the two notable exceptions are 201 :c func:`PyList_SetItem` and :cfunc:`PyTuple_SetItem`, which steal a reference201 :c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which steal a reference 202 202 to the item (but not to the tuple or list into which the item is put!). These 203 203 functions were designed to steal a reference because of a common idiom for … … 213 213 PyTuple_SetItem(t, 2, PyString_FromString("three")); 214 214 215 Here, :c func:`PyInt_FromLong` returns a new reference which is immediately216 stolen by :c func:`PyTuple_SetItem`. When you want to keep using an object217 although the reference to it will be stolen, use :c func:`Py_INCREF` to grab215 Here, :c:func:`PyInt_FromLong` returns a new reference which is immediately 216 stolen by :c:func:`PyTuple_SetItem`. When you want to keep using an object 217 although the reference to it will be stolen, use :c:func:`Py_INCREF` to grab 218 218 another reference before calling the reference-stealing function. 219 219 220 Incidentally, :c func:`PyTuple_SetItem` is the *only* way to set tuple items;221 :c func:`PySequence_SetItem` and :cfunc:`PyObject_SetItem` refuse to do this220 Incidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple items; 221 :c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to do this 222 222 since tuples are an immutable data type. You should only use 223 :c func:`PyTuple_SetItem` for tuples that you are creating yourself.224 225 Equivalent code for populating a list can be written using :c func:`PyList_New`226 and :c func:`PyList_SetItem`.223 :c:func:`PyTuple_SetItem` for tuples that you are creating yourself. 224 225 Equivalent code for populating a list can be written using :c:func:`PyList_New` 226 and :c:func:`PyList_SetItem`. 227 227 228 228 However, in practice, you will rarely use these ways of creating and populating 229 a tuple or list. There's a generic function, :c func:`Py_BuildValue`, that can229 a tuple or list. There's a generic function, :c:func:`Py_BuildValue`, that can 230 230 create most common objects from C values, directed by a :dfn:`format string`. 231 231 For example, the above two blocks of code could be replaced by the following … … 237 237 list = Py_BuildValue("[iis]", 1, 2, "three"); 238 238 239 It is much more common to use :c func:`PyObject_SetItem` and friends with items239 It is much more common to use :c:func:`PyObject_SetItem` and friends with items 240 240 whose references you are only borrowing, like arguments that were passed in to 241 241 the function you are writing. In that case, their behaviour regarding reference … … 256 256 if (!index) 257 257 return -1; 258 if (PyObject_SetItem(target, index, item) < 0) 258 if (PyObject_SetItem(target, index, item) < 0) { 259 Py_DECREF(index); 259 260 return -1; 261 } 260 262 Py_DECREF(index); 261 263 } … … 271 273 returned object is created on the fly, and the reference you get is the only 272 274 reference to the object. Therefore, the generic functions that return object 273 references, like :c func:`PyObject_GetItem` and :cfunc:`PySequence_GetItem`,275 references, like :c:func:`PyObject_GetItem` and :c:func:`PySequence_GetItem`, 274 276 always return a new reference (the caller becomes the owner of the reference). 275 277 … … 277 279 function depends on which function you call only --- *the plumage* (the type of 278 280 the object passed as an argument to the function) *doesn't enter into it!* 279 Thus, if you extract an item from a list using :c func:`PyList_GetItem`, you281 Thus, if you extract an item from a list using :c:func:`PyList_GetItem`, you 280 282 don't own the reference --- but if you obtain the same item from the same list 281 using :c func:`PySequence_GetItem` (which happens to take exactly the same283 using :c:func:`PySequence_GetItem` (which happens to take exactly the same 282 284 arguments), you do own a reference to the returned object. 283 285 … … 287 289 288 290 Here is an example of how you could write a function that computes the sum of 289 the items in a list of integers; once using :c func:`PyList_GetItem`, and once290 using :c func:`PySequence_GetItem`. ::291 the items in a list of integers; once using :c:func:`PyList_GetItem`, and once 292 using :c:func:`PySequence_GetItem`. :: 291 293 292 294 long … … 341 343 342 344 There are few other data types that play a significant role in the Python/C 343 API; most are simple C types such as :c type:`int`, :ctype:`long`,344 :c type:`double` and :ctype:`char\*`. A few structure types are used to345 API; most are simple C types such as :c:type:`int`, :c:type:`long`, 346 :c:type:`double` and :c:type:`char\*`. A few structure types are used to 345 347 describe static tables used to list the functions exported by a module or the 346 348 data attributes of a new object type, and another is used to describe the value … … 362 364 .. index:: single: PyErr_Occurred() 363 365 364 For C programmers, however, error checking always has to be explicit. All 365 functions in the Python/C API can raise exceptions, unless an explicit claim is 366 made otherwise in a function's documentation. In general, when a function 367 encounters an error, it sets an exception, discards any object references that 368 it owns, and returns an error indicator --- usually *NULL* or ``-1``. A few 369 functions return a Boolean true/false result, with false indicating an error. 370 Very few functions return no explicit error indicator or have an ambiguous 371 return value, and require explicit testing for errors with 372 :cfunc:`PyErr_Occurred`. 366 For C programmers, however, error checking always has to be explicit. All 367 functions in the Python/C API can raise exceptions, unless an explicit claim is 368 made otherwise in a function's documentation. In general, when a function 369 encounters an error, it sets an exception, discards any object references that 370 it owns, and returns an error indicator. If not documented otherwise, this 371 indicator is either *NULL* or ``-1``, depending on the function's return type. 372 A few functions return a Boolean true/false result, with false indicating an 373 error. Very few functions return no explicit error indicator or have an 374 ambiguous return value, and require explicit testing for errors with 375 :c:func:`PyErr_Occurred`. These exceptions are always explicitly documented. 373 376 374 377 .. index:: … … 379 382 using global storage in an unthreaded application). A thread can be in one of 380 383 two states: an exception has occurred, or not. The function 381 :c func:`PyErr_Occurred` can be used to check for this: it returns a borrowed384 :c:func:`PyErr_Occurred` can be used to check for this: it returns a borrowed 382 385 reference to the exception type object when an exception has occurred, and 383 386 *NULL* otherwise. There are a number of functions to set the exception state: 384 :c func:`PyErr_SetString` is the most common (though not the most general)385 function to set the exception state, and :c func:`PyErr_Clear` clears the387 :c:func:`PyErr_SetString` is the most common (though not the most general) 388 function to set the exception state, and :c:func:`PyErr_Clear` clears the 386 389 exception state. 387 390 … … 424 427 425 428 A simple example of detecting exceptions and passing them on is shown in the 426 :c func:`sum_sequence` example above. It so happens that thatexample doesn't429 :c:func:`sum_sequence` example above. It so happens that this example doesn't 427 430 need to clean up any owned references when it detects an error. The following 428 431 example function shows some error cleanup. First, to remind you why you like … … 491 494 492 495 This example represents an endorsed use of the ``goto`` statement in C! 493 It illustrates the use of :c func:`PyErr_ExceptionMatches` and494 :c func:`PyErr_Clear` to handle specific exceptions, and the use of495 :c func:`Py_XDECREF` to dispose of owned references that may be *NULL* (note the496 ``'X'`` in the name; :c func:`Py_DECREF` would crash when confronted with a496 It illustrates the use of :c:func:`PyErr_ExceptionMatches` and 497 :c:func:`PyErr_Clear` to handle specific exceptions, and the use of 498 :c:func:`Py_XDECREF` to dispose of owned references that may be *NULL* (note the 499 ``'X'`` in the name; :c:func:`Py_DECREF` would crash when confronted with a 497 500 *NULL* reference). It is important that the variables used to hold owned 498 501 references are initialized to *NULL* for this to work; likewise, the proposed … … 520 523 single: path (in module sys) 521 524 522 The basic initialization function is :c func:`Py_Initialize`. This initializes525 The basic initialization function is :c:func:`Py_Initialize`. This initializes 523 526 the table of loaded modules, and creates the fundamental modules 524 527 :mod:`__builtin__`, :mod:`__main__`, :mod:`sys`, and :mod:`exceptions`. It also 525 528 initializes the module search path (``sys.path``). 526 529 527 .. index:: single: PySys_SetArgv ()528 529 :c func:`Py_Initialize` does not set the "script argument list" (``sys.argv``).530 If this variable is needed by Python code that 531 be set explicitly with a call to ``PySys_SetArgv (argc, argv)`` subsequent to532 the call to :cfunc:`Py_Initialize`.530 .. index:: single: PySys_SetArgvEx() 531 532 :c:func:`Py_Initialize` does not set the "script argument list" (``sys.argv``). 533 If this variable is needed by Python code that will be executed later, it must 534 be set explicitly with a call to ``PySys_SetArgvEx(argc, argv, updatepath)`` 535 after the call to :c:func:`Py_Initialize`. 533 536 534 537 On most systems (in particular, on Unix and Windows, although the details are 535 slightly different), :c func:`Py_Initialize` calculates the module search path538 slightly different), :c:func:`Py_Initialize` calculates the module search path 536 539 based upon its best guess for the location of the standard Python interpreter 537 540 executable, assuming that the Python library is found in a fixed location … … 557 560 558 561 The embedding application can steer the search by calling 559 ``Py_SetProgramName(file)`` *before* calling :c func:`Py_Initialize`. Note that562 ``Py_SetProgramName(file)`` *before* calling :c:func:`Py_Initialize`. Note that 560 563 :envvar:`PYTHONHOME` still overrides this and :envvar:`PYTHONPATH` is still 561 564 inserted in front of the standard path. An application that requires total 562 control has to provide its own implementation of :c func:`Py_GetPath`,563 :c func:`Py_GetPrefix`, :cfunc:`Py_GetExecPrefix`, and564 :c func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`).565 control has to provide its own implementation of :c:func:`Py_GetPath`, 566 :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and 567 :c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`). 565 568 566 569 .. index:: single: Py_IsInitialized() … … 568 571 Sometimes, it is desirable to "uninitialize" Python. For instance, the 569 572 application may want to start over (make another call to 570 :c func:`Py_Initialize`) or the application is simply done with its use of573 :c:func:`Py_Initialize`) or the application is simply done with its use of 571 574 Python and wants to free memory allocated by Python. This can be accomplished 572 by calling :c func:`Py_Finalize`. The function :cfunc:`Py_IsInitialized` returns575 by calling :c:func:`Py_Finalize`. The function :c:func:`Py_IsInitialized` returns 573 576 true if Python is currently in the initialized state. More information about 574 these functions is given in a later chapter. Notice that :c func:`Py_Finalize`577 these functions is given in a later chapter. Notice that :c:func:`Py_Finalize` 575 578 does *not* free all memory allocated by the Python interpreter, e.g. memory 576 579 allocated by extension modules currently cannot be released. … … 592 595 frequently-used builds will be described in the remainder of this section. 593 596 594 Compiling the interpreter with the :c macro:`Py_DEBUG` macro defined produces595 what is generally meant by "a debug build" of Python. :c macro:`Py_DEBUG` is596 enabled in the Unix build by adding :option:`--with-pydebug` to the597 :file:` configure` command. It is also implied by the presence of the598 not-Python-specific :c macro:`_DEBUG` macro. When :cmacro:`Py_DEBUG` is enabled597 Compiling the interpreter with the :c:macro:`Py_DEBUG` macro defined produces 598 what is generally meant by "a debug build" of Python. :c:macro:`Py_DEBUG` is 599 enabled in the Unix build by adding ``--with-pydebug`` to the 600 :file:`./configure` command. It is also implied by the presence of the 601 not-Python-specific :c:macro:`_DEBUG` macro. When :c:macro:`Py_DEBUG` is enabled 599 602 in the Unix build, compiler optimization is disabled. 600 603 … … 625 628 There may be additional checks not mentioned here. 626 629 627 Defining :c macro:`Py_TRACE_REFS` enables reference tracing. When defined, a630 Defining :c:macro:`Py_TRACE_REFS` enables reference tracing. When defined, a 628 631 circular doubly linked list of active objects is maintained by adding two extra 629 fields to every :c type:`PyObject`. Total allocations are tracked as well. Upon632 fields to every :c:type:`PyObject`. Total allocations are tracked as well. Upon 630 633 exit, all existing references are printed. (In interactive mode this happens 631 after every statement run by the interpreter.) Implied by :c macro:`Py_DEBUG`.634 after every statement run by the interpreter.) Implied by :c:macro:`Py_DEBUG`. 632 635 633 636 Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution
Note:
See TracChangeset
for help on using the changeset viewer.