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