blob: a1c8d34a7ea02f0859ee6e390cef2c2e18ccdd78 [file] [log] [blame]
Stéphane Wirtelcbb64842019-05-17 11:55:34 +02001.. highlight:: c
Georg Brandl116aa622007-08-15 14:28:22 +00002
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
Barry Warsawb2e57942017-09-14 18:13:16 -070020Writing 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.
Georg Brandl116aa622007-08-15 14:28:22 +000025
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
Barry Warsawb2e57942017-09-14 18:13:16 -070033Coding 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
Georg Brandl116aa622007-08-15 14:28:22 +000043.. _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
Inada Naokic88fece2019-04-13 10:46:21 +090051 #define PY_SSIZE_T_CLEAN
52 #include <Python.h>
Georg Brandl116aa622007-08-15 14:28:22 +000053
54This implies inclusion of the following standard headers: ``<stdio.h>``,
Georg Brandl4f13d612010-11-23 18:14:57 +000055``<string.h>``, ``<errno.h>``, ``<limits.h>``, ``<assert.h>`` and ``<stdlib.h>``
56(if available).
Georg Brandl116aa622007-08-15 14:28:22 +000057
Georg Brandle720c0a2009-04-27 16:20:50 +000058.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000059
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
Inada Naokic88fece2019-04-13 10:46:21 +090064 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
Georg Brandl116aa622007-08-15 14:28:22 +000067All 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**Important:** user code should never define names that begin with ``Py`` or
73``_Py``. This confuses the reader, and jeopardizes the portability of the user
74code to future Python versions, which may define additional names beginning with
75one of these prefixes.
76
77The header files are typically installed with Python. On Unix, these are
78located in the directories :file:`{prefix}/include/pythonversion/` and
79:file:`{exec_prefix}/include/pythonversion/`, where :envvar:`prefix` and
80:envvar:`exec_prefix` are defined by the corresponding parameters to Python's
Serhiy Storchaka885bdc42016-02-11 13:10:36 +020081:program:`configure` script and *version* is
82``'%d.%d' % sys.version_info[:2]``. On Windows, the headers are installed
83in :file:`{prefix}/include`, where :envvar:`prefix` is the installation
84directory specified to the installer.
Georg Brandl116aa622007-08-15 14:28:22 +000085
86To include the headers, place both directories (if different) on your compiler's
87search path for includes. Do *not* place the parent directories on the search
88path and then use ``#include <pythonX.Y/Python.h>``; this will break on
89multi-platform builds since the platform independent headers under
90:envvar:`prefix` include the platform specific headers from
91:envvar:`exec_prefix`.
92
93C++ users should note that though the API is defined entirely using C, the
94header files do properly declare the entry points to be ``extern "C"``, so there
95is no need to do anything special to use the API from C++.
96
97
Barry Warsawb2e57942017-09-14 18:13:16 -070098Useful macros
99=============
100
101Several useful macros are defined in the Python header files. Many are
102defined closer to where they are useful (e.g. :c:macro:`Py_RETURN_NONE`).
103Others of a more general utility are defined here. This is not necessarily a
104complete listing.
105
106.. c:macro:: Py_UNREACHABLE()
107
108 Use this when you have a code path that you do not expect to be reached.
109 For example, in the ``default:`` clause in a ``switch`` statement for which
110 all possible values are covered in ``case`` statements. Use this in places
111 where you might be tempted to put an ``assert(0)`` or ``abort()`` call.
112
Petr Viktorin8bf288e2017-11-08 14:11:16 +0100113 .. versionadded:: 3.7
114
Barry Warsawb2e57942017-09-14 18:13:16 -0700115.. c:macro:: Py_ABS(x)
116
117 Return the absolute value of ``x``.
118
Victor Stinner54cc0c02017-11-08 06:06:24 -0800119 .. versionadded:: 3.3
120
Barry Warsawb2e57942017-09-14 18:13:16 -0700121.. c:macro:: Py_MIN(x, y)
122
123 Return the minimum value between ``x`` and ``y``.
124
Victor Stinner54cc0c02017-11-08 06:06:24 -0800125 .. versionadded:: 3.3
126
Barry Warsawb2e57942017-09-14 18:13:16 -0700127.. c:macro:: Py_MAX(x, y)
128
129 Return the maximum value between ``x`` and ``y``.
130
Victor Stinner54cc0c02017-11-08 06:06:24 -0800131 .. versionadded:: 3.3
132
Barry Warsawb2e57942017-09-14 18:13:16 -0700133.. c:macro:: Py_STRINGIFY(x)
134
135 Convert ``x`` to a C string. E.g. ``Py_STRINGIFY(123)`` returns
136 ``"123"``.
137
Victor Stinner54cc0c02017-11-08 06:06:24 -0800138 .. versionadded:: 3.4
139
Barry Warsawb2e57942017-09-14 18:13:16 -0700140.. c:macro:: Py_MEMBER_SIZE(type, member)
141
142 Return the size of a structure (``type``) ``member`` in bytes.
143
Victor Stinner54cc0c02017-11-08 06:06:24 -0800144 .. versionadded:: 3.6
145
Barry Warsawb2e57942017-09-14 18:13:16 -0700146.. c:macro:: Py_CHARMASK(c)
147
148 Argument must be a character or an integer in the range [-128, 127] or [0,
149 255]. This macro returns ``c`` cast to an ``unsigned char``.
150
Barry Warsawa51b90a2017-10-06 09:53:48 -0400151.. c:macro:: Py_GETENV(s)
152
153 Like ``getenv(s)``, but returns *NULL* if :option:`-E` was passed on the
154 command line (i.e. if ``Py_IgnoreEnvironmentFlag`` is set).
155
Petr Viktorin21381632017-11-08 16:59:20 +0100156.. c:macro:: Py_UNUSED(arg)
157
158 Use this for unused arguments in a function definition to silence compiler
Victor Stinnerb3a98432019-05-24 15:16:08 +0200159 warnings. Example: ``int func(int a, int Py_UNUSED(b)) { return a; }``.
Petr Viktorin21381632017-11-08 16:59:20 +0100160
161 .. versionadded:: 3.4
162
Zackery Spytz3c8724f2019-05-28 09:16:33 -0600163.. c:macro:: Py_DEPRECATED(version)
164
165 Use this for deprecated declarations. The macro must be placed before the
166 symbol name.
167
168 Example::
169
170 Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
171
172 .. versionchanged:: 3.8
173 MSVC support was added.
174
Barry Warsawb2e57942017-09-14 18:13:16 -0700175
Georg Brandl116aa622007-08-15 14:28:22 +0000176.. _api-objects:
177
178Objects, Types and Reference Counts
179===================================
180
181.. index:: object: type
182
183Most Python/C API functions have one or more arguments as well as a return value
Georg Brandl60203b42010-10-06 10:11:56 +0000184of type :c:type:`PyObject\*`. This type is a pointer to an opaque data type
Georg Brandl116aa622007-08-15 14:28:22 +0000185representing an arbitrary Python object. Since all Python object types are
186treated the same way by the Python language in most situations (e.g.,
187assignments, scope rules, and argument passing), it is only fitting that they
188should be represented by a single C type. Almost all Python objects live on the
189heap: you never declare an automatic or static variable of type
Georg Brandl60203b42010-10-06 10:11:56 +0000190:c:type:`PyObject`, only pointer variables of type :c:type:`PyObject\*` can be
Georg Brandl116aa622007-08-15 14:28:22 +0000191declared. The sole exception are the type objects; since these must never be
Georg Brandl60203b42010-10-06 10:11:56 +0000192deallocated, they are typically static :c:type:`PyTypeObject` objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
194All Python objects (even Python integers) have a :dfn:`type` and a
195:dfn:`reference count`. An object's type determines what kind of object it is
196(e.g., an integer, a list, or a user-defined function; there are many more as
197explained in :ref:`types`). For each of the well-known types there is a macro
198to check whether an object is of that type; for instance, ``PyList_Check(a)`` is
199true if (and only if) the object pointed to by *a* is a Python list.
200
201
202.. _api-refcounts:
203
204Reference Counts
205----------------
206
207The reference count is important because today's computers have a finite (and
208often severely limited) memory size; it counts how many different places there
209are that have a reference to an object. Such a place could be another object,
210or a global (or static) C variable, or a local variable in some C function.
211When an object's reference count becomes zero, the object is deallocated. If
212it contains references to other objects, their reference count is decremented.
213Those other objects may be deallocated in turn, if this decrement makes their
214reference count become zero, and so on. (There's an obvious problem with
215objects that reference each other here; for now, the solution is "don't do
216that.")
217
218.. index::
219 single: Py_INCREF()
220 single: Py_DECREF()
221
222Reference counts are always manipulated explicitly. The normal way is to use
Georg Brandl60203b42010-10-06 10:11:56 +0000223the macro :c:func:`Py_INCREF` to increment an object's reference count by one,
224and :c:func:`Py_DECREF` to decrement it by one. The :c:func:`Py_DECREF` macro
Georg Brandl116aa622007-08-15 14:28:22 +0000225is considerably more complex than the incref one, since it must check whether
226the reference count becomes zero and then cause the object's deallocator to be
227called. The deallocator is a function pointer contained in the object's type
228structure. The type-specific deallocator takes care of decrementing the
229reference counts for other objects contained in the object if this is a compound
230object type, such as a list, as well as performing any additional finalization
231that's needed. There's no chance that the reference count can overflow; at
232least as many bits are used to hold the reference count as there are distinct
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000233memory locations in virtual memory (assuming ``sizeof(Py_ssize_t) >= sizeof(void*)``).
Georg Brandl116aa622007-08-15 14:28:22 +0000234Thus, the reference count increment is a simple operation.
235
236It is not necessary to increment an object's reference count for every local
237variable that contains a pointer to an object. In theory, the object's
238reference count goes up by one when the variable is made to point to it and it
239goes down by one when the variable goes out of scope. However, these two
240cancel each other out, so at the end the reference count hasn't changed. The
241only real reason to use the reference count is to prevent the object from being
242deallocated as long as our variable is pointing to it. If we know that there
243is at least one other reference to the object that lives at least as long as
244our variable, there is no need to increment the reference count temporarily.
245An important situation where this arises is in objects that are passed as
246arguments to C functions in an extension module that are called from Python;
247the call mechanism guarantees to hold a reference to every argument for the
248duration of the call.
249
250However, a common pitfall is to extract an object from a list and hold on to it
251for a while without incrementing its reference count. Some other operation might
252conceivably remove the object from the list, decrementing its reference count
Beomsoo Kim05c1b382018-12-17 21:57:03 +0900253and possibly deallocating it. The real danger is that innocent-looking
Georg Brandl116aa622007-08-15 14:28:22 +0000254operations may invoke arbitrary Python code which could do this; there is a code
Georg Brandl60203b42010-10-06 10:11:56 +0000255path which allows control to flow back to the user from a :c:func:`Py_DECREF`, so
Georg Brandl116aa622007-08-15 14:28:22 +0000256almost any operation is potentially dangerous.
257
258A safe approach is to always use the generic operations (functions whose name
259begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``).
260These operations always increment the reference count of the object they return.
Georg Brandl60203b42010-10-06 10:11:56 +0000261This leaves the caller with the responsibility to call :c:func:`Py_DECREF` when
Georg Brandl116aa622007-08-15 14:28:22 +0000262they are done with the result; this soon becomes second nature.
263
264
265.. _api-refcountdetails:
266
267Reference Count Details
268^^^^^^^^^^^^^^^^^^^^^^^
269
270The reference count behavior of functions in the Python/C API is best explained
271in terms of *ownership of references*. Ownership pertains to references, never
272to objects (objects are not owned: they are always shared). "Owning a
273reference" means being responsible for calling Py_DECREF on it when the
274reference is no longer needed. Ownership can also be transferred, meaning that
275the code that receives ownership of the reference then becomes responsible for
Georg Brandl60203b42010-10-06 10:11:56 +0000276eventually decref'ing it by calling :c:func:`Py_DECREF` or :c:func:`Py_XDECREF`
Georg Brandl116aa622007-08-15 14:28:22 +0000277when it's no longer needed---or passing on this responsibility (usually to its
278caller). When a function passes ownership of a reference on to its caller, the
279caller is said to receive a *new* reference. When no ownership is transferred,
280the caller is said to *borrow* the reference. Nothing needs to be done for a
281borrowed reference.
282
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000283Conversely, when a calling function passes in a reference to an object, there
Georg Brandl116aa622007-08-15 14:28:22 +0000284are two possibilities: the function *steals* a reference to the object, or it
285does not. *Stealing a reference* means that when you pass a reference to a
286function, that function assumes that it now owns that reference, and you are not
287responsible for it any longer.
288
289.. index::
290 single: PyList_SetItem()
291 single: PyTuple_SetItem()
292
293Few functions steal references; the two notable exceptions are
Georg Brandl60203b42010-10-06 10:11:56 +0000294:c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which steal a reference
Georg Brandl116aa622007-08-15 14:28:22 +0000295to the item (but not to the tuple or list into which the item is put!). These
296functions were designed to steal a reference because of a common idiom for
297populating a tuple or list with newly created objects; for example, the code to
298create the tuple ``(1, 2, "three")`` could look like this (forgetting about
299error handling for the moment; a better way to code this is shown below)::
300
301 PyObject *t;
302
303 t = PyTuple_New(3);
Georg Brandld019fe22007-12-08 18:58:51 +0000304 PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
305 PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
Gregory P. Smith4b52ae82013-03-22 13:43:30 -0700306 PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));
Georg Brandl116aa622007-08-15 14:28:22 +0000307
Georg Brandl60203b42010-10-06 10:11:56 +0000308Here, :c:func:`PyLong_FromLong` returns a new reference which is immediately
309stolen by :c:func:`PyTuple_SetItem`. When you want to keep using an object
310although the reference to it will be stolen, use :c:func:`Py_INCREF` to grab
Georg Brandl116aa622007-08-15 14:28:22 +0000311another reference before calling the reference-stealing function.
312
Georg Brandl60203b42010-10-06 10:11:56 +0000313Incidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple items;
314:c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to do this
Georg Brandl116aa622007-08-15 14:28:22 +0000315since tuples are an immutable data type. You should only use
Georg Brandl60203b42010-10-06 10:11:56 +0000316:c:func:`PyTuple_SetItem` for tuples that you are creating yourself.
Georg Brandl116aa622007-08-15 14:28:22 +0000317
Georg Brandl60203b42010-10-06 10:11:56 +0000318Equivalent code for populating a list can be written using :c:func:`PyList_New`
319and :c:func:`PyList_SetItem`.
Georg Brandl116aa622007-08-15 14:28:22 +0000320
321However, in practice, you will rarely use these ways of creating and populating
Georg Brandl60203b42010-10-06 10:11:56 +0000322a tuple or list. There's a generic function, :c:func:`Py_BuildValue`, that can
Georg Brandl116aa622007-08-15 14:28:22 +0000323create most common objects from C values, directed by a :dfn:`format string`.
324For example, the above two blocks of code could be replaced by the following
325(which also takes care of the error checking)::
326
327 PyObject *tuple, *list;
328
329 tuple = Py_BuildValue("(iis)", 1, 2, "three");
330 list = Py_BuildValue("[iis]", 1, 2, "three");
331
Georg Brandl60203b42010-10-06 10:11:56 +0000332It is much more common to use :c:func:`PyObject_SetItem` and friends with items
Georg Brandl116aa622007-08-15 14:28:22 +0000333whose references you are only borrowing, like arguments that were passed in to
334the function you are writing. In that case, their behaviour regarding reference
335counts is much saner, since you don't have to increment a reference count so you
336can give a reference away ("have it be stolen"). For example, this function
337sets all items of a list (actually, any mutable sequence) to a given item::
338
339 int
340 set_all(PyObject *target, PyObject *item)
341 {
Antoine Pitrou04707c02012-01-27 14:07:29 +0100342 Py_ssize_t i, n;
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344 n = PyObject_Length(target);
345 if (n < 0)
346 return -1;
347 for (i = 0; i < n; i++) {
Antoine Pitrou04707c02012-01-27 14:07:29 +0100348 PyObject *index = PyLong_FromSsize_t(i);
Georg Brandl116aa622007-08-15 14:28:22 +0000349 if (!index)
350 return -1;
Antoine Pitrou04707c02012-01-27 14:07:29 +0100351 if (PyObject_SetItem(target, index, item) < 0) {
352 Py_DECREF(index);
Georg Brandl116aa622007-08-15 14:28:22 +0000353 return -1;
Antoine Pitrou04707c02012-01-27 14:07:29 +0100354 }
Georg Brandl116aa622007-08-15 14:28:22 +0000355 Py_DECREF(index);
356 }
357 return 0;
358 }
359
360.. index:: single: set_all()
361
362The situation is slightly different for function return values. While passing
363a reference to most functions does not change your ownership responsibilities
364for that reference, many functions that return a reference to an object give
365you ownership of the reference. The reason is simple: in many cases, the
366returned object is created on the fly, and the reference you get is the only
367reference to the object. Therefore, the generic functions that return object
Georg Brandl60203b42010-10-06 10:11:56 +0000368references, like :c:func:`PyObject_GetItem` and :c:func:`PySequence_GetItem`,
Georg Brandl116aa622007-08-15 14:28:22 +0000369always return a new reference (the caller becomes the owner of the reference).
370
371It is important to realize that whether you own a reference returned by a
372function depends on which function you call only --- *the plumage* (the type of
373the object passed as an argument to the function) *doesn't enter into it!*
Georg Brandl60203b42010-10-06 10:11:56 +0000374Thus, if you extract an item from a list using :c:func:`PyList_GetItem`, you
Georg Brandl116aa622007-08-15 14:28:22 +0000375don't own the reference --- but if you obtain the same item from the same list
Georg Brandl60203b42010-10-06 10:11:56 +0000376using :c:func:`PySequence_GetItem` (which happens to take exactly the same
Georg Brandl116aa622007-08-15 14:28:22 +0000377arguments), you do own a reference to the returned object.
378
379.. index::
380 single: PyList_GetItem()
381 single: PySequence_GetItem()
382
383Here is an example of how you could write a function that computes the sum of
Georg Brandl60203b42010-10-06 10:11:56 +0000384the items in a list of integers; once using :c:func:`PyList_GetItem`, and once
385using :c:func:`PySequence_GetItem`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387 long
388 sum_list(PyObject *list)
389 {
Antoine Pitrou04707c02012-01-27 14:07:29 +0100390 Py_ssize_t i, n;
391 long total = 0, value;
Georg Brandl116aa622007-08-15 14:28:22 +0000392 PyObject *item;
393
394 n = PyList_Size(list);
395 if (n < 0)
396 return -1; /* Not a list */
397 for (i = 0; i < n; i++) {
398 item = PyList_GetItem(list, i); /* Can't fail */
Georg Brandld019fe22007-12-08 18:58:51 +0000399 if (!PyLong_Check(item)) continue; /* Skip non-integers */
Antoine Pitrou04707c02012-01-27 14:07:29 +0100400 value = PyLong_AsLong(item);
401 if (value == -1 && PyErr_Occurred())
402 /* Integer too big to fit in a C long, bail out */
403 return -1;
404 total += value;
Georg Brandl116aa622007-08-15 14:28:22 +0000405 }
406 return total;
407 }
408
409.. index:: single: sum_list()
410
411::
412
413 long
414 sum_sequence(PyObject *sequence)
415 {
Antoine Pitrou04707c02012-01-27 14:07:29 +0100416 Py_ssize_t i, n;
417 long total = 0, value;
Georg Brandl116aa622007-08-15 14:28:22 +0000418 PyObject *item;
419 n = PySequence_Length(sequence);
420 if (n < 0)
421 return -1; /* Has no length */
422 for (i = 0; i < n; i++) {
423 item = PySequence_GetItem(sequence, i);
424 if (item == NULL)
425 return -1; /* Not a sequence, or other failure */
Antoine Pitrou04707c02012-01-27 14:07:29 +0100426 if (PyLong_Check(item)) {
427 value = PyLong_AsLong(item);
428 Py_DECREF(item);
429 if (value == -1 && PyErr_Occurred())
430 /* Integer too big to fit in a C long, bail out */
431 return -1;
432 total += value;
433 }
434 else {
435 Py_DECREF(item); /* Discard reference ownership */
436 }
Georg Brandl116aa622007-08-15 14:28:22 +0000437 }
438 return total;
439 }
440
441.. index:: single: sum_sequence()
442
443
444.. _api-types:
445
446Types
447-----
448
449There are few other data types that play a significant role in the Python/C
Georg Brandl60203b42010-10-06 10:11:56 +0000450API; most are simple C types such as :c:type:`int`, :c:type:`long`,
451:c:type:`double` and :c:type:`char\*`. A few structure types are used to
Georg Brandl116aa622007-08-15 14:28:22 +0000452describe static tables used to list the functions exported by a module or the
453data attributes of a new object type, and another is used to describe the value
454of a complex number. These will be discussed together with the functions that
455use them.
456
457
458.. _api-exceptions:
459
460Exceptions
461==========
462
463The Python programmer only needs to deal with exceptions if specific error
464handling is required; unhandled exceptions are automatically propagated to the
465caller, then to the caller's caller, and so on, until they reach the top-level
466interpreter, where they are reported to the user accompanied by a stack
467traceback.
468
469.. index:: single: PyErr_Occurred()
470
Georg Brandldd909db2010-10-17 06:32:59 +0000471For C programmers, however, error checking always has to be explicit. All
472functions in the Python/C API can raise exceptions, unless an explicit claim is
473made otherwise in a function's documentation. In general, when a function
474encounters an error, it sets an exception, discards any object references that
475it owns, and returns an error indicator. If not documented otherwise, this
476indicator is either *NULL* or ``-1``, depending on the function's return type.
477A few functions return a Boolean true/false result, with false indicating an
478error. Very few functions return no explicit error indicator or have an
479ambiguous return value, and require explicit testing for errors with
480:c:func:`PyErr_Occurred`. These exceptions are always explicitly documented.
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482.. index::
483 single: PyErr_SetString()
484 single: PyErr_Clear()
485
486Exception state is maintained in per-thread storage (this is equivalent to
487using global storage in an unthreaded application). A thread can be in one of
488two states: an exception has occurred, or not. The function
Georg Brandl60203b42010-10-06 10:11:56 +0000489:c:func:`PyErr_Occurred` can be used to check for this: it returns a borrowed
Georg Brandl116aa622007-08-15 14:28:22 +0000490reference to the exception type object when an exception has occurred, and
491*NULL* otherwise. There are a number of functions to set the exception state:
Georg Brandl60203b42010-10-06 10:11:56 +0000492:c:func:`PyErr_SetString` is the most common (though not the most general)
493function to set the exception state, and :c:func:`PyErr_Clear` clears the
Georg Brandl116aa622007-08-15 14:28:22 +0000494exception state.
495
496The full exception state consists of three objects (all of which can be
497*NULL*): the exception type, the corresponding exception value, and the
498traceback. These have the same meanings as the Python result of
499``sys.exc_info()``; however, they are not the same: the Python objects represent
500the last exception being handled by a Python :keyword:`try` ...
501:keyword:`except` statement, while the C level exception state only exists while
502an exception is being passed on between C functions until it reaches the Python
503bytecode interpreter's main loop, which takes care of transferring it to
504``sys.exc_info()`` and friends.
505
506.. index:: single: exc_info() (in module sys)
507
508Note that starting with Python 1.5, the preferred, thread-safe way to access the
509exception state from Python code is to call the function :func:`sys.exc_info`,
510which returns the per-thread exception state for Python code. Also, the
511semantics of both ways to access the exception state have changed so that a
512function which catches an exception will save and restore its thread's exception
513state so as to preserve the exception state of its caller. This prevents common
514bugs in exception handling code caused by an innocent-looking function
515overwriting the exception being handled; it also reduces the often unwanted
516lifetime extension for objects that are referenced by the stack frames in the
517traceback.
518
519As a general principle, a function that calls another function to perform some
520task should check whether the called function raised an exception, and if so,
521pass the exception state on to its caller. It should discard any object
522references that it owns, and return an error indicator, but it should *not* set
523another exception --- that would overwrite the exception that was just raised,
524and lose important information about the exact cause of the error.
525
526.. index:: single: sum_sequence()
527
528A simple example of detecting exceptions and passing them on is shown in the
Terry Jan Reedy65e69b32013-03-11 17:23:46 -0400529:c:func:`sum_sequence` example above. It so happens that this example doesn't
Georg Brandl116aa622007-08-15 14:28:22 +0000530need to clean up any owned references when it detects an error. The following
531example function shows some error cleanup. First, to remind you why you like
532Python, we show the equivalent Python code::
533
534 def incr_item(dict, key):
535 try:
536 item = dict[key]
537 except KeyError:
538 item = 0
539 dict[key] = item + 1
540
541.. index:: single: incr_item()
542
543Here is the corresponding C code, in all its glory::
544
545 int
546 incr_item(PyObject *dict, PyObject *key)
547 {
548 /* Objects all initialized to NULL for Py_XDECREF */
549 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
550 int rv = -1; /* Return value initialized to -1 (failure) */
551
552 item = PyObject_GetItem(dict, key);
553 if (item == NULL) {
554 /* Handle KeyError only: */
555 if (!PyErr_ExceptionMatches(PyExc_KeyError))
556 goto error;
557
558 /* Clear the error and use zero: */
559 PyErr_Clear();
Georg Brandld019fe22007-12-08 18:58:51 +0000560 item = PyLong_FromLong(0L);
Georg Brandl116aa622007-08-15 14:28:22 +0000561 if (item == NULL)
562 goto error;
563 }
Georg Brandld019fe22007-12-08 18:58:51 +0000564 const_one = PyLong_FromLong(1L);
Georg Brandl116aa622007-08-15 14:28:22 +0000565 if (const_one == NULL)
566 goto error;
567
568 incremented_item = PyNumber_Add(item, const_one);
569 if (incremented_item == NULL)
570 goto error;
571
572 if (PyObject_SetItem(dict, key, incremented_item) < 0)
573 goto error;
574 rv = 0; /* Success */
575 /* Continue with cleanup code */
576
577 error:
578 /* Cleanup code, shared by success and failure path */
579
580 /* Use Py_XDECREF() to ignore NULL references */
581 Py_XDECREF(item);
582 Py_XDECREF(const_one);
583 Py_XDECREF(incremented_item);
584
585 return rv; /* -1 for error, 0 for success */
586 }
587
588.. index:: single: incr_item()
589
590.. index::
591 single: PyErr_ExceptionMatches()
592 single: PyErr_Clear()
593 single: Py_XDECREF()
594
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000595This example represents an endorsed use of the ``goto`` statement in C!
Georg Brandl60203b42010-10-06 10:11:56 +0000596It illustrates the use of :c:func:`PyErr_ExceptionMatches` and
597:c:func:`PyErr_Clear` to handle specific exceptions, and the use of
598:c:func:`Py_XDECREF` to dispose of owned references that may be *NULL* (note the
599``'X'`` in the name; :c:func:`Py_DECREF` would crash when confronted with a
Georg Brandl116aa622007-08-15 14:28:22 +0000600*NULL* reference). It is important that the variables used to hold owned
601references are initialized to *NULL* for this to work; likewise, the proposed
602return value is initialized to ``-1`` (failure) and only set to success after
603the final call made is successful.
604
605
606.. _api-embedding:
607
608Embedding Python
609================
610
611The one important task that only embedders (as opposed to extension writers) of
612the Python interpreter have to worry about is the initialization, and possibly
613the finalization, of the Python interpreter. Most functionality of the
614interpreter can only be used after the interpreter has been initialized.
615
616.. index::
617 single: Py_Initialize()
Georg Brandl1a3284e2007-12-02 09:40:06 +0000618 module: builtins
Georg Brandl116aa622007-08-15 14:28:22 +0000619 module: __main__
620 module: sys
Georg Brandl116aa622007-08-15 14:28:22 +0000621 triple: module; search; path
622 single: path (in module sys)
623
Georg Brandl60203b42010-10-06 10:11:56 +0000624The basic initialization function is :c:func:`Py_Initialize`. This initializes
Georg Brandl116aa622007-08-15 14:28:22 +0000625the table of loaded modules, and creates the fundamental modules
Éric Araujo8b8f2ec2011-03-26 07:22:01 +0100626:mod:`builtins`, :mod:`__main__`, and :mod:`sys`. It also
Georg Brandl116aa622007-08-15 14:28:22 +0000627initializes the module search path (``sys.path``).
628
Benjamin Peterson2ebf8ce2010-06-27 21:48:35 +0000629.. index:: single: PySys_SetArgvEx()
Georg Brandl116aa622007-08-15 14:28:22 +0000630
Georg Brandl60203b42010-10-06 10:11:56 +0000631:c:func:`Py_Initialize` does not set the "script argument list" (``sys.argv``).
Benjamin Peterson2ebf8ce2010-06-27 21:48:35 +0000632If this variable is needed by Python code that will be executed later, it must
633be set explicitly with a call to ``PySys_SetArgvEx(argc, argv, updatepath)``
Georg Brandl60203b42010-10-06 10:11:56 +0000634after the call to :c:func:`Py_Initialize`.
Georg Brandl116aa622007-08-15 14:28:22 +0000635
636On most systems (in particular, on Unix and Windows, although the details are
Georg Brandl60203b42010-10-06 10:11:56 +0000637slightly different), :c:func:`Py_Initialize` calculates the module search path
Georg Brandl116aa622007-08-15 14:28:22 +0000638based upon its best guess for the location of the standard Python interpreter
639executable, assuming that the Python library is found in a fixed location
640relative to the Python interpreter executable. In particular, it looks for a
641directory named :file:`lib/python{X.Y}` relative to the parent directory
642where the executable named :file:`python` is found on the shell command search
643path (the environment variable :envvar:`PATH`).
644
645For instance, if the Python executable is found in
646:file:`/usr/local/bin/python`, it will assume that the libraries are in
647:file:`/usr/local/lib/python{X.Y}`. (In fact, this particular path is also
648the "fallback" location, used when no executable file named :file:`python` is
649found along :envvar:`PATH`.) The user can override this behavior by setting the
650environment variable :envvar:`PYTHONHOME`, or insert additional directories in
651front of the standard path by setting :envvar:`PYTHONPATH`.
652
653.. index::
654 single: Py_SetProgramName()
655 single: Py_GetPath()
656 single: Py_GetPrefix()
657 single: Py_GetExecPrefix()
658 single: Py_GetProgramFullPath()
659
660The embedding application can steer the search by calling
Georg Brandl60203b42010-10-06 10:11:56 +0000661``Py_SetProgramName(file)`` *before* calling :c:func:`Py_Initialize`. Note that
Georg Brandl116aa622007-08-15 14:28:22 +0000662:envvar:`PYTHONHOME` still overrides this and :envvar:`PYTHONPATH` is still
663inserted in front of the standard path. An application that requires total
Georg Brandl60203b42010-10-06 10:11:56 +0000664control has to provide its own implementation of :c:func:`Py_GetPath`,
665:c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and
666:c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`).
Georg Brandl116aa622007-08-15 14:28:22 +0000667
668.. index:: single: Py_IsInitialized()
669
670Sometimes, it is desirable to "uninitialize" Python. For instance, the
671application may want to start over (make another call to
Georg Brandl60203b42010-10-06 10:11:56 +0000672:c:func:`Py_Initialize`) or the application is simply done with its use of
Georg Brandl116aa622007-08-15 14:28:22 +0000673Python and wants to free memory allocated by Python. This can be accomplished
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000674by calling :c:func:`Py_FinalizeEx`. The function :c:func:`Py_IsInitialized` returns
Georg Brandl116aa622007-08-15 14:28:22 +0000675true if Python is currently in the initialized state. More information about
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000676these functions is given in a later chapter. Notice that :c:func:`Py_FinalizeEx`
Georg Brandl116aa622007-08-15 14:28:22 +0000677does *not* free all memory allocated by the Python interpreter, e.g. memory
678allocated by extension modules currently cannot be released.
679
680
681.. _api-debugging:
682
683Debugging Builds
684================
685
686Python can be built with several macros to enable extra checks of the
687interpreter and extension modules. These checks tend to add a large amount of
688overhead to the runtime so they are not enabled by default.
689
690A full list of the various types of debugging builds is in the file
691:file:`Misc/SpecialBuilds.txt` in the Python source distribution. Builds are
692available that support tracing of reference counts, debugging the memory
693allocator, or low-level profiling of the main interpreter loop. Only the most
694frequently-used builds will be described in the remainder of this section.
695
Georg Brandl60203b42010-10-06 10:11:56 +0000696Compiling the interpreter with the :c:macro:`Py_DEBUG` macro defined produces
697what is generally meant by "a debug build" of Python. :c:macro:`Py_DEBUG` is
Éric Araujod2f8cec2011-06-08 05:29:39 +0200698enabled in the Unix build by adding ``--with-pydebug`` to the
699:file:`./configure` command. It is also implied by the presence of the
Georg Brandl60203b42010-10-06 10:11:56 +0000700not-Python-specific :c:macro:`_DEBUG` macro. When :c:macro:`Py_DEBUG` is enabled
Georg Brandl116aa622007-08-15 14:28:22 +0000701in the Unix build, compiler optimization is disabled.
702
703In addition to the reference count debugging described below, the following
704extra checks are performed:
705
706* Extra checks are added to the object allocator.
707
708* Extra checks are added to the parser and compiler.
709
710* Downcasts from wide types to narrow types are checked for loss of information.
711
712* A number of assertions are added to the dictionary and set implementations.
713 In addition, the set object acquires a :meth:`test_c_api` method.
714
715* Sanity checks of the input arguments are added to frame creation.
716
Mark Dickinsonbf5c6a92009-01-17 10:21:23 +0000717* The storage for ints is initialized with a known invalid pattern to catch
Georg Brandl116aa622007-08-15 14:28:22 +0000718 reference to uninitialized digits.
719
720* Low-level tracing and extra exception checking are added to the runtime
721 virtual machine.
722
723* Extra checks are added to the memory arena implementation.
724
725* Extra debugging is added to the thread module.
726
727There may be additional checks not mentioned here.
728
Georg Brandl60203b42010-10-06 10:11:56 +0000729Defining :c:macro:`Py_TRACE_REFS` enables reference tracing. When defined, a
Georg Brandl116aa622007-08-15 14:28:22 +0000730circular doubly linked list of active objects is maintained by adding two extra
Georg Brandl60203b42010-10-06 10:11:56 +0000731fields to every :c:type:`PyObject`. Total allocations are tracked as well. Upon
Georg Brandl116aa622007-08-15 14:28:22 +0000732exit, all existing references are printed. (In interactive mode this happens
Georg Brandl60203b42010-10-06 10:11:56 +0000733after every statement run by the interpreter.) Implied by :c:macro:`Py_DEBUG`.
Georg Brandl116aa622007-08-15 14:28:22 +0000734
735Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution
736for more detailed information.
737