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