Home | History | Annotate | Download | only in c-api
      1 .. highlightlang:: c
      2 
      3 
      4 .. _api-intro:
      5 
      6 ************
      7 Introduction
      8 ************
      9 
     10 The Application Programmer's Interface to Python gives C and C++ programmers
     11 access to the Python interpreter at a variety of levels.  The API is equally
     12 usable from C++, but for brevity it is generally referred to as the Python/C
     13 API.  There are two fundamentally different reasons for using the Python/C API.
     14 The first reason is to write *extension modules* for specific purposes; these
     15 are C modules that extend the Python interpreter.  This is probably the most
     16 common use.  The second reason is to use Python as a component in a larger
     17 application; this technique is generally referred to as :dfn:`embedding` Python
     18 in an application.
     19 
     20 Writing an extension module is a relatively well-understood process, where a
     21 "cookbook" approach works well.  There are several tools that automate the
     22 process to some extent.  While people have embedded Python in other
     23 applications since its early existence, the process of embedding Python is
     24 less straightforward than writing an extension.
     25 
     26 Many API functions are useful independent of whether you're embedding  or
     27 extending Python; moreover, most applications that embed Python  will need to
     28 provide a custom extension as well, so it's probably a  good idea to become
     29 familiar with writing an extension before  attempting to embed Python in a real
     30 application.
     31 
     32 
     33 Coding standards
     34 ================
     35 
     36 If you're writing C code for inclusion in CPython, you **must** follow the
     37 guidelines and standards defined in :PEP:`7`.  These guidelines apply
     38 regardless of the version of Python you are contributing to.  Following these
     39 conventions is not necessary for your own third party extension modules,
     40 unless you eventually expect to contribute them to Python.
     41 
     42 
     43 .. _api-includes:
     44 
     45 Include Files
     46 =============
     47 
     48 All function, type and macro definitions needed to use the Python/C API are
     49 included in your code by the following line::
     50 
     51    #include "Python.h"
     52 
     53 This implies inclusion of the following standard headers: ``<stdio.h>``,
     54 ``<string.h>``, ``<errno.h>``, ``<limits.h>``, ``<assert.h>`` and ``<stdlib.h>``
     55 (if available).
     56 
     57 .. note::
     58 
     59    Since Python may define some pre-processor definitions which affect the standard
     60    headers on some systems, you *must* include :file:`Python.h` before any standard
     61    headers are included.
     62 
     63 All user visible names defined by Python.h (except those defined by the included
     64 standard headers) have one of the prefixes ``Py`` or ``_Py``.  Names beginning
     65 with ``_Py`` are for internal use by the Python implementation and should not be
     66 used by extension writers. Structure member names do not have a reserved prefix.
     67 
     68 **Important:** user code should never define names that begin with ``Py`` or
     69 ``_Py``.  This confuses the reader, and jeopardizes the portability of the user
     70 code to future Python versions, which may define additional names beginning with
     71 one of these prefixes.
     72 
     73 The header files are typically installed with Python.  On Unix, these  are
     74 located in the directories :file:`{prefix}/include/pythonversion/` and
     75 :file:`{exec_prefix}/include/pythonversion/`, where :envvar:`prefix` and
     76 :envvar:`exec_prefix` are defined by the corresponding parameters to Python's
     77 :program:`configure` script and *version* is
     78 ``'%d.%d' % sys.version_info[:2]``.  On Windows, the headers are installed
     79 in :file:`{prefix}/include`, where :envvar:`prefix` is the installation
     80 directory specified to the installer.
     81 
     82 To include the headers, place both directories (if different) on your compiler's
     83 search path for includes.  Do *not* place the parent directories on the search
     84 path and then use ``#include <pythonX.Y/Python.h>``; this will break on
     85 multi-platform builds since the platform independent headers under
     86 :envvar:`prefix` include the platform specific headers from
     87 :envvar:`exec_prefix`.
     88 
     89 C++ users should note that though the API is defined entirely using C, the
     90 header files do properly declare the entry points to be ``extern "C"``, so there
     91 is no need to do anything special to use the API from C++.
     92 
     93 
     94 Useful macros
     95 =============
     96 
     97 Several useful macros are defined in the Python header files.  Many are
     98 defined closer to where they are useful (e.g. :c:macro:`Py_RETURN_NONE`).
     99 Others of a more general utility are defined here.  This is not necessarily a
    100 complete listing.
    101 
    102 .. c:macro:: Py_UNREACHABLE()
    103 
    104    Use this when you have a code path that you do not expect to be reached.
    105    For example, in the ``default:`` clause in a ``switch`` statement for which
    106    all possible values are covered in ``case`` statements.  Use this in places
    107    where you might be tempted to put an ``assert(0)`` or ``abort()`` call.
    108 
    109    .. versionadded:: 3.7
    110 
    111 .. c:macro:: Py_ABS(x)
    112 
    113    Return the absolute value of ``x``.
    114 
    115    .. versionadded:: 3.3
    116 
    117 .. c:macro:: Py_MIN(x, y)
    118 
    119    Return the minimum value between ``x`` and ``y``.
    120 
    121    .. versionadded:: 3.3
    122 
    123 .. c:macro:: Py_MAX(x, y)
    124 
    125    Return the maximum value between ``x`` and ``y``.
    126 
    127    .. versionadded:: 3.3
    128 
    129 .. c:macro:: Py_STRINGIFY(x)
    130 
    131    Convert ``x`` to a C string.  E.g. ``Py_STRINGIFY(123)`` returns
    132    ``"123"``.
    133 
    134    .. versionadded:: 3.4
    135 
    136 .. c:macro:: Py_MEMBER_SIZE(type, member)
    137 
    138    Return the size of a structure (``type``) ``member`` in bytes.
    139 
    140    .. versionadded:: 3.6
    141 
    142 .. c:macro:: Py_CHARMASK(c)
    143 
    144    Argument must be a character or an integer in the range [-128, 127] or [0,
    145    255].  This macro returns ``c`` cast to an ``unsigned char``.
    146 
    147 .. c:macro:: Py_GETENV(s)
    148 
    149    Like ``getenv(s)``, but returns *NULL* if :option:`-E` was passed on the
    150    command line (i.e. if ``Py_IgnoreEnvironmentFlag`` is set).
    151 
    152 .. c:macro:: Py_UNUSED(arg)
    153 
    154    Use this for unused arguments in a function definition to silence compiler
    155    warnings, e.g. ``PyObject* func(PyObject *Py_UNUSED(ignored))``.
    156 
    157    .. versionadded:: 3.4
    158 
    159 
    160 .. _api-objects:
    161 
    162 Objects, Types and Reference Counts
    163 ===================================
    164 
    165 .. index:: object: type
    166 
    167 Most Python/C API functions have one or more arguments as well as a return value
    168 of type :c:type:`PyObject\*`.  This type is a pointer to an opaque data type
    169 representing an arbitrary Python object.  Since all Python object types are
    170 treated the same way by the Python language in most situations (e.g.,
    171 assignments, scope rules, and argument passing), it is only fitting that they
    172 should be represented by a single C type.  Almost all Python objects live on the
    173 heap: you never declare an automatic or static variable of type
    174 :c:type:`PyObject`, only pointer variables of type :c:type:`PyObject\*` can  be
    175 declared.  The sole exception are the type objects; since these must never be
    176 deallocated, they are typically static :c:type:`PyTypeObject` objects.
    177 
    178 All Python objects (even Python integers) have a :dfn:`type` and a
    179 :dfn:`reference count`.  An object's type determines what kind of object it is
    180 (e.g., an integer, a list, or a user-defined function; there are many more as
    181 explained in :ref:`types`).  For each of the well-known types there is a macro
    182 to check whether an object is of that type; for instance, ``PyList_Check(a)`` is
    183 true if (and only if) the object pointed to by *a* is a Python list.
    184 
    185 
    186 .. _api-refcounts:
    187 
    188 Reference Counts
    189 ----------------
    190 
    191 The reference count is important because today's computers have a  finite (and
    192 often severely limited) memory size; it counts how many  different places there
    193 are that have a reference to an object.  Such a  place could be another object,
    194 or a global (or static) C variable, or  a local variable in some C function.
    195 When an object's reference count  becomes zero, the object is deallocated.  If
    196 it contains references to  other objects, their reference count is decremented.
    197 Those other  objects may be deallocated in turn, if this decrement makes their
    198 reference count become zero, and so on.  (There's an obvious problem  with
    199 objects that reference each other here; for now, the solution is  "don't do
    200 that.")
    201 
    202 .. index::
    203    single: Py_INCREF()
    204    single: Py_DECREF()
    205 
    206 Reference counts are always manipulated explicitly.  The normal way is  to use
    207 the macro :c:func:`Py_INCREF` to increment an object's reference count by one,
    208 and :c:func:`Py_DECREF` to decrement it by   one.  The :c:func:`Py_DECREF` macro
    209 is considerably more complex than the incref one, since it must check whether
    210 the reference count becomes zero and then cause the object's deallocator to be
    211 called. The deallocator is a function pointer contained in the object's type
    212 structure.  The type-specific deallocator takes care of decrementing the
    213 reference counts for other objects contained in the object if this is a compound
    214 object type, such as a list, as well as performing any additional finalization
    215 that's needed.  There's no chance that the reference count can overflow; at
    216 least as many bits are used to hold the reference count as there are distinct
    217 memory locations in virtual memory (assuming ``sizeof(Py_ssize_t) >= sizeof(void*)``).
    218 Thus, the reference count increment is a simple operation.
    219 
    220 It is not necessary to increment an object's reference count for every  local
    221 variable that contains a pointer to an object.  In theory, the  object's
    222 reference count goes up by one when the variable is made to  point to it and it
    223 goes down by one when the variable goes out of  scope.  However, these two
    224 cancel each other out, so at the end the  reference count hasn't changed.  The
    225 only real reason to use the  reference count is to prevent the object from being
    226 deallocated as  long as our variable is pointing to it.  If we know that there
    227 is at  least one other reference to the object that lives at least as long as
    228 our variable, there is no need to increment the reference count  temporarily.
    229 An important situation where this arises is in objects  that are passed as
    230 arguments to C functions in an extension module  that are called from Python;
    231 the call mechanism guarantees to hold a  reference to every argument for the
    232 duration of the call.
    233 
    234 However, a common pitfall is to extract an object from a list and hold on to it
    235 for a while without incrementing its reference count. Some other operation might
    236 conceivably remove the object from the list, decrementing its reference count
    237 and possible deallocating it. The real danger is that innocent-looking
    238 operations may invoke arbitrary Python code which could do this; there is a code
    239 path which allows control to flow back to the user from a :c:func:`Py_DECREF`, so
    240 almost any operation is potentially dangerous.
    241 
    242 A safe approach is to always use the generic operations (functions  whose name
    243 begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``).
    244 These operations always increment the reference count of the object they return.
    245 This leaves the caller with the responsibility to call :c:func:`Py_DECREF` when
    246 they are done with the result; this soon becomes second nature.
    247 
    248 
    249 .. _api-refcountdetails:
    250 
    251 Reference Count Details
    252 ^^^^^^^^^^^^^^^^^^^^^^^
    253 
    254 The reference count behavior of functions in the Python/C API is best  explained
    255 in terms of *ownership of references*.  Ownership pertains to references, never
    256 to objects (objects are not owned: they are always shared).  "Owning a
    257 reference" means being responsible for calling Py_DECREF on it when the
    258 reference is no longer needed.  Ownership can also be transferred, meaning that
    259 the code that receives ownership of the reference then becomes responsible for
    260 eventually decref'ing it by calling :c:func:`Py_DECREF` or :c:func:`Py_XDECREF`
    261 when it's no longer needed---or passing on this responsibility (usually to its
    262 caller). When a function passes ownership of a reference on to its caller, the
    263 caller is said to receive a *new* reference.  When no ownership is transferred,
    264 the caller is said to *borrow* the reference. Nothing needs to be done for a
    265 borrowed reference.
    266 
    267 Conversely, when a calling function passes in a reference to an  object, there
    268 are two possibilities: the function *steals* a  reference to the object, or it
    269 does not.  *Stealing a reference* means that when you pass a reference to a
    270 function, that function assumes that it now owns that reference, and you are not
    271 responsible for it any longer.
    272 
    273 .. index::
    274    single: PyList_SetItem()
    275    single: PyTuple_SetItem()
    276 
    277 Few functions steal references; the two notable exceptions are
    278 :c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which  steal a reference
    279 to the item (but not to the tuple or list into which the item is put!).  These
    280 functions were designed to steal a reference because of a common idiom for
    281 populating a tuple or list with newly created objects; for example, the code to
    282 create the tuple ``(1, 2, "three")`` could look like this (forgetting about
    283 error handling for the moment; a better way to code this is shown below)::
    284 
    285    PyObject *t;
    286 
    287    t = PyTuple_New(3);
    288    PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
    289    PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
    290    PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));
    291 
    292 Here, :c:func:`PyLong_FromLong` returns a new reference which is immediately
    293 stolen by :c:func:`PyTuple_SetItem`.  When you want to keep using an object
    294 although the reference to it will be stolen, use :c:func:`Py_INCREF` to grab
    295 another reference before calling the reference-stealing function.
    296 
    297 Incidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple items;
    298 :c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to do this
    299 since tuples are an immutable data type.  You should only use
    300 :c:func:`PyTuple_SetItem` for tuples that you are creating yourself.
    301 
    302 Equivalent code for populating a list can be written using :c:func:`PyList_New`
    303 and :c:func:`PyList_SetItem`.
    304 
    305 However, in practice, you will rarely use these ways of creating and populating
    306 a tuple or list.  There's a generic function, :c:func:`Py_BuildValue`, that can
    307 create most common objects from C values, directed by a :dfn:`format string`.
    308 For example, the above two blocks of code could be replaced by the following
    309 (which also takes care of the error checking)::
    310 
    311    PyObject *tuple, *list;
    312 
    313    tuple = Py_BuildValue("(iis)", 1, 2, "three");
    314    list = Py_BuildValue("[iis]", 1, 2, "three");
    315 
    316 It is much more common to use :c:func:`PyObject_SetItem` and friends with items
    317 whose references you are only borrowing, like arguments that were passed in to
    318 the function you are writing.  In that case, their behaviour regarding reference
    319 counts is much saner, since you don't have to increment a reference count so you
    320 can give a reference away ("have it be stolen").  For example, this function
    321 sets all items of a list (actually, any mutable sequence) to a given item::
    322 
    323    int
    324    set_all(PyObject *target, PyObject *item)
    325    {
    326        Py_ssize_t i, n;
    327 
    328        n = PyObject_Length(target);
    329        if (n < 0)
    330            return -1;
    331        for (i = 0; i < n; i++) {
    332            PyObject *index = PyLong_FromSsize_t(i);
    333            if (!index)
    334                return -1;
    335            if (PyObject_SetItem(target, index, item) < 0) {
    336                Py_DECREF(index);
    337                return -1;
    338            }
    339            Py_DECREF(index);
    340        }
    341        return 0;
    342    }
    343 
    344 .. index:: single: set_all()
    345 
    346 The situation is slightly different for function return values.   While passing
    347 a reference to most functions does not change your  ownership responsibilities
    348 for that reference, many functions that  return a reference to an object give
    349 you ownership of the reference. The reason is simple: in many cases, the
    350 returned object is created  on the fly, and the reference you get is the only
    351 reference to the  object.  Therefore, the generic functions that return object
    352 references, like :c:func:`PyObject_GetItem` and  :c:func:`PySequence_GetItem`,
    353 always return a new reference (the caller becomes the owner of the reference).
    354 
    355 It is important to realize that whether you own a reference returned  by a
    356 function depends on which function you call only --- *the plumage* (the type of
    357 the object passed as an argument to the function) *doesn't enter into it!*
    358 Thus, if you  extract an item from a list using :c:func:`PyList_GetItem`, you
    359 don't own the reference --- but if you obtain the same item from the same list
    360 using :c:func:`PySequence_GetItem` (which happens to take exactly the same
    361 arguments), you do own a reference to the returned object.
    362 
    363 .. index::
    364    single: PyList_GetItem()
    365    single: PySequence_GetItem()
    366 
    367 Here is an example of how you could write a function that computes the sum of
    368 the items in a list of integers; once using  :c:func:`PyList_GetItem`, and once
    369 using :c:func:`PySequence_GetItem`. ::
    370 
    371    long
    372    sum_list(PyObject *list)
    373    {
    374        Py_ssize_t i, n;
    375        long total = 0, value;
    376        PyObject *item;
    377 
    378        n = PyList_Size(list);
    379        if (n < 0)
    380            return -1; /* Not a list */
    381        for (i = 0; i < n; i++) {
    382            item = PyList_GetItem(list, i); /* Can't fail */
    383            if (!PyLong_Check(item)) continue; /* Skip non-integers */
    384            value = PyLong_AsLong(item);
    385            if (value == -1 && PyErr_Occurred())
    386                /* Integer too big to fit in a C long, bail out */
    387                return -1;
    388            total += value;
    389        }
    390        return total;
    391    }
    392 
    393 .. index:: single: sum_list()
    394 
    395 ::
    396 
    397    long
    398    sum_sequence(PyObject *sequence)
    399    {
    400        Py_ssize_t i, n;
    401        long total = 0, value;
    402        PyObject *item;
    403        n = PySequence_Length(sequence);
    404        if (n < 0)
    405            return -1; /* Has no length */
    406        for (i = 0; i < n; i++) {
    407            item = PySequence_GetItem(sequence, i);
    408            if (item == NULL)
    409                return -1; /* Not a sequence, or other failure */
    410            if (PyLong_Check(item)) {
    411                value = PyLong_AsLong(item);
    412                Py_DECREF(item);
    413                if (value == -1 && PyErr_Occurred())
    414                    /* Integer too big to fit in a C long, bail out */
    415                    return -1;
    416                total += value;
    417            }
    418            else {
    419                Py_DECREF(item); /* Discard reference ownership */
    420            }
    421        }
    422        return total;
    423    }
    424 
    425 .. index:: single: sum_sequence()
    426 
    427 
    428 .. _api-types:
    429 
    430 Types
    431 -----
    432 
    433 There are few other data types that play a significant role in  the Python/C
    434 API; most are simple C types such as :c:type:`int`,  :c:type:`long`,
    435 :c:type:`double` and :c:type:`char\*`.  A few structure types  are used to
    436 describe static tables used to list the functions exported  by a module or the
    437 data attributes of a new object type, and another is used to describe the value
    438 of a complex number.  These will  be discussed together with the functions that
    439 use them.
    440 
    441 
    442 .. _api-exceptions:
    443 
    444 Exceptions
    445 ==========
    446 
    447 The Python programmer only needs to deal with exceptions if specific  error
    448 handling is required; unhandled exceptions are automatically  propagated to the
    449 caller, then to the caller's caller, and so on, until they reach the top-level
    450 interpreter, where they are reported to the  user accompanied by a stack
    451 traceback.
    452 
    453 .. index:: single: PyErr_Occurred()
    454 
    455 For C programmers, however, error checking always has to be explicit.  All
    456 functions in the Python/C API can raise exceptions, unless an explicit claim is
    457 made otherwise in a function's documentation.  In general, when a function
    458 encounters an error, it sets an exception, discards any object references that
    459 it owns, and returns an error indicator.  If not documented otherwise, this
    460 indicator is either *NULL* or ``-1``, depending on the function's return type.
    461 A few functions return a Boolean true/false result, with false indicating an
    462 error.  Very few functions return no explicit error indicator or have an
    463 ambiguous return value, and require explicit testing for errors with
    464 :c:func:`PyErr_Occurred`.  These exceptions are always explicitly documented.
    465 
    466 .. index::
    467    single: PyErr_SetString()
    468    single: PyErr_Clear()
    469 
    470 Exception state is maintained in per-thread storage (this is  equivalent to
    471 using global storage in an unthreaded application).  A  thread can be in one of
    472 two states: an exception has occurred, or not. The function
    473 :c:func:`PyErr_Occurred` can be used to check for this: it returns a borrowed
    474 reference to the exception type object when an exception has occurred, and
    475 *NULL* otherwise.  There are a number of functions to set the exception state:
    476 :c:func:`PyErr_SetString` is the most common (though not the most general)
    477 function to set the exception state, and :c:func:`PyErr_Clear` clears the
    478 exception state.
    479 
    480 The full exception state consists of three objects (all of which can  be
    481 *NULL*): the exception type, the corresponding exception  value, and the
    482 traceback.  These have the same meanings as the Python result of
    483 ``sys.exc_info()``; however, they are not the same: the Python objects represent
    484 the last exception being handled by a Python  :keyword:`try` ...
    485 :keyword:`except` statement, while the C level exception state only exists while
    486 an exception is being passed on between C functions until it reaches the Python
    487 bytecode interpreter's  main loop, which takes care of transferring it to
    488 ``sys.exc_info()`` and friends.
    489 
    490 .. index:: single: exc_info() (in module sys)
    491 
    492 Note that starting with Python 1.5, the preferred, thread-safe way to access the
    493 exception state from Python code is to call the function :func:`sys.exc_info`,
    494 which returns the per-thread exception state for Python code.  Also, the
    495 semantics of both ways to access the exception state have changed so that a
    496 function which catches an exception will save and restore its thread's exception
    497 state so as to preserve the exception state of its caller.  This prevents common
    498 bugs in exception handling code caused by an innocent-looking function
    499 overwriting the exception being handled; it also reduces the often unwanted
    500 lifetime extension for objects that are referenced by the stack frames in the
    501 traceback.
    502 
    503 As a general principle, a function that calls another function to  perform some
    504 task should check whether the called function raised an  exception, and if so,
    505 pass the exception state on to its caller.  It  should discard any object
    506 references that it owns, and return an  error indicator, but it should *not* set
    507 another exception --- that would overwrite the exception that was just raised,
    508 and lose important information about the exact cause of the error.
    509 
    510 .. index:: single: sum_sequence()
    511 
    512 A simple example of detecting exceptions and passing them on is shown in the
    513 :c:func:`sum_sequence` example above.  It so happens that this example doesn't
    514 need to clean up any owned references when it detects an error.  The following
    515 example function shows some error cleanup.  First, to remind you why you like
    516 Python, we show the equivalent Python code::
    517 
    518    def incr_item(dict, key):
    519        try:
    520            item = dict[key]
    521        except KeyError:
    522            item = 0
    523        dict[key] = item + 1
    524 
    525 .. index:: single: incr_item()
    526 
    527 Here is the corresponding C code, in all its glory::
    528 
    529    int
    530    incr_item(PyObject *dict, PyObject *key)
    531    {
    532        /* Objects all initialized to NULL for Py_XDECREF */
    533        PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
    534        int rv = -1; /* Return value initialized to -1 (failure) */
    535 
    536        item = PyObject_GetItem(dict, key);
    537        if (item == NULL) {
    538            /* Handle KeyError only: */
    539            if (!PyErr_ExceptionMatches(PyExc_KeyError))
    540                goto error;
    541 
    542            /* Clear the error and use zero: */
    543            PyErr_Clear();
    544            item = PyLong_FromLong(0L);
    545            if (item == NULL)
    546                goto error;
    547        }
    548        const_one = PyLong_FromLong(1L);
    549        if (const_one == NULL)
    550            goto error;
    551 
    552        incremented_item = PyNumber_Add(item, const_one);
    553        if (incremented_item == NULL)
    554            goto error;
    555 
    556        if (PyObject_SetItem(dict, key, incremented_item) < 0)
    557            goto error;
    558        rv = 0; /* Success */
    559        /* Continue with cleanup code */
    560 
    561     error:
    562        /* Cleanup code, shared by success and failure path */
    563 
    564        /* Use Py_XDECREF() to ignore NULL references */
    565        Py_XDECREF(item);
    566        Py_XDECREF(const_one);
    567        Py_XDECREF(incremented_item);
    568 
    569        return rv; /* -1 for error, 0 for success */
    570    }
    571 
    572 .. index:: single: incr_item()
    573 
    574 .. index::
    575    single: PyErr_ExceptionMatches()
    576    single: PyErr_Clear()
    577    single: Py_XDECREF()
    578 
    579 This example represents an endorsed use of the ``goto`` statement  in C!
    580 It illustrates the use of :c:func:`PyErr_ExceptionMatches` and
    581 :c:func:`PyErr_Clear` to handle specific exceptions, and the use of
    582 :c:func:`Py_XDECREF` to dispose of owned references that may be *NULL* (note the
    583 ``'X'`` in the name; :c:func:`Py_DECREF` would crash when confronted with a
    584 *NULL* reference).  It is important that the variables used to hold owned
    585 references are initialized to *NULL* for this to work; likewise, the proposed
    586 return value is initialized to ``-1`` (failure) and only set to success after
    587 the final call made is successful.
    588 
    589 
    590 .. _api-embedding:
    591 
    592 Embedding Python
    593 ================
    594 
    595 The one important task that only embedders (as opposed to extension writers) of
    596 the Python interpreter have to worry about is the initialization, and possibly
    597 the finalization, of the Python interpreter.  Most functionality of the
    598 interpreter can only be used after the interpreter has been initialized.
    599 
    600 .. index::
    601    single: Py_Initialize()
    602    module: builtins
    603    module: __main__
    604    module: sys
    605    triple: module; search; path
    606    single: path (in module sys)
    607 
    608 The basic initialization function is :c:func:`Py_Initialize`. This initializes
    609 the table of loaded modules, and creates the fundamental modules
    610 :mod:`builtins`, :mod:`__main__`, and :mod:`sys`.  It also
    611 initializes the module search path (``sys.path``).
    612 
    613 .. index:: single: PySys_SetArgvEx()
    614 
    615 :c:func:`Py_Initialize` does not set the "script argument list"  (``sys.argv``).
    616 If this variable is needed by Python code that will be executed later, it must
    617 be set explicitly with a call to  ``PySys_SetArgvEx(argc, argv, updatepath)``
    618 after the call to :c:func:`Py_Initialize`.
    619 
    620 On most systems (in particular, on Unix and Windows, although the details are
    621 slightly different), :c:func:`Py_Initialize` calculates the module search path
    622 based upon its best guess for the location of the standard Python interpreter
    623 executable, assuming that the Python library is found in a fixed location
    624 relative to the Python interpreter executable.  In particular, it looks for a
    625 directory named :file:`lib/python{X.Y}` relative to the parent directory
    626 where the executable named :file:`python` is found on the shell command search
    627 path (the environment variable :envvar:`PATH`).
    628 
    629 For instance, if the Python executable is found in
    630 :file:`/usr/local/bin/python`, it will assume that the libraries are in
    631 :file:`/usr/local/lib/python{X.Y}`.  (In fact, this particular path is also
    632 the "fallback" location, used when no executable file named :file:`python` is
    633 found along :envvar:`PATH`.)  The user can override this behavior by setting the
    634 environment variable :envvar:`PYTHONHOME`, or insert additional directories in
    635 front of the standard path by setting :envvar:`PYTHONPATH`.
    636 
    637 .. index::
    638    single: Py_SetProgramName()
    639    single: Py_GetPath()
    640    single: Py_GetPrefix()
    641    single: Py_GetExecPrefix()
    642    single: Py_GetProgramFullPath()
    643 
    644 The embedding application can steer the search by calling
    645 ``Py_SetProgramName(file)`` *before* calling  :c:func:`Py_Initialize`.  Note that
    646 :envvar:`PYTHONHOME` still overrides this and :envvar:`PYTHONPATH` is still
    647 inserted in front of the standard path.  An application that requires total
    648 control has to provide its own implementation of :c:func:`Py_GetPath`,
    649 :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and
    650 :c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`).
    651 
    652 .. index:: single: Py_IsInitialized()
    653 
    654 Sometimes, it is desirable to "uninitialize" Python.  For instance,  the
    655 application may want to start over (make another call to
    656 :c:func:`Py_Initialize`) or the application is simply done with its  use of
    657 Python and wants to free memory allocated by Python.  This can be accomplished
    658 by calling :c:func:`Py_FinalizeEx`.  The function :c:func:`Py_IsInitialized` returns
    659 true if Python is currently in the initialized state.  More information about
    660 these functions is given in a later chapter. Notice that :c:func:`Py_FinalizeEx`
    661 does *not* free all memory allocated by the Python interpreter, e.g. memory
    662 allocated by extension modules currently cannot be released.
    663 
    664 
    665 .. _api-debugging:
    666 
    667 Debugging Builds
    668 ================
    669 
    670 Python can be built with several macros to enable extra checks of the
    671 interpreter and extension modules.  These checks tend to add a large amount of
    672 overhead to the runtime so they are not enabled by default.
    673 
    674 A full list of the various types of debugging builds is in the file
    675 :file:`Misc/SpecialBuilds.txt` in the Python source distribution. Builds are
    676 available that support tracing of reference counts, debugging the memory
    677 allocator, or low-level profiling of the main interpreter loop.  Only the most
    678 frequently-used builds will be described in the remainder of this section.
    679 
    680 Compiling the interpreter with the :c:macro:`Py_DEBUG` macro defined produces
    681 what is generally meant by "a debug build" of Python. :c:macro:`Py_DEBUG` is
    682 enabled in the Unix build by adding ``--with-pydebug`` to the
    683 :file:`./configure` command.  It is also implied by the presence of the
    684 not-Python-specific :c:macro:`_DEBUG` macro.  When :c:macro:`Py_DEBUG` is enabled
    685 in the Unix build, compiler optimization is disabled.
    686 
    687 In addition to the reference count debugging described below, the following
    688 extra checks are performed:
    689 
    690 * Extra checks are added to the object allocator.
    691 
    692 * Extra checks are added to the parser and compiler.
    693 
    694 * Downcasts from wide types to narrow types are checked for loss of information.
    695 
    696 * A number of assertions are added to the dictionary and set implementations.
    697   In addition, the set object acquires a :meth:`test_c_api` method.
    698 
    699 * Sanity checks of the input arguments are added to frame creation.
    700 
    701 * The storage for ints is initialized with a known invalid pattern to catch
    702   reference to uninitialized digits.
    703 
    704 * Low-level tracing and extra exception checking are added to the runtime
    705   virtual machine.
    706 
    707 * Extra checks are added to the memory arena implementation.
    708 
    709 * Extra debugging is added to the thread module.
    710 
    711 There may be additional checks not mentioned here.
    712 
    713 Defining :c:macro:`Py_TRACE_REFS` enables reference tracing.  When defined, a
    714 circular doubly linked list of active objects is maintained by adding two extra
    715 fields to every :c:type:`PyObject`.  Total allocations are tracked as well.  Upon
    716 exit, all existing references are printed.  (In interactive mode this happens
    717 after every statement run by the interpreter.)  Implied by :c:macro:`Py_DEBUG`.
    718 
    719 Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution
    720 for more detailed information.
    721 
    722