17db96d56Sopenharmony_ci.. highlight:: c
27db96d56Sopenharmony_ci
37db96d56Sopenharmony_ci
47db96d56Sopenharmony_ci.. _api-intro:
57db96d56Sopenharmony_ci
67db96d56Sopenharmony_ci************
77db96d56Sopenharmony_ciIntroduction
87db96d56Sopenharmony_ci************
97db96d56Sopenharmony_ci
107db96d56Sopenharmony_ciThe Application Programmer's Interface to Python gives C and C++ programmers
117db96d56Sopenharmony_ciaccess to the Python interpreter at a variety of levels.  The API is equally
127db96d56Sopenharmony_ciusable from C++, but for brevity it is generally referred to as the Python/C
137db96d56Sopenharmony_ciAPI.  There are two fundamentally different reasons for using the Python/C API.
147db96d56Sopenharmony_ciThe first reason is to write *extension modules* for specific purposes; these
157db96d56Sopenharmony_ciare C modules that extend the Python interpreter.  This is probably the most
167db96d56Sopenharmony_cicommon use.  The second reason is to use Python as a component in a larger
177db96d56Sopenharmony_ciapplication; this technique is generally referred to as :dfn:`embedding` Python
187db96d56Sopenharmony_ciin an application.
197db96d56Sopenharmony_ci
207db96d56Sopenharmony_ciWriting an extension module is a relatively well-understood process, where a
217db96d56Sopenharmony_ci"cookbook" approach works well.  There are several tools that automate the
227db96d56Sopenharmony_ciprocess to some extent.  While people have embedded Python in other
237db96d56Sopenharmony_ciapplications since its early existence, the process of embedding Python is
247db96d56Sopenharmony_ciless straightforward than writing an extension.
257db96d56Sopenharmony_ci
267db96d56Sopenharmony_ciMany API functions are useful independent of whether you're embedding  or
277db96d56Sopenharmony_ciextending Python; moreover, most applications that embed Python  will need to
287db96d56Sopenharmony_ciprovide a custom extension as well, so it's probably a  good idea to become
297db96d56Sopenharmony_cifamiliar with writing an extension before  attempting to embed Python in a real
307db96d56Sopenharmony_ciapplication.
317db96d56Sopenharmony_ci
327db96d56Sopenharmony_ci
337db96d56Sopenharmony_ciCoding standards
347db96d56Sopenharmony_ci================
357db96d56Sopenharmony_ci
367db96d56Sopenharmony_ciIf you're writing C code for inclusion in CPython, you **must** follow the
377db96d56Sopenharmony_ciguidelines and standards defined in :PEP:`7`.  These guidelines apply
387db96d56Sopenharmony_ciregardless of the version of Python you are contributing to.  Following these
397db96d56Sopenharmony_ciconventions is not necessary for your own third party extension modules,
407db96d56Sopenharmony_ciunless you eventually expect to contribute them to Python.
417db96d56Sopenharmony_ci
427db96d56Sopenharmony_ci
437db96d56Sopenharmony_ci.. _api-includes:
447db96d56Sopenharmony_ci
457db96d56Sopenharmony_ciInclude Files
467db96d56Sopenharmony_ci=============
477db96d56Sopenharmony_ci
487db96d56Sopenharmony_ciAll function, type and macro definitions needed to use the Python/C API are
497db96d56Sopenharmony_ciincluded in your code by the following line::
507db96d56Sopenharmony_ci
517db96d56Sopenharmony_ci   #define PY_SSIZE_T_CLEAN
527db96d56Sopenharmony_ci   #include <Python.h>
537db96d56Sopenharmony_ci
547db96d56Sopenharmony_ciThis implies inclusion of the following standard headers: ``<stdio.h>``,
557db96d56Sopenharmony_ci``<string.h>``, ``<errno.h>``, ``<limits.h>``, ``<assert.h>`` and ``<stdlib.h>``
567db96d56Sopenharmony_ci(if available).
577db96d56Sopenharmony_ci
587db96d56Sopenharmony_ci.. note::
597db96d56Sopenharmony_ci
607db96d56Sopenharmony_ci   Since Python may define some pre-processor definitions which affect the standard
617db96d56Sopenharmony_ci   headers on some systems, you *must* include :file:`Python.h` before any standard
627db96d56Sopenharmony_ci   headers are included.
637db96d56Sopenharmony_ci
647db96d56Sopenharmony_ci   It is recommended to always define ``PY_SSIZE_T_CLEAN`` before including
657db96d56Sopenharmony_ci   ``Python.h``.  See :ref:`arg-parsing` for a description of this macro.
667db96d56Sopenharmony_ci
677db96d56Sopenharmony_ciAll user visible names defined by Python.h (except those defined by the included
687db96d56Sopenharmony_cistandard headers) have one of the prefixes ``Py`` or ``_Py``.  Names beginning
697db96d56Sopenharmony_ciwith ``_Py`` are for internal use by the Python implementation and should not be
707db96d56Sopenharmony_ciused by extension writers. Structure member names do not have a reserved prefix.
717db96d56Sopenharmony_ci
727db96d56Sopenharmony_ci.. note::
737db96d56Sopenharmony_ci
747db96d56Sopenharmony_ci   User code should never define names that begin with ``Py`` or ``_Py``. This
757db96d56Sopenharmony_ci   confuses the reader, and jeopardizes the portability of the user code to
767db96d56Sopenharmony_ci   future Python versions, which may define additional names beginning with one
777db96d56Sopenharmony_ci   of these prefixes.
787db96d56Sopenharmony_ci
797db96d56Sopenharmony_ciThe header files are typically installed with Python.  On Unix, these  are
807db96d56Sopenharmony_cilocated in the directories :file:`{prefix}/include/pythonversion/` and
817db96d56Sopenharmony_ci:file:`{exec_prefix}/include/pythonversion/`, where :option:`prefix <--prefix>` and
827db96d56Sopenharmony_ci:option:`exec_prefix <--exec-prefix>` are defined by the corresponding parameters to Python's
837db96d56Sopenharmony_ci:program:`configure` script and *version* is
847db96d56Sopenharmony_ci``'%d.%d' % sys.version_info[:2]``.  On Windows, the headers are installed
857db96d56Sopenharmony_ciin :file:`{prefix}/include`, where ``prefix`` is the installation
867db96d56Sopenharmony_cidirectory specified to the installer.
877db96d56Sopenharmony_ci
887db96d56Sopenharmony_ciTo include the headers, place both directories (if different) on your compiler's
897db96d56Sopenharmony_cisearch path for includes.  Do *not* place the parent directories on the search
907db96d56Sopenharmony_cipath and then use ``#include <pythonX.Y/Python.h>``; this will break on
917db96d56Sopenharmony_cimulti-platform builds since the platform independent headers under
927db96d56Sopenharmony_ci:option:`prefix <--prefix>` include the platform specific headers from
937db96d56Sopenharmony_ci:option:`exec_prefix <--exec-prefix>`.
947db96d56Sopenharmony_ci
957db96d56Sopenharmony_ciC++ users should note that although the API is defined entirely using C, the
967db96d56Sopenharmony_ciheader files properly declare the entry points to be ``extern "C"``. As a result,
977db96d56Sopenharmony_cithere is no need to do anything special to use the API from C++.
987db96d56Sopenharmony_ci
997db96d56Sopenharmony_ci
1007db96d56Sopenharmony_ciUseful macros
1017db96d56Sopenharmony_ci=============
1027db96d56Sopenharmony_ci
1037db96d56Sopenharmony_ciSeveral useful macros are defined in the Python header files.  Many are
1047db96d56Sopenharmony_cidefined closer to where they are useful (e.g. :c:macro:`Py_RETURN_NONE`).
1057db96d56Sopenharmony_ciOthers of a more general utility are defined here.  This is not necessarily a
1067db96d56Sopenharmony_cicomplete listing.
1077db96d56Sopenharmony_ci
1087db96d56Sopenharmony_ci.. c:macro:: Py_ABS(x)
1097db96d56Sopenharmony_ci
1107db96d56Sopenharmony_ci   Return the absolute value of ``x``.
1117db96d56Sopenharmony_ci
1127db96d56Sopenharmony_ci   .. versionadded:: 3.3
1137db96d56Sopenharmony_ci
1147db96d56Sopenharmony_ci.. c:macro:: Py_ALWAYS_INLINE
1157db96d56Sopenharmony_ci
1167db96d56Sopenharmony_ci   Ask the compiler to always inline a static inline function. The compiler can
1177db96d56Sopenharmony_ci   ignore it and decides to not inline the function.
1187db96d56Sopenharmony_ci
1197db96d56Sopenharmony_ci   It can be used to inline performance critical static inline functions when
1207db96d56Sopenharmony_ci   building Python in debug mode with function inlining disabled. For example,
1217db96d56Sopenharmony_ci   MSC disables function inlining when building in debug mode.
1227db96d56Sopenharmony_ci
1237db96d56Sopenharmony_ci   Marking blindly a static inline function with Py_ALWAYS_INLINE can result in
1247db96d56Sopenharmony_ci   worse performances (due to increased code size for example). The compiler is
1257db96d56Sopenharmony_ci   usually smarter than the developer for the cost/benefit analysis.
1267db96d56Sopenharmony_ci
1277db96d56Sopenharmony_ci   If Python is :ref:`built in debug mode <debug-build>` (if the ``Py_DEBUG``
1287db96d56Sopenharmony_ci   macro is defined), the :c:macro:`Py_ALWAYS_INLINE` macro does nothing.
1297db96d56Sopenharmony_ci
1307db96d56Sopenharmony_ci   It must be specified before the function return type. Usage::
1317db96d56Sopenharmony_ci
1327db96d56Sopenharmony_ci       static inline Py_ALWAYS_INLINE int random(void) { return 4; }
1337db96d56Sopenharmony_ci
1347db96d56Sopenharmony_ci   .. versionadded:: 3.11
1357db96d56Sopenharmony_ci
1367db96d56Sopenharmony_ci.. c:macro:: Py_CHARMASK(c)
1377db96d56Sopenharmony_ci
1387db96d56Sopenharmony_ci   Argument must be a character or an integer in the range [-128, 127] or [0,
1397db96d56Sopenharmony_ci   255].  This macro returns ``c`` cast to an ``unsigned char``.
1407db96d56Sopenharmony_ci
1417db96d56Sopenharmony_ci.. c:macro:: Py_DEPRECATED(version)
1427db96d56Sopenharmony_ci
1437db96d56Sopenharmony_ci   Use this for deprecated declarations.  The macro must be placed before the
1447db96d56Sopenharmony_ci   symbol name.
1457db96d56Sopenharmony_ci
1467db96d56Sopenharmony_ci   Example::
1477db96d56Sopenharmony_ci
1487db96d56Sopenharmony_ci      Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
1497db96d56Sopenharmony_ci
1507db96d56Sopenharmony_ci   .. versionchanged:: 3.8
1517db96d56Sopenharmony_ci      MSVC support was added.
1527db96d56Sopenharmony_ci
1537db96d56Sopenharmony_ci.. c:macro:: Py_GETENV(s)
1547db96d56Sopenharmony_ci
1557db96d56Sopenharmony_ci   Like ``getenv(s)``, but returns ``NULL`` if :option:`-E` was passed on the
1567db96d56Sopenharmony_ci   command line (i.e. if ``Py_IgnoreEnvironmentFlag`` is set).
1577db96d56Sopenharmony_ci
1587db96d56Sopenharmony_ci.. c:macro:: Py_MAX(x, y)
1597db96d56Sopenharmony_ci
1607db96d56Sopenharmony_ci   Return the maximum value between ``x`` and ``y``.
1617db96d56Sopenharmony_ci
1627db96d56Sopenharmony_ci   .. versionadded:: 3.3
1637db96d56Sopenharmony_ci
1647db96d56Sopenharmony_ci.. c:macro:: Py_MEMBER_SIZE(type, member)
1657db96d56Sopenharmony_ci
1667db96d56Sopenharmony_ci   Return the size of a structure (``type``) ``member`` in bytes.
1677db96d56Sopenharmony_ci
1687db96d56Sopenharmony_ci   .. versionadded:: 3.6
1697db96d56Sopenharmony_ci
1707db96d56Sopenharmony_ci.. c:macro:: Py_MIN(x, y)
1717db96d56Sopenharmony_ci
1727db96d56Sopenharmony_ci   Return the minimum value between ``x`` and ``y``.
1737db96d56Sopenharmony_ci
1747db96d56Sopenharmony_ci   .. versionadded:: 3.3
1757db96d56Sopenharmony_ci
1767db96d56Sopenharmony_ci.. c:macro:: Py_NO_INLINE
1777db96d56Sopenharmony_ci
1787db96d56Sopenharmony_ci   Disable inlining on a function. For example, it reduces the C stack
1797db96d56Sopenharmony_ci   consumption: useful on LTO+PGO builds which heavily inline code (see
1807db96d56Sopenharmony_ci   :issue:`33720`).
1817db96d56Sopenharmony_ci
1827db96d56Sopenharmony_ci   Usage::
1837db96d56Sopenharmony_ci
1847db96d56Sopenharmony_ci       Py_NO_INLINE static int random(void) { return 4; }
1857db96d56Sopenharmony_ci
1867db96d56Sopenharmony_ci   .. versionadded:: 3.11
1877db96d56Sopenharmony_ci
1887db96d56Sopenharmony_ci.. c:macro:: Py_STRINGIFY(x)
1897db96d56Sopenharmony_ci
1907db96d56Sopenharmony_ci   Convert ``x`` to a C string.  E.g. ``Py_STRINGIFY(123)`` returns
1917db96d56Sopenharmony_ci   ``"123"``.
1927db96d56Sopenharmony_ci
1937db96d56Sopenharmony_ci   .. versionadded:: 3.4
1947db96d56Sopenharmony_ci
1957db96d56Sopenharmony_ci.. c:macro:: Py_UNREACHABLE()
1967db96d56Sopenharmony_ci
1977db96d56Sopenharmony_ci   Use this when you have a code path that cannot be reached by design.
1987db96d56Sopenharmony_ci   For example, in the ``default:`` clause in a ``switch`` statement for which
1997db96d56Sopenharmony_ci   all possible values are covered in ``case`` statements.  Use this in places
2007db96d56Sopenharmony_ci   where you might be tempted to put an ``assert(0)`` or ``abort()`` call.
2017db96d56Sopenharmony_ci
2027db96d56Sopenharmony_ci   In release mode, the macro helps the compiler to optimize the code, and
2037db96d56Sopenharmony_ci   avoids a warning about unreachable code.  For example, the macro is
2047db96d56Sopenharmony_ci   implemented with ``__builtin_unreachable()`` on GCC in release mode.
2057db96d56Sopenharmony_ci
2067db96d56Sopenharmony_ci   A use for ``Py_UNREACHABLE()`` is following a call a function that
2077db96d56Sopenharmony_ci   never returns but that is not declared :c:macro:`_Py_NO_RETURN`.
2087db96d56Sopenharmony_ci
2097db96d56Sopenharmony_ci   If a code path is very unlikely code but can be reached under exceptional
2107db96d56Sopenharmony_ci   case, this macro must not be used.  For example, under low memory condition
2117db96d56Sopenharmony_ci   or if a system call returns a value out of the expected range.  In this
2127db96d56Sopenharmony_ci   case, it's better to report the error to the caller.  If the error cannot
2137db96d56Sopenharmony_ci   be reported to caller, :c:func:`Py_FatalError` can be used.
2147db96d56Sopenharmony_ci
2157db96d56Sopenharmony_ci   .. versionadded:: 3.7
2167db96d56Sopenharmony_ci
2177db96d56Sopenharmony_ci.. c:macro:: Py_UNUSED(arg)
2187db96d56Sopenharmony_ci
2197db96d56Sopenharmony_ci   Use this for unused arguments in a function definition to silence compiler
2207db96d56Sopenharmony_ci   warnings. Example: ``int func(int a, int Py_UNUSED(b)) { return a; }``.
2217db96d56Sopenharmony_ci
2227db96d56Sopenharmony_ci   .. versionadded:: 3.4
2237db96d56Sopenharmony_ci
2247db96d56Sopenharmony_ci.. c:macro:: PyDoc_STRVAR(name, str)
2257db96d56Sopenharmony_ci
2267db96d56Sopenharmony_ci   Creates a variable with name ``name`` that can be used in docstrings.
2277db96d56Sopenharmony_ci   If Python is built without docstrings, the value will be empty.
2287db96d56Sopenharmony_ci
2297db96d56Sopenharmony_ci   Use :c:macro:`PyDoc_STRVAR` for docstrings to support building
2307db96d56Sopenharmony_ci   Python without docstrings, as specified in :pep:`7`.
2317db96d56Sopenharmony_ci
2327db96d56Sopenharmony_ci   Example::
2337db96d56Sopenharmony_ci
2347db96d56Sopenharmony_ci      PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
2357db96d56Sopenharmony_ci
2367db96d56Sopenharmony_ci      static PyMethodDef deque_methods[] = {
2377db96d56Sopenharmony_ci          // ...
2387db96d56Sopenharmony_ci          {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
2397db96d56Sopenharmony_ci          // ...
2407db96d56Sopenharmony_ci      }
2417db96d56Sopenharmony_ci
2427db96d56Sopenharmony_ci.. c:macro:: PyDoc_STR(str)
2437db96d56Sopenharmony_ci
2447db96d56Sopenharmony_ci   Creates a docstring for the given input string or an empty string
2457db96d56Sopenharmony_ci   if docstrings are disabled.
2467db96d56Sopenharmony_ci
2477db96d56Sopenharmony_ci   Use :c:macro:`PyDoc_STR` in specifying docstrings to support
2487db96d56Sopenharmony_ci   building Python without docstrings, as specified in :pep:`7`.
2497db96d56Sopenharmony_ci
2507db96d56Sopenharmony_ci   Example::
2517db96d56Sopenharmony_ci
2527db96d56Sopenharmony_ci      static PyMethodDef pysqlite_row_methods[] = {
2537db96d56Sopenharmony_ci          {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
2547db96d56Sopenharmony_ci              PyDoc_STR("Returns the keys of the row.")},
2557db96d56Sopenharmony_ci          {NULL, NULL}
2567db96d56Sopenharmony_ci      };
2577db96d56Sopenharmony_ci
2587db96d56Sopenharmony_ci
2597db96d56Sopenharmony_ci.. _api-objects:
2607db96d56Sopenharmony_ci
2617db96d56Sopenharmony_ciObjects, Types and Reference Counts
2627db96d56Sopenharmony_ci===================================
2637db96d56Sopenharmony_ci
2647db96d56Sopenharmony_ci.. index:: pair: object; type
2657db96d56Sopenharmony_ci
2667db96d56Sopenharmony_ciMost Python/C API functions have one or more arguments as well as a return value
2677db96d56Sopenharmony_ciof type :c:expr:`PyObject*`.  This type is a pointer to an opaque data type
2687db96d56Sopenharmony_cirepresenting an arbitrary Python object.  Since all Python object types are
2697db96d56Sopenharmony_citreated the same way by the Python language in most situations (e.g.,
2707db96d56Sopenharmony_ciassignments, scope rules, and argument passing), it is only fitting that they
2717db96d56Sopenharmony_cishould be represented by a single C type.  Almost all Python objects live on the
2727db96d56Sopenharmony_ciheap: you never declare an automatic or static variable of type
2737db96d56Sopenharmony_ci:c:type:`PyObject`, only pointer variables of type :c:expr:`PyObject*` can  be
2747db96d56Sopenharmony_cideclared.  The sole exception are the type objects; since these must never be
2757db96d56Sopenharmony_cideallocated, they are typically static :c:type:`PyTypeObject` objects.
2767db96d56Sopenharmony_ci
2777db96d56Sopenharmony_ciAll Python objects (even Python integers) have a :dfn:`type` and a
2787db96d56Sopenharmony_ci:dfn:`reference count`.  An object's type determines what kind of object it is
2797db96d56Sopenharmony_ci(e.g., an integer, a list, or a user-defined function; there are many more as
2807db96d56Sopenharmony_ciexplained in :ref:`types`).  For each of the well-known types there is a macro
2817db96d56Sopenharmony_cito check whether an object is of that type; for instance, ``PyList_Check(a)`` is
2827db96d56Sopenharmony_citrue if (and only if) the object pointed to by *a* is a Python list.
2837db96d56Sopenharmony_ci
2847db96d56Sopenharmony_ci
2857db96d56Sopenharmony_ci.. _api-refcounts:
2867db96d56Sopenharmony_ci
2877db96d56Sopenharmony_ciReference Counts
2887db96d56Sopenharmony_ci----------------
2897db96d56Sopenharmony_ci
2907db96d56Sopenharmony_ciThe reference count is important because today's computers have a  finite (and
2917db96d56Sopenharmony_cioften severely limited) memory size; it counts how many  different places there
2927db96d56Sopenharmony_ciare that have a reference to an object.  Such a  place could be another object,
2937db96d56Sopenharmony_cior a global (or static) C variable, or  a local variable in some C function.
2947db96d56Sopenharmony_ciWhen an object's reference count  becomes zero, the object is deallocated.  If
2957db96d56Sopenharmony_ciit contains references to  other objects, their reference count is decremented.
2967db96d56Sopenharmony_ciThose other  objects may be deallocated in turn, if this decrement makes their
2977db96d56Sopenharmony_cireference count become zero, and so on.  (There's an obvious problem  with
2987db96d56Sopenharmony_ciobjects that reference each other here; for now, the solution is  "don't do
2997db96d56Sopenharmony_cithat.")
3007db96d56Sopenharmony_ci
3017db96d56Sopenharmony_ci.. index::
3027db96d56Sopenharmony_ci   single: Py_INCREF()
3037db96d56Sopenharmony_ci   single: Py_DECREF()
3047db96d56Sopenharmony_ci
3057db96d56Sopenharmony_ciReference counts are always manipulated explicitly.  The normal way is  to use
3067db96d56Sopenharmony_cithe macro :c:func:`Py_INCREF` to increment an object's reference count by one,
3077db96d56Sopenharmony_ciand :c:func:`Py_DECREF` to decrement it by   one.  The :c:func:`Py_DECREF` macro
3087db96d56Sopenharmony_ciis considerably more complex than the incref one, since it must check whether
3097db96d56Sopenharmony_cithe reference count becomes zero and then cause the object's deallocator to be
3107db96d56Sopenharmony_cicalled. The deallocator is a function pointer contained in the object's type
3117db96d56Sopenharmony_cistructure.  The type-specific deallocator takes care of decrementing the
3127db96d56Sopenharmony_cireference counts for other objects contained in the object if this is a compound
3137db96d56Sopenharmony_ciobject type, such as a list, as well as performing any additional finalization
3147db96d56Sopenharmony_cithat's needed.  There's no chance that the reference count can overflow; at
3157db96d56Sopenharmony_cileast as many bits are used to hold the reference count as there are distinct
3167db96d56Sopenharmony_cimemory locations in virtual memory (assuming ``sizeof(Py_ssize_t) >= sizeof(void*)``).
3177db96d56Sopenharmony_ciThus, the reference count increment is a simple operation.
3187db96d56Sopenharmony_ci
3197db96d56Sopenharmony_ciIt is not necessary to increment an object's reference count for every  local
3207db96d56Sopenharmony_civariable that contains a pointer to an object.  In theory, the  object's
3217db96d56Sopenharmony_cireference count goes up by one when the variable is made to  point to it and it
3227db96d56Sopenharmony_cigoes down by one when the variable goes out of  scope.  However, these two
3237db96d56Sopenharmony_cicancel each other out, so at the end the  reference count hasn't changed.  The
3247db96d56Sopenharmony_cionly real reason to use the  reference count is to prevent the object from being
3257db96d56Sopenharmony_cideallocated as  long as our variable is pointing to it.  If we know that there
3267db96d56Sopenharmony_ciis at  least one other reference to the object that lives at least as long as
3277db96d56Sopenharmony_ciour variable, there is no need to increment the reference count  temporarily.
3287db96d56Sopenharmony_ciAn important situation where this arises is in objects  that are passed as
3297db96d56Sopenharmony_ciarguments to C functions in an extension module  that are called from Python;
3307db96d56Sopenharmony_cithe call mechanism guarantees to hold a  reference to every argument for the
3317db96d56Sopenharmony_ciduration of the call.
3327db96d56Sopenharmony_ci
3337db96d56Sopenharmony_ciHowever, a common pitfall is to extract an object from a list and hold on to it
3347db96d56Sopenharmony_cifor a while without incrementing its reference count. Some other operation might
3357db96d56Sopenharmony_ciconceivably remove the object from the list, decrementing its reference count
3367db96d56Sopenharmony_ciand possibly deallocating it. The real danger is that innocent-looking
3377db96d56Sopenharmony_cioperations may invoke arbitrary Python code which could do this; there is a code
3387db96d56Sopenharmony_cipath which allows control to flow back to the user from a :c:func:`Py_DECREF`, so
3397db96d56Sopenharmony_cialmost any operation is potentially dangerous.
3407db96d56Sopenharmony_ci
3417db96d56Sopenharmony_ciA safe approach is to always use the generic operations (functions  whose name
3427db96d56Sopenharmony_cibegins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``).
3437db96d56Sopenharmony_ciThese operations always increment the reference count of the object they return.
3447db96d56Sopenharmony_ciThis leaves the caller with the responsibility to call :c:func:`Py_DECREF` when
3457db96d56Sopenharmony_cithey are done with the result; this soon becomes second nature.
3467db96d56Sopenharmony_ci
3477db96d56Sopenharmony_ci
3487db96d56Sopenharmony_ci.. _api-refcountdetails:
3497db96d56Sopenharmony_ci
3507db96d56Sopenharmony_ciReference Count Details
3517db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^
3527db96d56Sopenharmony_ci
3537db96d56Sopenharmony_ciThe reference count behavior of functions in the Python/C API is best  explained
3547db96d56Sopenharmony_ciin terms of *ownership of references*.  Ownership pertains to references, never
3557db96d56Sopenharmony_cito objects (objects are not owned: they are always shared).  "Owning a
3567db96d56Sopenharmony_cireference" means being responsible for calling Py_DECREF on it when the
3577db96d56Sopenharmony_cireference is no longer needed.  Ownership can also be transferred, meaning that
3587db96d56Sopenharmony_cithe code that receives ownership of the reference then becomes responsible for
3597db96d56Sopenharmony_cieventually decref'ing it by calling :c:func:`Py_DECREF` or :c:func:`Py_XDECREF`
3607db96d56Sopenharmony_ciwhen it's no longer needed---or passing on this responsibility (usually to its
3617db96d56Sopenharmony_cicaller). When a function passes ownership of a reference on to its caller, the
3627db96d56Sopenharmony_cicaller is said to receive a *new* reference.  When no ownership is transferred,
3637db96d56Sopenharmony_cithe caller is said to *borrow* the reference. Nothing needs to be done for a
3647db96d56Sopenharmony_ci:term:`borrowed reference`.
3657db96d56Sopenharmony_ci
3667db96d56Sopenharmony_ciConversely, when a calling function passes in a reference to an  object, there
3677db96d56Sopenharmony_ciare two possibilities: the function *steals* a  reference to the object, or it
3687db96d56Sopenharmony_cidoes not.  *Stealing a reference* means that when you pass a reference to a
3697db96d56Sopenharmony_cifunction, that function assumes that it now owns that reference, and you are not
3707db96d56Sopenharmony_ciresponsible for it any longer.
3717db96d56Sopenharmony_ci
3727db96d56Sopenharmony_ci.. index::
3737db96d56Sopenharmony_ci   single: PyList_SetItem()
3747db96d56Sopenharmony_ci   single: PyTuple_SetItem()
3757db96d56Sopenharmony_ci
3767db96d56Sopenharmony_ciFew functions steal references; the two notable exceptions are
3777db96d56Sopenharmony_ci:c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which  steal a reference
3787db96d56Sopenharmony_cito the item (but not to the tuple or list into which the item is put!).  These
3797db96d56Sopenharmony_cifunctions were designed to steal a reference because of a common idiom for
3807db96d56Sopenharmony_cipopulating a tuple or list with newly created objects; for example, the code to
3817db96d56Sopenharmony_cicreate the tuple ``(1, 2, "three")`` could look like this (forgetting about
3827db96d56Sopenharmony_cierror handling for the moment; a better way to code this is shown below)::
3837db96d56Sopenharmony_ci
3847db96d56Sopenharmony_ci   PyObject *t;
3857db96d56Sopenharmony_ci
3867db96d56Sopenharmony_ci   t = PyTuple_New(3);
3877db96d56Sopenharmony_ci   PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
3887db96d56Sopenharmony_ci   PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
3897db96d56Sopenharmony_ci   PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));
3907db96d56Sopenharmony_ci
3917db96d56Sopenharmony_ciHere, :c:func:`PyLong_FromLong` returns a new reference which is immediately
3927db96d56Sopenharmony_cistolen by :c:func:`PyTuple_SetItem`.  When you want to keep using an object
3937db96d56Sopenharmony_cialthough the reference to it will be stolen, use :c:func:`Py_INCREF` to grab
3947db96d56Sopenharmony_cianother reference before calling the reference-stealing function.
3957db96d56Sopenharmony_ci
3967db96d56Sopenharmony_ciIncidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple items;
3977db96d56Sopenharmony_ci:c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to do this
3987db96d56Sopenharmony_cisince tuples are an immutable data type.  You should only use
3997db96d56Sopenharmony_ci:c:func:`PyTuple_SetItem` for tuples that you are creating yourself.
4007db96d56Sopenharmony_ci
4017db96d56Sopenharmony_ciEquivalent code for populating a list can be written using :c:func:`PyList_New`
4027db96d56Sopenharmony_ciand :c:func:`PyList_SetItem`.
4037db96d56Sopenharmony_ci
4047db96d56Sopenharmony_ciHowever, in practice, you will rarely use these ways of creating and populating
4057db96d56Sopenharmony_cia tuple or list.  There's a generic function, :c:func:`Py_BuildValue`, that can
4067db96d56Sopenharmony_cicreate most common objects from C values, directed by a :dfn:`format string`.
4077db96d56Sopenharmony_ciFor example, the above two blocks of code could be replaced by the following
4087db96d56Sopenharmony_ci(which also takes care of the error checking)::
4097db96d56Sopenharmony_ci
4107db96d56Sopenharmony_ci   PyObject *tuple, *list;
4117db96d56Sopenharmony_ci
4127db96d56Sopenharmony_ci   tuple = Py_BuildValue("(iis)", 1, 2, "three");
4137db96d56Sopenharmony_ci   list = Py_BuildValue("[iis]", 1, 2, "three");
4147db96d56Sopenharmony_ci
4157db96d56Sopenharmony_ciIt is much more common to use :c:func:`PyObject_SetItem` and friends with items
4167db96d56Sopenharmony_ciwhose references you are only borrowing, like arguments that were passed in to
4177db96d56Sopenharmony_cithe function you are writing.  In that case, their behaviour regarding reference
4187db96d56Sopenharmony_cicounts is much saner, since you don't have to increment a reference count so you
4197db96d56Sopenharmony_cican give a reference away ("have it be stolen").  For example, this function
4207db96d56Sopenharmony_cisets all items of a list (actually, any mutable sequence) to a given item::
4217db96d56Sopenharmony_ci
4227db96d56Sopenharmony_ci   int
4237db96d56Sopenharmony_ci   set_all(PyObject *target, PyObject *item)
4247db96d56Sopenharmony_ci   {
4257db96d56Sopenharmony_ci       Py_ssize_t i, n;
4267db96d56Sopenharmony_ci
4277db96d56Sopenharmony_ci       n = PyObject_Length(target);
4287db96d56Sopenharmony_ci       if (n < 0)
4297db96d56Sopenharmony_ci           return -1;
4307db96d56Sopenharmony_ci       for (i = 0; i < n; i++) {
4317db96d56Sopenharmony_ci           PyObject *index = PyLong_FromSsize_t(i);
4327db96d56Sopenharmony_ci           if (!index)
4337db96d56Sopenharmony_ci               return -1;
4347db96d56Sopenharmony_ci           if (PyObject_SetItem(target, index, item) < 0) {
4357db96d56Sopenharmony_ci               Py_DECREF(index);
4367db96d56Sopenharmony_ci               return -1;
4377db96d56Sopenharmony_ci           }
4387db96d56Sopenharmony_ci           Py_DECREF(index);
4397db96d56Sopenharmony_ci       }
4407db96d56Sopenharmony_ci       return 0;
4417db96d56Sopenharmony_ci   }
4427db96d56Sopenharmony_ci
4437db96d56Sopenharmony_ci.. index:: single: set_all()
4447db96d56Sopenharmony_ci
4457db96d56Sopenharmony_ciThe situation is slightly different for function return values.   While passing
4467db96d56Sopenharmony_cia reference to most functions does not change your  ownership responsibilities
4477db96d56Sopenharmony_cifor that reference, many functions that  return a reference to an object give
4487db96d56Sopenharmony_ciyou ownership of the reference. The reason is simple: in many cases, the
4497db96d56Sopenharmony_cireturned object is created  on the fly, and the reference you get is the only
4507db96d56Sopenharmony_cireference to the  object.  Therefore, the generic functions that return object
4517db96d56Sopenharmony_cireferences, like :c:func:`PyObject_GetItem` and  :c:func:`PySequence_GetItem`,
4527db96d56Sopenharmony_cialways return a new reference (the caller becomes the owner of the reference).
4537db96d56Sopenharmony_ci
4547db96d56Sopenharmony_ciIt is important to realize that whether you own a reference returned  by a
4557db96d56Sopenharmony_cifunction depends on which function you call only --- *the plumage* (the type of
4567db96d56Sopenharmony_cithe object passed as an argument to the function) *doesn't enter into it!*
4577db96d56Sopenharmony_ciThus, if you  extract an item from a list using :c:func:`PyList_GetItem`, you
4587db96d56Sopenharmony_cidon't own the reference --- but if you obtain the same item from the same list
4597db96d56Sopenharmony_ciusing :c:func:`PySequence_GetItem` (which happens to take exactly the same
4607db96d56Sopenharmony_ciarguments), you do own a reference to the returned object.
4617db96d56Sopenharmony_ci
4627db96d56Sopenharmony_ci.. index::
4637db96d56Sopenharmony_ci   single: PyList_GetItem()
4647db96d56Sopenharmony_ci   single: PySequence_GetItem()
4657db96d56Sopenharmony_ci
4667db96d56Sopenharmony_ciHere is an example of how you could write a function that computes the sum of
4677db96d56Sopenharmony_cithe items in a list of integers; once using  :c:func:`PyList_GetItem`, and once
4687db96d56Sopenharmony_ciusing :c:func:`PySequence_GetItem`. ::
4697db96d56Sopenharmony_ci
4707db96d56Sopenharmony_ci   long
4717db96d56Sopenharmony_ci   sum_list(PyObject *list)
4727db96d56Sopenharmony_ci   {
4737db96d56Sopenharmony_ci       Py_ssize_t i, n;
4747db96d56Sopenharmony_ci       long total = 0, value;
4757db96d56Sopenharmony_ci       PyObject *item;
4767db96d56Sopenharmony_ci
4777db96d56Sopenharmony_ci       n = PyList_Size(list);
4787db96d56Sopenharmony_ci       if (n < 0)
4797db96d56Sopenharmony_ci           return -1; /* Not a list */
4807db96d56Sopenharmony_ci       for (i = 0; i < n; i++) {
4817db96d56Sopenharmony_ci           item = PyList_GetItem(list, i); /* Can't fail */
4827db96d56Sopenharmony_ci           if (!PyLong_Check(item)) continue; /* Skip non-integers */
4837db96d56Sopenharmony_ci           value = PyLong_AsLong(item);
4847db96d56Sopenharmony_ci           if (value == -1 && PyErr_Occurred())
4857db96d56Sopenharmony_ci               /* Integer too big to fit in a C long, bail out */
4867db96d56Sopenharmony_ci               return -1;
4877db96d56Sopenharmony_ci           total += value;
4887db96d56Sopenharmony_ci       }
4897db96d56Sopenharmony_ci       return total;
4907db96d56Sopenharmony_ci   }
4917db96d56Sopenharmony_ci
4927db96d56Sopenharmony_ci.. index:: single: sum_list()
4937db96d56Sopenharmony_ci
4947db96d56Sopenharmony_ci::
4957db96d56Sopenharmony_ci
4967db96d56Sopenharmony_ci   long
4977db96d56Sopenharmony_ci   sum_sequence(PyObject *sequence)
4987db96d56Sopenharmony_ci   {
4997db96d56Sopenharmony_ci       Py_ssize_t i, n;
5007db96d56Sopenharmony_ci       long total = 0, value;
5017db96d56Sopenharmony_ci       PyObject *item;
5027db96d56Sopenharmony_ci       n = PySequence_Length(sequence);
5037db96d56Sopenharmony_ci       if (n < 0)
5047db96d56Sopenharmony_ci           return -1; /* Has no length */
5057db96d56Sopenharmony_ci       for (i = 0; i < n; i++) {
5067db96d56Sopenharmony_ci           item = PySequence_GetItem(sequence, i);
5077db96d56Sopenharmony_ci           if (item == NULL)
5087db96d56Sopenharmony_ci               return -1; /* Not a sequence, or other failure */
5097db96d56Sopenharmony_ci           if (PyLong_Check(item)) {
5107db96d56Sopenharmony_ci               value = PyLong_AsLong(item);
5117db96d56Sopenharmony_ci               Py_DECREF(item);
5127db96d56Sopenharmony_ci               if (value == -1 && PyErr_Occurred())
5137db96d56Sopenharmony_ci                   /* Integer too big to fit in a C long, bail out */
5147db96d56Sopenharmony_ci                   return -1;
5157db96d56Sopenharmony_ci               total += value;
5167db96d56Sopenharmony_ci           }
5177db96d56Sopenharmony_ci           else {
5187db96d56Sopenharmony_ci               Py_DECREF(item); /* Discard reference ownership */
5197db96d56Sopenharmony_ci           }
5207db96d56Sopenharmony_ci       }
5217db96d56Sopenharmony_ci       return total;
5227db96d56Sopenharmony_ci   }
5237db96d56Sopenharmony_ci
5247db96d56Sopenharmony_ci.. index:: single: sum_sequence()
5257db96d56Sopenharmony_ci
5267db96d56Sopenharmony_ci
5277db96d56Sopenharmony_ci.. _api-types:
5287db96d56Sopenharmony_ci
5297db96d56Sopenharmony_ciTypes
5307db96d56Sopenharmony_ci-----
5317db96d56Sopenharmony_ci
5327db96d56Sopenharmony_ciThere are few other data types that play a significant role in  the Python/C
5337db96d56Sopenharmony_ciAPI; most are simple C types such as :c:expr:`int`,  :c:expr:`long`,
5347db96d56Sopenharmony_ci:c:expr:`double` and :c:expr:`char*`.  A few structure types  are used to
5357db96d56Sopenharmony_cidescribe static tables used to list the functions exported  by a module or the
5367db96d56Sopenharmony_cidata attributes of a new object type, and another is used to describe the value
5377db96d56Sopenharmony_ciof a complex number.  These will  be discussed together with the functions that
5387db96d56Sopenharmony_ciuse them.
5397db96d56Sopenharmony_ci
5407db96d56Sopenharmony_ci.. c:type:: Py_ssize_t
5417db96d56Sopenharmony_ci
5427db96d56Sopenharmony_ci   A signed integral type such that ``sizeof(Py_ssize_t) == sizeof(size_t)``.
5437db96d56Sopenharmony_ci   C99 doesn't define such a thing directly (size_t is an unsigned integral type).
5447db96d56Sopenharmony_ci   See :pep:`353` for details. ``PY_SSIZE_T_MAX`` is the largest positive value
5457db96d56Sopenharmony_ci   of type :c:type:`Py_ssize_t`.
5467db96d56Sopenharmony_ci
5477db96d56Sopenharmony_ci
5487db96d56Sopenharmony_ci.. _api-exceptions:
5497db96d56Sopenharmony_ci
5507db96d56Sopenharmony_ciExceptions
5517db96d56Sopenharmony_ci==========
5527db96d56Sopenharmony_ci
5537db96d56Sopenharmony_ciThe Python programmer only needs to deal with exceptions if specific  error
5547db96d56Sopenharmony_cihandling is required; unhandled exceptions are automatically  propagated to the
5557db96d56Sopenharmony_cicaller, then to the caller's caller, and so on, until they reach the top-level
5567db96d56Sopenharmony_ciinterpreter, where they are reported to the  user accompanied by a stack
5577db96d56Sopenharmony_citraceback.
5587db96d56Sopenharmony_ci
5597db96d56Sopenharmony_ci.. index:: single: PyErr_Occurred()
5607db96d56Sopenharmony_ci
5617db96d56Sopenharmony_ciFor C programmers, however, error checking always has to be explicit.  All
5627db96d56Sopenharmony_cifunctions in the Python/C API can raise exceptions, unless an explicit claim is
5637db96d56Sopenharmony_cimade otherwise in a function's documentation.  In general, when a function
5647db96d56Sopenharmony_ciencounters an error, it sets an exception, discards any object references that
5657db96d56Sopenharmony_ciit owns, and returns an error indicator.  If not documented otherwise, this
5667db96d56Sopenharmony_ciindicator is either ``NULL`` or ``-1``, depending on the function's return type.
5677db96d56Sopenharmony_ciA few functions return a Boolean true/false result, with false indicating an
5687db96d56Sopenharmony_cierror.  Very few functions return no explicit error indicator or have an
5697db96d56Sopenharmony_ciambiguous return value, and require explicit testing for errors with
5707db96d56Sopenharmony_ci:c:func:`PyErr_Occurred`.  These exceptions are always explicitly documented.
5717db96d56Sopenharmony_ci
5727db96d56Sopenharmony_ci.. index::
5737db96d56Sopenharmony_ci   single: PyErr_SetString()
5747db96d56Sopenharmony_ci   single: PyErr_Clear()
5757db96d56Sopenharmony_ci
5767db96d56Sopenharmony_ciException state is maintained in per-thread storage (this is  equivalent to
5777db96d56Sopenharmony_ciusing global storage in an unthreaded application).  A  thread can be in one of
5787db96d56Sopenharmony_citwo states: an exception has occurred, or not. The function
5797db96d56Sopenharmony_ci:c:func:`PyErr_Occurred` can be used to check for this: it returns a borrowed
5807db96d56Sopenharmony_cireference to the exception type object when an exception has occurred, and
5817db96d56Sopenharmony_ci``NULL`` otherwise.  There are a number of functions to set the exception state:
5827db96d56Sopenharmony_ci:c:func:`PyErr_SetString` is the most common (though not the most general)
5837db96d56Sopenharmony_cifunction to set the exception state, and :c:func:`PyErr_Clear` clears the
5847db96d56Sopenharmony_ciexception state.
5857db96d56Sopenharmony_ci
5867db96d56Sopenharmony_ciThe full exception state consists of three objects (all of which can  be
5877db96d56Sopenharmony_ci``NULL``): the exception type, the corresponding exception  value, and the
5887db96d56Sopenharmony_citraceback.  These have the same meanings as the Python result of
5897db96d56Sopenharmony_ci``sys.exc_info()``; however, they are not the same: the Python objects represent
5907db96d56Sopenharmony_cithe last exception being handled by a Python  :keyword:`try` ...
5917db96d56Sopenharmony_ci:keyword:`except` statement, while the C level exception state only exists while
5927db96d56Sopenharmony_cian exception is being passed on between C functions until it reaches the Python
5937db96d56Sopenharmony_cibytecode interpreter's  main loop, which takes care of transferring it to
5947db96d56Sopenharmony_ci``sys.exc_info()`` and friends.
5957db96d56Sopenharmony_ci
5967db96d56Sopenharmony_ci.. index:: single: exc_info() (in module sys)
5977db96d56Sopenharmony_ci
5987db96d56Sopenharmony_ciNote that starting with Python 1.5, the preferred, thread-safe way to access the
5997db96d56Sopenharmony_ciexception state from Python code is to call the function :func:`sys.exc_info`,
6007db96d56Sopenharmony_ciwhich returns the per-thread exception state for Python code.  Also, the
6017db96d56Sopenharmony_cisemantics of both ways to access the exception state have changed so that a
6027db96d56Sopenharmony_cifunction which catches an exception will save and restore its thread's exception
6037db96d56Sopenharmony_cistate so as to preserve the exception state of its caller.  This prevents common
6047db96d56Sopenharmony_cibugs in exception handling code caused by an innocent-looking function
6057db96d56Sopenharmony_cioverwriting the exception being handled; it also reduces the often unwanted
6067db96d56Sopenharmony_cilifetime extension for objects that are referenced by the stack frames in the
6077db96d56Sopenharmony_citraceback.
6087db96d56Sopenharmony_ci
6097db96d56Sopenharmony_ciAs a general principle, a function that calls another function to  perform some
6107db96d56Sopenharmony_citask should check whether the called function raised an  exception, and if so,
6117db96d56Sopenharmony_cipass the exception state on to its caller.  It  should discard any object
6127db96d56Sopenharmony_cireferences that it owns, and return an  error indicator, but it should *not* set
6137db96d56Sopenharmony_cianother exception --- that would overwrite the exception that was just raised,
6147db96d56Sopenharmony_ciand lose important information about the exact cause of the error.
6157db96d56Sopenharmony_ci
6167db96d56Sopenharmony_ci.. index:: single: sum_sequence()
6177db96d56Sopenharmony_ci
6187db96d56Sopenharmony_ciA simple example of detecting exceptions and passing them on is shown in the
6197db96d56Sopenharmony_ci:c:func:`sum_sequence` example above.  It so happens that this example doesn't
6207db96d56Sopenharmony_cineed to clean up any owned references when it detects an error.  The following
6217db96d56Sopenharmony_ciexample function shows some error cleanup.  First, to remind you why you like
6227db96d56Sopenharmony_ciPython, we show the equivalent Python code::
6237db96d56Sopenharmony_ci
6247db96d56Sopenharmony_ci   def incr_item(dict, key):
6257db96d56Sopenharmony_ci       try:
6267db96d56Sopenharmony_ci           item = dict[key]
6277db96d56Sopenharmony_ci       except KeyError:
6287db96d56Sopenharmony_ci           item = 0
6297db96d56Sopenharmony_ci       dict[key] = item + 1
6307db96d56Sopenharmony_ci
6317db96d56Sopenharmony_ci.. index:: single: incr_item()
6327db96d56Sopenharmony_ci
6337db96d56Sopenharmony_ciHere is the corresponding C code, in all its glory::
6347db96d56Sopenharmony_ci
6357db96d56Sopenharmony_ci   int
6367db96d56Sopenharmony_ci   incr_item(PyObject *dict, PyObject *key)
6377db96d56Sopenharmony_ci   {
6387db96d56Sopenharmony_ci       /* Objects all initialized to NULL for Py_XDECREF */
6397db96d56Sopenharmony_ci       PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
6407db96d56Sopenharmony_ci       int rv = -1; /* Return value initialized to -1 (failure) */
6417db96d56Sopenharmony_ci
6427db96d56Sopenharmony_ci       item = PyObject_GetItem(dict, key);
6437db96d56Sopenharmony_ci       if (item == NULL) {
6447db96d56Sopenharmony_ci           /* Handle KeyError only: */
6457db96d56Sopenharmony_ci           if (!PyErr_ExceptionMatches(PyExc_KeyError))
6467db96d56Sopenharmony_ci               goto error;
6477db96d56Sopenharmony_ci
6487db96d56Sopenharmony_ci           /* Clear the error and use zero: */
6497db96d56Sopenharmony_ci           PyErr_Clear();
6507db96d56Sopenharmony_ci           item = PyLong_FromLong(0L);
6517db96d56Sopenharmony_ci           if (item == NULL)
6527db96d56Sopenharmony_ci               goto error;
6537db96d56Sopenharmony_ci       }
6547db96d56Sopenharmony_ci       const_one = PyLong_FromLong(1L);
6557db96d56Sopenharmony_ci       if (const_one == NULL)
6567db96d56Sopenharmony_ci           goto error;
6577db96d56Sopenharmony_ci
6587db96d56Sopenharmony_ci       incremented_item = PyNumber_Add(item, const_one);
6597db96d56Sopenharmony_ci       if (incremented_item == NULL)
6607db96d56Sopenharmony_ci           goto error;
6617db96d56Sopenharmony_ci
6627db96d56Sopenharmony_ci       if (PyObject_SetItem(dict, key, incremented_item) < 0)
6637db96d56Sopenharmony_ci           goto error;
6647db96d56Sopenharmony_ci       rv = 0; /* Success */
6657db96d56Sopenharmony_ci       /* Continue with cleanup code */
6667db96d56Sopenharmony_ci
6677db96d56Sopenharmony_ci    error:
6687db96d56Sopenharmony_ci       /* Cleanup code, shared by success and failure path */
6697db96d56Sopenharmony_ci
6707db96d56Sopenharmony_ci       /* Use Py_XDECREF() to ignore NULL references */
6717db96d56Sopenharmony_ci       Py_XDECREF(item);
6727db96d56Sopenharmony_ci       Py_XDECREF(const_one);
6737db96d56Sopenharmony_ci       Py_XDECREF(incremented_item);
6747db96d56Sopenharmony_ci
6757db96d56Sopenharmony_ci       return rv; /* -1 for error, 0 for success */
6767db96d56Sopenharmony_ci   }
6777db96d56Sopenharmony_ci
6787db96d56Sopenharmony_ci.. index:: single: incr_item()
6797db96d56Sopenharmony_ci
6807db96d56Sopenharmony_ci.. index::
6817db96d56Sopenharmony_ci   single: PyErr_ExceptionMatches()
6827db96d56Sopenharmony_ci   single: PyErr_Clear()
6837db96d56Sopenharmony_ci   single: Py_XDECREF()
6847db96d56Sopenharmony_ci
6857db96d56Sopenharmony_ciThis example represents an endorsed use of the ``goto`` statement  in C!
6867db96d56Sopenharmony_ciIt illustrates the use of :c:func:`PyErr_ExceptionMatches` and
6877db96d56Sopenharmony_ci:c:func:`PyErr_Clear` to handle specific exceptions, and the use of
6887db96d56Sopenharmony_ci:c:func:`Py_XDECREF` to dispose of owned references that may be ``NULL`` (note the
6897db96d56Sopenharmony_ci``'X'`` in the name; :c:func:`Py_DECREF` would crash when confronted with a
6907db96d56Sopenharmony_ci``NULL`` reference).  It is important that the variables used to hold owned
6917db96d56Sopenharmony_cireferences are initialized to ``NULL`` for this to work; likewise, the proposed
6927db96d56Sopenharmony_cireturn value is initialized to ``-1`` (failure) and only set to success after
6937db96d56Sopenharmony_cithe final call made is successful.
6947db96d56Sopenharmony_ci
6957db96d56Sopenharmony_ci
6967db96d56Sopenharmony_ci.. _api-embedding:
6977db96d56Sopenharmony_ci
6987db96d56Sopenharmony_ciEmbedding Python
6997db96d56Sopenharmony_ci================
7007db96d56Sopenharmony_ci
7017db96d56Sopenharmony_ciThe one important task that only embedders (as opposed to extension writers) of
7027db96d56Sopenharmony_cithe Python interpreter have to worry about is the initialization, and possibly
7037db96d56Sopenharmony_cithe finalization, of the Python interpreter.  Most functionality of the
7047db96d56Sopenharmony_ciinterpreter can only be used after the interpreter has been initialized.
7057db96d56Sopenharmony_ci
7067db96d56Sopenharmony_ci.. index::
7077db96d56Sopenharmony_ci   single: Py_Initialize()
7087db96d56Sopenharmony_ci   pair: module; builtins
7097db96d56Sopenharmony_ci   pair: module; __main__
7107db96d56Sopenharmony_ci   pair: module; sys
7117db96d56Sopenharmony_ci   triple: module; search; path
7127db96d56Sopenharmony_ci   single: path (in module sys)
7137db96d56Sopenharmony_ci
7147db96d56Sopenharmony_ciThe basic initialization function is :c:func:`Py_Initialize`. This initializes
7157db96d56Sopenharmony_cithe table of loaded modules, and creates the fundamental modules
7167db96d56Sopenharmony_ci:mod:`builtins`, :mod:`__main__`, and :mod:`sys`.  It also
7177db96d56Sopenharmony_ciinitializes the module search path (``sys.path``).
7187db96d56Sopenharmony_ci
7197db96d56Sopenharmony_ci:c:func:`Py_Initialize` does not set the "script argument list"  (``sys.argv``).
7207db96d56Sopenharmony_ciIf this variable is needed by Python code that will be executed later, setting
7217db96d56Sopenharmony_ci:c:member:`PyConfig.argv` and :c:member:`PyConfig.parse_argv` must be set: see
7227db96d56Sopenharmony_ci:ref:`Python Initialization Configuration <init-config>`.
7237db96d56Sopenharmony_ci
7247db96d56Sopenharmony_ciOn most systems (in particular, on Unix and Windows, although the details are
7257db96d56Sopenharmony_cislightly different), :c:func:`Py_Initialize` calculates the module search path
7267db96d56Sopenharmony_cibased upon its best guess for the location of the standard Python interpreter
7277db96d56Sopenharmony_ciexecutable, assuming that the Python library is found in a fixed location
7287db96d56Sopenharmony_cirelative to the Python interpreter executable.  In particular, it looks for a
7297db96d56Sopenharmony_cidirectory named :file:`lib/python{X.Y}` relative to the parent directory
7307db96d56Sopenharmony_ciwhere the executable named :file:`python` is found on the shell command search
7317db96d56Sopenharmony_cipath (the environment variable :envvar:`PATH`).
7327db96d56Sopenharmony_ci
7337db96d56Sopenharmony_ciFor instance, if the Python executable is found in
7347db96d56Sopenharmony_ci:file:`/usr/local/bin/python`, it will assume that the libraries are in
7357db96d56Sopenharmony_ci:file:`/usr/local/lib/python{X.Y}`.  (In fact, this particular path is also
7367db96d56Sopenharmony_cithe "fallback" location, used when no executable file named :file:`python` is
7377db96d56Sopenharmony_cifound along :envvar:`PATH`.)  The user can override this behavior by setting the
7387db96d56Sopenharmony_cienvironment variable :envvar:`PYTHONHOME`, or insert additional directories in
7397db96d56Sopenharmony_cifront of the standard path by setting :envvar:`PYTHONPATH`.
7407db96d56Sopenharmony_ci
7417db96d56Sopenharmony_ci.. index::
7427db96d56Sopenharmony_ci   single: Py_SetProgramName()
7437db96d56Sopenharmony_ci   single: Py_GetPath()
7447db96d56Sopenharmony_ci   single: Py_GetPrefix()
7457db96d56Sopenharmony_ci   single: Py_GetExecPrefix()
7467db96d56Sopenharmony_ci   single: Py_GetProgramFullPath()
7477db96d56Sopenharmony_ci
7487db96d56Sopenharmony_ciThe embedding application can steer the search by calling
7497db96d56Sopenharmony_ci``Py_SetProgramName(file)`` *before* calling  :c:func:`Py_Initialize`.  Note that
7507db96d56Sopenharmony_ci:envvar:`PYTHONHOME` still overrides this and :envvar:`PYTHONPATH` is still
7517db96d56Sopenharmony_ciinserted in front of the standard path.  An application that requires total
7527db96d56Sopenharmony_cicontrol has to provide its own implementation of :c:func:`Py_GetPath`,
7537db96d56Sopenharmony_ci:c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and
7547db96d56Sopenharmony_ci:c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`).
7557db96d56Sopenharmony_ci
7567db96d56Sopenharmony_ci.. index:: single: Py_IsInitialized()
7577db96d56Sopenharmony_ci
7587db96d56Sopenharmony_ciSometimes, it is desirable to "uninitialize" Python.  For instance,  the
7597db96d56Sopenharmony_ciapplication may want to start over (make another call to
7607db96d56Sopenharmony_ci:c:func:`Py_Initialize`) or the application is simply done with its  use of
7617db96d56Sopenharmony_ciPython and wants to free memory allocated by Python.  This can be accomplished
7627db96d56Sopenharmony_ciby calling :c:func:`Py_FinalizeEx`.  The function :c:func:`Py_IsInitialized` returns
7637db96d56Sopenharmony_citrue if Python is currently in the initialized state.  More information about
7647db96d56Sopenharmony_cithese functions is given in a later chapter. Notice that :c:func:`Py_FinalizeEx`
7657db96d56Sopenharmony_cidoes *not* free all memory allocated by the Python interpreter, e.g. memory
7667db96d56Sopenharmony_ciallocated by extension modules currently cannot be released.
7677db96d56Sopenharmony_ci
7687db96d56Sopenharmony_ci
7697db96d56Sopenharmony_ci.. _api-debugging:
7707db96d56Sopenharmony_ci
7717db96d56Sopenharmony_ciDebugging Builds
7727db96d56Sopenharmony_ci================
7737db96d56Sopenharmony_ci
7747db96d56Sopenharmony_ciPython can be built with several macros to enable extra checks of the
7757db96d56Sopenharmony_ciinterpreter and extension modules.  These checks tend to add a large amount of
7767db96d56Sopenharmony_cioverhead to the runtime so they are not enabled by default.
7777db96d56Sopenharmony_ci
7787db96d56Sopenharmony_ciA full list of the various types of debugging builds is in the file
7797db96d56Sopenharmony_ci:file:`Misc/SpecialBuilds.txt` in the Python source distribution. Builds are
7807db96d56Sopenharmony_ciavailable that support tracing of reference counts, debugging the memory
7817db96d56Sopenharmony_ciallocator, or low-level profiling of the main interpreter loop.  Only the most
7827db96d56Sopenharmony_cifrequently used builds will be described in the remainder of this section.
7837db96d56Sopenharmony_ci
7847db96d56Sopenharmony_ciCompiling the interpreter with the :c:macro:`Py_DEBUG` macro defined produces
7857db96d56Sopenharmony_ciwhat is generally meant by :ref:`a debug build of Python <debug-build>`.
7867db96d56Sopenharmony_ci:c:macro:`Py_DEBUG` is enabled in the Unix build by adding
7877db96d56Sopenharmony_ci:option:`--with-pydebug` to the :file:`./configure` command.
7887db96d56Sopenharmony_ciIt is also implied by the presence of the
7897db96d56Sopenharmony_cinot-Python-specific :c:macro:`_DEBUG` macro.  When :c:macro:`Py_DEBUG` is enabled
7907db96d56Sopenharmony_ciin the Unix build, compiler optimization is disabled.
7917db96d56Sopenharmony_ci
7927db96d56Sopenharmony_ciIn addition to the reference count debugging described below, extra checks are
7937db96d56Sopenharmony_ciperformed, see :ref:`Python Debug Build <debug-build>`.
7947db96d56Sopenharmony_ci
7957db96d56Sopenharmony_ciDefining :c:macro:`Py_TRACE_REFS` enables reference tracing
7967db96d56Sopenharmony_ci(see the :option:`configure --with-trace-refs option <--with-trace-refs>`).
7977db96d56Sopenharmony_ciWhen defined, a circular doubly linked list of active objects is maintained by adding two extra
7987db96d56Sopenharmony_cifields to every :c:type:`PyObject`.  Total allocations are tracked as well.  Upon
7997db96d56Sopenharmony_ciexit, all existing references are printed.  (In interactive mode this happens
8007db96d56Sopenharmony_ciafter every statement run by the interpreter.)
8017db96d56Sopenharmony_ci
8027db96d56Sopenharmony_ciPlease refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution
8037db96d56Sopenharmony_cifor more detailed information.
8047db96d56Sopenharmony_ci
805