blob: 24e2156d9a8b8f912d8ffe76ba7e5afd6414dd79 [file] [log] [blame]
Fred Drake6659c301998-03-03 22:02:19 +00001\documentclass{manual}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003\title{Python/C API Reference Manual}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00004
5\input{boilerplate}
6
Marc-André Lemburga544ea22001-01-17 18:04:31 +00007\makeindex % tell \index to actually write the .idx file
Guido van Rossum9231c8f1997-05-15 21:43:21 +00008
9
10\begin{document}
11
Guido van Rossum9231c8f1997-05-15 21:43:21 +000012\maketitle
13
Fred Drake9f86b661998-07-28 21:55:19 +000014\ifhtml
15\chapter*{Front Matter\label{front}}
16\fi
17
Guido van Rossum9231c8f1997-05-15 21:43:21 +000018\input{copyright}
19
20\begin{abstract}
21
22\noindent
Fred Drake659ebfa2000-04-03 15:42:13 +000023This manual documents the API used by C and \Cpp{} programmers who
Fred Drakee058b4f1998-02-16 06:15:35 +000024want to write extension modules or embed Python. It is a companion to
Fred Drakebe486461999-11-09 17:03:03 +000025\citetitle[../ext/ext.html]{Extending and Embedding the Python
26Interpreter}, which describes the general principles of extension
27writing but does not document the API functions in detail.
Guido van Rossum9231c8f1997-05-15 21:43:21 +000028
Guido van Rossum5b8a5231997-12-30 04:38:44 +000029\strong{Warning:} The current version of this document is incomplete.
30I hope that it is nevertheless useful. I will continue to work on it,
31and release new versions from time to time, independent from Python
32source code releases.
33
Guido van Rossum9231c8f1997-05-15 21:43:21 +000034\end{abstract}
35
Fred Drake4d4f9e71998-01-13 22:25:02 +000036\tableofcontents
Guido van Rossum9231c8f1997-05-15 21:43:21 +000037
Guido van Rossum5060b3b1997-08-17 18:02:23 +000038% XXX Consider moving all this back to ext.tex and giving api.tex
39% XXX a *really* short intro only.
Guido van Rossum9231c8f1997-05-15 21:43:21 +000040
Fred Drakeefd146c1999-02-15 15:30:45 +000041\chapter{Introduction \label{intro}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +000042
Fred Drake659ebfa2000-04-03 15:42:13 +000043The Application Programmer's Interface to Python gives C and
44\Cpp{} programmers access to the Python interpreter at a variety of
45levels. The API is equally usable from \Cpp{}, but for brevity it is
46generally referred to as the Python/C API. There are two
47fundamentally different reasons for using the Python/C API. The first
48reason is to write \emph{extension modules} for specific purposes;
49these are C modules that extend the Python interpreter. This is
50probably the most common use. The second reason is to use Python as a
51component in a larger application; this technique is generally
52referred to as \dfn{embedding} Python in an application.
Guido van Rossum59a61351997-08-14 20:34:33 +000053
Guido van Rossum4a944d71997-08-14 20:35:38 +000054Writing an extension module is a relatively well-understood process,
55where a ``cookbook'' approach works well. There are several tools
56that automate the process to some extent. While people have embedded
57Python in other applications since its early existence, the process of
Fred Drakefc43d002001-05-21 15:03:35 +000058embedding Python is less straightforward than writing an extension.
Guido van Rossum59a61351997-08-14 20:34:33 +000059
Guido van Rossum4a944d71997-08-14 20:35:38 +000060Many API functions are useful independent of whether you're embedding
61or extending Python; moreover, most applications that embed Python
62will need to provide a custom extension as well, so it's probably a
63good idea to become familiar with writing an extension before
Guido van Rossum59a61351997-08-14 20:34:33 +000064attempting to embed Python in a real application.
65
Fred Drakeefd146c1999-02-15 15:30:45 +000066
67\section{Include Files \label{includes}}
Guido van Rossum580aa8d1997-11-25 15:34:51 +000068
69All function, type and macro definitions needed to use the Python/C
70API are included in your code by the following line:
71
Fred Drakee058b4f1998-02-16 06:15:35 +000072\begin{verbatim}
73#include "Python.h"
74\end{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +000075
Fred Drakee058b4f1998-02-16 06:15:35 +000076This implies inclusion of the following standard headers:
Fred Drake0b71cea2000-09-26 05:51:50 +000077\code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>},
78\code{<limits.h>}, and \code{<stdlib.h>} (if available).
Fred Drake396ca572001-09-06 16:30:30 +000079Since Python may define some pre-processor definitions which affect
80the standard headers on some systems, you must include \file{Python.h}
81before any standard headers are included.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000082
83All user visible names defined by Python.h (except those defined by
Fred Drakee058b4f1998-02-16 06:15:35 +000084the included standard headers) have one of the prefixes \samp{Py} or
Fred Drake659ebfa2000-04-03 15:42:13 +000085\samp{_Py}. Names beginning with \samp{_Py} are for internal use by
86the Python implementation and should not be used by extension writers.
87Structure member names do not have a reserved prefix.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000088
Fred Drakee058b4f1998-02-16 06:15:35 +000089\strong{Important:} user code should never define names that begin
90with \samp{Py} or \samp{_Py}. This confuses the reader, and
91jeopardizes the portability of the user code to future Python
92versions, which may define additional names beginning with one of
93these prefixes.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000094
Fred Drake659ebfa2000-04-03 15:42:13 +000095The header files are typically installed with Python. On \UNIX, these
96are located in the directories
97\file{\envvar{prefix}/include/python\var{version}/} and
98\file{\envvar{exec_prefix}/include/python\var{version}/}, where
99\envvar{prefix} and \envvar{exec_prefix} are defined by the
100corresponding parameters to Python's \program{configure} script and
101\var{version} is \code{sys.version[:3]}. On Windows, the headers are
102installed in \file{\envvar{prefix}/include}, where \envvar{prefix} is
103the installation directory specified to the installer.
104
105To include the headers, place both directories (if different) on your
106compiler's search path for includes. Do \emph{not} place the parent
107directories on the search path and then use
Fred Draked5d04352000-09-14 20:24:17 +0000108\samp{\#include <python\shortversion/Python.h>}; this will break on
Fred Drake659ebfa2000-04-03 15:42:13 +0000109multi-platform builds since the platform independent headers under
110\envvar{prefix} include the platform specific headers from
111\envvar{exec_prefix}.
112
Fred Drakebab29652001-07-10 16:10:08 +0000113\Cpp{} users should note that though the API is defined entirely using
114C, the header files do properly declare the entry points to be
115\code{extern "C"}, so there is no need to do anything special to use
116the API from \Cpp.
117
Fred Drakeefd146c1999-02-15 15:30:45 +0000118
119\section{Objects, Types and Reference Counts \label{objects}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000120
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000121Most Python/C API functions have one or more arguments as well as a
Fred Drake659ebfa2000-04-03 15:42:13 +0000122return value of type \ctype{PyObject*}. This type is a pointer
Fred Drakee058b4f1998-02-16 06:15:35 +0000123to an opaque data type representing an arbitrary Python
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000124object. Since all Python object types are treated the same way by the
125Python language in most situations (e.g., assignments, scope rules,
126and argument passing), it is only fitting that they should be
Fred Drake659ebfa2000-04-03 15:42:13 +0000127represented by a single C type. Almost all Python objects live on the
128heap: you never declare an automatic or static variable of type
129\ctype{PyObject}, only pointer variables of type \ctype{PyObject*} can
130be declared. The sole exception are the type objects\obindex{type};
131since these must never be deallocated, they are typically static
132\ctype{PyTypeObject} objects.
Guido van Rossum59a61351997-08-14 20:34:33 +0000133
Fred Drakee058b4f1998-02-16 06:15:35 +0000134All Python objects (even Python integers) have a \dfn{type} and a
135\dfn{reference count}. An object's type determines what kind of object
Guido van Rossum4a944d71997-08-14 20:35:38 +0000136it is (e.g., an integer, a list, or a user-defined function; there are
Fred Drakebe486461999-11-09 17:03:03 +0000137many more as explained in the \citetitle[../ref/ref.html]{Python
138Reference Manual}). For each of the well-known types there is a macro
139to check whether an object is of that type; for instance,
Fred Drake659ebfa2000-04-03 15:42:13 +0000140\samp{PyList_Check(\var{a})} is true if (and only if) the object
141pointed to by \var{a} is a Python list.
Guido van Rossum59a61351997-08-14 20:34:33 +0000142
Fred Drakeefd146c1999-02-15 15:30:45 +0000143
144\subsection{Reference Counts \label{refcounts}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000145
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000146The reference count is important because today's computers have a
Fred Drake003d8da1998-04-13 00:53:42 +0000147finite (and often severely limited) memory size; it counts how many
Guido van Rossum4a944d71997-08-14 20:35:38 +0000148different places there are that have a reference to an object. Such a
Fred Drake659ebfa2000-04-03 15:42:13 +0000149place could be another object, or a global (or static) C variable, or
150a local variable in some C function. When an object's reference count
Guido van Rossum4a944d71997-08-14 20:35:38 +0000151becomes zero, the object is deallocated. If it contains references to
152other objects, their reference count is decremented. Those other
153objects may be deallocated in turn, if this decrement makes their
154reference count become zero, and so on. (There's an obvious problem
155with objects that reference each other here; for now, the solution is
Fred Drake659ebfa2000-04-03 15:42:13 +0000156``don't do that.'')
Guido van Rossum59a61351997-08-14 20:34:33 +0000157
Guido van Rossum4a944d71997-08-14 20:35:38 +0000158Reference counts are always manipulated explicitly. The normal way is
Fred Drake659ebfa2000-04-03 15:42:13 +0000159to use the macro \cfunction{Py_INCREF()}\ttindex{Py_INCREF()} to
160increment an object's reference count by one, and
161\cfunction{Py_DECREF()}\ttindex{Py_DECREF()} to decrement it by
162one. The \cfunction{Py_DECREF()} macro is considerably more complex
163than the incref one, since it must check whether the reference count
164becomes zero and then cause the object's deallocator to be called.
165The deallocator is a function pointer contained in the object's type
166structure. The type-specific deallocator takes care of decrementing
167the reference counts for other objects contained in the object if this
168is a compound object type, such as a list, as well as performing any
169additional finalization that's needed. There's no chance that the
170reference count can overflow; at least as many bits are used to hold
171the reference count as there are distinct memory locations in virtual
172memory (assuming \code{sizeof(long) >= sizeof(char*)}). Thus, the
173reference count increment is a simple operation.
Guido van Rossum59a61351997-08-14 20:34:33 +0000174
Guido van Rossum4a944d71997-08-14 20:35:38 +0000175It is not necessary to increment an object's reference count for every
176local variable that contains a pointer to an object. In theory, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000177object's reference count goes up by one when the variable is made to
Guido van Rossum4a944d71997-08-14 20:35:38 +0000178point to it and it goes down by one when the variable goes out of
179scope. However, these two cancel each other out, so at the end the
180reference count hasn't changed. The only real reason to use the
181reference count is to prevent the object from being deallocated as
182long as our variable is pointing to it. If we know that there is at
183least one other reference to the object that lives at least as long as
184our variable, there is no need to increment the reference count
185temporarily. An important situation where this arises is in objects
Fred Drake659ebfa2000-04-03 15:42:13 +0000186that are passed as arguments to C functions in an extension module
Guido van Rossum4a944d71997-08-14 20:35:38 +0000187that are called from Python; the call mechanism guarantees to hold a
Guido van Rossum59a61351997-08-14 20:34:33 +0000188reference to every argument for the duration of the call.
189
Fred Drakee058b4f1998-02-16 06:15:35 +0000190However, a common pitfall is to extract an object from a list and
191hold on to it for a while without incrementing its reference count.
192Some other operation might conceivably remove the object from the
193list, decrementing its reference count and possible deallocating it.
194The real danger is that innocent-looking operations may invoke
195arbitrary Python code which could do this; there is a code path which
196allows control to flow back to the user from a \cfunction{Py_DECREF()},
197so almost any operation is potentially dangerous.
Guido van Rossum59a61351997-08-14 20:34:33 +0000198
Guido van Rossum4a944d71997-08-14 20:35:38 +0000199A safe approach is to always use the generic operations (functions
Fred Drake659ebfa2000-04-03 15:42:13 +0000200whose name begins with \samp{PyObject_}, \samp{PyNumber_},
201\samp{PySequence_} or \samp{PyMapping_}). These operations always
202increment the reference count of the object they return. This leaves
203the caller with the responsibility to call
204\cfunction{Py_DECREF()} when they are done with the result; this soon
205becomes second nature.
Guido van Rossum59a61351997-08-14 20:34:33 +0000206
Fred Drakeefd146c1999-02-15 15:30:45 +0000207
208\subsubsection{Reference Count Details \label{refcountDetails}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000209
210The reference count behavior of functions in the Python/C API is best
Fred Drake659ebfa2000-04-03 15:42:13 +0000211explained in terms of \emph{ownership of references}. Note that we
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000212talk of owning references, never of owning objects; objects are always
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000213shared! When a function owns a reference, it has to dispose of it
Fred Drakee058b4f1998-02-16 06:15:35 +0000214properly --- either by passing ownership on (usually to its caller) or
215by calling \cfunction{Py_DECREF()} or \cfunction{Py_XDECREF()}. When
216a function passes ownership of a reference on to its caller, the
217caller is said to receive a \emph{new} reference. When no ownership
218is transferred, the caller is said to \emph{borrow} the reference.
219Nothing needs to be done for a borrowed reference.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000220
Fred Drakea8455ab2000-06-16 19:58:42 +0000221Conversely, when a calling function passes it a reference to an
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000222object, there are two possibilities: the function \emph{steals} a
223reference to the object, or it does not. Few functions steal
Fred Drakee058b4f1998-02-16 06:15:35 +0000224references; the two notable exceptions are
Fred Drake659ebfa2000-04-03 15:42:13 +0000225\cfunction{PyList_SetItem()}\ttindex{PyList_SetItem()} and
226\cfunction{PyTuple_SetItem()}\ttindex{PyTuple_SetItem()}, which
Fred Drakee058b4f1998-02-16 06:15:35 +0000227steal a reference to the item (but not to the tuple or list into which
Fred Drake003d8da1998-04-13 00:53:42 +0000228the item is put!). These functions were designed to steal a reference
Fred Drakee058b4f1998-02-16 06:15:35 +0000229because of a common idiom for populating a tuple or list with newly
230created objects; for example, the code to create the tuple \code{(1,
2312, "three")} could look like this (forgetting about error handling for
Fred Drake659ebfa2000-04-03 15:42:13 +0000232the moment; a better way to code this is shown below):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000233
234\begin{verbatim}
235PyObject *t;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000236
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000237t = PyTuple_New(3);
238PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
239PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
240PyTuple_SetItem(t, 2, PyString_FromString("three"));
241\end{verbatim}
242
Fred Drakee058b4f1998-02-16 06:15:35 +0000243Incidentally, \cfunction{PyTuple_SetItem()} is the \emph{only} way to
244set tuple items; \cfunction{PySequence_SetItem()} and
245\cfunction{PyObject_SetItem()} refuse to do this since tuples are an
246immutable data type. You should only use
247\cfunction{PyTuple_SetItem()} for tuples that you are creating
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000248yourself.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000249
250Equivalent code for populating a list can be written using
Fred Drakee058b4f1998-02-16 06:15:35 +0000251\cfunction{PyList_New()} and \cfunction{PyList_SetItem()}. Such code
252can also use \cfunction{PySequence_SetItem()}; this illustrates the
253difference between the two (the extra \cfunction{Py_DECREF()} calls):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000254
255\begin{verbatim}
256PyObject *l, *x;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000257
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000258l = PyList_New(3);
259x = PyInt_FromLong(1L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000260PySequence_SetItem(l, 0, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000261x = PyInt_FromLong(2L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000262PySequence_SetItem(l, 1, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000263x = PyString_FromString("three");
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000264PySequence_SetItem(l, 2, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000265\end{verbatim}
266
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000267You might find it strange that the ``recommended'' approach takes more
268code. However, in practice, you will rarely use these ways of
269creating and populating a tuple or list. There's a generic function,
Fred Drakee058b4f1998-02-16 06:15:35 +0000270\cfunction{Py_BuildValue()}, that can create most common objects from
Fred Drake659ebfa2000-04-03 15:42:13 +0000271C values, directed by a \dfn{format string}. For example, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000272above two blocks of code could be replaced by the following (which
273also takes care of the error checking):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000274
275\begin{verbatim}
276PyObject *t, *l;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000277
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000278t = Py_BuildValue("(iis)", 1, 2, "three");
279l = Py_BuildValue("[iis]", 1, 2, "three");
280\end{verbatim}
281
Fred Drakee058b4f1998-02-16 06:15:35 +0000282It is much more common to use \cfunction{PyObject_SetItem()} and
283friends with items whose references you are only borrowing, like
284arguments that were passed in to the function you are writing. In
285that case, their behaviour regarding reference counts is much saner,
286since you don't have to increment a reference count so you can give a
287reference away (``have it be stolen''). For example, this function
288sets all items of a list (actually, any mutable sequence) to a given
289item:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000290
291\begin{verbatim}
292int set_all(PyObject *target, PyObject *item)
293{
294 int i, n;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000295
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000296 n = PyObject_Length(target);
297 if (n < 0)
298 return -1;
299 for (i = 0; i < n; i++) {
300 if (PyObject_SetItem(target, i, item) < 0)
301 return -1;
302 }
303 return 0;
304}
305\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000306\ttindex{set_all()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000307
308The situation is slightly different for function return values.
309While passing a reference to most functions does not change your
310ownership responsibilities for that reference, many functions that
311return a referece to an object give you ownership of the reference.
312The reason is simple: in many cases, the returned object is created
313on the fly, and the reference you get is the only reference to the
Fred Drakee058b4f1998-02-16 06:15:35 +0000314object. Therefore, the generic functions that return object
315references, like \cfunction{PyObject_GetItem()} and
Fred Drakebab29652001-07-10 16:10:08 +0000316\cfunction{PySequence_GetItem()}, always return a new reference (the
317caller becomes the owner of the reference).
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000318
319It is important to realize that whether you own a reference returned
Fred Drakee058b4f1998-02-16 06:15:35 +0000320by a function depends on which function you call only --- \emph{the
Fred Drakebab29652001-07-10 16:10:08 +0000321plumage} (the type of the type of the object passed as an
Fred Drakee058b4f1998-02-16 06:15:35 +0000322argument to the function) \emph{doesn't enter into it!} Thus, if you
323extract an item from a list using \cfunction{PyList_GetItem()}, you
324don't own the reference --- but if you obtain the same item from the
325same list using \cfunction{PySequence_GetItem()} (which happens to
326take exactly the same arguments), you do own a reference to the
327returned object.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000328
Fred Drakee058b4f1998-02-16 06:15:35 +0000329Here is an example of how you could write a function that computes the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000330sum of the items in a list of integers; once using
Fred Drake659ebfa2000-04-03 15:42:13 +0000331\cfunction{PyList_GetItem()}\ttindex{PyList_GetItem()}, and once using
332\cfunction{PySequence_GetItem()}\ttindex{PySequence_GetItem()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000333
334\begin{verbatim}
335long sum_list(PyObject *list)
336{
337 int i, n;
338 long total = 0;
339 PyObject *item;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000340
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000341 n = PyList_Size(list);
342 if (n < 0)
343 return -1; /* Not a list */
344 for (i = 0; i < n; i++) {
345 item = PyList_GetItem(list, i); /* Can't fail */
346 if (!PyInt_Check(item)) continue; /* Skip non-integers */
347 total += PyInt_AsLong(item);
348 }
349 return total;
350}
351\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000352\ttindex{sum_list()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000353
354\begin{verbatim}
355long sum_sequence(PyObject *sequence)
356{
357 int i, n;
358 long total = 0;
359 PyObject *item;
Fred Drake659ebfa2000-04-03 15:42:13 +0000360 n = PySequence_Length(sequence);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000361 if (n < 0)
362 return -1; /* Has no length */
363 for (i = 0; i < n; i++) {
Fred Drake659ebfa2000-04-03 15:42:13 +0000364 item = PySequence_GetItem(sequence, i);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000365 if (item == NULL)
366 return -1; /* Not a sequence, or other failure */
367 if (PyInt_Check(item))
368 total += PyInt_AsLong(item);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000369 Py_DECREF(item); /* Discard reference ownership */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000370 }
371 return total;
372}
373\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000374\ttindex{sum_sequence()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000375
Fred Drakeefd146c1999-02-15 15:30:45 +0000376
377\subsection{Types \label{types}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000378
379There are few other data types that play a significant role in
Fred Drake659ebfa2000-04-03 15:42:13 +0000380the Python/C API; most are simple C types such as \ctype{int},
381\ctype{long}, \ctype{double} and \ctype{char*}. A few structure types
Guido van Rossum4a944d71997-08-14 20:35:38 +0000382are used to describe static tables used to list the functions exported
Fred Drake659ebfa2000-04-03 15:42:13 +0000383by a module or the data attributes of a new object type, and another
384is used to describe the value of a complex number. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000385be discussed together with the functions that use them.
386
Fred Drakeefd146c1999-02-15 15:30:45 +0000387
388\section{Exceptions \label{exceptions}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000389
Guido van Rossum4a944d71997-08-14 20:35:38 +0000390The Python programmer only needs to deal with exceptions if specific
391error handling is required; unhandled exceptions are automatically
Fred Drake659ebfa2000-04-03 15:42:13 +0000392propagated to the caller, then to the caller's caller, and so on, until
Guido van Rossum4a944d71997-08-14 20:35:38 +0000393they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000394user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000395
Fred Drake659ebfa2000-04-03 15:42:13 +0000396For C programmers, however, error checking always has to be explicit.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000397All functions in the Python/C API can raise exceptions, unless an
398explicit claim is made otherwise in a function's documentation. In
399general, when a function encounters an error, it sets an exception,
400discards any object references that it owns, and returns an
Fred Drakee058b4f1998-02-16 06:15:35 +0000401error indicator --- usually \NULL{} or \code{-1}. A few functions
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000402return a Boolean true/false result, with false indicating an error.
403Very few functions return no explicit error indicator or have an
404ambiguous return value, and require explicit testing for errors with
Fred Drake659ebfa2000-04-03 15:42:13 +0000405\cfunction{PyErr_Occurred()}\ttindex{PyErr_Occurred()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000406
407Exception state is maintained in per-thread storage (this is
408equivalent to using global storage in an unthreaded application). A
Fred Drakec6fa34e1998-04-02 06:47:24 +0000409thread can be in one of two states: an exception has occurred, or not.
Fred Drakee058b4f1998-02-16 06:15:35 +0000410The function \cfunction{PyErr_Occurred()} can be used to check for
411this: it returns a borrowed reference to the exception type object
412when an exception has occurred, and \NULL{} otherwise. There are a
413number of functions to set the exception state:
Fred Drake659ebfa2000-04-03 15:42:13 +0000414\cfunction{PyErr_SetString()}\ttindex{PyErr_SetString()} is the most
415common (though not the most general) function to set the exception
416state, and \cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} clears the
417exception state.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000418
419The full exception state consists of three objects (all of which can
Fred Drakee058b4f1998-02-16 06:15:35 +0000420be \NULL{}): the exception type, the corresponding exception
Fred Drake659ebfa2000-04-03 15:42:13 +0000421value, and the traceback. These have the same meanings as the Python
422\withsubitem{(in module sys)}{
423 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
424objects \code{sys.exc_type}, \code{sys.exc_value}, and
425\code{sys.exc_traceback}; however, they are not the same: the Python
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000426objects represent the last exception being handled by a Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000427\keyword{try} \ldots\ \keyword{except} statement, while the C level
Fred Drakee058b4f1998-02-16 06:15:35 +0000428exception state only exists while an exception is being passed on
Fred Drake659ebfa2000-04-03 15:42:13 +0000429between C functions until it reaches the Python bytecode interpreter's
430main loop, which takes care of transferring it to \code{sys.exc_type}
431and friends.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000432
Fred Drakec6fa34e1998-04-02 06:47:24 +0000433Note that starting with Python 1.5, the preferred, thread-safe way to
Fred Drake659ebfa2000-04-03 15:42:13 +0000434access the exception state from Python code is to call the function
435\withsubitem{(in module sys)}{\ttindex{exc_info()}}
Fred Drakee058b4f1998-02-16 06:15:35 +0000436\function{sys.exc_info()}, which returns the per-thread exception state
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000437for Python code. Also, the semantics of both ways to access the
438exception state have changed so that a function which catches an
439exception will save and restore its thread's exception state so as to
440preserve the exception state of its caller. This prevents common bugs
441in exception handling code caused by an innocent-looking function
442overwriting the exception being handled; it also reduces the often
443unwanted lifetime extension for objects that are referenced by the
Fred Drakec6fa34e1998-04-02 06:47:24 +0000444stack frames in the traceback.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000445
446As a general principle, a function that calls another function to
447perform some task should check whether the called function raised an
448exception, and if so, pass the exception state on to its caller. It
Fred Drake659ebfa2000-04-03 15:42:13 +0000449should discard any object references that it owns, and return an
Fred Drakee058b4f1998-02-16 06:15:35 +0000450error indicator, but it should \emph{not} set another exception ---
451that would overwrite the exception that was just raised, and lose
452important information about the exact cause of the error.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000453
Fred Drake659ebfa2000-04-03 15:42:13 +0000454A simple example of detecting exceptions and passing them on is shown
455in the \cfunction{sum_sequence()}\ttindex{sum_sequence()} example
456above. It so happens that that example doesn't need to clean up any
457owned references when it detects an error. The following example
458function shows some error cleanup. First, to remind you why you like
459Python, we show the equivalent Python code:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000460
461\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000462def incr_item(dict, key):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000463 try:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000464 item = dict[key]
465 except KeyError:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000466 item = 0
Fred Drake6b3f3f22000-11-29 15:48:22 +0000467 dict[key] = item + 1
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000468\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000469\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000470
Fred Drake659ebfa2000-04-03 15:42:13 +0000471Here is the corresponding C code, in all its glory:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000472
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000473\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000474int incr_item(PyObject *dict, PyObject *key)
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000475{
476 /* Objects all initialized to NULL for Py_XDECREF */
477 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000478 int rv = -1; /* Return value initialized to -1 (failure) */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000479
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000480 item = PyObject_GetItem(dict, key);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000481 if (item == NULL) {
Fred Drakec6fa34e1998-04-02 06:47:24 +0000482 /* Handle KeyError only: */
Fred Drake6b3f3f22000-11-29 15:48:22 +0000483 if (!PyErr_ExceptionMatches(PyExc_KeyError))
484 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000485
486 /* Clear the error and use zero: */
487 PyErr_Clear();
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000488 item = PyInt_FromLong(0L);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000489 if (item == NULL)
490 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000491 }
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000492 const_one = PyInt_FromLong(1L);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000493 if (const_one == NULL)
494 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000495
496 incremented_item = PyNumber_Add(item, const_one);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000497 if (incremented_item == NULL)
498 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000499
Fred Drake6b3f3f22000-11-29 15:48:22 +0000500 if (PyObject_SetItem(dict, key, incremented_item) < 0)
501 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000502 rv = 0; /* Success */
503 /* Continue with cleanup code */
504
505 error:
506 /* Cleanup code, shared by success and failure path */
507
508 /* Use Py_XDECREF() to ignore NULL references */
509 Py_XDECREF(item);
510 Py_XDECREF(const_one);
511 Py_XDECREF(incremented_item);
512
513 return rv; /* -1 for error, 0 for success */
514}
515\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000516\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000517
Fred Drakef8830d11998-04-23 14:06:01 +0000518This example represents an endorsed use of the \keyword{goto} statement
Fred Drake659ebfa2000-04-03 15:42:13 +0000519in C! It illustrates the use of
520\cfunction{PyErr_ExceptionMatches()}\ttindex{PyErr_ExceptionMatches()} and
521\cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} to
522handle specific exceptions, and the use of
523\cfunction{Py_XDECREF()}\ttindex{Py_XDECREF()} to
524dispose of owned references that may be \NULL{} (note the
525\character{X} in the name; \cfunction{Py_DECREF()} would crash when
526confronted with a \NULL{} reference). It is important that the
527variables used to hold owned references are initialized to \NULL{} for
528this to work; likewise, the proposed return value is initialized to
529\code{-1} (failure) and only set to success after the final call made
530is successful.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000531
Guido van Rossum59a61351997-08-14 20:34:33 +0000532
Fred Drakeefd146c1999-02-15 15:30:45 +0000533\section{Embedding Python \label{embedding}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000534
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000535The one important task that only embedders (as opposed to extension
536writers) of the Python interpreter have to worry about is the
537initialization, and possibly the finalization, of the Python
538interpreter. Most functionality of the interpreter can only be used
539after the interpreter has been initialized.
Guido van Rossum59a61351997-08-14 20:34:33 +0000540
Fred Drake659ebfa2000-04-03 15:42:13 +0000541The basic initialization function is
542\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Fred Drakee058b4f1998-02-16 06:15:35 +0000543This initializes the table of loaded modules, and creates the
Fred Drake4de05a91998-02-16 14:25:26 +0000544fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake680cabb2001-08-14 15:32:16 +0000545\module{__main__}\refbimodindex{__main__}, \module{sys}\refbimodindex{sys},
546and \module{exceptions}.\refbimodindex{exceptions} It also initializes
547the module search path (\code{sys.path}).%
Fred Drakec6fa34e1998-04-02 06:47:24 +0000548\indexiii{module}{search}{path}
Fred Drake659ebfa2000-04-03 15:42:13 +0000549\withsubitem{(in module sys)}{\ttindex{path}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000550
Fred Drakee058b4f1998-02-16 06:15:35 +0000551\cfunction{Py_Initialize()} does not set the ``script argument list''
Guido van Rossum4a944d71997-08-14 20:35:38 +0000552(\code{sys.argv}). If this variable is needed by Python code that
553will be executed later, it must be set explicitly with a call to
Fred Drake659ebfa2000-04-03 15:42:13 +0000554\code{PySys_SetArgv(\var{argc},
555\var{argv})}\ttindex{PySys_SetArgv()} subsequent to the call to
556\cfunction{Py_Initialize()}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000557
Fred Drakeb0a78731998-01-13 18:51:10 +0000558On most systems (in particular, on \UNIX{} and Windows, although the
Fred Drake659ebfa2000-04-03 15:42:13 +0000559details are slightly different),
560\cfunction{Py_Initialize()} calculates the module search path based
561upon its best guess for the location of the standard Python
562interpreter executable, assuming that the Python library is found in a
563fixed location relative to the Python interpreter executable. In
564particular, it looks for a directory named
Fred Draked5d04352000-09-14 20:24:17 +0000565\file{lib/python\shortversion} relative to the parent directory where
566the executable named \file{python} is found on the shell command
567search path (the environment variable \envvar{PATH}).
Guido van Rossum42cefd01997-10-05 15:27:29 +0000568
569For instance, if the Python executable is found in
Fred Drakee058b4f1998-02-16 06:15:35 +0000570\file{/usr/local/bin/python}, it will assume that the libraries are in
Fred Draked5d04352000-09-14 20:24:17 +0000571\file{/usr/local/lib/python\shortversion}. (In fact, this particular path
Fred Drakee058b4f1998-02-16 06:15:35 +0000572is also the ``fallback'' location, used when no executable file named
Fred Drakec6fa34e1998-04-02 06:47:24 +0000573\file{python} is found along \envvar{PATH}.) The user can override
574this behavior by setting the environment variable \envvar{PYTHONHOME},
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000575or insert additional directories in front of the standard path by
Fred Drakec6fa34e1998-04-02 06:47:24 +0000576setting \envvar{PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000577
Guido van Rossum4a944d71997-08-14 20:35:38 +0000578The embedding application can steer the search by calling
Fred Drake659ebfa2000-04-03 15:42:13 +0000579\code{Py_SetProgramName(\var{file})}\ttindex{Py_SetProgramName()} \emph{before} calling
Fred Drakec6fa34e1998-04-02 06:47:24 +0000580\cfunction{Py_Initialize()}. Note that \envvar{PYTHONHOME} still
581overrides this and \envvar{PYTHONPATH} is still inserted in front of
Fred Drakee058b4f1998-02-16 06:15:35 +0000582the standard path. An application that requires total control has to
Fred Drake659ebfa2000-04-03 15:42:13 +0000583provide its own implementation of
584\cfunction{Py_GetPath()}\ttindex{Py_GetPath()},
585\cfunction{Py_GetPrefix()}\ttindex{Py_GetPrefix()},
586\cfunction{Py_GetExecPrefix()}\ttindex{Py_GetExecPrefix()}, and
587\cfunction{Py_GetProgramFullPath()}\ttindex{Py_GetProgramFullPath()} (all
588defined in \file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000589
Guido van Rossum4a944d71997-08-14 20:35:38 +0000590Sometimes, it is desirable to ``uninitialize'' Python. For instance,
591the application may want to start over (make another call to
Fred Drakee058b4f1998-02-16 06:15:35 +0000592\cfunction{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000593use of Python and wants to free all memory allocated by Python. This
Fred Drakee058b4f1998-02-16 06:15:35 +0000594can be accomplished by calling \cfunction{Py_Finalize()}. The function
Fred Drake659ebfa2000-04-03 15:42:13 +0000595\cfunction{Py_IsInitialized()}\ttindex{Py_IsInitialized()} returns
596true if Python is currently in the initialized state. More
597information about these functions is given in a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000598
Guido van Rossum4a944d71997-08-14 20:35:38 +0000599
Fred Drakeefd146c1999-02-15 15:30:45 +0000600\chapter{The Very High Level Layer \label{veryhigh}}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000601
Fred Drakee5bf8b21998-02-12 21:22:28 +0000602The functions in this chapter will let you execute Python source code
603given in a file or a buffer, but they will not let you interact in a
604more detailed way with the interpreter.
Guido van Rossum4a944d71997-08-14 20:35:38 +0000605
Fred Drake659ebfa2000-04-03 15:42:13 +0000606Several of these functions accept a start symbol from the grammar as a
607parameter. The available start symbols are \constant{Py_eval_input},
608\constant{Py_file_input}, and \constant{Py_single_input}. These are
609described following the functions which accept them as parameters.
610
Fred Drake510d08b2000-08-14 02:50:21 +0000611Note also that several of these functions take \ctype{FILE*}
612parameters. On particular issue which needs to be handled carefully
613is that the \ctype{FILE} structure for different C libraries can be
614different and incompatible. Under Windows (at least), it is possible
615for dynamically linked extensions to actually use different libraries,
616so care should be taken that \ctype{FILE*} parameters are only passed
617to these functions if it is certain that they were created by the same
618library that the Python runtime is using.
619
Fred Drake24e62192001-05-21 15:56:55 +0000620\begin{cfuncdesc}{int}{Py_Main}{int argc, char **argv}
621 The main program for the standard interpreter. This is made
622 available for programs which embed Python. The \var{argc} and
623 \var{argv} parameters should be prepared exactly as those which are
624 passed to a C program's \cfunction{main()} function. It is
625 important to note that the argument list may be modified (but the
626 contents of the strings pointed to by the argument list are not).
627 The return value will be the integer passed to the
628 \function{sys.exit()} function, \code{1} if the interpreter exits
629 due to an exception, or \code{2} if the parameter list does not
630 represent a valid Python command line.
631\end{cfuncdesc}
632
Fred Drakec6fa34e1998-04-02 06:47:24 +0000633\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000634 If \var{fp} refers to a file associated with an interactive device
635 (console or terminal input or \UNIX{} pseudo-terminal), return the
636 value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
637 result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
Fred Drakea8d73412000-08-11 20:39:29 +0000638 \NULL{}, this function uses \code{"???"} as the filename.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000639\end{cfuncdesc}
640
Fred Drakec6fa34e1998-04-02 06:47:24 +0000641\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
Fred Drake0041a941999-04-29 04:20:46 +0000642 Executes the Python source code from \var{command} in the
643 \module{__main__} module. If \module{__main__} does not already
644 exist, it is created. Returns \code{0} on success or \code{-1} if
645 an exception was raised. If there was an error, there is no way to
646 get the exception information.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000647\end{cfuncdesc}
648
Fred Drakec6fa34e1998-04-02 06:47:24 +0000649\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000650 Similar to \cfunction{PyRun_SimpleString()}, but the Python source
651 code is read from \var{fp} instead of an in-memory string.
652 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000653\end{cfuncdesc}
654
Fred Drakec6fa34e1998-04-02 06:47:24 +0000655\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000656 Read and execute a single statement from a file associated with an
657 interactive device. If \var{filename} is \NULL, \code{"???"} is
658 used instead. The user will be prompted using \code{sys.ps1} and
659 \code{sys.ps2}. Returns \code{0} when the input was executed
660 successfully, \code{-1} if there was an exception, or an error code
661 from the \file{errcode.h} include file distributed as part of Python
662 in case of a parse error. (Note that \file{errcode.h} is not
663 included by \file{Python.h}, so must be included specifically if
664 needed.)
Fred Drakee5bf8b21998-02-12 21:22:28 +0000665\end{cfuncdesc}
666
Fred Drakec6fa34e1998-04-02 06:47:24 +0000667\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000668 Read and execute statements from a file associated with an
669 interactive device until \EOF{} is reached. If \var{filename} is
670 \NULL, \code{"???"} is used instead. The user will be prompted
671 using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000672\end{cfuncdesc}
673
Fred Drakec6fa34e1998-04-02 06:47:24 +0000674\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
675 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000676 Parse Python source code from \var{str} using the start token
677 \var{start}. The result can be used to create a code object which
678 can be evaluated efficiently. This is useful if a code fragment
679 must be evaluated many times.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000680\end{cfuncdesc}
681
Fred Drakec6fa34e1998-04-02 06:47:24 +0000682\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
683 char *filename, int start}
Fred Drake0041a941999-04-29 04:20:46 +0000684 Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
685 source code is read from \var{fp} instead of an in-memory string.
686 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000687\end{cfuncdesc}
688
Fred Drakec6fa34e1998-04-02 06:47:24 +0000689\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
690 PyObject *globals,
691 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000692 Execute Python source code from \var{str} in the context specified
693 by the dictionaries \var{globals} and \var{locals}. The parameter
694 \var{start} specifies the start token that should be used to parse
695 the source code.
696
697 Returns the result of executing the code as a Python object, or
698 \NULL{} if an exception was raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000699\end{cfuncdesc}
700
Fred Drakec6fa34e1998-04-02 06:47:24 +0000701\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
702 int start, PyObject *globals,
703 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000704 Similar to \cfunction{PyRun_String()}, but the Python source code is
Fred Drake659ebfa2000-04-03 15:42:13 +0000705 read from \var{fp} instead of an in-memory string.
706 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000707\end{cfuncdesc}
708
Fred Drakec6fa34e1998-04-02 06:47:24 +0000709\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
710 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000711 Parse and compile the Python source code in \var{str}, returning the
712 resulting code object. The start token is given by \var{start};
Fred Drakec924b8d1999-08-23 18:57:25 +0000713 this can be used to constrain the code which can be compiled and should
714 be \constant{Py_eval_input}, \constant{Py_file_input}, or
715 \constant{Py_single_input}. The filename specified by
716 \var{filename} is used to construct the code object and may appear
717 in tracebacks or \exception{SyntaxError} exception messages. This
718 returns \NULL{} if the code cannot be parsed or compiled.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000719\end{cfuncdesc}
720
Fred Drakec924b8d1999-08-23 18:57:25 +0000721\begin{cvardesc}{int}{Py_eval_input}
722 The start symbol from the Python grammar for isolated expressions;
Fred Drake659ebfa2000-04-03 15:42:13 +0000723 for use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
Fred Drakec924b8d1999-08-23 18:57:25 +0000724\end{cvardesc}
725
726\begin{cvardesc}{int}{Py_file_input}
727 The start symbol from the Python grammar for sequences of statements
728 as read from a file or other source; for use with
Fred Drake659ebfa2000-04-03 15:42:13 +0000729 \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
730 the symbol to use when compiling arbitrarily long Python source code.
Fred Drakec924b8d1999-08-23 18:57:25 +0000731\end{cvardesc}
732
733\begin{cvardesc}{int}{Py_single_input}
734 The start symbol from the Python grammar for a single statement; for
Fred Drake659ebfa2000-04-03 15:42:13 +0000735 use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
736 This is the symbol used for the interactive interpreter loop.
Fred Drakec924b8d1999-08-23 18:57:25 +0000737\end{cvardesc}
738
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000739
Fred Drakeefd146c1999-02-15 15:30:45 +0000740\chapter{Reference Counting \label{countingRefs}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000741
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000742The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000743of Python objects.
744
745\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
Fred Drakec6fa34e1998-04-02 06:47:24 +0000746Increment the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000747not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000748\cfunction{Py_XINCREF()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000749\end{cfuncdesc}
750
751\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000752Increment the reference count for object \var{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000753\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000754\end{cfuncdesc}
755
756\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000757Decrement the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000758not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000759\cfunction{Py_XDECREF()}. If the reference count reaches zero, the
760object's type's deallocation function (which must not be \NULL{}) is
761invoked.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000762
763\strong{Warning:} The deallocation function can cause arbitrary Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000764code to be invoked (e.g. when a class instance with a
765\method{__del__()} method is deallocated). While exceptions in such
766code are not propagated, the executed code has free access to all
767Python global variables. This means that any object that is reachable
768from a global variable should be in a consistent state before
769\cfunction{Py_DECREF()} is invoked. For example, code to delete an
770object from a list should copy a reference to the deleted object in a
771temporary variable, update the list data structure, and then call
772\cfunction{Py_DECREF()} for the temporary variable.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000773\end{cfuncdesc}
774
775\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000776Decrement the reference count for object \var{o}. The object may be
777\NULL{}, in which case the macro has no effect; otherwise the effect
778is the same as for \cfunction{Py_DECREF()}, and the same warning
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000779applies.
780\end{cfuncdesc}
781
Fred Drake659ebfa2000-04-03 15:42:13 +0000782The following functions or macros are only for use within the
783interpreter core: \cfunction{_Py_Dealloc()},
784\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
785well as the global variable \cdata{_Py_RefTotal}.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000786
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000787
Fred Drakeefd146c1999-02-15 15:30:45 +0000788\chapter{Exception Handling \label{exceptionHandling}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000789
Fred Drake659ebfa2000-04-03 15:42:13 +0000790The functions described in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000791exceptions. It is important to understand some of the basics of
Fred Drake659ebfa2000-04-03 15:42:13 +0000792Python exception handling. It works somewhat like the
793\UNIX{} \cdata{errno} variable: there is a global indicator (per
794thread) of the last error that occurred. Most functions don't clear
795this on success, but will set it to indicate the cause of the error on
796failure. Most functions also return an error indicator, usually
797\NULL{} if they are supposed to return a pointer, or \code{-1} if they
798return an integer (exception: the \cfunction{PyArg_Parse*()} functions
799return \code{1} for success and \code{0} for failure). When a
800function must fail because some function it called failed, it
801generally doesn't set the error indicator; the function it called
802already set it.
Guido van Rossumae110af1997-05-22 20:11:52 +0000803
804The error indicator consists of three Python objects corresponding to
Fred Drake659ebfa2000-04-03 15:42:13 +0000805\withsubitem{(in module sys)}{
806 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000807the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
808\code{sys.exc_traceback}. API functions exist to interact with the
809error indicator in various ways. There is a separate error indicator
810for each thread.
811
812% XXX Order of these should be more thoughtful.
813% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000814
815\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000816Print a standard traceback to \code{sys.stderr} and clear the error
817indicator. Call this function only when the error indicator is set.
818(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000819\end{cfuncdesc}
820
Fred Drakec6fa34e1998-04-02 06:47:24 +0000821\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000822Test whether the error indicator is set. If set, return the exception
Fred Drakee058b4f1998-02-16 06:15:35 +0000823\emph{type} (the first argument to the last call to one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000824\cfunction{PyErr_Set*()} functions or to \cfunction{PyErr_Restore()}). If
Fred Drakee058b4f1998-02-16 06:15:35 +0000825not set, return \NULL{}. You do not own a reference to the return
826value, so you do not need to \cfunction{Py_DECREF()} it.
Fred Drake659ebfa2000-04-03 15:42:13 +0000827\strong{Note:} Do not compare the return value to a specific
Fred Drakee058b4f1998-02-16 06:15:35 +0000828exception; use \cfunction{PyErr_ExceptionMatches()} instead, shown
Fred Drake659ebfa2000-04-03 15:42:13 +0000829below. (The comparison could easily fail since the exception may be
830an instance instead of a class, in the case of a class exception, or
831it may the a subclass of the expected exception.)
Guido van Rossum42cefd01997-10-05 15:27:29 +0000832\end{cfuncdesc}
833
834\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000835Equivalent to
Fred Drakee058b4f1998-02-16 06:15:35 +0000836\samp{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
Fred Drake659ebfa2000-04-03 15:42:13 +0000837This should only be called when an exception is actually set; a memory
838access violation will occur if no exception has been raised.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000839\end{cfuncdesc}
840
841\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000842Return true if the \var{given} exception matches the exception in
843\var{exc}. If \var{exc} is a class object, this also returns true
Fred Drake659ebfa2000-04-03 15:42:13 +0000844when \var{given} is an instance of a subclass. If \var{exc} is a tuple, all
Guido van Rossum42cefd01997-10-05 15:27:29 +0000845exceptions in the tuple (and recursively in subtuples) are searched
Fred Drake659ebfa2000-04-03 15:42:13 +0000846for a match. If \var{given} is \NULL, a memory access violation will
847occur.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000848\end{cfuncdesc}
849
850\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000851Under certain circumstances, the values returned by
Fred Drakee058b4f1998-02-16 06:15:35 +0000852\cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning that
853\code{*\var{exc}} is a class object but \code{*\var{val}} is not an
854instance of the same class. This function can be used to instantiate
855the class in that case. If the values are already normalized, nothing
Fred Drake659ebfa2000-04-03 15:42:13 +0000856happens. The delayed normalization is implemented to improve
857performance.
Guido van Rossumae110af1997-05-22 20:11:52 +0000858\end{cfuncdesc}
859
860\begin{cfuncdesc}{void}{PyErr_Clear}{}
861Clear the error indicator. If the error indicator is not set, there
862is no effect.
863\end{cfuncdesc}
864
Fred Drake659ebfa2000-04-03 15:42:13 +0000865\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
866 PyObject **ptraceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000867Retrieve the error indicator into three variables whose addresses are
868passed. If the error indicator is not set, set all three variables to
869\NULL{}. If it is set, it will be cleared and you own a reference to
Fred Drake659ebfa2000-04-03 15:42:13 +0000870each object retrieved. The value and traceback object may be
871\NULL{} even when the type object is not. \strong{Note:} This
872function is normally only used by code that needs to handle exceptions
873or by code that needs to save and restore the error indicator
874temporarily.
Guido van Rossumae110af1997-05-22 20:11:52 +0000875\end{cfuncdesc}
876
Fred Drake17e63432000-08-31 05:50:40 +0000877\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
878 PyObject *traceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000879Set the error indicator from the three objects. If the error
880indicator is already set, it is cleared first. If the objects are
881\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
882and non-\NULL{} value or traceback. The exception type should be a
883string or class; if it is a class, the value should be an instance of
884that class. Do not pass an invalid exception type or value.
885(Violating these rules will cause subtle problems later.) This call
Fred Drakebab29652001-07-10 16:10:08 +0000886takes away a reference to each object: you must own a reference
Guido van Rossumae110af1997-05-22 20:11:52 +0000887to each object before the call and after the call you no longer own
888these references. (If you don't understand this, don't use this
Fred Drake659ebfa2000-04-03 15:42:13 +0000889function. I warned you.) \strong{Note:} This function is normally
Guido van Rossumae110af1997-05-22 20:11:52 +0000890only used by code that needs to save and restore the error indicator
891temporarily.
892\end{cfuncdesc}
893
894\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
895This is the most common way to set the error indicator. The first
896argument specifies the exception type; it is normally one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000897standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
Guido van Rossumae110af1997-05-22 20:11:52 +0000898increment its reference count. The second argument is an error
899message; it is converted to a string object.
900\end{cfuncdesc}
901
902\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +0000903This function is similar to \cfunction{PyErr_SetString()} but lets you
Guido van Rossumae110af1997-05-22 20:11:52 +0000904specify an arbitrary Python object for the ``value'' of the exception.
905You need not increment its reference count.
906\end{cfuncdesc}
907
Fred Drake73577702000-04-10 18:50:14 +0000908\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
Moshe Zadka57a59322000-09-01 09:47:20 +0000909 const char *format, \moreargs}
Fred Drake89fb0352000-10-14 05:49:30 +0000910This function sets the error indicator. \var{exception} should be a
911Python exception (string or class, not an instance).
Fred Drake5566c1c2001-01-19 22:48:33 +0000912\var{format} should be a string, containing format codes, similar to
Moshe Zadka57a59322000-09-01 09:47:20 +0000913\cfunction{printf}. The \code{width.precision} before a format code
914is parsed, but the width part is ignored.
915
916\begin{tableii}{c|l}{character}{Character}{Meaning}
917 \lineii{c}{Character, as an \ctype{int} parameter}
918 \lineii{d}{Number in decimal, as an \ctype{int} parameter}
919 \lineii{x}{Number in hexadecimal, as an \ctype{int} parameter}
920 \lineii{x}{A string, as a \ctype{char *} parameter}
921\end{tableii}
922
923An unrecognized format character causes all the rest of
924the format string to be copied as-is to the result string,
925and any extra arguments discarded.
926
927A new reference is returned, which is owned by the caller.
Jeremy Hylton98605b52000-04-10 18:40:57 +0000928\end{cfuncdesc}
929
Guido van Rossumae110af1997-05-22 20:11:52 +0000930\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +0000931This is a shorthand for \samp{PyErr_SetObject(\var{type}, Py_None)}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000932\end{cfuncdesc}
933
934\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000935This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000936\var{message})}, where \var{message} indicates that a built-in operation
937was invoked with an illegal argument. It is mostly for internal use.
938\end{cfuncdesc}
939
Fred Drakec6fa34e1998-04-02 06:47:24 +0000940\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000941This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
Guido van Rossumae110af1997-05-22 20:11:52 +0000942returns \NULL{} so an object allocation function can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000943\samp{return PyErr_NoMemory();} when it runs out of memory.
Guido van Rossumae110af1997-05-22 20:11:52 +0000944\end{cfuncdesc}
945
Fred Drakec6fa34e1998-04-02 06:47:24 +0000946\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
Fred Drake659ebfa2000-04-03 15:42:13 +0000947This is a convenience function to raise an exception when a C library
948function has returned an error and set the C variable \cdata{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000949It constructs a tuple object whose first item is the integer
Fred Drakef8830d11998-04-23 14:06:01 +0000950\cdata{errno} value and whose second item is the corresponding error
Fred Drake659ebfa2000-04-03 15:42:13 +0000951message (gotten from \cfunction{strerror()}\ttindex{strerror()}), and
952then calls
Fred Drakee058b4f1998-02-16 06:15:35 +0000953\samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
Fred Drakef8830d11998-04-23 14:06:01 +0000954the \cdata{errno} value is \constant{EINTR}, indicating an interrupted
Fred Drakee058b4f1998-02-16 06:15:35 +0000955system call, this calls \cfunction{PyErr_CheckSignals()}, and if that set
Guido van Rossumae110af1997-05-22 20:11:52 +0000956the error indicator, leaves it set to that. The function always
957returns \NULL{}, so a wrapper function around a system call can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000958\samp{return PyErr_SetFromErrno();} when the system call returns an
959error.
Guido van Rossumae110af1997-05-22 20:11:52 +0000960\end{cfuncdesc}
961
Fred Drake490d34d2001-06-20 21:39:12 +0000962\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrnoWithFilename}{PyObject *type,
963 char *filename}
964Similar to \cfunction{PyErr_SetFromErrno()}, with the additional
965behavior that if \var{filename} is not \NULL, it is passed to the
966constructor of \var{type} as a third parameter. In the case of
967exceptions such as \exception{IOError} and \exception{OSError}, this
968is used to define the \member{filename} attribute of the exception
969instance.
970\end{cfuncdesc}
971
Guido van Rossumae110af1997-05-22 20:11:52 +0000972\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000973This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000974\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000975operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000976argument. It is mostly for internal use.
977\end{cfuncdesc}
978
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000979\begin{cfuncdesc}{int}{PyErr_Warn}{PyObject *category, char *message}
980Issue a warning message. The \var{category} argument is a warning
Fred Drake5566c1c2001-01-19 22:48:33 +0000981category (see below) or \NULL; the \var{message} argument is a message
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000982string.
983
984This function normally prints a warning message to \var{sys.stderr};
985however, it is also possible that the user has specified that warnings
986are to be turned into errors, and in that case this will raise an
987exception. It is also possible that the function raises an exception
988because of a problem with the warning machinery (the implementation
989imports the \module{warnings} module to do the heavy lifting). The
990return value is \code{0} if no exception is raised, or \code{-1} if
991an exception is raised. (It is not possible to determine whether a
992warning message is actually printed, nor what the reason is for the
993exception; this is intentional.) If an exception is raised, the
Fred Drake5566c1c2001-01-19 22:48:33 +0000994caller should do its normal exception handling
995(e.g. \cfunction{Py_DECREF()} owned references and return an error
996value).
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000997
998Warning categories must be subclasses of \cdata{Warning}; the default
999warning category is \cdata{RuntimeWarning}. The standard Python
1000warning categories are available as global variables whose names are
1001\samp{PyExc_} followed by the Python exception name. These have the
1002type \ctype{PyObject*}; they are all class objects. Their names are
1003\cdata{PyExc_Warning}, \cdata{PyExc_UserWarning},
1004\cdata{PyExc_DeprecationWarning}, \cdata{PyExc_SyntaxWarning}, and
1005\cdata{PyExc_RuntimeWarning}. \cdata{PyExc_Warning} is a subclass of
1006\cdata{PyExc_Exception}; the other warning categories are subclasses
1007of \cdata{PyExc_Warning}.
1008
1009For information about warning control, see the documentation for the
Fred Drake316ef7c2001-01-04 05:56:34 +00001010\module{warnings} module and the \programopt{-W} option in the command
1011line documentation. There is no C API for warning control.
Guido van Rossum3dbb4062000-12-19 03:53:01 +00001012\end{cfuncdesc}
1013
Guido van Rossum1874c8f2001-02-28 23:46:44 +00001014\begin{cfuncdesc}{int}{PyErr_WarnExplicit}{PyObject *category, char *message,
1015char *filename, int lineno, char *module, PyObject *registry}
1016Issue a warning message with explicit control over all warning
1017attributes. This is a straightforward wrapper around the Python
1018function \function{warnings.warn_explicit()}, see there for more
1019information. The \var{module} and \var{registry} arguments may be
1020set to \code{NULL} to get the default effect described there.
1021\end{cfuncdesc}
1022
Guido van Rossumae110af1997-05-22 20:11:52 +00001023\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
1024This function interacts with Python's signal handling. It checks
1025whether a signal has been sent to the processes and if so, invokes the
Fred Drake4de05a91998-02-16 14:25:26 +00001026corresponding signal handler. If the
1027\module{signal}\refbimodindex{signal} module is supported, this can
1028invoke a signal handler written in Python. In all cases, the default
Fred Drake659ebfa2000-04-03 15:42:13 +00001029effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
1030\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
1031\exception{KeyboardInterrupt} exception. If an exception is raised the
Fred Drakee058b4f1998-02-16 06:15:35 +00001032error indicator is set and the function returns \code{1}; otherwise
1033the function returns \code{0}. The error indicator may or may not be
1034cleared if it was previously set.
Guido van Rossumae110af1997-05-22 20:11:52 +00001035\end{cfuncdesc}
1036
1037\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001038This function is obsolete. It simulates the effect of a
1039\constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
Fred Drakee058b4f1998-02-16 06:15:35 +00001040\cfunction{PyErr_CheckSignals()} is called,
Fred Drake659ebfa2000-04-03 15:42:13 +00001041\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
1042\exception{KeyboardInterrupt} will be raised.
1043It may be called without holding the interpreter lock.
Guido van Rossumae110af1997-05-22 20:11:52 +00001044\end{cfuncdesc}
1045
Fred Drakec6fa34e1998-04-02 06:47:24 +00001046\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
1047 PyObject *base,
1048 PyObject *dict}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001049This utility function creates and returns a new exception object. The
Fred Drake659ebfa2000-04-03 15:42:13 +00001050\var{name} argument must be the name of the new exception, a C string
1051of the form \code{module.class}. The \var{base} and
Fred Draked04038d2000-06-29 20:15:14 +00001052\var{dict} arguments are normally \NULL{}. This creates a
Fred Drake659ebfa2000-04-03 15:42:13 +00001053class object derived from the root for all exceptions, the built-in
1054name \exception{Exception} (accessible in C as
Fred Draked04038d2000-06-29 20:15:14 +00001055\cdata{PyExc_Exception}). The \member{__module__} attribute of the
1056new class is set to the first part (up to the last dot) of the
1057\var{name} argument, and the class name is set to the last part (after
1058the last dot). The \var{base} argument can be used to specify an
1059alternate base class. The \var{dict} argument can be used to specify
1060a dictionary of class variables and methods.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001061\end{cfuncdesc}
1062
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001063\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
1064This utility function prints a warning message to \var{sys.stderr}
1065when an exception has been set but it is impossible for the
1066interpreter to actually raise the exception. It is used, for example,
1067when an exception occurs in an \member{__del__} method.
1068
1069The function is called with a single argument \var{obj} that
1070identifies where the context in which the unraisable exception
1071occurred. The repr of \var{obj} will be printed in the warning
1072message.
1073\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001074
Fred Drakeefd146c1999-02-15 15:30:45 +00001075\section{Standard Exceptions \label{standardExceptions}}
Guido van Rossumae110af1997-05-22 20:11:52 +00001076
1077All standard Python exceptions are available as global variables whose
Fred Drake659ebfa2000-04-03 15:42:13 +00001078names are \samp{PyExc_} followed by the Python exception name. These
1079have the type \ctype{PyObject*}; they are all class objects. For
1080completeness, here are all the variables:
1081
1082\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
1083 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
1084 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
1085 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
1086 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
1087 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
1088 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
1089 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
1090 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
1091 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
1092 \lineiii{PyExc_IOError}{\exception{IOError}}{}
1093 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
1094 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
1095 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
1096 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
1097 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
1098 \lineiii{PyExc_NameError}{\exception{NameError}}{}
1099 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
1100 \lineiii{PyExc_OSError}{\exception{OSError}}{}
1101 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
1102 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
1103 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
1104 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
1105 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
1106 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
1107 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
Fred Drakea8d73412000-08-11 20:39:29 +00001108 \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(2)}
Fred Drake659ebfa2000-04-03 15:42:13 +00001109 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
1110\end{tableiii}
1111
1112\noindent
Fred Drakea8d73412000-08-11 20:39:29 +00001113Notes:
Fred Drake659ebfa2000-04-03 15:42:13 +00001114\begin{description}
1115\item[(1)]
Fred Draked04038d2000-06-29 20:15:14 +00001116 This is a base class for other standard exceptions.
Fred Drakea8d73412000-08-11 20:39:29 +00001117
1118\item[(2)]
1119 Only defined on Windows; protect code that uses this by testing that
1120 the preprocessor macro \code{MS_WINDOWS} is defined.
Fred Drake659ebfa2000-04-03 15:42:13 +00001121\end{description}
1122
1123
1124\section{Deprecation of String Exceptions}
1125
Fred Draked04038d2000-06-29 20:15:14 +00001126All exceptions built into Python or provided in the standard library
1127are derived from \exception{Exception}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001128\withsubitem{(built-in exception)}{\ttindex{Exception}}
Fred Drake659ebfa2000-04-03 15:42:13 +00001129
Fred Draked04038d2000-06-29 20:15:14 +00001130String exceptions are still supported in the interpreter to allow
Fred Drake659ebfa2000-04-03 15:42:13 +00001131existing code to run unmodified, but this will also change in a future
1132release.
Guido van Rossumae110af1997-05-22 20:11:52 +00001133
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001134
Fred Drakeefd146c1999-02-15 15:30:45 +00001135\chapter{Utilities \label{utilities}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001136
Fred Drake88fdaa72001-07-20 20:56:11 +00001137The functions in this chapter perform various utility tasks, ranging
1138from helping C code be more portable across platforms, using Python
1139modules from C, and parsing function arguments and constructing Python
1140values from C values.
1141
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001142
Fred Drake377fb1e2001-07-14 03:01:48 +00001143\section{Operating System Utilities \label{os}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001144
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001145\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001146Return true (nonzero) if the standard I/O file \var{fp} with name
1147\var{filename} is deemed interactive. This is the case for files for
1148which \samp{isatty(fileno(\var{fp}))} is true. If the global flag
Fred Drakef8830d11998-04-23 14:06:01 +00001149\cdata{Py_InteractiveFlag} is true, this function also returns true if
Fred Drake5566c1c2001-01-19 22:48:33 +00001150the \var{filename} pointer is \NULL{} or if the name is equal to one of
Fred Drakea8455ab2000-06-16 19:58:42 +00001151the strings \code{'<stdin>'} or \code{'???'}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001152\end{cfuncdesc}
1153
1154\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001155Return the time of last modification of the file \var{filename}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001156The result is encoded in the same way as the timestamp returned by
Fred Drake659ebfa2000-04-03 15:42:13 +00001157the standard C library function \cfunction{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001158\end{cfuncdesc}
1159
Fred Drakecabbc3b2000-06-28 15:53:13 +00001160\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
1161Function to update some internal state after a process fork; this
1162should be called in the new process if the Python interpreter will
1163continue to be used. If a new executable is loaded into the new
1164process, this function does not need to be called.
1165\end{cfuncdesc}
1166
Fred Drake17e63432000-08-31 05:50:40 +00001167\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
1168Return true when the interpreter runs out of stack space. This is a
1169reliable check, but is only available when \code{USE_STACKCHECK} is
1170defined (currently on Windows using the Microsoft Visual C++ compiler
1171and on the Macintosh). \code{USE_CHECKSTACK} will be defined
1172automatically; you should never change the definition in your own
1173code.
1174\end{cfuncdesc}
1175
Guido van Rossumc96ec6e2000-09-16 16:30:48 +00001176\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i}
1177Return the current signal handler for signal \var{i}.
1178This is a thin wrapper around either \cfunction{sigaction} or
1179\cfunction{signal}. Do not call those functions directly!
1180\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1181\end{cfuncdesc}
1182
1183\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h}
1184Set the signal handler for signal \var{i} to be \var{h};
1185return the old signal handler.
1186This is a thin wrapper around either \cfunction{sigaction} or
1187\cfunction{signal}. Do not call those functions directly!
1188\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1189\end{cfuncdesc}
1190
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001191
Fred Drakeefd146c1999-02-15 15:30:45 +00001192\section{Process Control \label{processControl}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001193
1194\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
1195Print a fatal error message and kill the process. No cleanup is
1196performed. This function should only be invoked when a condition is
1197detected that would make it dangerous to continue using the Python
1198interpreter; e.g., when the object administration appears to be
Fred Drake659ebfa2000-04-03 15:42:13 +00001199corrupted. On \UNIX{}, the standard C library function
1200\cfunction{abort()}\ttindex{abort()} is called which will attempt to
1201produce a \file{core} file.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001202\end{cfuncdesc}
1203
1204\begin{cfuncdesc}{void}{Py_Exit}{int status}
Fred Drake659ebfa2000-04-03 15:42:13 +00001205Exit the current process. This calls
1206\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
1207then calls the standard C library function
1208\code{exit(\var{status})}\ttindex{exit()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001209\end{cfuncdesc}
1210
1211\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drake659ebfa2000-04-03 15:42:13 +00001212Register a cleanup function to be called by
1213\cfunction{Py_Finalize()}\ttindex{Py_Finalize()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001214The cleanup function will be called with no arguments and should
Fred Drake659ebfa2000-04-03 15:42:13 +00001215return no value. At most 32 \index{cleanup functions}cleanup
1216functions can be registered.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001217When the registration is successful, \cfunction{Py_AtExit()} returns
1218\code{0}; on failure, it returns \code{-1}. The cleanup function
1219registered last is called first. Each cleanup function will be called
1220at most once. Since Python's internal finallization will have
1221completed before the cleanup function, no Python APIs should be called
1222by \var{func}.
1223\end{cfuncdesc}
1224
1225
Fred Drakeefd146c1999-02-15 15:30:45 +00001226\section{Importing Modules \label{importing}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001227
Fred Drakec6fa34e1998-04-02 06:47:24 +00001228\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00001229This is a simplified interface to
1230\cfunction{PyImport_ImportModuleEx()} below, leaving the
1231\var{globals} and \var{locals} arguments set to \NULL{}. When the
Fred Drakebab29652001-07-10 16:10:08 +00001232\var{name} argument contains a dot (when it specifies a
Fred Drake659ebfa2000-04-03 15:42:13 +00001233submodule of a package), the \var{fromlist} argument is set to the
1234list \code{['*']} so that the return value is the named module rather
1235than the top-level package containing it as would otherwise be the
1236case. (Unfortunately, this has an additional side effect when
1237\var{name} in fact specifies a subpackage instead of a submodule: the
1238submodules specified in the package's \code{__all__} variable are
1239\index{package variable!\code{__all__}}
1240\withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a
1241new reference to the imported module, or
1242\NULL{} with an exception set on failure (the module may still be
1243created in this case --- examine \code{sys.modules} to find out).
1244\withsubitem{(in module sys)}{\ttindex{modules}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001245\end{cfuncdesc}
1246
Fred Drake01978582001-08-08 19:14:53 +00001247\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name,
1248 PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001249Import a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001250Python function \function{__import__()}\bifuncindex{__import__}, as
1251the standard \function{__import__()} function calls this function
1252directly.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001253
Guido van Rossum42cefd01997-10-05 15:27:29 +00001254The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001255top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001256(the module may still be created in this case). Like for
Fred Drakee058b4f1998-02-16 06:15:35 +00001257\function{__import__()}, the return value when a submodule of a
1258package was requested is normally the top-level package, unless a
1259non-empty \var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001260\end{cfuncdesc}
1261
Fred Drakec6fa34e1998-04-02 06:47:24 +00001262\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001263This is a higher-level interface that calls the current ``import hook
Fred Drakee058b4f1998-02-16 06:15:35 +00001264function''. It invokes the \function{__import__()} function from the
Guido van Rossum42cefd01997-10-05 15:27:29 +00001265\code{__builtins__} of the current globals. This means that the
1266import is done using whatever import hooks are installed in the
Fred Drake4de05a91998-02-16 14:25:26 +00001267current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
1268\module{ihooks}\refstmodindex{ihooks}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001269\end{cfuncdesc}
1270
Fred Drakec6fa34e1998-04-02 06:47:24 +00001271\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001272Reload a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001273Python function \function{reload()}\bifuncindex{reload}, as the standard
Fred Drakee058b4f1998-02-16 06:15:35 +00001274\function{reload()} function calls this function directly. Return a
1275new reference to the reloaded module, or \NULL{} with an exception set
1276on failure (the module still exists in this case).
Guido van Rossum42cefd01997-10-05 15:27:29 +00001277\end{cfuncdesc}
1278
Fred Drakec6fa34e1998-04-02 06:47:24 +00001279\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001280Return the module object corresponding to a module name. The
1281\var{name} argument may be of the form \code{package.module}). First
1282check the modules dictionary if there's one there, and if not, create
Fred Drake659ebfa2000-04-03 15:42:13 +00001283a new one and insert in in the modules dictionary.
Guido van Rossuma096a2e1998-11-02 17:02:42 +00001284Warning: this function does not load or import the module; if the
1285module wasn't already loaded, you will get an empty module object.
1286Use \cfunction{PyImport_ImportModule()} or one of its variants to
1287import a module.
Fred Drake659ebfa2000-04-03 15:42:13 +00001288Return \NULL{} with an exception set on failure.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001289\end{cfuncdesc}
1290
Fred Drakec6fa34e1998-04-02 06:47:24 +00001291\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001292Given a module name (possibly of the form \code{package.module}) and a
1293code object read from a Python bytecode file or obtained from the
Fred Drake53fb7721998-02-16 06:23:20 +00001294built-in function \function{compile()}\bifuncindex{compile}, load the
1295module. Return a new reference to the module object, or \NULL{} with
1296an exception set if an error occurred (the module may still be created
1297in this case). (This function would reload the module if it was
1298already imported.)
Guido van Rossum42cefd01997-10-05 15:27:29 +00001299\end{cfuncdesc}
1300
1301\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001302Return the magic number for Python bytecode files (a.k.a.
1303\file{.pyc} and \file{.pyo} files). The magic number should be
1304present in the first four bytes of the bytecode file, in little-endian
1305byte order.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001306\end{cfuncdesc}
1307
Fred Drakec6fa34e1998-04-02 06:47:24 +00001308\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001309Return the dictionary used for the module administration
1310(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1311variable.
1312\end{cfuncdesc}
1313
1314\begin{cfuncdesc}{void}{_PyImport_Init}{}
1315Initialize the import mechanism. For internal use only.
1316\end{cfuncdesc}
1317
1318\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1319Empty the module table. For internal use only.
1320\end{cfuncdesc}
1321
1322\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1323Finalize the import mechanism. For internal use only.
1324\end{cfuncdesc}
1325
Fred Drakec6fa34e1998-04-02 06:47:24 +00001326\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001327For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001328\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001329
Fred Drakec6fa34e1998-04-02 06:47:24 +00001330\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001331For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001332\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001333
Fred Drake1d158692000-06-18 05:21:21 +00001334\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
1335Load a frozen module named \var{name}. Return \code{1} for success,
1336\code{0} if the module is not found, and \code{-1} with an exception
1337set if the initialization failed. To access the imported module on a
1338successful load, use \cfunction{PyImport_ImportModule()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00001339(Note the misnomer --- this function would reload the module if it was
Guido van Rossum42cefd01997-10-05 15:27:29 +00001340already imported.)
1341\end{cfuncdesc}
1342
Fred Drake659ebfa2000-04-03 15:42:13 +00001343\begin{ctypedesc}[_frozen]{struct _frozen}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001344This is the structure type definition for frozen module descriptors,
Fred Drakec6fa34e1998-04-02 06:47:24 +00001345as generated by the \program{freeze}\index{freeze utility} utility
1346(see \file{Tools/freeze/} in the Python source distribution). Its
Fred Drakee0d9a832000-09-01 05:30:00 +00001347definition, found in \file{Include/import.h}, is:
Fred Drakec6fa34e1998-04-02 06:47:24 +00001348
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001349\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001350struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001351 char *name;
1352 unsigned char *code;
1353 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001354};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001355\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001356\end{ctypedesc}
1357
Fred Drakec6fa34e1998-04-02 06:47:24 +00001358\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
Fred Drakef8830d11998-04-23 14:06:01 +00001359This pointer is initialized to point to an array of \ctype{struct
Fred Drake659ebfa2000-04-03 15:42:13 +00001360_frozen} records, terminated by one whose members are all
1361\NULL{} or zero. When a frozen module is imported, it is searched in
1362this table. Third-party code could play tricks with this to provide a
Guido van Rossum42cefd01997-10-05 15:27:29 +00001363dynamically created collection of frozen modules.
1364\end{cvardesc}
1365
Fred Drakee0d9a832000-09-01 05:30:00 +00001366\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
1367 void (*initfunc)(void)}
1368Add a single module to the existing table of built-in modules. This
1369is a convenience wrapper around \cfunction{PyImport_ExtendInittab()},
1370returning \code{-1} if the table could not be extended. The new
1371module can be imported by the name \var{name}, and uses the function
1372\var{initfunc} as the initialization function called on the first
1373attempted import. This should be called before
1374\cfunction{Py_Initialize()}.
1375\end{cfuncdesc}
1376
1377\begin{ctypedesc}[_inittab]{struct _inittab}
1378Structure describing a single entry in the list of built-in modules.
1379Each of these structures gives the name and initialization function
1380for a module built into the interpreter. Programs which embed Python
1381may use an array of these structures in conjunction with
1382\cfunction{PyImport_ExtendInittab()} to provide additional built-in
1383modules. The structure is defined in \file{Include/import.h} as:
1384
1385\begin{verbatim}
1386struct _inittab {
1387 char *name;
1388 void (*initfunc)(void);
1389};
1390\end{verbatim}
1391\end{ctypedesc}
1392
1393\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
1394Add a collection of modules to the table of built-in modules. The
1395\var{newtab} array must end with a sentinel entry which contains
1396\NULL{} for the \member{name} field; failure to provide the sentinel
1397value can result in a memory fault. Returns \code{0} on success or
1398\code{-1} if insufficient memory could be allocated to extend the
1399internal table. In the event of failure, no modules are added to the
1400internal table. This should be called before
1401\cfunction{Py_Initialize()}.
1402\end{cfuncdesc}
1403
Guido van Rossum42cefd01997-10-05 15:27:29 +00001404
Fred Drake88fdaa72001-07-20 20:56:11 +00001405\section{Parsing arguements and building values
1406 \label{arg-parsing}}
1407
1408These functions are useful when creating your own extensions functions
1409and methods. Additional information and examples are available in
1410\citetitle[../ext/ext.html]{Extending and Embedding the Python
1411Interpreter}.
1412
1413\begin{cfuncdesc}{int}{PyArg_ParseTuple}{PyObject *args, char *format,
1414 \moreargs}
1415 Parse the parameters of a function that takes only positional
1416 parameters into local variables. Returns true on success; on
1417 failure, it returns false and raises the appropriate exception. See
1418 \citetitle[../ext/parseTuple.html]{Extending and Embedding the
1419 Python Interpreter} for more information.
1420\end{cfuncdesc}
1421
1422\begin{cfuncdesc}{int}{PyArg_ParseTupleAndKeywords}{PyObject *args,
1423 PyObject *kw, char *format, char *keywords[],
1424 \moreargs}
1425 Parse the parameters of a function that takes both positional and
1426 keyword parameters into local variables. Returns true on success;
1427 on failure, it returns false and raises the appropriate exception.
1428 See \citetitle[../ext/parseTupleAndKeywords.html]{Extending and
1429 Embedding the Python Interpreter} for more information.
1430\end{cfuncdesc}
1431
1432\begin{cfuncdesc}{int}{PyArg_Parse}{PyObject *args, char *format,
1433 \moreargs}
1434 Function used to deconstruct the argument lists of ``old-style''
1435 functions --- these are functions which use the
1436 \constant{METH_OLDARGS} parameter parsing method. This is not
1437 recommended for use in parameter parsing in new code, and most code
1438 in the standard interpreter has been modified to no longer use this
1439 for that purpose. It does remain a convenient way to decompose
1440 other tuples, however, and may continue to be used for that
1441 purpose.
1442\end{cfuncdesc}
1443
1444\begin{cfuncdesc}{PyObject*}{Py_BuildValue}{char *format,
1445 \moreargs}
1446 Create a new value based on a format string similar to those
1447 accepted by the \cfunction{PyArg_Parse*()} family of functions and a
1448 sequence of values. Returns the value or \NULL{} in the case of an
1449 error; an exception will be raised if \NULL{} is returned. For more
1450 information on the format string and additional parameters, see
1451 \citetitle[../ext/buildValue.html]{Extending and Embedding the
1452 Python Interpreter}.
1453\end{cfuncdesc}
1454
1455
1456
Fred Drakeefd146c1999-02-15 15:30:45 +00001457\chapter{Abstract Objects Layer \label{abstract}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001458
1459The functions in this chapter interact with Python objects regardless
1460of their type, or with wide classes of object types (e.g. all
1461numerical types, or all sequence types). When used on object types
Fred Drake659ebfa2000-04-03 15:42:13 +00001462for which they do not apply, they will raise a Python exception.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001463
Fred Drakeefd146c1999-02-15 15:30:45 +00001464\section{Object Protocol \label{object}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001465
1466\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00001467Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error.
1468The flags argument is used to enable certain printing options. The
1469only option currently supported is \constant{Py_PRINT_RAW}; if given,
1470the \function{str()} of the object is written instead of the
1471\function{repr()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001472\end{cfuncdesc}
1473
1474\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001475Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1476\code{0} otherwise. This is equivalent to the Python expression
1477\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001478This function always succeeds.
1479\end{cfuncdesc}
1480
Fred Drake659ebfa2000-04-03 15:42:13 +00001481\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
1482 char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001483Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001484Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001485This is the equivalent of the Python expression
1486\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001487\end{cfuncdesc}
1488
1489
1490\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001491Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1492\code{0} otherwise. This is equivalent to the Python expression
1493\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001494This function always succeeds.
1495\end{cfuncdesc}
1496
1497
Fred Drake659ebfa2000-04-03 15:42:13 +00001498\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
1499 PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001500Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001501Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001502This is the equivalent of the Python expression
1503\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001504\end{cfuncdesc}
1505
1506
Fred Drake01978582001-08-08 19:14:53 +00001507\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o,
1508 char *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001509Set the value of the attribute named \var{attr_name}, for object
1510\var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1511the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1512\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001513\end{cfuncdesc}
1514
1515
Fred Drake01978582001-08-08 19:14:53 +00001516\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o,
1517 PyObject *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001518Set the value of the attribute named \var{attr_name}, for
1519object \var{o},
1520to the value \var{v}. Returns \code{-1} on failure. This is
1521the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1522\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001523\end{cfuncdesc}
1524
1525
1526\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001527Delete attribute named \var{attr_name}, for object \var{o}. Returns
1528\code{-1} on failure. This is the equivalent of the Python
1529statement: \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001530\end{cfuncdesc}
1531
1532
1533\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001534Delete attribute named \var{attr_name}, for object \var{o}. Returns
1535\code{-1} on failure. This is the equivalent of the Python
1536statement \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001537\end{cfuncdesc}
1538
1539
1540\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
Fred Drakee058b4f1998-02-16 06:15:35 +00001541Compare the values of \var{o1} and \var{o2} using a routine provided
1542by \var{o1}, if one exists, otherwise with a routine provided by
1543\var{o2}. The result of the comparison is returned in \var{result}.
1544Returns \code{-1} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001545statement\bifuncindex{cmp} \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001546\end{cfuncdesc}
1547
1548
1549\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001550Compare the values of \var{o1} and \var{o2} using a routine provided
1551by \var{o1}, if one exists, otherwise with a routine provided by
1552\var{o2}. Returns the result of the comparison on success. On error,
1553the value returned is undefined; use \cfunction{PyErr_Occurred()} to
Fred Drake659ebfa2000-04-03 15:42:13 +00001554detect an error. This is equivalent to the Python
1555expression\bifuncindex{cmp} \samp{cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001556\end{cfuncdesc}
1557
1558
1559\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001560Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001561string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001562the equivalent of the Python expression \samp{repr(\var{o})}.
1563Called by the \function{repr()}\bifuncindex{repr} built-in function
1564and by reverse quotes.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001565\end{cfuncdesc}
1566
1567
1568\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001569Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001570string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001571the equivalent of the Python expression \samp{str(\var{o})}.
1572Called by the \function{str()}\bifuncindex{str} built-in function and
1573by the \keyword{print} statement.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001574\end{cfuncdesc}
1575
1576
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001577\begin{cfuncdesc}{PyObject*}{PyObject_Unicode}{PyObject *o}
1578Compute a Unicode string representation of object \var{o}. Returns the
1579Unicode string representation on success, \NULL{} on failure. This is
1580the equivalent of the Python expression \samp{unistr(\var{o})}.
1581Called by the \function{unistr()}\bifuncindex{unistr} built-in function.
1582\end{cfuncdesc}
1583
Fred Drake58c8f9f2001-03-28 21:14:32 +00001584\begin{cfuncdesc}{int}{PyObject_IsInstance}{PyObject *inst, PyObject *cls}
1585Return \code{1} if \var{inst} is an instance of the class \var{cls} or
1586a subclass of \var{cls}. If \var{cls} is a type object rather than a
1587class object, \cfunction{PyObject_IsInstance()} returns \code{1} if
1588\var{inst} is of type \var{cls}. If \var{inst} is not a class
1589instance and \var{cls} is neither a type object or class object,
1590\var{inst} must have a \member{__class__} attribute --- the class
1591relationship of the value of that attribute with \var{cls} will be
1592used to determine the result of this function.
1593\versionadded{2.1}
1594\end{cfuncdesc}
1595
1596Subclass determination is done in a fairly straightforward way, but
1597includes a wrinkle that implementors of extensions to the class system
1598may want to be aware of. If \class{A} and \class{B} are class
1599objects, \class{B} is a subclass of \class{A} if it inherits from
1600\class{A} either directly or indirectly. If either is not a class
1601object, a more general mechanism is used to determine the class
1602relationship of the two objects. When testing if \var{B} is a
1603subclass of \var{A}, if \var{A} is \var{B},
1604\cfunction{PyObject_IsSubclass()} returns true. If \var{A} and
1605\var{B} are different objects, \var{B}'s \member{__bases__} attribute
1606is searched in a depth-first fashion for \var{A} --- the presence of
1607the \member{__bases__} attribute is considered sufficient for this
1608determination.
1609
1610\begin{cfuncdesc}{int}{PyObject_IsSubclass}{PyObject *derived,
1611 PyObject *cls}
1612Returns \code{1} if the class \var{derived} is identical to or derived
1613from the class \var{cls}, otherwise returns \code{0}. In case of an
1614error, returns \code{-1}. If either \var{derived} or \var{cls} is not
1615an actual class object, this function uses the generic algorithm
1616described above.
1617\versionadded{2.1}
1618\end{cfuncdesc}
1619
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001620
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001621\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001622Determine if the object \var{o} is callable. Return \code{1} if the
Fred Drakee058b4f1998-02-16 06:15:35 +00001623object is callable and \code{0} otherwise.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001624This function always succeeds.
1625\end{cfuncdesc}
1626
1627
Fred Drake659ebfa2000-04-03 15:42:13 +00001628\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
1629 PyObject *args}
Fred Drakee058b4f1998-02-16 06:15:35 +00001630Call a callable Python object \var{callable_object}, with
1631arguments given by the tuple \var{args}. If no arguments are
Fred Drake659ebfa2000-04-03 15:42:13 +00001632needed, then \var{args} may be \NULL{}. Returns the result of the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001633call on success, or \NULL{} on failure. This is the equivalent
Fred Drakef90490e2001-08-02 18:00:28 +00001634of the Python expression \samp{apply(\var{callable_object},
1635\var{args})} or \samp{\var{callable_object}(*\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001636\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001637\end{cfuncdesc}
1638
Fred Drake5566c1c2001-01-19 22:48:33 +00001639\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object,
1640 char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001641Call a callable Python object \var{callable_object}, with a
Fred Drake659ebfa2000-04-03 15:42:13 +00001642variable number of C arguments. The C arguments are described
Fred Drakee058b4f1998-02-16 06:15:35 +00001643using a \cfunction{Py_BuildValue()} style format string. The format may
1644be \NULL{}, indicating that no arguments are provided. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001645result of the call on success, or \NULL{} on failure. This is
Fred Drakef90490e2001-08-02 18:00:28 +00001646the equivalent of the Python expression
1647\samp{apply(\var{callable_object}\var{args})} or
1648\samp{\var{callable_object}(*\var{args})}.
1649\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001650\end{cfuncdesc}
1651
1652
Fred Drake5566c1c2001-01-19 22:48:33 +00001653\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o,
1654 char *method, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001655Call the method named \var{m} of object \var{o} with a variable number
Fred Drake659ebfa2000-04-03 15:42:13 +00001656of C arguments. The C arguments are described by a
Fred Drakee058b4f1998-02-16 06:15:35 +00001657\cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1658indicating that no arguments are provided. Returns the result of the
1659call on success, or \NULL{} on failure. This is the equivalent of the
1660Python expression \samp{\var{o}.\var{method}(\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001661Note that special method names, such as \method{__add__()},
1662\method{__getitem__()}, and so on are not supported. The specific
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001663abstract-object routines for these must be used.
1664\end{cfuncdesc}
1665
1666
1667\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001668Compute and return the hash value of an object \var{o}. On
1669failure, return \code{-1}. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001670expression \samp{hash(\var{o})}.\bifuncindex{hash}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001671\end{cfuncdesc}
1672
1673
1674\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001675Returns \code{1} if the object \var{o} is considered to be true, and
1676\code{0} otherwise. This is equivalent to the Python expression
1677\samp{not not \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001678This function always succeeds.
1679\end{cfuncdesc}
1680
1681
1682\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1683On success, returns a type object corresponding to the object
Fred Drakee058b4f1998-02-16 06:15:35 +00001684type of object \var{o}. On failure, returns \NULL{}. This is
1685equivalent to the Python expression \samp{type(\var{o})}.
Fred Drake53fb7721998-02-16 06:23:20 +00001686\bifuncindex{type}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001687\end{cfuncdesc}
1688
1689\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001690Return the length of object \var{o}. If the object \var{o} provides
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001691both sequence and mapping protocols, the sequence length is
Fred Drake659ebfa2000-04-03 15:42:13 +00001692returned. On error, \code{-1} is returned. This is the equivalent
1693to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001694\end{cfuncdesc}
1695
1696
1697\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001698Return element of \var{o} corresponding to the object \var{key} or
1699\NULL{} on failure. This is the equivalent of the Python expression
1700\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001701\end{cfuncdesc}
1702
1703
Fred Drake01978582001-08-08 19:14:53 +00001704\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o,
1705 PyObject *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001706Map the object \var{key} to the value \var{v}.
1707Returns \code{-1} on failure. This is the equivalent
1708of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001709\end{cfuncdesc}
1710
1711
Guido van Rossumd1dbf631999-01-22 20:10:49 +00001712\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001713Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1714failure. This is the equivalent of the Python statement \samp{del
1715\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001716\end{cfuncdesc}
1717
Andrew M. Kuchling8c46b302000-07-13 23:58:16 +00001718\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
1719Derives a file-descriptor from a Python object. If the object
1720is an integer or long integer, its value is returned. If not, the
1721object's \method{fileno()} method is called if it exists; the method
1722must return an integer or long integer, which is returned as the file
1723descriptor value. Returns \code{-1} on failure.
1724\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001725
Tim Peters7eea37e2001-09-04 22:08:56 +00001726\begin{cfuncdesc}{PyObject*}{PyObject_Dir}{PyObject *o}
1727This is equivalent to the Python expression \samp{dir(\var{o})},
1728returning a (possibly empty) list of strings appropriate for the
1729object argument, or \NULL{} in case of error.
1730If the argument is \NULL{}, this is like the Python \samp{dir()},
1731returning the names of the current locals; in this case, if no
1732execution frame is active then \NULL{} is returned but
1733\cfunction{PyErr_Occurred()} will return false.
1734\end{cfuncdesc}
1735
Fred Drake01978582001-08-08 19:14:53 +00001736
Fred Drakeefd146c1999-02-15 15:30:45 +00001737\section{Number Protocol \label{number}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001738
1739\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001740Returns \code{1} if the object \var{o} provides numeric protocols, and
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001741false otherwise.
1742This function always succeeds.
1743\end{cfuncdesc}
1744
1745
1746\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001747Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1748failure. This is the equivalent of the Python expression
1749\samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001750\end{cfuncdesc}
1751
1752
1753\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
Fred Drake659ebfa2000-04-03 15:42:13 +00001754Returns the result of subtracting \var{o2} from \var{o1}, or
1755\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001756\samp{\var{o1} - \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001757\end{cfuncdesc}
1758
1759
1760\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001761Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1762failure. This is the equivalent of the Python expression
1763\samp{\var{o1} * \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001764\end{cfuncdesc}
1765
1766
1767\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001768Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1769failure.
1770This is the equivalent of the Python expression \samp{\var{o1} /
1771\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001772\end{cfuncdesc}
1773
1774
Fred Drake01978582001-08-08 19:14:53 +00001775\begin{cfuncdesc}{PyObject*}{PyNumber_FloorDivide}{PyObject *o1, PyObject *o2}
1776Return the floor of \var{o1} divided by \var{o2}, or \NULL{} on
1777failure. This is equivalent to the ``classic'' division of integers.
1778\versionadded{2.2}
1779\end{cfuncdesc}
1780
1781
1782\begin{cfuncdesc}{PyObject*}{PyNumber_TrueDivide}{PyObject *o1, PyObject *o2}
1783Return a reasonable approximation for the mathematical value of
1784\var{o1} divided by \var{o2}, or \NULL{} on failure. The return value
1785is ``approximate'' because binary floating point numbers are
1786approximate; it is not possible to represent all real numbers in base
1787two. This function can return a floating point value when passed two
1788integers.
1789\versionadded{2.2}
1790\end{cfuncdesc}
1791
1792
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001793\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001794Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1795failure. This is the equivalent of the Python expression
Fred Drake659ebfa2000-04-03 15:42:13 +00001796\samp{\var{o1} \%\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001797\end{cfuncdesc}
1798
1799
1800\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
Fred Drake53fb7721998-02-16 06:23:20 +00001801See the built-in function \function{divmod()}\bifuncindex{divmod}.
1802Returns \NULL{} on failure. This is the equivalent of the Python
1803expression \samp{divmod(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001804\end{cfuncdesc}
1805
1806
Fred Drake01978582001-08-08 19:14:53 +00001807\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1,
1808 PyObject *o2, PyObject *o3}
Fred Drake53fb7721998-02-16 06:23:20 +00001809See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1810\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001811\samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
Fred Drake659ebfa2000-04-03 15:42:13 +00001812If \var{o3} is to be ignored, pass \cdata{Py_None} in its place
1813(passing \NULL{} for \var{o3} would cause an illegal memory access).
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001814\end{cfuncdesc}
1815
1816
1817\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001818Returns the negation of \var{o} on success, or \NULL{} on failure.
1819This is the equivalent of the Python expression \samp{-\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001820\end{cfuncdesc}
1821
1822
1823\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001824Returns \var{o} on success, or \NULL{} on failure.
1825This is the equivalent of the Python expression \samp{+\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001826\end{cfuncdesc}
1827
1828
1829\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001830Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1831the equivalent of the Python expression \samp{abs(\var{o})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001832\bifuncindex{abs}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001833\end{cfuncdesc}
1834
1835
1836\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001837Returns the bitwise negation of \var{o} on success, or \NULL{} on
1838failure. This is the equivalent of the Python expression
1839\samp{\~\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001840\end{cfuncdesc}
1841
1842
1843\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001844Returns the result of left shifting \var{o1} by \var{o2} on success,
1845or \NULL{} on failure. This is the equivalent of the Python
Fred Draked20d8b32001-04-13 14:52:39 +00001846expression \samp{\var{o1} <\code{<} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001847\end{cfuncdesc}
1848
1849
1850\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001851Returns the result of right shifting \var{o1} by \var{o2} on success,
1852or \NULL{} on failure. This is the equivalent of the Python
Fred Draked20d8b32001-04-13 14:52:39 +00001853expression \samp{\var{o1} >\code{>} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001854\end{cfuncdesc}
1855
1856
1857\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001858Returns the ``bitwise and'' of \var{o2} and \var{o2} on success and
1859\NULL{} on failure. This is the equivalent of the Python expression
Fred Drake5566c1c2001-01-19 22:48:33 +00001860\samp{\var{o1} \&\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001861\end{cfuncdesc}
1862
1863
1864\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001865Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success,
Fred Drakee058b4f1998-02-16 06:15:35 +00001866or \NULL{} on failure. This is the equivalent of the Python
Fred Drake755c23d2001-07-14 03:05:53 +00001867expression \samp{\var{o1} \textasciicircum{} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001868\end{cfuncdesc}
1869
1870\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001871Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
1872\NULL{} on failure. This is the equivalent of the Python expression
1873\samp{\var{o1} | \var{o2}}.
1874\end{cfuncdesc}
1875
1876
1877\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAdd}{PyObject *o1, PyObject *o2}
Fred Drake01978582001-08-08 19:14:53 +00001878Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1879failure. The operation is done \emph{in-place} when \var{o1} supports
1880it. This is the equivalent of the Python statement \samp{\var{o1} +=
1881\var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001882\end{cfuncdesc}
1883
1884
Fred Drake01978582001-08-08 19:14:53 +00001885\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceSubtract}{PyObject *o1,
1886 PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001887Returns the result of subtracting \var{o2} from \var{o1}, or
Fred Drake01978582001-08-08 19:14:53 +00001888\NULL{} on failure. The operation is done \emph{in-place} when
1889\var{o1} supports it. This is the equivalent of the Python statement
1890\samp{\var{o1} -= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001891\end{cfuncdesc}
1892
1893
Fred Drake01978582001-08-08 19:14:53 +00001894\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceMultiply}{PyObject *o1,
1895 PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001896Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1897failure. The operation is done \emph{in-place} when \var{o1} supports it.
Fred Drake01978582001-08-08 19:14:53 +00001898This is the equivalent of the Python statement \samp{\var{o1} *= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001899\end{cfuncdesc}
1900
1901
Fred Drake01978582001-08-08 19:14:53 +00001902\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceDivide}{PyObject *o1,
1903 PyObject *o2}
1904Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1905failure. The operation is done \emph{in-place} when \var{o1} supports
1906it. This is the equivalent of the Python statement \samp{\var{o1} /=
1907\var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001908\end{cfuncdesc}
1909
1910
Fred Drake01978582001-08-08 19:14:53 +00001911\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceFloorDivide}{PyObject *o1,
1912 PyObject *o2}
1913Returns the mathematical of dividing \var{o1} by \var{o2}, or \NULL{}
1914on failure. The operation is done \emph{in-place} when \var{o1}
1915supports it. This is the equivalent of the Python statement
1916\samp{\var{o1} //= \var{o2}}.
1917\versionadded{2.2}
1918\end{cfuncdesc}
1919
1920
1921\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceTrueDivide}{PyObject *o1,
1922 PyObject *o2}
1923Return a reasonable approximation for the mathematical value of
1924\var{o1} divided by \var{o2}, or \NULL{} on failure. The return value
1925is ``approximate'' because binary floating point numbers are
1926approximate; it is not possible to represent all real numbers in base
1927two. This function can return a floating point value when passed two
1928integers. The operation is done \emph{in-place} when \var{o1}
1929supports it.
1930\versionadded{2.2}
1931\end{cfuncdesc}
1932
1933
1934\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRemainder}{PyObject *o1,
1935 PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001936Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1937failure. The operation is done \emph{in-place} when \var{o1} supports it.
Fred Drake01978582001-08-08 19:14:53 +00001938This is the equivalent of the Python statement \samp{\var{o1} \%= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001939\end{cfuncdesc}
1940
1941
Fred Drake01978582001-08-08 19:14:53 +00001942\begin{cfuncdesc}{PyObject*}{PyNumber_InPlacePower}{PyObject *o1,
1943 PyObject *o2, PyObject *o3}
1944See the built-in function \function{pow()}.\bifuncindex{pow} Returns
1945\NULL{} on failure. The operation is done \emph{in-place} when
1946\var{o1} supports it. This is the equivalent of the Python statement
1947\samp{\var{o1} **= \var{o2}} when o3 is \cdata{Py_None}, or an
1948in-place variant of \samp{pow(\var{o1}, \var{o2}, \var{o3})}
1949otherwise. If \var{o3} is to be ignored, pass \cdata{Py_None} in its
1950place (passing \NULL{} for \var{o3} would cause an illegal memory
1951access).
Fred Drake7740a012000-09-12 20:27:05 +00001952\end{cfuncdesc}
1953
Fred Drake01978582001-08-08 19:14:53 +00001954\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceLshift}{PyObject *o1,
1955 PyObject *o2}
1956Returns the result of left shifting \var{o1} by \var{o2} on success,
1957or \NULL{} on failure. The operation is done \emph{in-place} when
1958\var{o1} supports it. This is the equivalent of the Python statement
1959\samp{\var{o1} <\code{<=} \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001960\end{cfuncdesc}
1961
1962
Fred Drake01978582001-08-08 19:14:53 +00001963\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRshift}{PyObject *o1,
1964 PyObject *o2}
1965Returns the result of right shifting \var{o1} by \var{o2} on success,
1966or \NULL{} on failure. The operation is done \emph{in-place} when
1967\var{o1} supports it. This is the equivalent of the Python statement
1968\samp{\var{o1} >\code{>=} \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001969\end{cfuncdesc}
1970
1971
1972\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAnd}{PyObject *o1, PyObject *o2}
Fred Drake5566c1c2001-01-19 22:48:33 +00001973Returns the ``bitwise and'' of \var{o1} and \var{o2} on success
1974and \NULL{} on failure. The operation is done \emph{in-place} when
Fred Drake01978582001-08-08 19:14:53 +00001975\var{o1} supports it. This is the equivalent of the Python statement
Fred Drake5566c1c2001-01-19 22:48:33 +00001976\samp{\var{o1} \&= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001977\end{cfuncdesc}
1978
1979
1980\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceXor}{PyObject *o1, PyObject *o2}
Fred Drake01978582001-08-08 19:14:53 +00001981Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on
1982success, or \NULL{} on failure. The operation is done \emph{in-place}
1983when \var{o1} supports it. This is the equivalent of the Python
1984statement \samp{\var{o1} \textasciicircum= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001985\end{cfuncdesc}
1986
1987\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2}
Fred Drake01978582001-08-08 19:14:53 +00001988Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
1989\NULL{} on failure. The operation is done \emph{in-place} when
1990\var{o1} supports it. This is the equivalent of the Python statement
1991\samp{\var{o1} |= \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001992\end{cfuncdesc}
1993
Fred Drakec0e6c5b2000-09-22 18:17:49 +00001994\begin{cfuncdesc}{int}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001995This function takes the addresses of two variables of type
Fred Drake659ebfa2000-04-03 15:42:13 +00001996\ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} and
1997\code{*\var{p2}} have the same type, increment their reference count
1998and return \code{0} (success). If the objects can be converted to a
1999common numeric type, replace \code{*p1} and \code{*p2} by their
2000converted value (with 'new' reference counts), and return \code{0}.
2001If no conversion is possible, or if some other error occurs, return
2002\code{-1} (failure) and don't increment the reference counts. The
2003call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
2004statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
2005\bifuncindex{coerce}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002006\end{cfuncdesc}
2007
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002008\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002009Returns the \var{o} converted to an integer object on success, or
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002010\NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00002011expression \samp{int(\var{o})}.\bifuncindex{int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002012\end{cfuncdesc}
2013
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002014\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002015Returns the \var{o} converted to a long integer object on success,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002016or \NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00002017expression \samp{long(\var{o})}.\bifuncindex{long}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002018\end{cfuncdesc}
2019
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002020\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002021Returns the \var{o} converted to a float object on success, or
2022\NULL{} on failure. This is the equivalent of the Python expression
2023\samp{float(\var{o})}.\bifuncindex{float}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002024\end{cfuncdesc}
2025
2026
Fred Drakeefd146c1999-02-15 15:30:45 +00002027\section{Sequence Protocol \label{sequence}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002028
2029\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002030Return \code{1} if the object provides sequence protocol, and
2031\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002032\end{cfuncdesc}
2033
Fred Drakec6a3cb42001-04-04 01:25:17 +00002034\begin{cfuncdesc}{int}{PySequence_Size}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002035Returns the number of objects in sequence \var{o} on success, and
2036\code{-1} on failure. For objects that do not provide sequence
2037protocol, this is equivalent to the Python expression
2038\samp{len(\var{o})}.\bifuncindex{len}
2039\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002040
Fred Drakec6a3cb42001-04-04 01:25:17 +00002041\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
2042Alternate name for \cfunction{PySequence_Size()}.
2043\end{cfuncdesc}
2044
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002045\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00002046Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002047failure. This is the equivalent of the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002048expression \samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002049\end{cfuncdesc}
2050
2051
2052\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Fred Drake659ebfa2000-04-03 15:42:13 +00002053Return the result of repeating sequence object
2054\var{o} \var{count} times, or \NULL{} on failure. This is the
2055equivalent of the Python expression \samp{\var{o} * \var{count}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002056\end{cfuncdesc}
2057
Fred Drake01978582001-08-08 19:14:53 +00002058\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceConcat}{PyObject *o1,
2059 PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00002060Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
2061failure. The operation is done \emph{in-place} when \var{o1} supports it.
2062This is the equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
2063\end{cfuncdesc}
2064
2065
2066\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceRepeat}{PyObject *o, int count}
2067Return the result of repeating sequence object \var{o} \var{count} times, or
2068\NULL{} on failure. The operation is done \emph{in-place} when \var{o}
2069supports it. This is the equivalent of the Python expression \samp{\var{o}
2070*= \var{count}}.
2071\end{cfuncdesc}
2072
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002073
2074\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00002075Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
2076is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002077\end{cfuncdesc}
2078
2079
2080\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00002081Return the slice of sequence object \var{o} between \var{i1} and
2082\var{i2}, or \NULL{} on failure. This is the equivalent of the Python
2083expression \samp{\var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002084\end{cfuncdesc}
2085
2086
2087\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00002088Assign object \var{v} to the \var{i}th element of \var{o}.
2089Returns \code{-1} on failure. This is the equivalent of the Python
2090statement \samp{\var{o}[\var{i}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002091\end{cfuncdesc}
2092
2093\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
Fred Drake5566c1c2001-01-19 22:48:33 +00002094Delete the \var{i}th element of object \var{o}. Returns
Fred Drakee058b4f1998-02-16 06:15:35 +00002095\code{-1} on failure. This is the equivalent of the Python
2096statement \samp{del \var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002097\end{cfuncdesc}
2098
Fred Drake659ebfa2000-04-03 15:42:13 +00002099\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
2100 int i2, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00002101Assign the sequence object \var{v} to the slice in sequence
2102object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
2103the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002104\end{cfuncdesc}
2105
2106\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00002107Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
2108Returns \code{-1} on failure. This is the equivalent of the Python
2109statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002110\end{cfuncdesc}
2111
2112\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002113Returns the \var{o} as a tuple on success, and \NULL{} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00002114This is equivalent to the Python expression \samp{tuple(\var{o})}.
2115\bifuncindex{tuple}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002116\end{cfuncdesc}
2117
2118\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00002119Return the number of occurrences of \var{value} in \var{o}, that is,
2120return the number of keys for which \code{\var{o}[\var{key}] ==
2121\var{value}}. On failure, return \code{-1}. This is equivalent to
2122the Python expression \samp{\var{o}.count(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002123\end{cfuncdesc}
2124
Fred Drake659ebfa2000-04-03 15:42:13 +00002125\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00002126Determine if \var{o} contains \var{value}. If an item in \var{o} is
2127equal to \var{value}, return \code{1}, otherwise return \code{0}. On
2128error, return \code{-1}. This is equivalent to the Python expression
2129\samp{\var{value} in \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002130\end{cfuncdesc}
2131
2132\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00002133Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
2134\var{value}}. On error, return \code{-1}. This is equivalent to
2135the Python expression \samp{\var{o}.index(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002136\end{cfuncdesc}
2137
Fred Drakea8455ab2000-06-16 19:58:42 +00002138\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
2139Return a list object with the same contents as the arbitrary sequence
2140\var{o}. The returned list is guaranteed to be new.
2141\end{cfuncdesc}
2142
2143\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
2144Return a tuple object with the same contents as the arbitrary sequence
2145\var{o}. If \var{o} is a tuple, a new reference will be returned,
2146otherwise a tuple will be constructed with the appropriate contents.
2147\end{cfuncdesc}
2148
Fred Drakef39ed671998-02-26 22:01:23 +00002149
Fred Drake81cccb72000-09-12 15:22:05 +00002150\begin{cfuncdesc}{PyObject*}{PySequence_Fast}{PyObject *o, const char *m}
2151Returns the sequence \var{o} as a tuple, unless it is already a
2152tuple or list, in which case \var{o} is returned. Use
2153\cfunction{PySequence_Fast_GET_ITEM()} to access the members of the
2154result. Returns \NULL{} on failure. If the object is not a sequence,
2155raises \exception{TypeError} with \var{m} as the message text.
2156\end{cfuncdesc}
2157
2158\begin{cfuncdesc}{PyObject*}{PySequence_Fast_GET_ITEM}{PyObject *o, int i}
2159Return the \var{i}th element of \var{o}, assuming that \var{o} was
2160returned by \cfunction{PySequence_Fast()}, and that \var{i} is within
2161bounds. The caller is expected to get the length of the sequence by
Fred Drake96a2a802001-05-29 18:51:41 +00002162calling \cfunction{PySequence_Size()} on \var{o}, since lists and tuples
Fred Drake81cccb72000-09-12 15:22:05 +00002163are guaranteed to always return their true length.
2164\end{cfuncdesc}
2165
2166
Fred Drakeefd146c1999-02-15 15:30:45 +00002167\section{Mapping Protocol \label{mapping}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002168
2169\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002170Return \code{1} if the object provides mapping protocol, and
2171\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002172\end{cfuncdesc}
2173
2174
2175\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002176Returns the number of keys in object \var{o} on success, and
2177\code{-1} on failure. For objects that do not provide mapping
2178protocol, this is equivalent to the Python expression
2179\samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002180\end{cfuncdesc}
2181
2182
2183\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002184Remove the mapping for object \var{key} from the object \var{o}.
2185Return \code{-1} on failure. This is equivalent to
2186the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002187\end{cfuncdesc}
2188
2189
2190\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002191Remove the mapping for object \var{key} from the object \var{o}.
2192Return \code{-1} on failure. This is equivalent to
2193the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002194\end{cfuncdesc}
2195
2196
2197\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
Fred Drake659ebfa2000-04-03 15:42:13 +00002198On success, return \code{1} if the mapping object has the key
2199\var{key} and \code{0} otherwise. This is equivalent to the Python
2200expression \samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002201This function always succeeds.
2202\end{cfuncdesc}
2203
2204
2205\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002206Return \code{1} if the mapping object has the key \var{key} and
2207\code{0} otherwise. This is equivalent to the Python expression
2208\samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002209This function always succeeds.
2210\end{cfuncdesc}
2211
2212
2213\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002214On success, return a list of the keys in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002215failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002216expression \samp{\var{o}.keys()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002217\end{cfuncdesc}
2218
2219
2220\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002221On success, return a list of the values in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002222failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002223expression \samp{\var{o}.values()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002224\end{cfuncdesc}
2225
2226
2227\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002228On success, return a list of the items in object \var{o}, where
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002229each item is a tuple containing a key-value pair. On
2230failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002231expression \samp{\var{o}.items()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002232\end{cfuncdesc}
2233
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002234
2235\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002236Return element of \var{o} corresponding to the object \var{key} or
2237\NULL{} on failure. This is the equivalent of the Python expression
2238\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002239\end{cfuncdesc}
2240
Fred Drakedbcaeda2001-05-07 17:42:18 +00002241\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key,
2242 PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00002243Map the object \var{key} to the value \var{v} in object \var{o}.
2244Returns \code{-1} on failure. This is the equivalent of the Python
2245statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002246\end{cfuncdesc}
2247
2248
Fred Drakedbcaeda2001-05-07 17:42:18 +00002249\section{Iterator Protocol \label{iterator}}
2250
Fred Drakea8e08272001-05-07 17:47:07 +00002251\versionadded{2.2}
2252
Fred Drakedbcaeda2001-05-07 17:42:18 +00002253There are only a couple of functions specifically for working with
2254iterators.
2255
2256\begin{cfuncdesc}{int}{PyIter_Check}{PyObject *o}
2257 Return true if the object \var{o} supports the iterator protocol.
2258\end{cfuncdesc}
2259
2260\begin{cfuncdesc}{PyObject*}{PyIter_Next}{PyObject *o}
2261 Return the next value from the iteration \var{o}. If the object is
2262 an iterator, this retrieves the next value from the iteration, and
2263 returns \NULL{} with no exception set if there are no remaining
2264 items. If the object is not an iterator, \exception{TypeError} is
2265 raised, or if there is an error in retrieving the item, returns
2266 \NULL{} and passes along the exception.
2267\end{cfuncdesc}
2268
2269To write a loop which iterates over an iterator, the C code should
2270look something like this:
2271
2272\begin{verbatim}
2273PyObject *iterator = ...;
2274PyObject *item;
2275
2276while (item = PyIter_Next(iter)) {
2277 /* do something with item */
2278}
2279if (PyErr_Occurred()) {
2280 /* propogate error */
2281}
2282else {
2283 /* continue doing useful work */
2284}
2285\end{verbatim}
2286
2287
Fred Drakeefd146c1999-02-15 15:30:45 +00002288\chapter{Concrete Objects Layer \label{concrete}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002289
2290The functions in this chapter are specific to certain Python object
2291types. Passing them an object of the wrong type is not a good idea;
2292if you receive an object from a Python program and you are not sure
2293that it has the right type, you must perform a type check first;
Fred Drake5566c1c2001-01-19 22:48:33 +00002294for example, to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00002295\cfunction{PyDict_Check()}. The chapter is structured like the
2296``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002297
Fred Drake89024422000-10-23 16:00:54 +00002298\strong{Warning:}
2299While the functions described in this chapter carefully check the type
2300of the objects which are passed in, many of them do not check for
2301\NULL{} being passed instead of a valid object. Allowing \NULL{} to
2302be passed in can cause memory access violations and immediate
2303termination of the interpreter.
2304
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002305
Fred Drakeefd146c1999-02-15 15:30:45 +00002306\section{Fundamental Objects \label{fundamental}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002307
Fred Drakee5bf8b21998-02-12 21:22:28 +00002308This section describes Python type objects and the singleton object
2309\code{None}.
2310
2311
Fred Drakeefd146c1999-02-15 15:30:45 +00002312\subsection{Type Objects \label{typeObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002313
Fred Drake659ebfa2000-04-03 15:42:13 +00002314\obindex{type}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002315\begin{ctypedesc}{PyTypeObject}
Fred Drake659ebfa2000-04-03 15:42:13 +00002316The C structure of the objects used to describe built-in types.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002317\end{ctypedesc}
2318
Fred Drake659ebfa2000-04-03 15:42:13 +00002319\begin{cvardesc}{PyObject*}{PyType_Type}
Fred Drakeefd146c1999-02-15 15:30:45 +00002320This is the type object for type objects; it is the same object as
2321\code{types.TypeType} in the Python layer.
Fred Drake659ebfa2000-04-03 15:42:13 +00002322\withsubitem{(in module types)}{\ttindex{TypeType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002323\end{cvardesc}
2324
Fred Drake659ebfa2000-04-03 15:42:13 +00002325\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
2326Returns true is the object \var{o} is a type object.
2327\end{cfuncdesc}
2328
2329\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
2330Returns true if the type object \var{o} sets the feature
Fred Drakef0e08ef2001-02-03 01:11:26 +00002331\var{feature}. Type features are denoted by single bit flags.
Fred Drake659ebfa2000-04-03 15:42:13 +00002332\end{cfuncdesc}
2333
Fred Drakee5bf8b21998-02-12 21:22:28 +00002334
Fred Drakeefd146c1999-02-15 15:30:45 +00002335\subsection{The None Object \label{noneObject}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002336
Fred Drake659ebfa2000-04-03 15:42:13 +00002337\obindex{None@\texttt{None}}
2338Note that the \ctype{PyTypeObject} for \code{None} is not directly
2339exposed in the Python/C API. Since \code{None} is a singleton,
2340testing for object identity (using \samp{==} in C) is sufficient.
2341There is no \cfunction{PyNone_Check()} function for the same reason.
2342
2343\begin{cvardesc}{PyObject*}{Py_None}
Guido van Rossum44475131998-04-21 15:30:01 +00002344The Python \code{None} object, denoting lack of value. This object has
2345no methods.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002346\end{cvardesc}
2347
2348
Fred Drakefa774872001-07-11 20:35:37 +00002349\section{Numeric Objects \label{numericObjects}}
2350
2351\obindex{numeric}
2352
2353
2354\subsection{Plain Integer Objects \label{intObjects}}
2355
2356\obindex{integer}
2357\begin{ctypedesc}{PyIntObject}
2358This subtype of \ctype{PyObject} represents a Python integer object.
2359\end{ctypedesc}
2360
2361\begin{cvardesc}{PyTypeObject}{PyInt_Type}
2362This instance of \ctype{PyTypeObject} represents the Python plain
2363integer type. This is the same object as \code{types.IntType}.
2364\withsubitem{(in modules types)}{\ttindex{IntType}}
2365\end{cvardesc}
2366
2367\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
2368Returns true if \var{o} is of type \cdata{PyInt_Type}.
2369\end{cfuncdesc}
2370
2371\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
2372Creates a new integer object with a value of \var{ival}.
2373
2374The current implementation keeps an array of integer objects for all
2375integers between \code{-1} and \code{100}, when you create an int in
2376that range you actually just get back a reference to the existing
2377object. So it should be possible to change the value of \code{1}. I
2378suspect the behaviour of Python in this case is undefined. :-)
2379\end{cfuncdesc}
2380
2381\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
2382Will first attempt to cast the object to a \ctype{PyIntObject}, if
2383it is not already one, and then return its value.
2384\end{cfuncdesc}
2385
2386\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
2387Returns the value of the object \var{io}. No error checking is
2388performed.
2389\end{cfuncdesc}
2390
2391\begin{cfuncdesc}{long}{PyInt_GetMax}{}
2392Returns the system's idea of the largest integer it can handle
2393(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
2394header files).
2395\end{cfuncdesc}
2396
2397
2398\subsection{Long Integer Objects \label{longObjects}}
2399
2400\obindex{long integer}
2401\begin{ctypedesc}{PyLongObject}
2402This subtype of \ctype{PyObject} represents a Python long integer
2403object.
2404\end{ctypedesc}
2405
2406\begin{cvardesc}{PyTypeObject}{PyLong_Type}
2407This instance of \ctype{PyTypeObject} represents the Python long
2408integer type. This is the same object as \code{types.LongType}.
2409\withsubitem{(in modules types)}{\ttindex{LongType}}
2410\end{cvardesc}
2411
2412\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
2413Returns true if its argument is a \ctype{PyLongObject}.
2414\end{cfuncdesc}
2415
2416\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
2417Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on
2418failure.
2419\end{cfuncdesc}
2420
2421\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
2422Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
2423long}, or \NULL{} on failure.
2424\end{cfuncdesc}
2425
2426\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
2427Returns a new \ctype{PyLongObject} object from the integer part of
2428\var{v}, or \NULL{} on failure.
2429\end{cfuncdesc}
2430
2431\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
2432Returns a C \ctype{long} representation of the contents of
2433\var{pylong}. If \var{pylong} is greater than
2434\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is
2435raised.\withsubitem{(built-in exception)}{\ttindex{OverflowError}}
2436\end{cfuncdesc}
2437
2438\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
2439Returns a C \ctype{unsigned long} representation of the contents of
2440\var{pylong}. If \var{pylong} is greater than
2441\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError}
2442is raised.\withsubitem{(built-in exception)}{\ttindex{OverflowError}}
2443\end{cfuncdesc}
2444
2445\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
2446Returns a C \ctype{double} representation of the contents of \var{pylong}.
2447\end{cfuncdesc}
2448
2449\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
2450 int base}
2451Return a new \ctype{PyLongObject} based on the string value in
2452\var{str}, which is interpreted according to the radix in \var{base}.
2453If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first
2454character in \var{str} which follows the representation of the
2455number. If \var{base} is \code{0}, the radix will be determined base
2456on the leading characters of \var{str}: if \var{str} starts with
2457\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts
2458with \code{'0'}, radix 8 will be used; otherwise radix 10 will be
2459used. If \var{base} is not \code{0}, it must be between \code{2} and
2460\code{36}, inclusive. Leading spaces are ignored. If there are no
2461digits, \exception{ValueError} will be raised.
2462\end{cfuncdesc}
2463
2464
2465\subsection{Floating Point Objects \label{floatObjects}}
2466
2467\obindex{floating point}
2468\begin{ctypedesc}{PyFloatObject}
2469This subtype of \ctype{PyObject} represents a Python floating point
2470object.
2471\end{ctypedesc}
2472
2473\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2474This instance of \ctype{PyTypeObject} represents the Python floating
2475point type. This is the same object as \code{types.FloatType}.
2476\withsubitem{(in modules types)}{\ttindex{FloatType}}
2477\end{cvardesc}
2478
2479\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2480Returns true if its argument is a \ctype{PyFloatObject}.
2481\end{cfuncdesc}
2482
2483\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
2484Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
2485failure.
2486\end{cfuncdesc}
2487
2488\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
2489Returns a C \ctype{double} representation of the contents of \var{pyfloat}.
2490\end{cfuncdesc}
2491
2492\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
2493Returns a C \ctype{double} representation of the contents of
2494\var{pyfloat}, but without error checking.
2495\end{cfuncdesc}
2496
2497
2498\subsection{Complex Number Objects \label{complexObjects}}
2499
2500\obindex{complex number}
2501Python's complex number objects are implemented as two distinct types
2502when viewed from the C API: one is the Python object exposed to
2503Python programs, and the other is a C structure which represents the
2504actual complex number value. The API provides functions for working
2505with both.
2506
2507\subsubsection{Complex Numbers as C Structures}
2508
2509Note that the functions which accept these structures as parameters
2510and return them as results do so \emph{by value} rather than
2511dereferencing them through pointers. This is consistent throughout
2512the API.
2513
2514\begin{ctypedesc}{Py_complex}
2515The C structure which corresponds to the value portion of a Python
2516complex number object. Most of the functions for dealing with complex
2517number objects use structures of this type as input or output values,
2518as appropriate. It is defined as:
2519
2520\begin{verbatim}
2521typedef struct {
2522 double real;
2523 double imag;
2524} Py_complex;
2525\end{verbatim}
2526\end{ctypedesc}
2527
2528\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
2529Return the sum of two complex numbers, using the C
2530\ctype{Py_complex} representation.
2531\end{cfuncdesc}
2532
2533\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
2534Return the difference between two complex numbers, using the C
2535\ctype{Py_complex} representation.
2536\end{cfuncdesc}
2537
2538\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
2539Return the negation of the complex number \var{complex}, using the C
2540\ctype{Py_complex} representation.
2541\end{cfuncdesc}
2542
2543\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
2544Return the product of two complex numbers, using the C
2545\ctype{Py_complex} representation.
2546\end{cfuncdesc}
2547
2548\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
2549 Py_complex divisor}
2550Return the quotient of two complex numbers, using the C
2551\ctype{Py_complex} representation.
2552\end{cfuncdesc}
2553
2554\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
2555Return the exponentiation of \var{num} by \var{exp}, using the C
2556\ctype{Py_complex} representation.
2557\end{cfuncdesc}
2558
2559
2560\subsubsection{Complex Numbers as Python Objects}
2561
2562\begin{ctypedesc}{PyComplexObject}
2563This subtype of \ctype{PyObject} represents a Python complex number object.
2564\end{ctypedesc}
2565
2566\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2567This instance of \ctype{PyTypeObject} represents the Python complex
2568number type.
2569\end{cvardesc}
2570
2571\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2572Returns true if its argument is a \ctype{PyComplexObject}.
2573\end{cfuncdesc}
2574
2575\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
2576Create a new Python complex number object from a C
2577\ctype{Py_complex} value.
2578\end{cfuncdesc}
2579
2580\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
2581Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
2582\end{cfuncdesc}
2583
2584\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2585Returns the real part of \var{op} as a C \ctype{double}.
2586\end{cfuncdesc}
2587
2588\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2589Returns the imaginary part of \var{op} as a C \ctype{double}.
2590\end{cfuncdesc}
2591
2592\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2593Returns the \ctype{Py_complex} value of the complex number \var{op}.
2594\end{cfuncdesc}
2595
2596
2597
Fred Drakeefd146c1999-02-15 15:30:45 +00002598\section{Sequence Objects \label{sequenceObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002599
Fred Drake659ebfa2000-04-03 15:42:13 +00002600\obindex{sequence}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002601Generic operations on sequence objects were discussed in the previous
2602chapter; this section deals with the specific kinds of sequence
2603objects that are intrinsic to the Python language.
2604
2605
Fred Drakeefd146c1999-02-15 15:30:45 +00002606\subsection{String Objects \label{stringObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002607
Fred Drake89024422000-10-23 16:00:54 +00002608These functions raise \exception{TypeError} when expecting a string
2609parameter and are called with a non-string parameter.
2610
Fred Drake659ebfa2000-04-03 15:42:13 +00002611\obindex{string}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002612\begin{ctypedesc}{PyStringObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002613This subtype of \ctype{PyObject} represents a Python string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002614\end{ctypedesc}
2615
2616\begin{cvardesc}{PyTypeObject}{PyString_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002617This instance of \ctype{PyTypeObject} represents the Python string
2618type; it is the same object as \code{types.TypeType} in the Python
2619layer.\withsubitem{(in module types)}{\ttindex{StringType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002620\end{cvardesc}
2621
2622\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002623Returns true if the object \var{o} is a string object.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002624\end{cfuncdesc}
2625
Fred Drakec6fa34e1998-04-02 06:47:24 +00002626\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002627Returns a new string object with the value \var{v} on success, and
2628\NULL{} on failure.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002629\end{cfuncdesc}
2630
Fred Drake659ebfa2000-04-03 15:42:13 +00002631\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
2632 int len}
2633Returns a new string object with the value \var{v} and length
2634\var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
2635the contents of the string are uninitialized.
2636\end{cfuncdesc}
2637
Barry Warsawc86aa572001-08-28 02:31:28 +00002638\begin{cfuncdesc}{PyObject*}{PyString_FromFormat}{const char *format, ...}
2639Takes a C \code{printf}-style \var{format} string and a variable
2640number of arguments, calculates the size of the resulting Python
2641string and returns a string with the values formatted into it. The
2642variable arguments must be C types and must correspond exactly to the
2643format characters in the \var{format} string. The following format
2644characters are allowed:
2645\begin{tableiii}{l|l|l}{member}{Format Characters}{Type}{Comment}
2646 \lineiii{\%\%}{\emph{n/a}}{The literal \% character.}
2647 \lineiii{\%c}{int}{A single character, represented as an C int.}
2648 \lineiii{\%d}{int}{Exactly equivalent to \code{printf("\%d")}.}
2649 \lineiii{\%ld}{long}{Exactly equivalent to \code{printf("\%ld")}.}
2650 \lineiii{\%i}{int}{Exactly equivalent to \code{printf("\%i")}.}
2651 \lineiii{\%x}{int}{Exactly equivalent to \code{printf("\%x")}.}
2652 \lineiii{\%s}{char*}{A null-terminated C character array.}
2653 \lineiii{\%p}{void*}{The hex representation of a C pointer.
2654 Mostly equivalent to \code{printf("\%p")} except that it is
2655 guaranteed to start with the literal \code{0x} regardless of
2656 what the platform's \code{printf} yields.}
2657\end{tableiii}
2658\end{cfuncdesc}
2659
2660\begin{cfuncdesc}{PyObject*}{PyString_FromFormatV}{const char *format,
2661 va_list vargs}
2662Identical to \function{PyString_FromFormat()} except that it takes
2663exactly two arguments.
2664\end{cfuncdesc}
2665
Fred Drakec6fa34e1998-04-02 06:47:24 +00002666\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002667Returns the length of the string in string object \var{string}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002668\end{cfuncdesc}
2669
Fred Drake659ebfa2000-04-03 15:42:13 +00002670\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
Fred Drake5d644212000-10-07 12:31:50 +00002671Macro form of \cfunction{PyString_Size()} but without error
Fred Drake659ebfa2000-04-03 15:42:13 +00002672checking.
2673\end{cfuncdesc}
2674
Fred Drakec6fa34e1998-04-02 06:47:24 +00002675\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
Fred Drake659ebfa2000-04-03 15:42:13 +00002676Returns a null-terminated representation of the contents of
2677\var{string}. The pointer refers to the internal buffer of
Fred Drake89024422000-10-23 16:00:54 +00002678\var{string}, not a copy. The data must not be modified in any way,
2679unless the string was just created using
2680\code{PyString_FromStringAndSize(NULL, \var{size})}.
2681It must not be deallocated.
Fred Drake659ebfa2000-04-03 15:42:13 +00002682\end{cfuncdesc}
2683
2684\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
2685Macro form of \cfunction{PyString_AsString()} but without error
2686checking.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002687\end{cfuncdesc}
2688
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002689\begin{cfuncdesc}{int}{PyString_AsStringAndSize}{PyObject *obj,
2690 char **buffer,
2691 int *length}
2692Returns a null-terminated representation of the contents of the object
2693\var{obj} through the output variables \var{buffer} and \var{length}.
2694
2695The function accepts both string and Unicode objects as input. For
2696Unicode objects it returns the default encoded version of the object.
2697If \var{length} is set to \NULL{}, the resulting buffer may not contain
2698null characters; if it does, the function returns -1 and a
2699TypeError is raised.
2700
2701The buffer refers to an internal string buffer of \var{obj}, not a
Fred Drake89024422000-10-23 16:00:54 +00002702copy. The data must not be modified in any way, unless the string was
2703just created using \code{PyString_FromStringAndSize(NULL,
2704\var{size})}. It must not be deallocated.
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002705\end{cfuncdesc}
2706
Fred Drakec6fa34e1998-04-02 06:47:24 +00002707\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
2708 PyObject *newpart}
Fred Drake66b989c1999-02-15 20:15:39 +00002709Creates a new string object in \var{*string} containing the
Fred Drakeddc6c272000-03-31 18:22:38 +00002710contents of \var{newpart} appended to \var{string}; the caller will
2711own the new reference. The reference to the old value of \var{string}
2712will be stolen. If the new string
Fred Drake66b989c1999-02-15 20:15:39 +00002713cannot be created, the old reference to \var{string} will still be
2714discarded and the value of \var{*string} will be set to
2715\NULL{}; the appropriate exception will be set.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002716\end{cfuncdesc}
2717
2718\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
2719 PyObject *newpart}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002720Creates a new string object in \var{*string} containing the contents
Guido van Rossum44475131998-04-21 15:30:01 +00002721of \var{newpart} appended to \var{string}. This version decrements
2722the reference count of \var{newpart}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002723\end{cfuncdesc}
2724
2725\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
Guido van Rossum44475131998-04-21 15:30:01 +00002726A way to resize a string object even though it is ``immutable''.
2727Only use this to build up a brand new string object; don't use this if
2728the string may already be known in other parts of the code.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002729\end{cfuncdesc}
2730
2731\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
2732 PyObject *args}
Guido van Rossum44475131998-04-21 15:30:01 +00002733Returns a new string object from \var{format} and \var{args}. Analogous
Fred Drake659ebfa2000-04-03 15:42:13 +00002734to \code{\var{format} \%\ \var{args}}. The \var{args} argument must be
Guido van Rossum44475131998-04-21 15:30:01 +00002735a tuple.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002736\end{cfuncdesc}
2737
2738\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
Guido van Rossum44475131998-04-21 15:30:01 +00002739Intern the argument \var{*string} in place. The argument must be the
2740address of a pointer variable pointing to a Python string object.
2741If there is an existing interned string that is the same as
2742\var{*string}, it sets \var{*string} to it (decrementing the reference
2743count of the old string object and incrementing the reference count of
2744the interned string object), otherwise it leaves \var{*string} alone
2745and interns it (incrementing its reference count). (Clarification:
2746even though there is a lot of talk about reference counts, think of
Fred Drakef8830d11998-04-23 14:06:01 +00002747this function as reference-count-neutral; you own the object after
2748the call if and only if you owned it before the call.)
Fred Drakec6fa34e1998-04-02 06:47:24 +00002749\end{cfuncdesc}
2750
2751\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
Fred Drakef8830d11998-04-23 14:06:01 +00002752A combination of \cfunction{PyString_FromString()} and
2753\cfunction{PyString_InternInPlace()}, returning either a new string object
Guido van Rossum44475131998-04-21 15:30:01 +00002754that has been interned, or a new (``owned'') reference to an earlier
2755interned string object with the same value.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002756\end{cfuncdesc}
2757
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002758\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
2759 int size,
2760 const char *encoding,
2761 const char *errors}
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002762Creates an object by decoding \var{size} bytes of the encoded
2763buffer \var{s} using the codec registered
2764for \var{encoding}. \var{encoding} and \var{errors} have the same meaning
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002765as the parameters of the same name in the unicode() builtin
2766function. The codec to be used is looked up using the Python codec
2767registry. Returns \NULL{} in case an exception was raised by the
2768codec.
2769\end{cfuncdesc}
2770
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002771\begin{cfuncdesc}{PyObject*}{PyString_AsDecodedObject}{PyObject *str,
2772 const char *encoding,
2773 const char *errors}
2774Decodes a string object by passing it to the codec registered
2775for \var{encoding} and returns the result as Python
2776object. \var{encoding} and \var{errors} have the same meaning as the
2777parameters of the same name in the string .encode() method. The codec
2778to be used is looked up using the Python codec registry. Returns
2779\NULL{} in case an exception was raised by the codec.
2780\end{cfuncdesc}
2781
2782\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const char *s,
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002783 int size,
2784 const char *encoding,
2785 const char *errors}
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002786Encodes the \ctype{char} buffer of the given size by passing it to
2787the codec registered for \var{encoding} and returns a Python object.
2788\var{encoding} and \var{errors} have the same
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002789meaning as the parameters of the same name in the string .encode()
2790method. The codec to be used is looked up using the Python codec
2791registry. Returns \NULL{} in case an exception was raised by the
2792codec.
2793\end{cfuncdesc}
2794
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002795\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedObject}{PyObject *str,
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002796 const char *encoding,
2797 const char *errors}
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002798Encodes a string object using the codec registered
2799for \var{encoding} and returns the result as Python
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002800object. \var{encoding} and \var{errors} have the same meaning as the
2801parameters of the same name in the string .encode() method. The codec
2802to be used is looked up using the Python codec registry. Returns
2803\NULL{} in case an exception was raised by the codec.
2804\end{cfuncdesc}
2805
Fred Drakee5bf8b21998-02-12 21:22:28 +00002806
Fred Drakea4cd2612000-04-06 14:10:29 +00002807\subsection{Unicode Objects \label{unicodeObjects}}
2808\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
2809
2810%--- Unicode Type -------------------------------------------------------
2811
2812These are the basic Unicode object types used for the Unicode
2813implementation in Python:
2814
2815\begin{ctypedesc}{Py_UNICODE}
2816This type represents a 16-bit unsigned storage type which is used by
2817Python internally as basis for holding Unicode ordinals. On platforms
2818where \ctype{wchar_t} is available and also has 16-bits,
2819\ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
2820native platform compatibility. On all other platforms,
2821\ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
2822\end{ctypedesc}
2823
2824\begin{ctypedesc}{PyUnicodeObject}
2825This subtype of \ctype{PyObject} represents a Python Unicode object.
2826\end{ctypedesc}
2827
2828\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
2829This instance of \ctype{PyTypeObject} represents the Python Unicode type.
2830\end{cvardesc}
2831
2832%--- These are really C macros... is there a macrodesc TeX macro ?
2833
2834The following APIs are really C macros and can be used to do fast
2835checks and to access internal read-only data of Unicode objects:
2836
2837\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
2838Returns true if the object \var{o} is a Unicode object.
2839\end{cfuncdesc}
2840
2841\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
2842Returns the size of the object. o has to be a
2843PyUnicodeObject (not checked).
2844\end{cfuncdesc}
2845
2846\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
2847Returns the size of the object's internal buffer in bytes. o has to be
2848a PyUnicodeObject (not checked).
2849\end{cfuncdesc}
2850
Fred Drake992fe5a2000-06-16 21:04:15 +00002851\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002852Returns a pointer to the internal Py_UNICODE buffer of the object. o
2853has to be a PyUnicodeObject (not checked).
2854\end{cfuncdesc}
2855
Fred Drake992fe5a2000-06-16 21:04:15 +00002856\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002857Returns a (const char *) pointer to the internal buffer of the object.
2858o has to be a PyUnicodeObject (not checked).
2859\end{cfuncdesc}
2860
2861% --- Unicode character properties ---------------------------------------
2862
2863Unicode provides many different character properties. The most often
2864needed ones are available through these macros which are mapped to C
2865functions depending on the Python configuration.
2866
2867\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
2868Returns 1/0 depending on whether \var{ch} is a whitespace character.
2869\end{cfuncdesc}
2870
2871\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
2872Returns 1/0 depending on whether \var{ch} is a lowercase character.
2873\end{cfuncdesc}
2874
2875\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
Fred Drakeae96aab2000-07-03 13:38:10 +00002876Returns 1/0 depending on whether \var{ch} is an uppercase character.
Fred Drakea4cd2612000-04-06 14:10:29 +00002877\end{cfuncdesc}
2878
2879\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
2880Returns 1/0 depending on whether \var{ch} is a titlecase character.
2881\end{cfuncdesc}
2882
2883\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
2884Returns 1/0 depending on whether \var{ch} is a linebreak character.
2885\end{cfuncdesc}
2886
2887\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
2888Returns 1/0 depending on whether \var{ch} is a decimal character.
2889\end{cfuncdesc}
2890
2891\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
2892Returns 1/0 depending on whether \var{ch} is a digit character.
2893\end{cfuncdesc}
2894
2895\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
2896Returns 1/0 depending on whether \var{ch} is a numeric character.
2897\end{cfuncdesc}
2898
Fred Drakeae96aab2000-07-03 13:38:10 +00002899\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
2900Returns 1/0 depending on whether \var{ch} is an alphabetic character.
2901\end{cfuncdesc}
2902
2903\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
2904Returns 1/0 depending on whether \var{ch} is an alphanumeric character.
2905\end{cfuncdesc}
2906
Fred Drakea4cd2612000-04-06 14:10:29 +00002907These APIs can be used for fast direct character conversions:
2908
2909\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
2910Returns the character \var{ch} converted to lower case.
2911\end{cfuncdesc}
2912
2913\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
2914Returns the character \var{ch} converted to upper case.
2915\end{cfuncdesc}
2916
2917\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
2918Returns the character \var{ch} converted to title case.
2919\end{cfuncdesc}
2920
2921\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
2922Returns the character \var{ch} converted to a decimal positive integer.
2923Returns -1 in case this is not possible. Does not raise exceptions.
2924\end{cfuncdesc}
2925
2926\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
2927Returns the character \var{ch} converted to a single digit integer.
2928Returns -1 in case this is not possible. Does not raise exceptions.
2929\end{cfuncdesc}
2930
2931\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
2932Returns the character \var{ch} converted to a (positive) double.
2933Returns -1.0 in case this is not possible. Does not raise exceptions.
2934\end{cfuncdesc}
2935
2936% --- Plain Py_UNICODE ---------------------------------------------------
2937
2938To create Unicode objects and access their basic sequence properties,
2939use these APIs:
2940
2941\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
2942 int size}
2943
2944Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
2945given size. \var{u} may be \NULL{} which causes the contents to be
2946undefined. It is the user's responsibility to fill in the needed data.
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002947The buffer is copied into the new object. If the buffer is not \NULL{},
2948the return value might be a shared object. Therefore, modification of
2949the resulting Unicode Object is only allowed when \var{u} is \NULL{}.
Fred Drakea4cd2612000-04-06 14:10:29 +00002950\end{cfuncdesc}
2951
Fred Drake1d158692000-06-18 05:21:21 +00002952\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002953Return a read-only pointer to the Unicode object's internal
2954\ctype{Py_UNICODE} buffer.
2955\end{cfuncdesc}
2956
2957\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
2958Return the length of the Unicode object.
2959\end{cfuncdesc}
2960
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002961\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
2962 const char *encoding,
2963 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002964
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002965Coerce an encoded object obj to an Unicode object and return a
2966reference with incremented refcount.
Fred Drakea4cd2612000-04-06 14:10:29 +00002967
2968Coercion is done in the following way:
2969\begin{enumerate}
2970\item Unicode objects are passed back as-is with incremented
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002971 refcount. Note: these cannot be decoded; passing a non-NULL
2972 value for encoding will result in a TypeError.
Fred Drakea4cd2612000-04-06 14:10:29 +00002973
2974\item String and other char buffer compatible objects are decoded
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002975 according to the given encoding and using the error handling
2976 defined by errors. Both can be NULL to have the interface use
2977 the default values (see the next section for details).
Fred Drakea4cd2612000-04-06 14:10:29 +00002978
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002979\item All other objects cause an exception.
Fred Drakea4cd2612000-04-06 14:10:29 +00002980\end{enumerate}
2981The API returns NULL in case of an error. The caller is responsible
2982for decref'ing the returned objects.
2983\end{cfuncdesc}
2984
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002985\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
2986
2987Shortcut for PyUnicode_FromEncodedObject(obj, NULL, ``strict'')
2988which is used throughout the interpreter whenever coercion to
2989Unicode is needed.
2990\end{cfuncdesc}
2991
Fred Drakea4cd2612000-04-06 14:10:29 +00002992% --- wchar_t support for platforms which support it ---------------------
2993
2994If the platform supports \ctype{wchar_t} and provides a header file
2995wchar.h, Python can interface directly to this type using the
2996following functions. Support is optimized if Python's own
2997\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
2998
2999\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
3000 int size}
3001Create a Unicode Object from the \ctype{whcar_t} buffer \var{w} of the
3002given size. Returns \NULL{} on failure.
3003\end{cfuncdesc}
3004
3005\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
3006 wchar_t *w,
3007 int size}
Fred Drakea4cd2612000-04-06 14:10:29 +00003008Copies the Unicode Object contents into the \ctype{whcar_t} buffer
3009\var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
3010Returns the number of \ctype{whcar_t} characters copied or -1 in case
3011of an error.
3012\end{cfuncdesc}
3013
3014
3015\subsubsection{Builtin Codecs \label{builtinCodecs}}
3016
3017Python provides a set of builtin codecs which are written in C
3018for speed. All of these codecs are directly usable via the
3019following functions.
3020
3021Many of the following APIs take two arguments encoding and
3022errors. These parameters encoding and errors have the same semantics
3023as the ones of the builtin unicode() Unicode object constructor.
3024
3025Setting encoding to NULL causes the default encoding to be used which
Martin v. Löwis7c82a3e02001-09-05 17:09:48 +00003026is \ASCII{}. The file system calls should use
3027\var{Py_FileSystemDefaultEncoding} as the encoding for file
3028names. This variable should be treated as read-only: On some systems,
3029it will be a pointer to a static string, on others, it will change at
3030run-time, e.g. when the application invokes setlocale.
Fred Drakea4cd2612000-04-06 14:10:29 +00003031
3032Error handling is set by errors which may also be set to NULL meaning
3033to use the default handling defined for the codec. Default error
3034handling for all builtin codecs is ``strict'' (ValueErrors are raised).
3035
3036The codecs all use a similar interface. Only deviation from the
3037following generic ones are documented for simplicity.
3038
3039% --- Generic Codecs -----------------------------------------------------
3040
3041These are the generic codec APIs:
3042
3043\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
3044 int size,
3045 const char *encoding,
3046 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003047Create a Unicode object by decoding \var{size} bytes of the encoded
3048string \var{s}. \var{encoding} and \var{errors} have the same meaning
3049as the parameters of the same name in the unicode() builtin
3050function. The codec to be used is looked up using the Python codec
3051registry. Returns \NULL{} in case an exception was raised by the
3052codec.
3053\end{cfuncdesc}
3054
3055\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
3056 int size,
3057 const char *encoding,
3058 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003059Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
3060Python string object. \var{encoding} and \var{errors} have the same
3061meaning as the parameters of the same name in the Unicode .encode()
3062method. The codec to be used is looked up using the Python codec
3063registry. Returns \NULL{} in case an exception was raised by the
3064codec.
3065\end{cfuncdesc}
3066
3067\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
3068 const char *encoding,
3069 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003070Encodes a Unicode object and returns the result as Python string
3071object. \var{encoding} and \var{errors} have the same meaning as the
3072parameters of the same name in the Unicode .encode() method. The codec
3073to be used is looked up using the Python codec registry. Returns
3074\NULL{} in case an exception was raised by the codec.
3075\end{cfuncdesc}
3076
3077% --- UTF-8 Codecs -------------------------------------------------------
3078
3079These are the UTF-8 codec APIs:
3080
3081\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
3082 int size,
3083 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003084Creates a Unicode object by decoding \var{size} bytes of the UTF-8
3085encoded string \var{s}. Returns \NULL{} in case an exception was
3086raised by the codec.
3087\end{cfuncdesc}
3088
3089\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
3090 int size,
3091 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003092Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
3093and returns a Python string object. Returns \NULL{} in case an
3094exception was raised by the codec.
3095\end{cfuncdesc}
3096
3097\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003098Encodes a Unicode objects using UTF-8 and returns the result as Python
3099string object. Error handling is ``strict''. Returns
3100\NULL{} in case an exception was raised by the codec.
3101\end{cfuncdesc}
3102
3103% --- UTF-16 Codecs ------------------------------------------------------ */
3104
3105These are the UTF-16 codec APIs:
3106
3107\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
3108 int size,
3109 const char *errors,
3110 int *byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00003111Decodes \var{length} bytes from a UTF-16 encoded buffer string and
3112returns the corresponding Unicode object.
3113
3114\var{errors} (if non-NULL) defines the error handling. It defaults
3115to ``strict''.
3116
3117If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
3118the given byte order:
3119
3120\begin{verbatim}
3121 *byteorder == -1: little endian
3122 *byteorder == 0: native order
3123 *byteorder == 1: big endian
3124\end{verbatim}
3125
3126and then switches according to all byte order marks (BOM) it finds in
3127the input data. BOM marks are not copied into the resulting Unicode
3128string. After completion, \var{*byteorder} is set to the current byte
3129order at the end of input data.
3130
3131If \var{byteorder} is \NULL{}, the codec starts in native order mode.
3132
3133Returns \NULL{} in case an exception was raised by the codec.
3134\end{cfuncdesc}
3135
3136\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
3137 int size,
3138 const char *errors,
3139 int byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00003140Returns a Python string object holding the UTF-16 encoded value of the
3141Unicode data in \var{s}.
3142
Fred Drakea8455ab2000-06-16 19:58:42 +00003143If \var{byteorder} is not \code{0}, output is written according to the
Fred Drakea4cd2612000-04-06 14:10:29 +00003144following byte order:
3145
3146\begin{verbatim}
3147 byteorder == -1: little endian
3148 byteorder == 0: native byte order (writes a BOM mark)
3149 byteorder == 1: big endian
3150\end{verbatim}
3151
Fred Drakea8455ab2000-06-16 19:58:42 +00003152If byteorder is \code{0}, the output string will always start with the
Fred Drakea4cd2612000-04-06 14:10:29 +00003153Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
3154prepended.
3155
3156Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
3157reduced to UCS-2. This trick makes it possible to add full UTF-16
3158capabilities at a later point without comprimising the APIs.
3159
3160Returns \NULL{} in case an exception was raised by the codec.
3161\end{cfuncdesc}
3162
3163\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003164Returns a Python string using the UTF-16 encoding in native byte
3165order. The string always starts with a BOM mark. Error handling is
3166``strict''. Returns \NULL{} in case an exception was raised by the
3167codec.
3168\end{cfuncdesc}
3169
3170% --- Unicode-Escape Codecs ----------------------------------------------
3171
3172These are the ``Unicode Esacpe'' codec APIs:
3173
3174\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
3175 int size,
3176 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003177Creates a Unicode object by decoding \var{size} bytes of the Unicode-Esacpe
3178encoded string \var{s}. Returns \NULL{} in case an exception was
3179raised by the codec.
3180\end{cfuncdesc}
3181
3182\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
3183 int size,
3184 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003185Encodes the \ctype{Py_UNICODE} buffer of the given size using Unicode-Escape
3186and returns a Python string object. Returns \NULL{} in case an
3187exception was raised by the codec.
3188\end{cfuncdesc}
3189
3190\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003191Encodes a Unicode objects using Unicode-Escape and returns the result
3192as Python string object. Error handling is ``strict''. Returns
3193\NULL{} in case an exception was raised by the codec.
3194\end{cfuncdesc}
3195
3196% --- Raw-Unicode-Escape Codecs ------------------------------------------
3197
3198These are the ``Raw Unicode Esacpe'' codec APIs:
3199
3200\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
3201 int size,
3202 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003203Creates a Unicode object by decoding \var{size} bytes of the Raw-Unicode-Esacpe
3204encoded string \var{s}. Returns \NULL{} in case an exception was
3205raised by the codec.
3206\end{cfuncdesc}
3207
3208\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
3209 int size,
3210 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003211Encodes the \ctype{Py_UNICODE} buffer of the given size using Raw-Unicode-Escape
3212and returns a Python string object. Returns \NULL{} in case an
3213exception was raised by the codec.
3214\end{cfuncdesc}
3215
3216\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003217Encodes a Unicode objects using Raw-Unicode-Escape and returns the result
3218as Python string object. Error handling is ``strict''. Returns
3219\NULL{} in case an exception was raised by the codec.
3220\end{cfuncdesc}
3221
3222% --- Latin-1 Codecs -----------------------------------------------------
3223
3224These are the Latin-1 codec APIs:
3225
3226Latin-1 corresponds to the first 256 Unicode ordinals and only these
3227are accepted by the codecs during encoding.
3228
3229\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00003230 int size,
3231 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003232Creates a Unicode object by decoding \var{size} bytes of the Latin-1
3233encoded string \var{s}. Returns \NULL{} in case an exception was
3234raised by the codec.
3235\end{cfuncdesc}
3236
3237\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00003238 int size,
3239 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003240Encodes the \ctype{Py_UNICODE} buffer of the given size using Latin-1
3241and returns a Python string object. Returns \NULL{} in case an
3242exception was raised by the codec.
3243\end{cfuncdesc}
3244
3245\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003246Encodes a Unicode objects using Latin-1 and returns the result as
3247Python string object. Error handling is ``strict''. Returns
3248\NULL{} in case an exception was raised by the codec.
3249\end{cfuncdesc}
3250
3251% --- ASCII Codecs -------------------------------------------------------
3252
Fred Drake1d158692000-06-18 05:21:21 +00003253These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
3254accepted. All other codes generate errors.
Fred Drakea4cd2612000-04-06 14:10:29 +00003255
3256\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00003257 int size,
3258 const char *errors}
3259Creates a Unicode object by decoding \var{size} bytes of the
3260\ASCII{} encoded string \var{s}. Returns \NULL{} in case an exception
3261was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003262\end{cfuncdesc}
3263
3264\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00003265 int size,
3266 const char *errors}
3267Encodes the \ctype{Py_UNICODE} buffer of the given size using
3268\ASCII{} and returns a Python string object. Returns \NULL{} in case
3269an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003270\end{cfuncdesc}
3271
3272\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
Fred Drake1d158692000-06-18 05:21:21 +00003273Encodes a Unicode objects using \ASCII{} and returns the result as Python
Fred Drakea4cd2612000-04-06 14:10:29 +00003274string object. Error handling is ``strict''. Returns
3275\NULL{} in case an exception was raised by the codec.
3276\end{cfuncdesc}
3277
3278% --- Character Map Codecs -----------------------------------------------
3279
3280These are the mapping codec APIs:
3281
3282This codec is special in that it can be used to implement many
3283different codecs (and this is in fact what was done to obtain most of
3284the standard codecs included in the \module{encodings} package). The
3285codec uses mapping to encode and decode characters.
3286
3287Decoding mappings must map single string characters to single Unicode
3288characters, integers (which are then interpreted as Unicode ordinals)
3289or None (meaning "undefined mapping" and causing an error).
3290
3291Encoding mappings must map single Unicode characters to single string
3292characters, integers (which are then interpreted as Latin-1 ordinals)
3293or None (meaning "undefined mapping" and causing an error).
3294
3295The mapping objects provided must only support the __getitem__ mapping
3296interface.
3297
3298If a character lookup fails with a LookupError, the character is
3299copied as-is meaning that its ordinal value will be interpreted as
3300Unicode or Latin-1 ordinal resp. Because of this, mappings only need
3301to contain those mappings which map characters to different code
3302points.
3303
3304\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
3305 int size,
3306 PyObject *mapping,
3307 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003308Creates a Unicode object by decoding \var{size} bytes of the encoded
3309string \var{s} using the given \var{mapping} object. Returns \NULL{}
3310in case an exception was raised by the codec.
3311\end{cfuncdesc}
3312
3313\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
3314 int size,
3315 PyObject *mapping,
3316 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003317Encodes the \ctype{Py_UNICODE} buffer of the given size using the
3318given \var{mapping} object and returns a Python string object.
3319Returns \NULL{} in case an exception was raised by the codec.
3320\end{cfuncdesc}
3321
3322\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
3323 PyObject *mapping}
Fred Drakea4cd2612000-04-06 14:10:29 +00003324Encodes a Unicode objects using the given \var{mapping} object and
3325returns the result as Python string object. Error handling is
3326``strict''. Returns \NULL{} in case an exception was raised by the
3327codec.
3328\end{cfuncdesc}
3329
3330The following codec API is special in that maps Unicode to Unicode.
3331
3332\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
3333 int size,
3334 PyObject *table,
3335 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003336Translates a \ctype{Py_UNICODE} buffer of the given length by applying
3337a character mapping \var{table} to it and returns the resulting
Fred Drake1d158692000-06-18 05:21:21 +00003338Unicode object. Returns \NULL{} when an exception was raised by the
3339codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003340
3341The \var{mapping} table must map Unicode ordinal integers to Unicode
3342ordinal integers or None (causing deletion of the character).
3343
3344Mapping tables must only provide the __getitem__ interface,
3345e.g. dictionaries or sequences. Unmapped character ordinals (ones
3346which cause a LookupError) are left untouched and are copied as-is.
Fred Drakea4cd2612000-04-06 14:10:29 +00003347\end{cfuncdesc}
3348
3349% --- MBCS codecs for Windows --------------------------------------------
3350
Fred Drake1d158692000-06-18 05:21:21 +00003351These are the MBCS codec APIs. They are currently only available on
Fred Drakea4cd2612000-04-06 14:10:29 +00003352Windows and use the Win32 MBCS converters to implement the
Fred Drake1d158692000-06-18 05:21:21 +00003353conversions. Note that MBCS (or DBCS) is a class of encodings, not
3354just one. The target encoding is defined by the user settings on the
3355machine running the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003356
3357\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
3358 int size,
3359 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003360Creates a Unicode object by decoding \var{size} bytes of the MBCS
Fred Drake1d158692000-06-18 05:21:21 +00003361encoded string \var{s}. Returns \NULL{} in case an exception was
Fred Drakea4cd2612000-04-06 14:10:29 +00003362raised by the codec.
3363\end{cfuncdesc}
3364
3365\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
3366 int size,
3367 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003368Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
3369and returns a Python string object. Returns \NULL{} in case an
3370exception was raised by the codec.
3371\end{cfuncdesc}
3372
3373\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003374Encodes a Unicode objects using MBCS and returns the result as Python
Fred Drake1d158692000-06-18 05:21:21 +00003375string object. Error handling is ``strict''. Returns \NULL{} in case
3376an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003377\end{cfuncdesc}
3378
3379% --- Methods & Slots ----------------------------------------------------
3380
3381\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
3382
3383The following APIs are capable of handling Unicode objects and strings
3384on input (we refer to them as strings in the descriptions) and return
3385Unicode objects or integers as apporpriate.
3386
3387They all return \NULL{} or -1 in case an exception occurrs.
3388
3389\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
3390 PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00003391Concat two strings giving a new Unicode string.
3392\end{cfuncdesc}
3393
3394\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
3395 PyObject *sep,
3396 int maxsplit}
Fred Drakea4cd2612000-04-06 14:10:29 +00003397Split a string giving a list of Unicode strings.
3398
3399If sep is NULL, splitting will be done at all whitespace
3400substrings. Otherwise, splits occur at the given separator.
3401
3402At most maxsplit splits will be done. If negative, no limit is set.
3403
3404Separators are not included in the resulting list.
3405\end{cfuncdesc}
3406
3407\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
3408 int maxsplit}
Fred Drake1d158692000-06-18 05:21:21 +00003409Split a Unicode string at line breaks, returning a list of Unicode
3410strings. CRLF is considered to be one line break. The Line break
3411characters are not included in the resulting strings.
Fred Drakea4cd2612000-04-06 14:10:29 +00003412\end{cfuncdesc}
3413
3414\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
3415 PyObject *table,
3416 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003417Translate a string by applying a character mapping table to it and
3418return the resulting Unicode object.
3419
3420The mapping table must map Unicode ordinal integers to Unicode ordinal
3421integers or None (causing deletion of the character).
3422
3423Mapping tables must only provide the __getitem__ interface,
3424e.g. dictionaries or sequences. Unmapped character ordinals (ones
3425which cause a LookupError) are left untouched and are copied as-is.
3426
3427\var{errors} has the usual meaning for codecs. It may be \NULL{}
3428which indicates to use the default error handling.
Fred Drakea4cd2612000-04-06 14:10:29 +00003429\end{cfuncdesc}
3430
3431\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
3432 PyObject *seq}
Fred Drakea4cd2612000-04-06 14:10:29 +00003433Join a sequence of strings using the given separator and return
3434the resulting Unicode string.
3435\end{cfuncdesc}
3436
3437\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
3438 PyObject *substr,
3439 int start,
3440 int end,
3441 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00003442Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
3443the given tail end (\var{direction} == -1 means to do a prefix match,
3444\var{direction} == 1 a suffix match), 0 otherwise.
3445\end{cfuncdesc}
3446
3447\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
3448 PyObject *substr,
3449 int start,
3450 int end,
3451 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00003452Return the first position of \var{substr} in
3453\var{str}[\var{start}:\var{end}] using the given \var{direction}
3454(\var{direction} == 1 means to do a forward search,
3455\var{direction} == -1 a backward search), 0 otherwise.
3456\end{cfuncdesc}
3457
3458\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
3459 PyObject *substr,
3460 int start,
3461 int end}
Fred Drakea4cd2612000-04-06 14:10:29 +00003462Count the number of occurrences of \var{substr} in
3463\var{str}[\var{start}:\var{end}]
3464\end{cfuncdesc}
3465
3466\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
3467 PyObject *substr,
3468 PyObject *replstr,
3469 int maxcount}
Fred Drakea4cd2612000-04-06 14:10:29 +00003470Replace at most \var{maxcount} occurrences of \var{substr} in
3471\var{str} with \var{replstr} and return the resulting Unicode object.
3472\var{maxcount} == -1 means: replace all occurrences.
3473\end{cfuncdesc}
3474
Fred Drake1d158692000-06-18 05:21:21 +00003475\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00003476Compare two strings and return -1, 0, 1 for less than, equal,
3477greater than resp.
3478\end{cfuncdesc}
3479
3480\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
3481 PyObject *args}
Fred Drake1d158692000-06-18 05:21:21 +00003482Returns a new string object from \var{format} and \var{args}; this is
3483analogous to \code{\var{format} \%\ \var{args}}. The
3484\var{args} argument must be a tuple.
Fred Drakea4cd2612000-04-06 14:10:29 +00003485\end{cfuncdesc}
3486
3487\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
3488 PyObject *element}
Fred Drakea4cd2612000-04-06 14:10:29 +00003489Checks whether \var{element} is contained in \var{container} and
Fred Drake1d158692000-06-18 05:21:21 +00003490returns true or false accordingly.
Fred Drakea4cd2612000-04-06 14:10:29 +00003491
Fred Drake1d158692000-06-18 05:21:21 +00003492\var{element} has to coerce to a one element Unicode string. \code{-1} is
Fred Drakea4cd2612000-04-06 14:10:29 +00003493returned in case of an error.
3494\end{cfuncdesc}
3495
3496
Fred Drake58c5a2a1999-08-04 13:13:24 +00003497\subsection{Buffer Objects \label{bufferObjects}}
Fred Drake659ebfa2000-04-03 15:42:13 +00003498\sectionauthor{Greg Stein}{gstein@lyra.org}
Fred Drake58c5a2a1999-08-04 13:13:24 +00003499
Fred Drake659ebfa2000-04-03 15:42:13 +00003500\obindex{buffer}
3501Python objects implemented in C can export a group of functions called
3502the ``buffer\index{buffer interface} interface.'' These functions can
3503be used by an object to expose its data in a raw, byte-oriented
3504format. Clients of the object can use the buffer interface to access
3505the object data directly, without needing to copy it first.
3506
3507Two examples of objects that support
3508the buffer interface are strings and arrays. The string object exposes
3509the character contents in the buffer interface's byte-oriented
3510form. An array can also expose its contents, but it should be noted
3511that array elements may be multi-byte values.
3512
3513An example user of the buffer interface is the file object's
3514\method{write()} method. Any object that can export a series of bytes
3515through the buffer interface can be written to a file. There are a
Fred Drake88fdaa72001-07-20 20:56:11 +00003516number of format codes to \cfunction{PyArg_ParseTuple()} that operate
Fred Drake659ebfa2000-04-03 15:42:13 +00003517against an object's buffer interface, returning data from the target
3518object.
3519
3520More information on the buffer interface is provided in the section
3521``Buffer Object Structures'' (section \ref{buffer-structs}), under
3522the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
3523
3524A ``buffer object'' is defined in the \file{bufferobject.h} header
3525(included by \file{Python.h}). These objects look very similar to
3526string objects at the Python programming level: they support slicing,
3527indexing, concatenation, and some other standard string
3528operations. However, their data can come from one of two sources: from
3529a block of memory, or from another object which exports the buffer
3530interface.
3531
3532Buffer objects are useful as a way to expose the data from another
3533object's buffer interface to the Python programmer. They can also be
3534used as a zero-copy slicing mechanism. Using their ability to
3535reference a block of memory, it is possible to expose any data to the
3536Python programmer quite easily. The memory could be a large, constant
3537array in a C extension, it could be a raw block of memory for
3538manipulation before passing to an operating system library, or it
3539could be used to pass around structured data in its native, in-memory
3540format.
3541
3542\begin{ctypedesc}{PyBufferObject}
3543This subtype of \ctype{PyObject} represents a buffer object.
3544\end{ctypedesc}
Fred Drake58c5a2a1999-08-04 13:13:24 +00003545
3546\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
3547The instance of \ctype{PyTypeObject} which represents the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00003548buffer type; it is the same object as \code{types.BufferType} in the
3549Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003550\end{cvardesc}
3551
3552\begin{cvardesc}{int}{Py_END_OF_BUFFER}
Fred Drake659ebfa2000-04-03 15:42:13 +00003553This constant may be passed as the \var{size} parameter to
3554\cfunction{PyBuffer_FromObject()} or
3555\cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the new
3556\ctype{PyBufferObject} should refer to \var{base} object from the
3557specified \var{offset} to the end of its exported buffer. Using this
3558enables the caller to avoid querying the \var{base} object for its
3559length.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003560\end{cvardesc}
3561
3562\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
3563Return true if the argument has type \cdata{PyBuffer_Type}.
3564\end{cfuncdesc}
3565
3566\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
3567 int offset, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003568Return a new read-only buffer object. This raises
3569\exception{TypeError} if \var{base} doesn't support the read-only
3570buffer protocol or doesn't provide exactly one buffer segment, or it
3571raises \exception{ValueError} if \var{offset} is less than zero. The
3572buffer will hold a reference to the \var{base} object, and the
3573buffer's contents will refer to the \var{base} object's buffer
3574interface, starting as position \var{offset} and extending for
3575\var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
3576the new buffer's contents extend to the length of the
3577\var{base} object's exported buffer data.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003578\end{cfuncdesc}
3579
3580\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
3581 int offset,
3582 int size}
3583Return a new writable buffer object. Parameters and exceptions are
3584similar to those for \cfunction{PyBuffer_FromObject()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003585If the \var{base} object does not export the writeable buffer
3586protocol, then \exception{TypeError} is raised.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003587\end{cfuncdesc}
3588
3589\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003590Return a new read-only buffer object that reads from a specified
3591location in memory, with a specified size.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003592The caller is responsible for ensuring that the memory buffer, passed
3593in as \var{ptr}, is not deallocated while the returned buffer object
3594exists. Raises \exception{ValueError} if \var{size} is less than
Fred Drake659ebfa2000-04-03 15:42:13 +00003595zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be passed
3596for the \var{size} parameter; \exception{ValueError} will be raised in
3597that case.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003598\end{cfuncdesc}
3599
3600\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003601Similar to \cfunction{PyBuffer_FromMemory()}, but the returned buffer
3602is writable.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003603\end{cfuncdesc}
3604
3605\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
3606Returns a new writable buffer object that maintains its own memory
Fred Drake659ebfa2000-04-03 15:42:13 +00003607buffer of \var{size} bytes. \exception{ValueError} is returned if
3608\var{size} is not zero or positive.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003609\end{cfuncdesc}
3610
Guido van Rossum44475131998-04-21 15:30:01 +00003611
Fred Drakeefd146c1999-02-15 15:30:45 +00003612\subsection{Tuple Objects \label{tupleObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003613
Fred Drake659ebfa2000-04-03 15:42:13 +00003614\obindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003615\begin{ctypedesc}{PyTupleObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003616This subtype of \ctype{PyObject} represents a Python tuple object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003617\end{ctypedesc}
3618
3619\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003620This instance of \ctype{PyTypeObject} represents the Python tuple
3621type; it is the same object as \code{types.TupleType} in the Python
3622layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003623\end{cvardesc}
3624
3625\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
3626Return true if the argument is a tuple object.
3627\end{cfuncdesc}
3628
Fred Drake659ebfa2000-04-03 15:42:13 +00003629\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
3630Return a new tuple object of size \var{len}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003631\end{cfuncdesc}
3632
Fred Drakea05460c2001-02-12 17:38:18 +00003633\begin{cfuncdesc}{int}{PyTuple_Size}{PyObject *p}
Fred Drakee058b4f1998-02-16 06:15:35 +00003634Takes a pointer to a tuple object, and returns the size
Fred Drakee5bf8b21998-02-12 21:22:28 +00003635of that tuple.
3636\end{cfuncdesc}
3637
Fred Drake0e40c3d2001-08-20 16:48:59 +00003638\begin{cfuncdesc}{int}{PyTuple_GET_SIZE}{PyObject *p}
3639Return the size of the tuple \var{p}, which must be non-\NULL{} and
3640point to a tuple; no error checking is performed.
3641\end{cfuncdesc}
3642
Fred Drakea05460c2001-02-12 17:38:18 +00003643\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003644Returns the object at position \var{pos} in the tuple pointed
3645to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003646sets an \exception{IndexError} exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003647\end{cfuncdesc}
3648
Fred Drakea05460c2001-02-12 17:38:18 +00003649\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyObject *p, int pos}
Fred Drakefac312f2001-05-29 15:13:00 +00003650Like \cfunction{PyTuple_GetItem()}, but does no checking of its
3651arguments.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003652\end{cfuncdesc}
3653
Fred Drakea05460c2001-02-12 17:38:18 +00003654\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyObject *p,
3655 int low, int high}
Fred Drakee058b4f1998-02-16 06:15:35 +00003656Takes a slice of the tuple pointed to by \var{p} from
3657\var{low} to \var{high} and returns it as a new tuple.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003658\end{cfuncdesc}
3659
Fred Drake659ebfa2000-04-03 15:42:13 +00003660\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
3661 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003662Inserts a reference to object \var{o} at position \var{pos} of
3663the tuple pointed to by \var{p}. It returns \code{0} on success.
Fred Drake659ebfa2000-04-03 15:42:13 +00003664\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003665\end{cfuncdesc}
3666
Fred Drake659ebfa2000-04-03 15:42:13 +00003667\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
3668 int pos, PyObject *o}
Fred Drakefac312f2001-05-29 15:13:00 +00003669Like \cfunction{PyTuple_SetItem()}, but does no error checking, and
Fred Drakee5bf8b21998-02-12 21:22:28 +00003670should \emph{only} be used to fill in brand new tuples.
Fred Drake659ebfa2000-04-03 15:42:13 +00003671\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003672\end{cfuncdesc}
3673
Fred Drakefac312f2001-05-29 15:13:00 +00003674\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyObject **p, int newsize}
Fred Drake659ebfa2000-04-03 15:42:13 +00003675Can be used to resize a tuple. \var{newsize} will be the new length
3676of the tuple. Because tuples are \emph{supposed} to be immutable,
3677this should only be used if there is only one reference to the object.
3678Do \emph{not} use this if the tuple may already be known to some other
Fred Drakefac312f2001-05-29 15:13:00 +00003679part of the code. The tuple will always grow or shrink at the end.
3680Think of this as destroying the old tuple and creating a new one, only
3681more efficiently. Returns \code{0} on success. Client code should
3682never assume that the resulting value of \code{*\var{p}} will be the
3683same as before calling this function. If the object referenced by
3684\code{*\var{p}} is replaced, the original \code{*\var{p}} is
3685destroyed. On failure, returns \code{-1} and sets \code{*\var{p}} to
3686\NULL, and raises \exception{MemoryError} or \exception{SystemError}.
3687\versionchanged[Removed unused third parameter, \var{last_is_sticky}]{2.2}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003688\end{cfuncdesc}
3689
3690
Fred Drakeefd146c1999-02-15 15:30:45 +00003691\subsection{List Objects \label{listObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003692
Fred Drake659ebfa2000-04-03 15:42:13 +00003693\obindex{list}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003694\begin{ctypedesc}{PyListObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003695This subtype of \ctype{PyObject} represents a Python list object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003696\end{ctypedesc}
3697
3698\begin{cvardesc}{PyTypeObject}{PyList_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003699This instance of \ctype{PyTypeObject} represents the Python list
3700type. This is the same object as \code{types.ListType}.
3701\withsubitem{(in module types)}{\ttindex{ListType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003702\end{cvardesc}
3703
3704\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003705Returns true if its argument is a \ctype{PyListObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003706\end{cfuncdesc}
3707
Fred Drake659ebfa2000-04-03 15:42:13 +00003708\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
3709Returns a new list of length \var{len} on success, or \NULL{} on
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003710failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003711\end{cfuncdesc}
3712
Fred Drakec6fa34e1998-04-02 06:47:24 +00003713\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003714Returns the length of the list object in \var{list}; this is
3715equivalent to \samp{len(\var{list})} on a list object.
3716\bifuncindex{len}
3717\end{cfuncdesc}
3718
3719\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
Fred Drake5d644212000-10-07 12:31:50 +00003720Macro form of \cfunction{PyList_Size()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003721\end{cfuncdesc}
3722
Fred Drakec6fa34e1998-04-02 06:47:24 +00003723\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
Guido van Rossum44475131998-04-21 15:30:01 +00003724Returns the object at position \var{pos} in the list pointed
3725to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003726sets an \exception{IndexError} exception.
3727\end{cfuncdesc}
3728
3729\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
3730Macro form of \cfunction{PyList_GetItem()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003731\end{cfuncdesc}
3732
Fred Drakec6fa34e1998-04-02 06:47:24 +00003733\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
3734 PyObject *item}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003735Sets the item at index \var{index} in list to \var{item}.
Fred Drakebab29652001-07-10 16:10:08 +00003736Returns \code{0} on success or \code{-1} on failure.
Fred Drake00d0cb62001-06-03 03:12:57 +00003737\strong{Note:} This function ``steals'' a reference to \var{item} and
3738discards a reference to an item already in the list at the affected
3739position.
Fred Drake659ebfa2000-04-03 15:42:13 +00003740\end{cfuncdesc}
3741
Fred Drakebab29652001-07-10 16:10:08 +00003742\begin{cfuncdesc}{void}{PyList_SET_ITEM}{PyObject *list, int i,
Fred Drake659ebfa2000-04-03 15:42:13 +00003743 PyObject *o}
3744Macro form of \cfunction{PyList_SetItem()} without error checking.
Fred Drake00d0cb62001-06-03 03:12:57 +00003745\strong{Note:} This function ``steals'' a reference to \var{item},
3746and, unlike \cfunction{PyList_SetItem()}, does \emph{not} discard a
Fred Drakebab29652001-07-10 16:10:08 +00003747reference to any item that it being replaced; any reference in
3748\var{list} at position \var{i} will be leaked. This is normally only
3749used to fill in new lists where there is no previous content.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003750\end{cfuncdesc}
3751
Fred Drakec6fa34e1998-04-02 06:47:24 +00003752\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
Guido van Rossum44475131998-04-21 15:30:01 +00003753 PyObject *item}
3754Inserts the item \var{item} into list \var{list} in front of index
Fred Drake659ebfa2000-04-03 15:42:13 +00003755\var{index}. Returns \code{0} if successful; returns \code{-1} and
3756raises an exception if unsuccessful. Analogous to
3757\code{\var{list}.insert(\var{index}, \var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003758\end{cfuncdesc}
3759
Fred Drakec6fa34e1998-04-02 06:47:24 +00003760\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
Guido van Rossum44475131998-04-21 15:30:01 +00003761Appends the object \var{item} at the end of list \var{list}. Returns
Fred Drake659ebfa2000-04-03 15:42:13 +00003762\code{0} if successful; returns \code{-1} and sets an exception if
3763unsuccessful. Analogous to \code{\var{list}.append(\var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003764\end{cfuncdesc}
3765
Fred Drakec6fa34e1998-04-02 06:47:24 +00003766\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
3767 int low, int high}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003768Returns a list of the objects in \var{list} containing the objects
Guido van Rossum44475131998-04-21 15:30:01 +00003769\emph{between} \var{low} and \var{high}. Returns NULL and sets an
3770exception if unsuccessful.
Fred Drake659ebfa2000-04-03 15:42:13 +00003771Analogous to \code{\var{list}[\var{low}:\var{high}]}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003772\end{cfuncdesc}
3773
Fred Drakec6fa34e1998-04-02 06:47:24 +00003774\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
3775 int low, int high,
3776 PyObject *itemlist}
Fred Drake659ebfa2000-04-03 15:42:13 +00003777Sets the slice of \var{list} between \var{low} and \var{high} to the
3778contents of \var{itemlist}. Analogous to
3779\code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
3780\code{0} on success, \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003781\end{cfuncdesc}
3782
Fred Drakec6fa34e1998-04-02 06:47:24 +00003783\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003784Sorts the items of \var{list} in place. Returns \code{0} on success,
3785\code{-1} on failure. This is equivalent to
3786\samp{\var{list}.sort()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003787\end{cfuncdesc}
3788
Fred Drakec6fa34e1998-04-02 06:47:24 +00003789\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003790Reverses the items of \var{list} in place. Returns \code{0} on
3791success, \code{-1} on failure. This is the equivalent of
3792\samp{\var{list}.reverse()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003793\end{cfuncdesc}
3794
Fred Drakec6fa34e1998-04-02 06:47:24 +00003795\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003796Returns a new tuple object containing the contents of \var{list};
3797equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003798\end{cfuncdesc}
3799
3800
Fred Drakeefd146c1999-02-15 15:30:45 +00003801\section{Mapping Objects \label{mapObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003802
Fred Drake659ebfa2000-04-03 15:42:13 +00003803\obindex{mapping}
3804
3805
Fred Drakeefd146c1999-02-15 15:30:45 +00003806\subsection{Dictionary Objects \label{dictObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003807
Fred Drake659ebfa2000-04-03 15:42:13 +00003808\obindex{dictionary}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003809\begin{ctypedesc}{PyDictObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003810This subtype of \ctype{PyObject} represents a Python dictionary object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003811\end{ctypedesc}
3812
3813\begin{cvardesc}{PyTypeObject}{PyDict_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003814This instance of \ctype{PyTypeObject} represents the Python dictionary
3815type. This is exposed to Python programs as \code{types.DictType} and
3816\code{types.DictionaryType}.
3817\withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003818\end{cvardesc}
3819
3820\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003821Returns true if its argument is a \ctype{PyDictObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003822\end{cfuncdesc}
3823
Fred Drakec6fa34e1998-04-02 06:47:24 +00003824\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003825Returns a new empty dictionary, or \NULL{} on failure.
3826\end{cfuncdesc}
3827
3828\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
3829Empties an existing dictionary of all key-value pairs.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003830\end{cfuncdesc}
3831
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003832\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
Fred Drake0e40c3d2001-08-20 16:48:59 +00003833Returns a new dictionary that contains the same key-value pairs as
3834\var{p}.
Fred Drake11ee9022001-08-10 21:31:12 +00003835\versionadded{1.6}
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003836\end{cfuncdesc}
3837
Fred Drake659ebfa2000-04-03 15:42:13 +00003838\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
3839 PyObject *val}
Fred Drakebab29652001-07-10 16:10:08 +00003840Inserts \var{value} into the dictionary \var{p} with a key of \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003841\var{key} must be hashable; if it isn't, \exception{TypeError} will be
3842raised.
Fred Drakebab29652001-07-10 16:10:08 +00003843Returns \code{0} on success or \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003844\end{cfuncdesc}
3845
Fred Drake83e01bf2001-03-16 15:41:29 +00003846\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p,
Fred Drakee5bf8b21998-02-12 21:22:28 +00003847 char *key,
3848 PyObject *val}
Fred Drakebab29652001-07-10 16:10:08 +00003849Inserts \var{value} into the dictionary \var{p} using \var{key}
Fred Drake1d158692000-06-18 05:21:21 +00003850as a key. \var{key} should be a \ctype{char*}. The key object is
Fred Drakee058b4f1998-02-16 06:15:35 +00003851created using \code{PyString_FromString(\var{key})}.
Fred Drakebab29652001-07-10 16:10:08 +00003852Returns \code{0} on success or \code{-1} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00003853\ttindex{PyString_FromString()}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003854\end{cfuncdesc}
3855
Fred Drake659ebfa2000-04-03 15:42:13 +00003856\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003857Removes the entry in dictionary \var{p} with key \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003858\var{key} must be hashable; if it isn't, \exception{TypeError} is
3859raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003860\end{cfuncdesc}
3861
Fred Drake659ebfa2000-04-03 15:42:13 +00003862\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003863Removes the entry in dictionary \var{p} which has a key
Fred Drake659ebfa2000-04-03 15:42:13 +00003864specified by the string \var{key}.
Fred Drakebab29652001-07-10 16:10:08 +00003865Returns \code{0} on success or \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003866\end{cfuncdesc}
3867
Fred Drake659ebfa2000-04-03 15:42:13 +00003868\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003869Returns the object from dictionary \var{p} which has a key
Guido van Rossum44475131998-04-21 15:30:01 +00003870\var{key}. Returns \NULL{} if the key \var{key} is not present, but
Fred Drake659ebfa2000-04-03 15:42:13 +00003871\emph{without} setting an exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003872\end{cfuncdesc}
3873
Fred Drake659ebfa2000-04-03 15:42:13 +00003874\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
Fred Drakef8830d11998-04-23 14:06:01 +00003875This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
Fred Drake659ebfa2000-04-03 15:42:13 +00003876specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003877\end{cfuncdesc}
3878
Fred Drake659ebfa2000-04-03 15:42:13 +00003879\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003880Returns a \ctype{PyListObject} containing all the items
Guido van Rossum44475131998-04-21 15:30:01 +00003881from the dictionary, as in the dictinoary method \method{items()} (see
Fred Drakebe486461999-11-09 17:03:03 +00003882the \citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003883\end{cfuncdesc}
3884
Fred Drake659ebfa2000-04-03 15:42:13 +00003885\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003886Returns a \ctype{PyListObject} containing all the keys
Guido van Rossum44475131998-04-21 15:30:01 +00003887from the dictionary, as in the dictionary method \method{keys()} (see the
Fred Drakebe486461999-11-09 17:03:03 +00003888\citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003889\end{cfuncdesc}
3890
Fred Drake659ebfa2000-04-03 15:42:13 +00003891\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003892Returns a \ctype{PyListObject} containing all the values
Guido van Rossum44475131998-04-21 15:30:01 +00003893from the dictionary \var{p}, as in the dictionary method
Fred Drakebe486461999-11-09 17:03:03 +00003894\method{values()} (see the \citetitle[../lib/lib.html]{Python Library
3895Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003896\end{cfuncdesc}
3897
Fred Drake659ebfa2000-04-03 15:42:13 +00003898\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
3899Returns the number of items in the dictionary. This is equivalent to
3900\samp{len(\var{p})} on a dictionary.\bifuncindex{len}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003901\end{cfuncdesc}
3902
Fred Drake83e01bf2001-03-16 15:41:29 +00003903\begin{cfuncdesc}{int}{PyDict_Next}{PyObject *p, int *ppos,
Fred Drake7d45d342000-08-11 17:07:32 +00003904 PyObject **pkey, PyObject **pvalue}
Fred Drake83e01bf2001-03-16 15:41:29 +00003905Iterate over all key-value pairs in the dictionary \var{p}. The
3906\ctype{int} referred to by \var{ppos} must be initialized to \code{0}
3907prior to the first call to this function to start the iteration; the
3908function returns true for each pair in the dictionary, and false once
3909all pairs have been reported. The parameters \var{pkey} and
3910\var{pvalue} should either point to \ctype{PyObject*} variables that
3911will be filled in with each key and value, respectively, or may be
Fred Drake8d00a0f2001-04-13 17:55:02 +00003912\NULL.
3913
Fred Drake83e01bf2001-03-16 15:41:29 +00003914For example:
Fred Drakee5bf8b21998-02-12 21:22:28 +00003915
Fred Drake83e01bf2001-03-16 15:41:29 +00003916\begin{verbatim}
3917PyObject *key, *value;
3918int pos = 0;
3919
3920while (PyDict_Next(self->dict, &pos, &key, &value)) {
3921 /* do something interesting with the values... */
3922 ...
3923}
3924\end{verbatim}
Fred Drake8d00a0f2001-04-13 17:55:02 +00003925
3926The dictionary \var{p} should not be mutated during iteration. It is
3927safe (since Python 2.1) to modify the values of the keys as you
Fred Drake11ee9022001-08-10 21:31:12 +00003928iterate over the dictionary, but only so long as the set of keys does
3929not change. For example:
Fred Drake8d00a0f2001-04-13 17:55:02 +00003930
3931\begin{verbatim}
3932PyObject *key, *value;
3933int pos = 0;
3934
3935while (PyDict_Next(self->dict, &pos, &key, &value)) {
3936 int i = PyInt_AS_LONG(value) + 1;
3937 PyObject *o = PyInt_FromLong(i);
3938 if (o == NULL)
3939 return -1;
3940 if (PyDict_SetItem(self->dict, key, o) < 0) {
3941 Py_DECREF(o);
3942 return -1;
3943 }
3944 Py_DECREF(o);
3945}
3946\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003947\end{cfuncdesc}
3948
Fred Drake11ee9022001-08-10 21:31:12 +00003949\begin{cfuncdesc}{int}{PyDict_Merge}{PyObject *a, PyObject *b, int override}
3950Iterate over dictionary \var{b} adding key-value pairs to dictionary
3951\var{a}. If \var{override} is true, existing pairs in \var{a} will be
3952replaced if a matching key is found in \var{b}, otherwise pairs will
3953only be added if there is not a matching key in \var{a}. Returns
3954\code{0} on success or \code{-1} if an exception was raised.
3955\versionadded{2.2}
3956\end{cfuncdesc}
3957
3958\begin{cfuncdesc}{int}{PyDict_Update}{PyObject *a, PyObject *b}
3959This is the same as \code{PyDict_Merge(\var{a}, \var{b}, 1)} in C, or
3960\code{\var{a}.update(\var{b})} in Python. Returns \code{0} on success
3961or \code{-1} if an exception was raised.
3962\versionadded{2.2}
3963\end{cfuncdesc}
3964
Fred Drakee5bf8b21998-02-12 21:22:28 +00003965
Fred Drakeefd146c1999-02-15 15:30:45 +00003966\section{Other Objects \label{otherObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003967
Fred Drakeefd146c1999-02-15 15:30:45 +00003968\subsection{File Objects \label{fileObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003969
Fred Drake659ebfa2000-04-03 15:42:13 +00003970\obindex{file}
3971Python's built-in file objects are implemented entirely on the
3972\ctype{FILE*} support from the C standard library. This is an
3973implementation detail and may change in future releases of Python.
3974
Fred Drakee5bf8b21998-02-12 21:22:28 +00003975\begin{ctypedesc}{PyFileObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003976This subtype of \ctype{PyObject} represents a Python file object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003977\end{ctypedesc}
3978
3979\begin{cvardesc}{PyTypeObject}{PyFile_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003980This instance of \ctype{PyTypeObject} represents the Python file
3981type. This is exposed to Python programs as \code{types.FileType}.
3982\withsubitem{(in module types)}{\ttindex{FileType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003983\end{cvardesc}
3984
3985\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003986Returns true if its argument is a \ctype{PyFileObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003987\end{cfuncdesc}
3988
Fred Drake659ebfa2000-04-03 15:42:13 +00003989\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
3990On success, returns a new file object that is opened on the
3991file given by \var{filename}, with a file mode given by \var{mode},
3992where \var{mode} has the same semantics as the standard C routine
3993\cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003994\end{cfuncdesc}
3995
Fred Drakec6fa34e1998-04-02 06:47:24 +00003996\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
Fred Drake659ebfa2000-04-03 15:42:13 +00003997 char *name, char *mode,
3998 int (*close)(FILE*)}
3999Creates a new \ctype{PyFileObject} from the already-open standard C
4000file pointer, \var{fp}. The function \var{close} will be called when
4001the file should be closed. Returns \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004002\end{cfuncdesc}
4003
Fred Drake659ebfa2000-04-03 15:42:13 +00004004\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
4005Returns the file object associated with \var{p} as a \ctype{FILE*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004006\end{cfuncdesc}
4007
Fred Drakec6fa34e1998-04-02 06:47:24 +00004008\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004009Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
4010function reads one line from the object \var{p}. \var{p} may be a
4011file object or any object with a \method{readline()} method. If
4012\var{n} is \code{0}, exactly one line is read, regardless of the
4013length of the line. If \var{n} is greater than \code{0}, no more than
4014\var{n} bytes will be read from the file; a partial line can be
4015returned. In both cases, an empty string is returned if the end of
4016the file is reached immediately. If \var{n} is less than \code{0},
4017however, one line is read regardless of length, but
4018\exception{EOFError} is raised if the end of the file is reached
4019immediately.
4020\withsubitem{(built-in exception)}{\ttindex{EOFError}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00004021\end{cfuncdesc}
4022
Fred Drakec6fa34e1998-04-02 06:47:24 +00004023\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004024Returns the name of the file specified by \var{p} as a string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004025\end{cfuncdesc}
4026
4027\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004028Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
4029only. This should only be called immediately after file object
4030creation.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004031\end{cfuncdesc}
4032
Fred Drake659ebfa2000-04-03 15:42:13 +00004033\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
4034This function exists for internal use by the interpreter.
4035Sets the \member{softspace} attribute of \var{p} to \var{newflag} and
4036\withsubitem{(file attribute)}{\ttindex{softspace}}returns the
4037previous value. \var{p} does not have to be a file object
4038for this function to work properly; any object is supported (thought
4039its only interesting if the \member{softspace} attribute can be set).
4040This function clears any errors, and will return \code{0} as the
4041previous value if the attribute either does not exist or if there were
4042errors in retrieving it. There is no way to detect errors from this
4043function, but doing so should not be needed.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004044\end{cfuncdesc}
4045
Fred Drakec6fa34e1998-04-02 06:47:24 +00004046\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
4047 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00004048Writes object \var{obj} to file object \var{p}. The only supported
4049flag for \var{flags} is \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW};
4050if given, the \function{str()} of the object is written instead of the
4051\function{repr()}. Returns \code{0} on success or \code{-1} on
4052failure; the appropriate exception will be set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004053\end{cfuncdesc}
4054
Fred Drake024ef6f2001-08-10 14:27:38 +00004055\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004056Writes string \var{s} to file object \var{p}. Returns \code{0} on
4057success or \code{-1} on failure; the appropriate exception will be
4058set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004059\end{cfuncdesc}
4060
4061
Fred Drake5838d0f2001-01-28 06:39:35 +00004062\subsection{Instance Objects \label{instanceObjects}}
4063
4064\obindex{instance}
4065There are very few functions specific to instance objects.
4066
4067\begin{cvardesc}{PyTypeObject}{PyInstance_Type}
4068 Type object for class instances.
4069\end{cvardesc}
4070
4071\begin{cfuncdesc}{int}{PyInstance_Check}{PyObject *obj}
4072 Returns true if \var{obj} is an instance.
4073\end{cfuncdesc}
4074
4075\begin{cfuncdesc}{PyObject*}{PyInstance_New}{PyObject *class,
4076 PyObject *arg,
4077 PyObject *kw}
4078 Create a new instance of a specific class. The parameters \var{arg}
4079 and \var{kw} are used as the positional and keyword parameters to
4080 the object's constructor.
4081\end{cfuncdesc}
4082
4083\begin{cfuncdesc}{PyObject*}{PyInstance_NewRaw}{PyObject *class,
4084 PyObject *dict}
4085 Create a new instance of a specific class without calling it's
4086 constructor. \var{class} is the class of new object. The
4087 \var{dict} parameter will be used as the object's \member{__dict__};
4088 if \NULL, a new dictionary will be created for the instance.
4089\end{cfuncdesc}
4090
4091
Fred Drakef8d7a5d2001-09-06 17:12:44 +00004092\subsection{Method Objects \label{method-objects}}
4093
4094\obindex{method}
4095There are some useful functions that are useful for working with
4096method objects.
4097
4098\begin{cvardesc}{PyTypeObject}{PyMethod_Type}
4099 This instance of \ctype{PyTypeObject} represents the Python method
4100 type. This is exposed to Python programs as \code{types.MethodType}.
4101 \withsubitem{(in module types)}{\ttindex{MethodType}}
4102\end{cvardesc}
4103
4104\begin{cfuncdesc}{int}{PyMethod_Check}{PyObject *o}
4105 Return true if \var{o} is a method object (has type
4106 \cdata{PyMethod_Type}). The parameter must not be \NULL.
4107\end{cfuncdesc}
4108
4109\begin{cfuncdesc}{PyObject*}{PyMethod_New}{PyObject *func.
4110 PyObject *self, PyObject *class}
4111 Return a new method object, with \var{func} being any callable
4112 object; this is the function that will be called when the method is
4113 called. If this method should be bound to an instance, \var{self}
4114 should be the instance and \var{class} should be the class of
4115 \var{self}, otherwise \var{self} should be \NULL{} and \var{class}
4116 should be the class which provides the unbound method..
4117\end{cfuncdesc}
4118
4119\begin{cfuncdesc}{PyObject*}{PyMethod_Class}{PyObject *meth}
4120 Return the class object from which the method \var{meth} was
4121 created; if this was created from an instance, it will be the class
4122 of the instance.
4123\end{cfuncdesc}
4124
4125\begin{cfuncdesc}{PyObject*}{PyMethod_GET_CLASS}{PyObject *meth}
4126 Macro version of \cfunction{PyMethod_Class()} which avoids error
4127 checking.
4128\end{cfuncdesc}
4129
4130\begin{cfuncdesc}{PyObject*}{PyMethod_Function}{PyObject *meth}
4131 Return the function object associated with the method \var{meth}.
4132\end{cfuncdesc}
4133
4134\begin{cfuncdesc}{PyObject*}{PyMethod_GET_FUNCTION}{PyObject *meth}
4135 Macro version of \cfunction{PyMethod_Function()} which avoids error
4136 checking.
4137\end{cfuncdesc}
4138
4139\begin{cfuncdesc}{PyObject*}{PyMethod_Self}{PyObject *meth}
4140 Return the instance associated with the method \var{meth} if it is
4141 bound, otherwise return \NULL.
4142\end{cfuncdesc}
4143
4144\begin{cfuncdesc}{PyObject*}{PyMethod_GET_SELF}{PyObject *meth}
4145 Macro version of \cfunction{PyMethod_Self()} which avoids error
4146 checking.
4147\end{cfuncdesc}
4148
4149
Fred Drakeefd146c1999-02-15 15:30:45 +00004150\subsection{Module Objects \label{moduleObjects}}
4151
4152\obindex{module}
4153There are only a few functions special to module objects.
4154
Fred Drake659ebfa2000-04-03 15:42:13 +00004155\begin{cvardesc}{PyTypeObject}{PyModule_Type}
4156This instance of \ctype{PyTypeObject} represents the Python module
4157type. This is exposed to Python programs as \code{types.ModuleType}.
4158\withsubitem{(in module types)}{\ttindex{ModuleType}}
4159\end{cvardesc}
4160
4161\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
4162Returns true if its argument is a module object.
Fred Drakeefd146c1999-02-15 15:30:45 +00004163\end{cfuncdesc}
4164
Fred Drake659ebfa2000-04-03 15:42:13 +00004165\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
4166Return a new module object with the \member{__name__} attribute set to
4167\var{name}. Only the module's \member{__doc__} and
4168\member{__name__} attributes are filled in; the caller is responsible
4169for providing a \member{__file__} attribute.
4170\withsubitem{(module attribute)}{
4171 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
4172\end{cfuncdesc}
4173
4174\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00004175Return the dictionary object that implements \var{module}'s namespace;
4176this object is the same as the \member{__dict__} attribute of the
4177module object. This function never fails.
Fred Drake659ebfa2000-04-03 15:42:13 +00004178\withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakeefd146c1999-02-15 15:30:45 +00004179\end{cfuncdesc}
4180
Fred Drake659ebfa2000-04-03 15:42:13 +00004181\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00004182Return \var{module}'s \member{__name__} value. If the module does not
Fred Drake659ebfa2000-04-03 15:42:13 +00004183provide one, or if it is not a string, \exception{SystemError} is
4184raised and \NULL{} is returned.
4185\withsubitem{(module attribute)}{\ttindex{__name__}}
4186\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00004187\end{cfuncdesc}
4188
Fred Drake659ebfa2000-04-03 15:42:13 +00004189\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00004190Return the name of the file from which \var{module} was loaded using
4191\var{module}'s \member{__file__} attribute. If this is not defined,
Fred Drake659ebfa2000-04-03 15:42:13 +00004192or if it is not a string, raise \exception{SystemError} and return
4193\NULL.
4194\withsubitem{(module attribute)}{\ttindex{__file__}}
4195\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00004196\end{cfuncdesc}
4197
Fred Drake891150b2000-09-23 03:25:42 +00004198\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
4199 char *name, PyObject *value}
4200Add an object to \var{module} as \var{name}. This is a convenience
4201function which can be used from the module's initialization function.
4202This steals a reference to \var{value}. Returns \code{-1} on error,
4203\code{0} on success.
4204\versionadded{2.0}
4205\end{cfuncdesc}
4206
4207\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
4208 char *name, int value}
4209Add an integer constant to \var{module} as \var{name}. This convenience
4210function can be used from the module's initialization function.
4211Returns \code{-1} on error, \code{0} on success.
4212\versionadded{2.0}
4213\end{cfuncdesc}
4214
4215\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
4216 char *name, char *value}
4217Add a string constant to \var{module} as \var{name}. This convenience
4218function can be used from the module's initialization function. The
4219string \var{value} must be null-terminated. Returns \code{-1} on
4220error, \code{0} on success.
4221\versionadded{2.0}
4222\end{cfuncdesc}
4223
Fred Drakeefd146c1999-02-15 15:30:45 +00004224
4225\subsection{CObjects \label{cObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00004226
Fred Drake659ebfa2000-04-03 15:42:13 +00004227\obindex{CObject}
4228Refer to \emph{Extending and Embedding the Python Interpreter},
4229section 1.12 (``Providing a C API for an Extension Module''), for more
4230information on using these objects.
4231
4232
Guido van Rossum44475131998-04-21 15:30:01 +00004233\begin{ctypedesc}{PyCObject}
Fred Drakef8830d11998-04-23 14:06:01 +00004234This subtype of \ctype{PyObject} represents an opaque value, useful for
Fred Drake659ebfa2000-04-03 15:42:13 +00004235C extension modules who need to pass an opaque value (as a
4236\ctype{void*} pointer) through Python code to other C code. It is
Guido van Rossum44475131998-04-21 15:30:01 +00004237often used to make a C function pointer defined in one module
4238available to other modules, so the regular import mechanism can be
4239used to access C APIs defined in dynamically loaded modules.
4240\end{ctypedesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00004241
Fred Drake659ebfa2000-04-03 15:42:13 +00004242\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
4243Returns true if its argument is a \ctype{PyCObject}.
4244\end{cfuncdesc}
4245
4246\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00004247 void (*destr)(void *)}
Fred Drake1d158692000-06-18 05:21:21 +00004248Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drakedab44681999-05-13 18:41:14 +00004249\var{destr} function will be called when the object is reclaimed, unless
4250it is \NULL.
Guido van Rossum44475131998-04-21 15:30:01 +00004251\end{cfuncdesc}
4252
Fred Drake659ebfa2000-04-03 15:42:13 +00004253\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00004254 void* desc, void (*destr)(void *, void *) }
Fred Drakef8830d11998-04-23 14:06:01 +00004255Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
4256\var{destr} function will be called when the object is reclaimed. The
4257\var{desc} argument can be used to pass extra callback data for the
4258destructor function.
Guido van Rossum44475131998-04-21 15:30:01 +00004259\end{cfuncdesc}
4260
Fred Drake659ebfa2000-04-03 15:42:13 +00004261\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
4262Returns the object \ctype{void *} that the
4263\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00004264\end{cfuncdesc}
4265
Fred Drake659ebfa2000-04-03 15:42:13 +00004266\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
4267Returns the description \ctype{void *} that the
4268\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00004269\end{cfuncdesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00004270
Fred Drake659ebfa2000-04-03 15:42:13 +00004271
Fred Drakeefd146c1999-02-15 15:30:45 +00004272\chapter{Initialization, Finalization, and Threads
4273 \label{initialization}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004274
Guido van Rossum4a944d71997-08-14 20:35:38 +00004275\begin{cfuncdesc}{void}{Py_Initialize}{}
4276Initialize the Python interpreter. In an application embedding
4277Python, this should be called before using any other Python/C API
Fred Drake659ebfa2000-04-03 15:42:13 +00004278functions; with the exception of
4279\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
4280\cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
4281\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
4282and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
4283This initializes the table of loaded modules (\code{sys.modules}), and
4284\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}creates the
4285fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake4de05a91998-02-16 14:25:26 +00004286\module{__main__}\refbimodindex{__main__} and
4287\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drake659ebfa2000-04-03 15:42:13 +00004288search\indexiii{module}{search}{path} path (\code{sys.path}).
4289It does not set \code{sys.argv}; use
4290\cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
4291is a no-op when called for a second time (without calling
4292\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is no
4293return value; it is a fatal error if the initialization fails.
Guido van Rossum42cefd01997-10-05 15:27:29 +00004294\end{cfuncdesc}
4295
4296\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00004297Return true (nonzero) when the Python interpreter has been
Fred Drakee058b4f1998-02-16 06:15:35 +00004298initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
4299called, this returns false until \cfunction{Py_Initialize()} is called
Guido van Rossum42cefd01997-10-05 15:27:29 +00004300again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004301\end{cfuncdesc}
4302
4303\begin{cfuncdesc}{void}{Py_Finalize}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004304Undo all initializations made by \cfunction{Py_Initialize()} and
4305subsequent use of Python/C API functions, and destroy all
4306sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
4307created and not yet destroyed since the last call to
4308\cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
4309by the Python interpreter. This is a no-op when called for a second
4310time (without calling \cfunction{Py_Initialize()} again first). There
4311is no return value; errors during finalization are ignored.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004312
4313This function is provided for a number of reasons. An embedding
4314application might want to restart Python without having to restart the
4315application itself. An application that has loaded the Python
4316interpreter from a dynamically loadable library (or DLL) might want to
4317free all memory allocated by Python before unloading the DLL. During a
4318hunt for memory leaks in an application a developer might want to free
4319all memory allocated by Python before exiting from the application.
4320
Fred Drakee058b4f1998-02-16 06:15:35 +00004321\strong{Bugs and caveats:} The destruction of modules and objects in
Guido van Rossum4a944d71997-08-14 20:35:38 +00004322modules is done in random order; this may cause destructors
Fred Drakee058b4f1998-02-16 06:15:35 +00004323(\method{__del__()} methods) to fail when they depend on other objects
Guido van Rossum4a944d71997-08-14 20:35:38 +00004324(even functions) or modules. Dynamically loaded extension modules
4325loaded by Python are not unloaded. Small amounts of memory allocated
4326by the Python interpreter may not be freed (if you find a leak, please
4327report it). Memory tied up in circular references between objects is
4328not freed. Some memory allocated by extension modules may not be
4329freed. Some extension may not work properly if their initialization
4330routine is called more than once; this can happen if an applcation
Fred Drakee058b4f1998-02-16 06:15:35 +00004331calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
4332than once.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004333\end{cfuncdesc}
4334
Fred Drakec6fa34e1998-04-02 06:47:24 +00004335\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
Fred Drake4de05a91998-02-16 14:25:26 +00004336Create a new sub-interpreter. This is an (almost) totally separate
4337environment for the execution of Python code. In particular, the new
4338interpreter has separate, independent versions of all imported
4339modules, including the fundamental modules
4340\module{__builtin__}\refbimodindex{__builtin__},
4341\module{__main__}\refbimodindex{__main__} and
4342\module{sys}\refbimodindex{sys}. The table of loaded modules
4343(\code{sys.modules}) and the module search path (\code{sys.path}) are
4344also separate. The new environment has no \code{sys.argv} variable.
4345It has new standard I/O stream file objects \code{sys.stdin},
4346\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drake659ebfa2000-04-03 15:42:13 +00004347same underlying \ctype{FILE} structures in the C library).
4348\withsubitem{(in module sys)}{
4349 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004350
4351The return value points to the first thread state created in the new
4352sub-interpreter. This thread state is made the current thread state.
4353Note that no actual thread is created; see the discussion of thread
4354states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004355\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00004356is stored in the current thread state and there may not be a current
4357thread state. (Like all other Python/C API functions, the global
4358interpreter lock must be held before calling this function and is
4359still held when it returns; however, unlike most other Python/C API
4360functions, there needn't be a current thread state on entry.)
4361
4362Extension modules are shared between (sub-)interpreters as follows:
4363the first time a particular extension is imported, it is initialized
4364normally, and a (shallow) copy of its module's dictionary is
4365squirreled away. When the same extension is imported by another
4366(sub-)interpreter, a new module is initialized and filled with the
Fred Drakee058b4f1998-02-16 06:15:35 +00004367contents of this copy; the extension's \code{init} function is not
4368called. Note that this is different from what happens when an
4369extension is imported after the interpreter has been completely
Fred Drake659ebfa2000-04-03 15:42:13 +00004370re-initialized by calling
4371\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
4372\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
4373the extension's \code{init\var{module}} function \emph{is} called
4374again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004375
Fred Drakee058b4f1998-02-16 06:15:35 +00004376\strong{Bugs and caveats:} Because sub-interpreters (and the main
Guido van Rossum4a944d71997-08-14 20:35:38 +00004377interpreter) are part of the same process, the insulation between them
Fred Drakee058b4f1998-02-16 06:15:35 +00004378isn't perfect --- for example, using low-level file operations like
Fred Drake659ebfa2000-04-03 15:42:13 +00004379\withsubitem{(in module os)}{\ttindex{close()}}
Fred Drakef8830d11998-04-23 14:06:01 +00004380\function{os.close()} they can (accidentally or maliciously) affect each
Guido van Rossum4a944d71997-08-14 20:35:38 +00004381other's open files. Because of the way extensions are shared between
4382(sub-)interpreters, some extensions may not work properly; this is
4383especially likely when the extension makes use of (static) global
4384variables, or when the extension manipulates its module's dictionary
4385after its initialization. It is possible to insert objects created in
4386one sub-interpreter into a namespace of another sub-interpreter; this
4387should be done with great care to avoid sharing user-defined
4388functions, methods, instances or classes between sub-interpreters,
4389since import operations executed by such objects may affect the
4390wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
4391a hard-to-fix bug that will be addressed in a future release.)
4392\end{cfuncdesc}
4393
4394\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
4395Destroy the (sub-)interpreter represented by the given thread state.
4396The given thread state must be the current thread state. See the
4397discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004398thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00004399interpreted are destroyed. (The global interpreter lock must be held
4400before calling this function and is still held when it returns.)
Fred Drake659ebfa2000-04-03 15:42:13 +00004401\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will destroy all
4402sub-interpreters that haven't been explicitly destroyed at that point.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004403\end{cfuncdesc}
4404
4405\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00004406This function should be called before
4407\cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
Guido van Rossum4a944d71997-08-14 20:35:38 +00004408for the first time, if it is called at all. It tells the interpreter
Fred Drake659ebfa2000-04-03 15:42:13 +00004409the value of the \code{argv[0]} argument to the
4410\cfunction{main()}\ttindex{main()} function of the program. This is
4411used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some other
Guido van Rossum4a944d71997-08-14 20:35:38 +00004412functions below to find the Python run-time libraries relative to the
Fred Drakea8455ab2000-06-16 19:58:42 +00004413interpreter executable. The default value is \code{'python'}. The
Guido van Rossum4a944d71997-08-14 20:35:38 +00004414argument should point to a zero-terminated character string in static
4415storage whose contents will not change for the duration of the
4416program's execution. No code in the Python interpreter will change
4417the contents of this storage.
4418\end{cfuncdesc}
4419
Fred Drakec6fa34e1998-04-02 06:47:24 +00004420\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00004421Return the program name set with
4422\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
Guido van Rossum4a944d71997-08-14 20:35:38 +00004423default. The returned string points into static storage; the caller
4424should not modify its value.
4425\end{cfuncdesc}
4426
Fred Drakec6fa34e1998-04-02 06:47:24 +00004427\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004428Return the \emph{prefix} for installed platform-independent files. This
Guido van Rossum4a944d71997-08-14 20:35:38 +00004429is derived through a number of complicated rules from the program name
Fred Drakee058b4f1998-02-16 06:15:35 +00004430set with \cfunction{Py_SetProgramName()} and some environment variables;
Fred Drakea8455ab2000-06-16 19:58:42 +00004431for example, if the program name is \code{'/usr/local/bin/python'},
4432the prefix is \code{'/usr/local'}. The returned string points into
Guido van Rossum4a944d71997-08-14 20:35:38 +00004433static storage; the caller should not modify its value. This
Fred Drakec94d9341998-04-12 02:39:13 +00004434corresponds to the \makevar{prefix} variable in the top-level
Fred Drakea8455ab2000-06-16 19:58:42 +00004435\file{Makefile} and the \longprogramopt{prefix} argument to the
Fred Drakee058b4f1998-02-16 06:15:35 +00004436\program{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00004437Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00004438also the next function.
4439\end{cfuncdesc}
4440
Fred Drakec6fa34e1998-04-02 06:47:24 +00004441\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004442Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
Guido van Rossum4a944d71997-08-14 20:35:38 +00004443files. This is derived through a number of complicated rules from the
Fred Drakee058b4f1998-02-16 06:15:35 +00004444program name set with \cfunction{Py_SetProgramName()} and some environment
Guido van Rossum4a944d71997-08-14 20:35:38 +00004445variables; for example, if the program name is
Fred Drakea8455ab2000-06-16 19:58:42 +00004446\code{'/usr/local/bin/python'}, the exec-prefix is
4447\code{'/usr/local'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00004448the caller should not modify its value. This corresponds to the
Fred Drakec94d9341998-04-12 02:39:13 +00004449\makevar{exec_prefix} variable in the top-level \file{Makefile} and the
Fred Drakea8455ab2000-06-16 19:58:42 +00004450\longprogramopt{exec-prefix} argument to the
Fred Drake310ee611999-11-09 17:31:42 +00004451\program{configure} script at build time. The value is available to
4452Python code as \code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004453
4454Background: The exec-prefix differs from the prefix when platform
4455dependent files (such as executables and shared libraries) are
4456installed in a different directory tree. In a typical installation,
4457platform dependent files may be installed in the
Fred Drakea8455ab2000-06-16 19:58:42 +00004458\file{/usr/local/plat} subtree while platform independent may be
4459installed in \file{/usr/local}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004460
4461Generally speaking, a platform is a combination of hardware and
4462software families, e.g. Sparc machines running the Solaris 2.x
4463operating system are considered the same platform, but Intel machines
4464running Solaris 2.x are another platform, and Intel machines running
4465Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00004466operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004467operating systems are a different story; the installation strategies
4468on those systems are so different that the prefix and exec-prefix are
4469meaningless, and set to the empty string. Note that compiled Python
4470bytecode files are platform independent (but not independent from the
4471Python version by which they were compiled!).
4472
Fred Drakee058b4f1998-02-16 06:15:35 +00004473System administrators will know how to configure the \program{mount} or
Fred Drakea8455ab2000-06-16 19:58:42 +00004474\program{automount} programs to share \file{/usr/local} between platforms
4475while having \file{/usr/local/plat} be a different filesystem for each
Guido van Rossum4a944d71997-08-14 20:35:38 +00004476platform.
4477\end{cfuncdesc}
4478
Fred Drakec6fa34e1998-04-02 06:47:24 +00004479\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004480Return the full program name of the Python executable; this is
4481computed as a side-effect of deriving the default module search path
Fred Drake659ebfa2000-04-03 15:42:13 +00004482from the program name (set by
4483\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
4484The returned string points into static storage; the caller should not
Guido van Rossum4a944d71997-08-14 20:35:38 +00004485modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00004486\code{sys.executable}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004487\withsubitem{(in module sys)}{\ttindex{executable}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004488\end{cfuncdesc}
4489
Fred Drakec6fa34e1998-04-02 06:47:24 +00004490\begin{cfuncdesc}{char*}{Py_GetPath}{}
Fred Drake4de05a91998-02-16 14:25:26 +00004491\indexiii{module}{search}{path}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004492Return the default module search path; this is computed from the
Fred Drakee058b4f1998-02-16 06:15:35 +00004493program name (set by \cfunction{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00004494environment variables. The returned string consists of a series of
4495directory names separated by a platform dependent delimiter character.
Fred Drakef8830d11998-04-23 14:06:01 +00004496The delimiter character is \character{:} on \UNIX{}, \character{;} on
Fred Drake659ebfa2000-04-03 15:42:13 +00004497DOS/Windows, and \character{\e n} (the \ASCII{} newline character) on
Fred Drakee5bc4971998-02-12 23:36:49 +00004498Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00004499should not modify its value. The value is available to Python code
Fred Drake659ebfa2000-04-03 15:42:13 +00004500as the list \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}},
4501which may be modified to change the future search path for loaded
4502modules.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004503
4504% XXX should give the exact rules
4505\end{cfuncdesc}
4506
Fred Drakec6fa34e1998-04-02 06:47:24 +00004507\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004508Return the version of this Python interpreter. This is a string that
4509looks something like
4510
Guido van Rossum09270b51997-08-15 18:57:32 +00004511\begin{verbatim}
Fred Drakee058b4f1998-02-16 06:15:35 +00004512"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
Guido van Rossum09270b51997-08-15 18:57:32 +00004513\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004514
4515The first word (up to the first space character) is the current Python
4516version; the first three characters are the major and minor version
4517separated by a period. The returned string points into static storage;
4518the caller should not modify its value. The value is available to
4519Python code as the list \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004520\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004521\end{cfuncdesc}
4522
Fred Drakec6fa34e1998-04-02 06:47:24 +00004523\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00004524Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00004525this is formed from the ``official'' name of the operating system,
4526converted to lower case, followed by the major revision number; e.g.,
4527for Solaris 2.x, which is also known as SunOS 5.x, the value is
Fred Drakea8455ab2000-06-16 19:58:42 +00004528\code{'sunos5'}. On Macintosh, it is \code{'mac'}. On Windows, it
4529is \code{'win'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00004530the caller should not modify its value. The value is available to
4531Python code as \code{sys.platform}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004532\withsubitem{(in module sys)}{\ttindex{platform}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004533\end{cfuncdesc}
4534
Fred Drakec6fa34e1998-04-02 06:47:24 +00004535\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004536Return the official copyright string for the current Python version,
4537for example
4538
Fred Drakea8455ab2000-06-16 19:58:42 +00004539\code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004540
4541The returned string points into static storage; the caller should not
4542modify its value. The value is available to Python code as the list
4543\code{sys.copyright}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004544\withsubitem{(in module sys)}{\ttindex{copyright}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004545\end{cfuncdesc}
4546
Fred Drakec6fa34e1998-04-02 06:47:24 +00004547\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004548Return an indication of the compiler used to build the current Python
Fred Drakee058b4f1998-02-16 06:15:35 +00004549version, in square brackets, for example:
Guido van Rossum4a944d71997-08-14 20:35:38 +00004550
Fred Drakee058b4f1998-02-16 06:15:35 +00004551\begin{verbatim}
4552"[GCC 2.7.2.2]"
4553\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004554
4555The returned string points into static storage; the caller should not
4556modify its value. The value is available to Python code as part of
4557the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004558\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004559\end{cfuncdesc}
4560
Fred Drakec6fa34e1998-04-02 06:47:24 +00004561\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004562Return information about the sequence number and build date and time
4563of the current Python interpreter instance, for example
4564
Guido van Rossum09270b51997-08-15 18:57:32 +00004565\begin{verbatim}
4566"#67, Aug 1 1997, 22:34:28"
4567\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004568
4569The returned string points into static storage; the caller should not
4570modify its value. The value is available to Python code as part of
4571the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004572\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004573\end{cfuncdesc}
4574
4575\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
Fred Drake659ebfa2000-04-03 15:42:13 +00004576Set \code{sys.argv} based on \var{argc} and \var{argv}. These
4577parameters are similar to those passed to the program's
4578\cfunction{main()}\ttindex{main()} function with the difference that
4579the first entry should refer to the script file to be executed rather
4580than the executable hosting the Python interpreter. If there isn't a
4581script that will be run, the first entry in \var{argv} can be an empty
4582string. If this function fails to initialize \code{sys.argv}, a fatal
4583condition is signalled using
4584\cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
4585\withsubitem{(in module sys)}{\ttindex{argv}}
4586% XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
4587% check w/ Guido.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004588\end{cfuncdesc}
4589
4590% XXX Other PySys thingies (doesn't really belong in this chapter)
4591
Fred Drakeefd146c1999-02-15 15:30:45 +00004592\section{Thread State and the Global Interpreter Lock
4593 \label{threads}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004594
Fred Drake659ebfa2000-04-03 15:42:13 +00004595\index{global interpreter lock}
4596\index{interpreter lock}
4597\index{lock, interpreter}
4598
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004599The Python interpreter is not fully thread safe. In order to support
4600multi-threaded Python programs, there's a global lock that must be
4601held by the current thread before it can safely access Python objects.
4602Without the lock, even the simplest operations could cause problems in
Fred Drake7baf3d41998-02-20 00:45:52 +00004603a multi-threaded program: for example, when two threads simultaneously
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004604increment the reference count of the same object, the reference count
4605could end up being incremented only once instead of twice.
4606
4607Therefore, the rule exists that only the thread that has acquired the
4608global interpreter lock may operate on Python objects or call Python/C
4609API functions. In order to support multi-threaded Python programs,
Fred Drake659ebfa2000-04-03 15:42:13 +00004610the interpreter regularly releases and reacquires the lock --- by
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004611default, every ten bytecode instructions (this can be changed with
Fred Drake659ebfa2000-04-03 15:42:13 +00004612\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
Fred Drakee058b4f1998-02-16 06:15:35 +00004613\function{sys.setcheckinterval()}). The lock is also released and
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004614reacquired around potentially blocking I/O operations like reading or
4615writing a file, so that other threads can run while the thread that
4616requests the I/O is waiting for the I/O operation to complete.
4617
4618The Python interpreter needs to keep some bookkeeping information
Fred Drakee058b4f1998-02-16 06:15:35 +00004619separate per thread --- for this it uses a data structure called
Fred Drake659ebfa2000-04-03 15:42:13 +00004620\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
46211.5; in earlier versions, such state was stored in global variables,
4622and switching threads could cause problems. In particular, exception
4623handling is now thread safe, when the application uses
4624\withsubitem{(in module sys)}{\ttindex{exc_info()}}
4625\function{sys.exc_info()} to access the exception last raised in the
4626current thread.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004627
4628There's one global variable left, however: the pointer to the current
Fred Drake659ebfa2000-04-03 15:42:13 +00004629\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
4630thread packages have a way to store ``per-thread global data,''
4631Python's internal platform independent thread abstraction doesn't
4632support this yet. Therefore, the current thread state must be
4633manipulated explicitly.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004634
4635This is easy enough in most cases. Most code manipulating the global
4636interpreter lock has the following simple structure:
4637
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004638\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004639Save the thread state in a local variable.
4640Release the interpreter lock.
4641...Do some blocking I/O operation...
4642Reacquire the interpreter lock.
4643Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004644\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004645
4646This is so common that a pair of macros exists to simplify it:
4647
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004648\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004649Py_BEGIN_ALLOW_THREADS
4650...Do some blocking I/O operation...
4651Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004652\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004653
Fred Drake659ebfa2000-04-03 15:42:13 +00004654The \code{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS} macro
4655opens a new block and declares a hidden local variable; the
4656\code{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS} macro closes
Fred Drakee058b4f1998-02-16 06:15:35 +00004657the block. Another advantage of using these two macros is that when
4658Python is compiled without thread support, they are defined empty,
4659thus saving the thread state and lock manipulations.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004660
4661When thread support is enabled, the block above expands to the
4662following code:
4663
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004664\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004665 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004666
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004667 _save = PyEval_SaveThread();
4668 ...Do some blocking I/O operation...
4669 PyEval_RestoreThread(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004670\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004671
4672Using even lower level primitives, we can get roughly the same effect
4673as follows:
4674
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004675\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004676 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004677
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004678 _save = PyThreadState_Swap(NULL);
4679 PyEval_ReleaseLock();
4680 ...Do some blocking I/O operation...
4681 PyEval_AcquireLock();
4682 PyThreadState_Swap(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004683\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004684
4685There are some subtle differences; in particular,
Fred Drake659ebfa2000-04-03 15:42:13 +00004686\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
4687and restores the value of the global variable
4688\cdata{errno}\ttindex{errno}, since the lock manipulation does not
Fred Drakef8830d11998-04-23 14:06:01 +00004689guarantee that \cdata{errno} is left alone. Also, when thread support
Fred Drake659ebfa2000-04-03 15:42:13 +00004690is disabled,
4691\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
Fred Drakee058b4f1998-02-16 06:15:35 +00004692\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
Fred Drake659ebfa2000-04-03 15:42:13 +00004693case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
4694\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
4695available. This is done so that dynamically loaded extensions
4696compiled with thread support enabled can be loaded by an interpreter
4697that was compiled with disabled thread support.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004698
4699The global interpreter lock is used to protect the pointer to the
4700current thread state. When releasing the lock and saving the thread
4701state, the current thread state pointer must be retrieved before the
4702lock is released (since another thread could immediately acquire the
4703lock and store its own thread state in the global variable).
Fred Drakeffe58ca2000-09-29 17:31:54 +00004704Conversely, when acquiring the lock and restoring the thread state,
4705the lock must be acquired before storing the thread state pointer.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004706
4707Why am I going on with so much detail about this? Because when
Fred Drake659ebfa2000-04-03 15:42:13 +00004708threads are created from C, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004709lock, nor is there a thread state data structure for them. Such
4710threads must bootstrap themselves into existence, by first creating a
4711thread state data structure, then acquiring the lock, and finally
4712storing their thread state pointer, before they can start using the
4713Python/C API. When they are done, they should reset the thread state
4714pointer, release the lock, and finally free their thread state data
4715structure.
4716
4717When creating a thread data structure, you need to provide an
4718interpreter state data structure. The interpreter state data
4719structure hold global data that is shared by all threads in an
4720interpreter, for example the module administration
4721(\code{sys.modules}). Depending on your needs, you can either create
4722a new interpreter state data structure, or share the interpreter state
4723data structure used by the Python main thread (to access the latter,
Fred Drakef8830d11998-04-23 14:06:01 +00004724you must obtain the thread state and access its \member{interp} member;
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004725this must be done by a thread that is created by Python or by the main
4726thread after Python is initialized).
4727
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004728
4729\begin{ctypedesc}{PyInterpreterState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004730This data structure represents the state shared by a number of
4731cooperating threads. Threads belonging to the same interpreter
4732share their module administration and a few other internal items.
4733There are no public members in this structure.
4734
4735Threads belonging to different interpreters initially share nothing,
4736except process state like available memory, open file descriptors and
4737such. The global interpreter lock is also shared by all threads,
4738regardless of to which interpreter they belong.
4739\end{ctypedesc}
4740
4741\begin{ctypedesc}{PyThreadState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004742This data structure represents the state of a single thread. The only
Fred Drakef8830d11998-04-23 14:06:01 +00004743public data member is \ctype{PyInterpreterState *}\member{interp},
4744which points to this thread's interpreter state.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004745\end{ctypedesc}
4746
4747\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
4748Initialize and acquire the global interpreter lock. It should be
4749called in the main thread before creating a second thread or engaging
Fred Drakee058b4f1998-02-16 06:15:35 +00004750in any other thread operations such as
Fred Drake659ebfa2000-04-03 15:42:13 +00004751\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
4752\code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
4753It is not needed before calling
4754\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
4755\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004756
4757This is a no-op when called for a second time. It is safe to call
Fred Drake659ebfa2000-04-03 15:42:13 +00004758this function before calling
4759\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004760
4761When only the main thread exists, no lock operations are needed. This
4762is a common situation (most Python programs do not use threads), and
4763the lock operations slow the interpreter down a bit. Therefore, the
4764lock is not created initially. This situation is equivalent to having
4765acquired the lock: when there is only a single thread, all object
4766accesses are safe. Therefore, when this function initializes the
Fred Drake4de05a91998-02-16 14:25:26 +00004767lock, it also acquires it. Before the Python
4768\module{thread}\refbimodindex{thread} module creates a new thread,
4769knowing that either it has the lock or the lock hasn't been created
4770yet, it calls \cfunction{PyEval_InitThreads()}. When this call
4771returns, it is guaranteed that the lock has been created and that it
4772has acquired it.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004773
4774It is \strong{not} safe to call this function when it is unknown which
4775thread (if any) currently has the global interpreter lock.
4776
4777This function is not available when thread support is disabled at
4778compile time.
4779\end{cfuncdesc}
4780
Guido van Rossum4a944d71997-08-14 20:35:38 +00004781\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004782Acquire the global interpreter lock. The lock must have been created
4783earlier. If this thread already has the lock, a deadlock ensues.
4784This function is not available when thread support is disabled at
4785compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004786\end{cfuncdesc}
4787
4788\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004789Release the global interpreter lock. The lock must have been created
4790earlier. This function is not available when thread support is
Fred Drakee058b4f1998-02-16 06:15:35 +00004791disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004792\end{cfuncdesc}
4793
4794\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004795Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004796state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004797have been created earlier. If this thread already has the lock,
4798deadlock ensues. This function is not available when thread support
Fred Drakee058b4f1998-02-16 06:15:35 +00004799is disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004800\end{cfuncdesc}
4801
4802\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004803Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004804interpreter lock. The lock must have been created earlier and must be
4805held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004806be \NULL{}, is only used to check that it represents the current
Fred Drakee058b4f1998-02-16 06:15:35 +00004807thread state --- if it isn't, a fatal error is reported. This
4808function is not available when thread support is disabled at compile
4809time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004810\end{cfuncdesc}
4811
Fred Drakec6fa34e1998-04-02 06:47:24 +00004812\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004813Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004814support is enabled) and reset the thread state to \NULL{},
4815returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004816the lock has been created, the current thread must have acquired it.
4817(This function is available even when thread support is disabled at
4818compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004819\end{cfuncdesc}
4820
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004821\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004822Acquire the interpreter lock (if it has been created and thread
4823support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004824must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004825thread must not have acquired it, otherwise deadlock ensues. (This
4826function is available even when thread support is disabled at compile
4827time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004828\end{cfuncdesc}
4829
Fred Drake659ebfa2000-04-03 15:42:13 +00004830The following macros are normally used without a trailing semicolon;
4831look for example usage in the Python source distribution.
4832
4833\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004834This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004835\samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004836Note that it contains an opening brace; it must be matched with a
4837following \code{Py_END_ALLOW_THREADS} macro. See above for further
4838discussion of this macro. It is a no-op when thread support is
4839disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004840\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004841
Fred Drake659ebfa2000-04-03 15:42:13 +00004842\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004843This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004844\samp{PyEval_RestoreThread(_save); \}}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004845Note that it contains a closing brace; it must be matched with an
4846earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
4847discussion of this macro. It is a no-op when thread support is
4848disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004849\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004850
Thomas Wouterse30ac572001-07-09 14:35:01 +00004851\begin{csimplemacrodesc}{Py_BLOCK_THREADS}
Fred Drakebab29652001-07-10 16:10:08 +00004852This macro expands to \samp{PyEval_RestoreThread(_save);}: it
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004853is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
4854brace. It is a no-op when thread support is disabled at compile
4855time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004856\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004857
Thomas Wouterse30ac572001-07-09 14:35:01 +00004858\begin{csimplemacrodesc}{Py_UNBLOCK_THREADS}
Fred Drakebab29652001-07-10 16:10:08 +00004859This macro expands to \samp{_save = PyEval_SaveThread();}: it is
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004860equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
4861and variable declaration. It is a no-op when thread support is
4862disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004863\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004864
4865All of the following functions are only available when thread support
4866is enabled at compile time, and must be called only when the
Fred Drake9d20ac31998-02-16 15:27:08 +00004867interpreter lock has been created.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004868
Fred Drakec6fa34e1998-04-02 06:47:24 +00004869\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004870Create a new interpreter state object. The interpreter lock need not
4871be held, but may be held if it is necessary to serialize calls to this
4872function.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004873\end{cfuncdesc}
4874
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004875\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
4876Reset all information in an interpreter state object. The interpreter
4877lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004878\end{cfuncdesc}
4879
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004880\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
4881Destroy an interpreter state object. The interpreter lock need not be
4882held. The interpreter state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004883call to \cfunction{PyInterpreterState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004884\end{cfuncdesc}
4885
Fred Drakec6fa34e1998-04-02 06:47:24 +00004886\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004887Create a new thread state object belonging to the given interpreter
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004888object. The interpreter lock need not be held, but may be held if it
4889is necessary to serialize calls to this function.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004890\end{cfuncdesc}
4891
4892\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
4893Reset all information in a thread state object. The interpreter lock
4894must be held.
4895\end{cfuncdesc}
4896
4897\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
4898Destroy a thread state object. The interpreter lock need not be
4899held. The thread state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004900call to \cfunction{PyThreadState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004901\end{cfuncdesc}
4902
Fred Drakec6fa34e1998-04-02 06:47:24 +00004903\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004904Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004905When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004906error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004907\end{cfuncdesc}
4908
Fred Drakec6fa34e1998-04-02 06:47:24 +00004909\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004910Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004911argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004912must be held.
4913\end{cfuncdesc}
4914
Fred Drake24e62192001-05-21 15:56:55 +00004915\begin{cfuncdesc}{PyObject*}{PyThreadState_GetDict}{}
4916Return a dictionary in which extensions can store thread-specific
4917state information. Each extension should use a unique key to use to
4918store state in the dictionary. If this function returns \NULL, an
4919exception has been raised and the caller should allow it to
4920propogate.
4921\end{cfuncdesc}
4922
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004923
Fred Drake68db7302001-07-17 19:48:30 +00004924\section{Profiling and Tracing \label{profiling}}
4925
4926\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
4927
4928The Python interpreter provides some low-level support for attaching
4929profiling and execution tracing facilities. These are used for
4930profiling, debugging, and coverage analysis tools.
4931
4932Starting with Python 2.2, the implementation of this facility was
4933substantially revised, and an interface from C was added. This C
4934interface allows the profiling or tracing code to avoid the overhead
4935of calling through Python-level callable objects, making a direct C
4936function call instead. The essential attributes of the facility have
4937not changed; the interface allows trace functions to be installed
4938per-thread, and the basic events reported to the trace function are
4939the same as had been reported to the Python-level trace functions in
4940previous versions.
4941
4942\begin{ctypedesc}[Py_tracefunc]{int (*Py_tracefunc)(PyObject *obj,
4943 PyFrameObject *frame, int what,
4944 PyObject *arg)}
4945 The type of the trace function registered using
4946 \cfunction{PyEval_SetProfile()} and \cfunction{PyEval_SetTrace()}.
4947 The first parameter is the object passed to the registration
4948 function,
4949\end{ctypedesc}
4950
4951\begin{cvardesc}{int}{PyTrace_CALL}
4952 The value of the \var{what} parameter to a \ctype{Py_tracefunc}
4953 function when a new function or method call is being reported.
4954\end{cvardesc}
4955
4956\begin{cvardesc}{int}{PyTrace_EXCEPT}
4957\end{cvardesc}
4958
4959\begin{cvardesc}{int}{PyTrace_LINE}
4960 The value passed as the \var{what} parameter to a trace function
4961 (but not a profiling function) when a line-number event is being
4962 reported.
4963\end{cvardesc}
4964
4965\begin{cvardesc}{int}{PyTrace_RETURN}
4966 The value for the \var{what} parameter to \ctype{Py_tracefunc}
4967 functions when a call is returning without propogating an exception.
4968\end{cvardesc}
4969
4970\begin{cfuncdesc}{void}{PyEval_SetProfile}{Py_tracefunc func, PyObject *obj}
Fred Drakef90490e2001-08-02 18:00:28 +00004971 Set the profiler function to \var{func}. The \var{obj} parameter is
4972 passed to the function as its first parameter, and may be any Python
4973 object, or \NULL. If the profile function needs to maintain state,
4974 using a different value for \var{obj} for each thread provides a
4975 convenient and thread-safe place to store it. The profile function
4976 is called for all monitored events except the line-number events.
Fred Drake68db7302001-07-17 19:48:30 +00004977\end{cfuncdesc}
4978
4979\begin{cfuncdesc}{void}{PyEval_SetTrace}{Py_tracefunc func, PyObject *obj}
Fred Drakef90490e2001-08-02 18:00:28 +00004980 Set the the tracing function to \var{func}. This is similar to
4981 \cfunction{PyEval_SetProfile()}, except the tracing function does
4982 receive line-number events.
Fred Drake68db7302001-07-17 19:48:30 +00004983\end{cfuncdesc}
4984
4985
Fred Drake01978582001-08-08 19:14:53 +00004986\section{Advanced Debugger Support \label{advanced-debugging}}
4987\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
4988
4989These functions are only intended to be used by advanced debugging
4990tools.
4991
4992\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Head}{}
4993Return the interpreter state object at the head of the list of all
4994such objects.
4995\versionadded{2.2}
4996\end{cfuncdesc}
4997
4998\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Next}{PyInterpreterState *interp}
4999Return the next interpreter state object after \var{interp} from the
5000list of all such objects.
5001\versionadded{2.2}
5002\end{cfuncdesc}
5003
5004\begin{cfuncdesc}{PyThreadState *}{PyInterpreterState_ThreadHead}{PyInterpreterState *interp}
5005Return the a pointer to the first \ctype{PyThreadState} object in the
5006list of threads associated with the interpreter \var{interp}.
5007\versionadded{2.2}
5008\end{cfuncdesc}
5009
5010\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Next}{PyThreadState *tstate}
5011Return the next thread state object after \var{tstate} from the list
5012of all such objects belonging to the same \ctype{PyInterpreterState}
5013object.
5014\versionadded{2.2}
5015\end{cfuncdesc}
5016
5017
Fred Drake659ebfa2000-04-03 15:42:13 +00005018\chapter{Memory Management \label{memory}}
5019\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
5020
5021
5022\section{Overview \label{memoryOverview}}
5023
5024Memory management in Python involves a private heap containing all
5025Python objects and data structures. The management of this private
5026heap is ensured internally by the \emph{Python memory manager}. The
5027Python memory manager has different components which deal with various
5028dynamic storage management aspects, like sharing, segmentation,
5029preallocation or caching.
5030
5031At the lowest level, a raw memory allocator ensures that there is
5032enough room in the private heap for storing all Python-related data
5033by interacting with the memory manager of the operating system. On top
5034of the raw memory allocator, several object-specific allocators
5035operate on the same heap and implement distinct memory management
5036policies adapted to the peculiarities of every object type. For
5037example, integer objects are managed differently within the heap than
5038strings, tuples or dictionaries because integers imply different
5039storage requirements and speed/space tradeoffs. The Python memory
5040manager thus delegates some of the work to the object-specific
5041allocators, but ensures that the latter operate within the bounds of
5042the private heap.
5043
5044It is important to understand that the management of the Python heap
5045is performed by the interpreter itself and that the user has no
5046control on it, even if she regularly manipulates object pointers to
5047memory blocks inside that heap. The allocation of heap space for
5048Python objects and other internal buffers is performed on demand by
5049the Python memory manager through the Python/C API functions listed in
5050this document.
5051
5052To avoid memory corruption, extension writers should never try to
5053operate on Python objects with the functions exported by the C
5054library: \cfunction{malloc()}\ttindex{malloc()},
5055\cfunction{calloc()}\ttindex{calloc()},
5056\cfunction{realloc()}\ttindex{realloc()} and
5057\cfunction{free()}\ttindex{free()}. This will result in
5058mixed calls between the C allocator and the Python memory manager
5059with fatal consequences, because they implement different algorithms
5060and operate on different heaps. However, one may safely allocate and
5061release memory blocks with the C library allocator for individual
5062purposes, as shown in the following example:
5063
5064\begin{verbatim}
5065 PyObject *res;
5066 char *buf = (char *) malloc(BUFSIZ); /* for I/O */
5067
5068 if (buf == NULL)
5069 return PyErr_NoMemory();
5070 ...Do some I/O operation involving buf...
5071 res = PyString_FromString(buf);
5072 free(buf); /* malloc'ed */
5073 return res;
5074\end{verbatim}
5075
5076In this example, the memory request for the I/O buffer is handled by
5077the C library allocator. The Python memory manager is involved only
5078in the allocation of the string object returned as a result.
5079
5080In most situations, however, it is recommended to allocate memory from
5081the Python heap specifically because the latter is under control of
5082the Python memory manager. For example, this is required when the
5083interpreter is extended with new object types written in C. Another
5084reason for using the Python heap is the desire to \emph{inform} the
5085Python memory manager about the memory needs of the extension module.
5086Even when the requested memory is used exclusively for internal,
5087highly-specific purposes, delegating all memory requests to the Python
5088memory manager causes the interpreter to have a more accurate image of
5089its memory footprint as a whole. Consequently, under certain
5090circumstances, the Python memory manager may or may not trigger
5091appropriate actions, like garbage collection, memory compaction or
5092other preventive procedures. Note that by using the C library
5093allocator as shown in the previous example, the allocated memory for
5094the I/O buffer escapes completely the Python memory manager.
5095
5096
5097\section{Memory Interface \label{memoryInterface}}
5098
5099The following function sets, modeled after the ANSI C standard, are
5100available for allocating and releasing memory from the Python heap:
5101
5102
Fred Drake7d45d342000-08-11 17:07:32 +00005103\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
5104Allocates \var{n} bytes and returns a pointer of type \ctype{void*} to
Fred Drakebab29652001-07-10 16:10:08 +00005105the allocated memory, or \NULL{} if the request fails. Requesting zero
Fred Drake659ebfa2000-04-03 15:42:13 +00005106bytes returns a non-\NULL{} pointer.
Fred Drakebab29652001-07-10 16:10:08 +00005107The memory will not have been initialized in any way.
Fred Drake659ebfa2000-04-03 15:42:13 +00005108\end{cfuncdesc}
5109
Fred Drake7d45d342000-08-11 17:07:32 +00005110\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00005111Resizes the memory block pointed to by \var{p} to \var{n} bytes. The
5112contents will be unchanged to the minimum of the old and the new
5113sizes. If \var{p} is \NULL{}, the call is equivalent to
Fred Drakebab29652001-07-10 16:10:08 +00005114\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the
5115memory block is resized but is not freed, and the returned pointer is
5116non-\NULL{}. Unless \var{p} is \NULL{}, it must have been returned by
5117a previous call to \cfunction{PyMem_Malloc()} or
5118\cfunction{PyMem_Realloc()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00005119\end{cfuncdesc}
5120
Fred Drake7d45d342000-08-11 17:07:32 +00005121\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00005122Frees the memory block pointed to by \var{p}, which must have been
5123returned by a previous call to \cfunction{PyMem_Malloc()} or
5124\cfunction{PyMem_Realloc()}. Otherwise, or if
5125\cfunction{PyMem_Free(p)} has been called before, undefined behaviour
5126occurs. If \var{p} is \NULL{}, no operation is performed.
5127\end{cfuncdesc}
5128
Fred Drake659ebfa2000-04-03 15:42:13 +00005129The following type-oriented macros are provided for convenience. Note
5130that \var{TYPE} refers to any C type.
5131
Fred Drakef913e542000-09-12 20:17:17 +00005132\begin{cfuncdesc}{\var{TYPE}*}{PyMem_New}{TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00005133Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
5134sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
5135\ctype{\var{TYPE}*}.
Fred Drakebab29652001-07-10 16:10:08 +00005136The memory will not have been initialized in any way.
Fred Drake659ebfa2000-04-03 15:42:13 +00005137\end{cfuncdesc}
5138
Fred Drakef913e542000-09-12 20:17:17 +00005139\begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00005140Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
5141to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
5142cast to \ctype{\var{TYPE}*}.
5143\end{cfuncdesc}
5144
Fred Drakef913e542000-09-12 20:17:17 +00005145\begin{cfuncdesc}{void}{PyMem_Del}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00005146Same as \cfunction{PyMem_Free()}.
5147\end{cfuncdesc}
5148
Fred Drakef913e542000-09-12 20:17:17 +00005149In addition, the following macro sets are provided for calling the
5150Python memory allocator directly, without involving the C API functions
5151listed above. However, note that their use does not preserve binary
5152compatibility accross Python versions and is therefore deprecated in
5153extension modules.
5154
5155\cfunction{PyMem_MALLOC()}, \cfunction{PyMem_REALLOC()}, \cfunction{PyMem_FREE()}.
5156
5157\cfunction{PyMem_NEW()}, \cfunction{PyMem_RESIZE()}, \cfunction{PyMem_DEL()}.
5158
Fred Drake659ebfa2000-04-03 15:42:13 +00005159
5160\section{Examples \label{memoryExamples}}
5161
5162Here is the example from section \ref{memoryOverview}, rewritten so
5163that the I/O buffer is allocated from the Python heap by using the
5164first function set:
5165
5166\begin{verbatim}
5167 PyObject *res;
5168 char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
5169
5170 if (buf == NULL)
5171 return PyErr_NoMemory();
5172 /* ...Do some I/O operation involving buf... */
5173 res = PyString_FromString(buf);
5174 PyMem_Free(buf); /* allocated with PyMem_Malloc */
5175 return res;
5176\end{verbatim}
5177
Fred Drakef913e542000-09-12 20:17:17 +00005178The same code using the type-oriented function set:
Fred Drake659ebfa2000-04-03 15:42:13 +00005179
5180\begin{verbatim}
5181 PyObject *res;
Fred Drakef913e542000-09-12 20:17:17 +00005182 char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
Fred Drake659ebfa2000-04-03 15:42:13 +00005183
5184 if (buf == NULL)
5185 return PyErr_NoMemory();
5186 /* ...Do some I/O operation involving buf... */
5187 res = PyString_FromString(buf);
Fred Drakef913e542000-09-12 20:17:17 +00005188 PyMem_Del(buf); /* allocated with PyMem_New */
Fred Drake659ebfa2000-04-03 15:42:13 +00005189 return res;
5190\end{verbatim}
5191
Fred Drakef913e542000-09-12 20:17:17 +00005192Note that in the two examples above, the buffer is always
5193manipulated via functions belonging to the same set. Indeed, it
Fred Drake659ebfa2000-04-03 15:42:13 +00005194is required to use the same memory API family for a given
5195memory block, so that the risk of mixing different allocators is
5196reduced to a minimum. The following code sequence contains two errors,
5197one of which is labeled as \emph{fatal} because it mixes two different
5198allocators operating on different heaps.
5199
5200\begin{verbatim}
Fred Drakef913e542000-09-12 20:17:17 +00005201char *buf1 = PyMem_New(char, BUFSIZ);
Fred Drake659ebfa2000-04-03 15:42:13 +00005202char *buf2 = (char *) malloc(BUFSIZ);
5203char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
5204...
Fred Drakef913e542000-09-12 20:17:17 +00005205PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
Fred Drake659ebfa2000-04-03 15:42:13 +00005206free(buf2); /* Right -- allocated via malloc() */
Fred Drakef913e542000-09-12 20:17:17 +00005207free(buf1); /* Fatal -- should be PyMem_Del() */
Fred Drake659ebfa2000-04-03 15:42:13 +00005208\end{verbatim}
5209
5210In addition to the functions aimed at handling raw memory blocks from
5211the Python heap, objects in Python are allocated and released with
Fred Drakef913e542000-09-12 20:17:17 +00005212\cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()} and
5213\cfunction{PyObject_Del()}, or with their corresponding macros
5214\cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()} and
Fred Drakee06f0f92000-06-30 15:52:39 +00005215\cfunction{PyObject_DEL()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00005216
Fred Drakee06f0f92000-06-30 15:52:39 +00005217These will be explained in the next chapter on defining and
5218implementing new object types in C.
Fred Drake659ebfa2000-04-03 15:42:13 +00005219
5220
Fred Drakeefd146c1999-02-15 15:30:45 +00005221\chapter{Defining New Object Types \label{newTypes}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00005222
Fred Drake88fdaa72001-07-20 20:56:11 +00005223
5224\section{Allocating Objects on the Heap
5225 \label{allocating-objects}}
5226
Fred Drakec6fa34e1998-04-02 06:47:24 +00005227\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00005228\end{cfuncdesc}
5229
Fred Drakef913e542000-09-12 20:17:17 +00005230\begin{cfuncdesc}{PyVarObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00005231\end{cfuncdesc}
5232
Fred Drakef913e542000-09-12 20:17:17 +00005233\begin{cfuncdesc}{void}{_PyObject_Del}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00005234\end{cfuncdesc}
5235
Fred Drakef913e542000-09-12 20:17:17 +00005236\begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op,
Fred Drakebab29652001-07-10 16:10:08 +00005237 PyTypeObject *type}
5238 Initialize a newly-allocated object \var{op} with its type and
5239 initial reference. Returns the initialized object. If \var{type}
5240 indicates that the object participates in the cyclic garbage
5241 detector, it it added to the detector's set of observed objects.
5242 Other fields of the object are not affected.
Fred Drakef913e542000-09-12 20:17:17 +00005243\end{cfuncdesc}
5244
5245\begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op,
Fred Drakebab29652001-07-10 16:10:08 +00005246 PyTypeObject *type, int size}
5247 This does everything \cfunction{PyObject_Init()} does, and also
5248 initializes the length information for a variable-size object.
Fred Drakef913e542000-09-12 20:17:17 +00005249\end{cfuncdesc}
5250
5251\begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type}
Fred Drakebab29652001-07-10 16:10:08 +00005252 Allocate a new Python object using the C structure type \var{TYPE}
5253 and the Python type object \var{type}. Fields not defined by the
5254 Python object header are not initialized; the object's reference
5255 count will be one. The size of the memory
5256 allocation is determined from the \member{tp_basicsize} field of the
5257 type object.
Fred Drakef913e542000-09-12 20:17:17 +00005258\end{cfuncdesc}
5259
5260\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type,
5261 int size}
Fred Drakebab29652001-07-10 16:10:08 +00005262 Allocate a new Python object using the C structure type \var{TYPE}
5263 and the Python type object \var{type}. Fields not defined by the
5264 Python object header are not initialized. The allocated memory
5265 allows for the \var{TYPE} structure plus \var{size} fields of the
5266 size given by the \member{tp_itemsize} field of \var{type}. This is
5267 useful for implementing objects like tuples, which are able to
5268 determine their size at construction time. Embedding the array of
5269 fields into the same allocation decreases the number of allocations,
5270 improving the memory management efficiency.
Fred Drakef913e542000-09-12 20:17:17 +00005271\end{cfuncdesc}
5272
5273\begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op}
Fred Drakebab29652001-07-10 16:10:08 +00005274 Releases memory allocated to an object using
5275 \cfunction{PyObject_New()} or \cfunction{PyObject_NewVar()}. This
5276 is normally called from the \member{tp_dealloc} handler specified in
5277 the object's type. The fields of the object should not be accessed
5278 after this call as the memory is no longer a valid Python object.
Fred Drakef913e542000-09-12 20:17:17 +00005279\end{cfuncdesc}
5280
5281\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW}{TYPE, PyTypeObject *type}
Fred Drakebab29652001-07-10 16:10:08 +00005282 Macro version of \cfunction{PyObject_New()}, to gain performance at
5283 the expense of safety. This does not check \var{type} for a \NULL{}
5284 value.
Fred Drakef913e542000-09-12 20:17:17 +00005285\end{cfuncdesc}
5286
5287\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
5288 int size}
Fred Drakebab29652001-07-10 16:10:08 +00005289 Macro version of \cfunction{PyObject_NewVar()}, to gain performance
5290 at the expense of safety. This does not check \var{type} for a
5291 \NULL{} value.
Fred Drakef913e542000-09-12 20:17:17 +00005292\end{cfuncdesc}
5293
5294\begin{cfuncdesc}{void}{PyObject_DEL}{PyObject *op}
Fred Drakebab29652001-07-10 16:10:08 +00005295 Macro version of \cfunction{PyObject_Del()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00005296\end{cfuncdesc}
5297
Fred Drakeee814bf2000-11-28 22:34:32 +00005298\begin{cfuncdesc}{PyObject*}{Py_InitModule}{char *name,
5299 PyMethodDef *methods}
5300 Create a new module object based on a name and table of functions,
5301 returning the new module object.
5302\end{cfuncdesc}
5303
5304\begin{cfuncdesc}{PyObject*}{Py_InitModule3}{char *name,
5305 PyMethodDef *methods,
5306 char *doc}
5307 Create a new module object based on a name and table of functions,
5308 returning the new module object. If \var{doc} is non-\NULL, it will
5309 be used to define the docstring for the module.
5310\end{cfuncdesc}
5311
5312\begin{cfuncdesc}{PyObject*}{Py_InitModule4}{char *name,
5313 PyMethodDef *methods,
5314 char *doc, PyObject *self,
5315 int apiver}
5316 Create a new module object based on a name and table of functions,
5317 returning the new module object. If \var{doc} is non-\NULL, it will
5318 be used to define the docstring for the module. If \var{self} is
5319 non-\NULL, it will passed to the functions of the module as their
5320 (otherwise \NULL) first parameter. (This was added as an
5321 experimental feature, and there are no known uses in the current
5322 version of Python.) For \var{apiver}, the only value which should
5323 be passed is defined by the constant \constant{PYTHON_API_VERSION}.
5324
5325 \strong{Note:} Most uses of this function should probably be using
5326 the \cfunction{Py_InitModule3()} instead; only use this if you are
5327 sure you need it.
5328\end{cfuncdesc}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00005329
Fred Drake659ebfa2000-04-03 15:42:13 +00005330DL_IMPORT
5331
Fred Drakebab29652001-07-10 16:10:08 +00005332\begin{cvardesc}{PyObject}{_Py_NoneStruct}
5333 Object which is visible in Python as \code{None}. This should only
5334 be accessed using the \code{Py_None} macro, which evaluates to a
5335 pointer to this object.
5336\end{cvardesc}
Fred Drake659ebfa2000-04-03 15:42:13 +00005337
5338
5339\section{Common Object Structures \label{common-structs}}
5340
Guido van Rossumae110af1997-05-22 20:11:52 +00005341PyObject, PyVarObject
5342
5343PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
5344
5345Typedefs:
5346unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
5347intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
Guido van Rossumae110af1997-05-22 20:11:52 +00005348destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
5349setattrofunc, cmpfunc, reprfunc, hashfunc
5350
Fred Drakea8455ab2000-06-16 19:58:42 +00005351\begin{ctypedesc}{PyCFunction}
5352Type of the functions used to implement most Python callables in C.
5353\end{ctypedesc}
5354
5355\begin{ctypedesc}{PyMethodDef}
5356Structure used to describe a method of an extension type. This
5357structure has four fields:
5358
5359\begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
5360 \lineiii{ml_name}{char *}{name of the method}
5361 \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
5362 \lineiii{ml_flags}{int}{flag bits indicating how the call should be
5363 constructed}
5364 \lineiii{ml_doc}{char *}{points to the contents of the docstring}
5365\end{tableiii}
5366\end{ctypedesc}
5367
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00005368The \var{ml_meth} is a C function pointer. The functions may be of
5369different types, but they always return \ctype{PyObject*}. If the
5370function is not of the \ctype{PyCFunction}, the compiler will require
5371a cast in the method table. Even though \ctype{PyCFunction} defines
5372the first parameter as \ctype{PyObject*}, it is common that the method
5373implementation uses a the specific C type of the \var{self} object.
5374
5375The flags can have the following values. Only METH_VARARGS and
5376METH_KEYWORDS can be combined; the others can't.
5377
5378\begin{datadesc}{METH_VARARGS}
5379
5380This is the typical calling convention, where the methods have the
5381type \ctype{PyMethodDef}. The function expects two \ctype{PyObject*}.
5382The first one is the \var{self} object for methods; for module
5383functions, it has the value given to \cfunction{PyInitModule4} (or
5384\NULL{} if \cfunction{PyInitModule} was used). The second parameter
5385(often called \var{args}) is a tuple object representing all
5386arguments. This parameter is typically processed using
5387\cfunction{PyArg_ParseTuple}.
5388
5389\end{datadesc}
5390
5391\begin{datadesc}{METH_KEYWORDS}
5392
5393Methods with these flags must be of type
5394\ctype{PyCFunctionWithKeywords}. The function expects three
5395parameters: \var{self}, \var{args}, and a dictionary of all the keyword
5396arguments. The flag is typically combined with METH_VARARGS, and the
5397parameters are typically processed using
5398\cfunction{PyArg_ParseTupleAndKeywords}.
5399
5400\end{datadesc}
5401
5402\begin{datadesc}{METH_NOARGS}
5403
5404Methods without parameters don't need to check whether arguments are
5405given if they are listed with the \code{METH_NOARGS} flag. They need
5406to be of type \ctype{PyNoArgsFunction}, i.e. they expect a single
5407\var{self} parameter.
5408
5409\end{datadesc}
5410
5411\begin{datadesc}{METH_O}
5412
5413Methods with a single object argument can be listed with the
5414\code{METH_O} flag, instead of invoking \cfunction{PyArg_ParseTuple}
5415with a \code{``O''} argument. They have the type \ctype{PyCFunction},
5416with the \var{self} parameter, and a \ctype{PyObject*} parameter
5417representing the single argument.
5418
5419\end{datadesc}
5420
5421\begin{datadesc}{METH_OLDARGS}
5422
5423This calling convention is deprecated. The method must be of type
5424\ctype{PyCFunction}. The second argument is \NULL{} if no arguments
5425are given, a single object if exactly one argument is given, and a
5426tuple of objects if more than one argument is given.
5427
5428\end{datadesc}
5429
Fred Drakea8455ab2000-06-16 19:58:42 +00005430\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef[] table,
5431 PyObject *ob, char *name}
5432Return a bound method object for an extension type implemented in C.
5433This function also handles the special attribute \member{__methods__},
5434returning a list of all the method names defined in \var{table}.
5435\end{cfuncdesc}
5436
Fred Drake659ebfa2000-04-03 15:42:13 +00005437
5438\section{Mapping Object Structures \label{mapping-structs}}
5439
5440\begin{ctypedesc}{PyMappingMethods}
5441Structure used to hold pointers to the functions used to implement the
5442mapping protocol for an extension type.
5443\end{ctypedesc}
5444
5445
5446\section{Number Object Structures \label{number-structs}}
5447
5448\begin{ctypedesc}{PyNumberMethods}
5449Structure used to hold pointers to the functions an extension type
5450uses to implement the number protocol.
5451\end{ctypedesc}
5452
5453
5454\section{Sequence Object Structures \label{sequence-structs}}
5455
5456\begin{ctypedesc}{PySequenceMethods}
5457Structure used to hold pointers to the functions which an object uses
5458to implement the sequence protocol.
5459\end{ctypedesc}
5460
5461
5462\section{Buffer Object Structures \label{buffer-structs}}
5463\sectionauthor{Greg J. Stein}{greg@lyra.org}
5464
5465The buffer interface exports a model where an object can expose its
5466internal data as a set of chunks of data, where each chunk is
5467specified as a pointer/length pair. These chunks are called
5468\dfn{segments} and are presumed to be non-contiguous in memory.
5469
5470If an object does not export the buffer interface, then its
5471\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
5472should be \NULL{}. Otherwise, the \member{tp_as_buffer} will point to
5473a \ctype{PyBufferProcs} structure.
5474
5475\strong{Note:} It is very important that your
Fred Drakec392b572001-03-21 22:15:01 +00005476\ctype{PyTypeObject} structure uses \constant{Py_TPFLAGS_DEFAULT} for
5477the value of the \member{tp_flags} member rather than \code{0}. This
Fred Drake659ebfa2000-04-03 15:42:13 +00005478tells the Python runtime that your \ctype{PyBufferProcs} structure
5479contains the \member{bf_getcharbuffer} slot. Older versions of Python
5480did not have this member, so a new Python interpreter using an old
5481extension needs to be able to test for its presence before using it.
5482
5483\begin{ctypedesc}{PyBufferProcs}
5484Structure used to hold the function pointers which define an
5485implementation of the buffer protocol.
5486
5487The first slot is \member{bf_getreadbuffer}, of type
5488\ctype{getreadbufferproc}. If this slot is \NULL{}, then the object
5489does not support reading from the internal data. This is
5490non-sensical, so implementors should fill this in, but callers should
5491test that the slot contains a non-\NULL{} value.
5492
5493The next slot is \member{bf_getwritebuffer} having type
5494\ctype{getwritebufferproc}. This slot may be \NULL{} if the object
5495does not allow writing into its returned buffers.
5496
5497The third slot is \member{bf_getsegcount}, with type
5498\ctype{getsegcountproc}. This slot must not be \NULL{} and is used to
5499inform the caller how many segments the object contains. Simple
5500objects such as \ctype{PyString_Type} and
5501\ctype{PyBuffer_Type} objects contain a single segment.
5502
5503The last slot is \member{bf_getcharbuffer}, of type
5504\ctype{getcharbufferproc}. This slot will only be present if the
Fred Drakec392b572001-03-21 22:15:01 +00005505\constant{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
Fred Drake659ebfa2000-04-03 15:42:13 +00005506\member{tp_flags} field of the object's \ctype{PyTypeObject}. Before using
5507this slot, the caller should test whether it is present by using the
5508\cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()} function.
5509If present, it may be \NULL, indicating that the object's contents
5510cannot be used as \emph{8-bit characters}.
5511The slot function may also raise an error if the object's contents
5512cannot be interpreted as 8-bit characters. For example, if the object
5513is an array which is configured to hold floating point values, an
5514exception may be raised if a caller attempts to use
5515\member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
5516This notion of exporting the internal buffers as ``text'' is used to
5517distinguish between objects that are binary in nature, and those which
5518have character-based content.
5519
5520\strong{Note:} The current policy seems to state that these characters
5521may be multi-byte characters. This implies that a buffer size of
5522\var{N} does not mean there are \var{N} characters present.
5523\end{ctypedesc}
5524
5525\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
5526Flag bit set in the type structure to indicate that the
5527\member{bf_getcharbuffer} slot is known. This being set does not
5528indicate that the object supports the buffer interface or that the
5529\member{bf_getcharbuffer} slot is non-\NULL.
5530\end{datadesc}
5531
5532\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
5533 (PyObject *self, int segment, void **ptrptr)}
5534Return a pointer to a readable segment of the buffer. This function
5535is allowed to raise an exception, in which case it must return
5536\code{-1}. The \var{segment} which is passed must be zero or
5537positive, and strictly less than the number of segments returned by
Greg Stein4d4d0032001-04-07 16:14:49 +00005538the \member{bf_getsegcount} slot function. On success, it returns the
5539length of the buffer memory, and sets \code{*\var{ptrptr}} to a
5540pointer to that memory.
Fred Drake659ebfa2000-04-03 15:42:13 +00005541\end{ctypedesc}
5542
5543\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
5544 (PyObject *self, int segment, void **ptrptr)}
Greg Stein4d4d0032001-04-07 16:14:49 +00005545Return a pointer to a writable memory buffer in \code{*\var{ptrptr}},
5546and the length of that segment as the function return value.
5547The memory buffer must correspond to buffer segment \var{segment}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00005548Must return \code{-1} and set an exception on error.
5549\exception{TypeError} should be raised if the object only supports
5550read-only buffers, and \exception{SystemError} should be raised when
5551\var{segment} specifies a segment that doesn't exist.
5552% Why doesn't it raise ValueError for this one?
Fred Drake659ebfa2000-04-03 15:42:13 +00005553% GJS: because you shouldn't be calling it with an invalid
5554% segment. That indicates a blatant programming error in the C
5555% code.
Fred Drake58c5a2a1999-08-04 13:13:24 +00005556\end{ctypedesc}
5557
Fred Drake659ebfa2000-04-03 15:42:13 +00005558\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
5559 (PyObject *self, int *lenp)}
5560Return the number of memory segments which comprise the buffer. If
5561\var{lenp} is not \NULL, the implementation must report the sum of the
5562sizes (in bytes) of all segments in \code{*\var{lenp}}.
5563The function cannot fail.
5564\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00005565
Fred Drake659ebfa2000-04-03 15:42:13 +00005566\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
5567 (PyObject *self, int segment, const char **ptrptr)}
5568\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00005569
Guido van Rossumae110af1997-05-22 20:11:52 +00005570
Fred Drakef90490e2001-08-02 18:00:28 +00005571\section{Supporting the Iterator Protocol
5572 \label{supporting-iteration}}
5573
5574
Fred Drakec392b572001-03-21 22:15:01 +00005575\section{Supporting Cyclic Garbarge Collection
5576 \label{supporting-cycle-detection}}
5577
5578Python's support for detecting and collecting garbage which involves
5579circular references requires support from object types which are
5580``containers'' for other objects which may also be containers. Types
5581which do not store references to other objects, or which only store
5582references to atomic types (such as numbers or strings), do not need
5583to provide any explicit support for garbage collection.
5584
5585To create a container type, the \member{tp_flags} field of the type
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005586object must include the \constant{Py_TPFLAGS_HAVE_GC} and provide an
5587implementation of the \member{tp_traverse} handler. If instances of the
5588type are mutable, a \member{tp_clear} implementation must also be
5589provided.
Fred Drakec392b572001-03-21 22:15:01 +00005590
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005591\begin{datadesc}{Py_TPFLAGS_HAVE_GC}
Fred Drakec392b572001-03-21 22:15:01 +00005592 Objects with a type with this flag set must conform with the rules
5593 documented here. For convenience these objects will be referred to
5594 as container objects.
5595\end{datadesc}
5596
Fred Drakee28d8ae2001-03-22 16:30:17 +00005597Constructors for container types must conform to two rules:
5598
5599\begin{enumerate}
5600\item The memory for the object must be allocated using
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005601 \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_VarNew()}.
Fred Drakee28d8ae2001-03-22 16:30:17 +00005602
5603\item Once all the fields which may contain references to other
5604 containers are initialized, it must call
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005605 \cfunction{PyObject_GC_Track()}.
Fred Drakee28d8ae2001-03-22 16:30:17 +00005606\end{enumerate}
5607
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005608\begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_New}{TYPE, PyTypeObject *type}
5609 Analogous to \cfunction{PyObject_New()} but for container objects with
5610 the \constant{Py_TPFLAGS_HAVE_GC} flag set.
5611\end{cfuncdesc}
5612
5613\begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_NewVar}{TYPE, PyTypeObject *type,
5614 int size}
5615 Analogous to \cfunction{PyObject_NewVar()} but for container objects
5616 with the \constant{Py_TPFLAGS_HAVE_GC} flag set.
5617\end{cfuncdesc}
5618
5619\begin{cfuncdesc}{PyVarObject *}{PyObject_GC_Resize}{PyVarObject *op, int}
5620 Resize an object allocated by \cfunction{PyObject_NewVar()}. Returns
5621 the resized object or \NULL{} on failure.
5622\end{cfuncdesc}
5623
5624\begin{cfuncdesc}{void}{PyObject_GC_Track}{PyObject *op}
Fred Drakec392b572001-03-21 22:15:01 +00005625 Adds the object \var{op} to the set of container objects tracked by
5626 the collector. The collector can run at unexpected times so objects
5627 must be valid while being tracked. This should be called once all
5628 the fields followed by the \member{tp_traverse} handler become valid,
5629 usually near the end of the constructor.
5630\end{cfuncdesc}
5631
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005632\begin{cfuncdesc}{void}{_PyObject_GC_TRACK}{PyObject *op}
5633 A macro version of \cfunction{PyObject_GC_Track()}. It should not be
5634 used for extension modules.
5635\end{cfuncdesc}
5636
Fred Drakee28d8ae2001-03-22 16:30:17 +00005637Similarly, the deallocator for the object must conform to a similar
5638pair of rules:
5639
5640\begin{enumerate}
5641\item Before fields which refer to other containers are invalidated,
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005642 \cfunction{PyObject_GC_UnTrack()} must be called.
Fred Drakee28d8ae2001-03-22 16:30:17 +00005643
5644\item The object's memory must be deallocated using
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005645 \cfunction{PyObject_GC_Del()}.
Fred Drakee28d8ae2001-03-22 16:30:17 +00005646\end{enumerate}
5647
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005648\begin{cfuncdesc}{void}{PyObject_GC_Del}{PyObject *op}
5649 Releases memory allocated to an object using
5650 \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_NewVar()}.
5651\end{cfuncdesc}
5652
5653\begin{cfuncdesc}{void}{PyObject_GC_UnTrack}{PyObject *op}
Fred Drakec392b572001-03-21 22:15:01 +00005654 Remove the object \var{op} from the set of container objects tracked
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005655 by the collector. Note that \cfunction{PyObject_GC_Track()} can be
Fred Drakec392b572001-03-21 22:15:01 +00005656 called again on this object to add it back to the set of tracked
5657 objects. The deallocator (\member{tp_dealloc} handler) should call
5658 this for the object before any of the fields used by the
5659 \member{tp_traverse} handler become invalid.
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005660\end{cfuncdesc}
Fred Drake8f6df462001-03-23 17:42:09 +00005661
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005662\begin{cfuncdesc}{void}{_PyObject_GC_UNTRACK}{PyObject *op}
5663 A macro version of \cfunction{PyObject_GC_UnTrack()}. It should not be
5664 used for extension modules.
Fred Drakec392b572001-03-21 22:15:01 +00005665\end{cfuncdesc}
5666
5667The \member{tp_traverse} handler accepts a function parameter of this
5668type:
5669
5670\begin{ctypedesc}[visitproc]{int (*visitproc)(PyObject *object, void *arg)}
5671 Type of the visitor function passed to the \member{tp_traverse}
5672 handler. The function should be called with an object to traverse
5673 as \var{object} and the third parameter to the \member{tp_traverse}
5674 handler as \var{arg}.
5675\end{ctypedesc}
5676
5677The \member{tp_traverse} handler must have the following type:
5678
5679\begin{ctypedesc}[traverseproc]{int (*traverseproc)(PyObject *self,
5680 visitproc visit, void *arg)}
5681 Traversal function for a container object. Implementations must
5682 call the \var{visit} function for each object directly contained by
5683 \var{self}, with the parameters to \var{visit} being the contained
5684 object and the \var{arg} value passed to the handler. If
5685 \var{visit} returns a non-zero value then an error has occurred and
5686 that value should be returned immediately.
5687\end{ctypedesc}
5688
5689The \member{tp_clear} handler must be of the \ctype{inquiry} type, or
5690\NULL{} if the object is immutable.
5691
5692\begin{ctypedesc}[inquiry]{int (*inquiry)(PyObject *self)}
5693 Drop references that may have created reference cycles. Immutable
5694 objects do not have to define this method since they can never
5695 directly create reference cycles. Note that the object must still
Fred Drakebab29652001-07-10 16:10:08 +00005696 be valid after calling this method (don't just call
Fred Drakec392b572001-03-21 22:15:01 +00005697 \cfunction{Py_DECREF()} on a reference). The collector will call
5698 this method if it detects that this object is involved in a
5699 reference cycle.
5700\end{ctypedesc}
5701
5702
Fred Drakee28d8ae2001-03-22 16:30:17 +00005703\subsection{Example Cycle Collector Support
5704 \label{example-cycle-support}}
5705
5706This example shows only enough of the implementation of an extension
5707type to show how the garbage collector support needs to be added. It
5708shows the definition of the object structure, the
5709\member{tp_traverse}, \member{tp_clear} and \member{tp_dealloc}
5710implementations, the type structure, and a constructor --- the module
5711initialization needed to export the constructor to Python is not shown
5712as there are no special considerations there for the collector. To
5713make this interesting, assume that the module exposes ways for the
5714\member{container} field of the object to be modified. Note that
5715since no checks are made on the type of the object used to initialize
5716\member{container}, we have to assume that it may be a container.
5717
5718\begin{verbatim}
5719#include "Python.h"
5720
5721typedef struct {
5722 PyObject_HEAD
5723 PyObject *container;
5724} MyObject;
5725
5726static int
5727my_traverse(MyObject *self, visitproc visit, void *arg)
5728{
5729 if (self->container != NULL)
5730 return visit(self->container, arg);
5731 else
5732 return 0;
5733}
5734
5735static int
5736my_clear(MyObject *self)
5737{
5738 Py_XDECREF(self->container);
5739 self->container = NULL;
5740
5741 return 0;
5742}
5743
5744static void
5745my_dealloc(MyObject *self)
5746{
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005747 PyObject_GC_UnTrack((PyObject *) self);
Fred Drakee28d8ae2001-03-22 16:30:17 +00005748 Py_XDECREF(self->container);
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005749 PyObject_GC_Del(self);
Fred Drakee28d8ae2001-03-22 16:30:17 +00005750}
5751\end{verbatim}
5752
5753\begin{verbatim}
5754statichere PyTypeObject
5755MyObject_Type = {
5756 PyObject_HEAD_INIT(NULL)
5757 0,
5758 "MyObject",
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005759 sizeof(MyObject),
Fred Drakee28d8ae2001-03-22 16:30:17 +00005760 0,
5761 (destructor)my_dealloc, /* tp_dealloc */
5762 0, /* tp_print */
5763 0, /* tp_getattr */
5764 0, /* tp_setattr */
5765 0, /* tp_compare */
5766 0, /* tp_repr */
5767 0, /* tp_as_number */
5768 0, /* tp_as_sequence */
5769 0, /* tp_as_mapping */
5770 0, /* tp_hash */
5771 0, /* tp_call */
5772 0, /* tp_str */
5773 0, /* tp_getattro */
5774 0, /* tp_setattro */
5775 0, /* tp_as_buffer */
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005776 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
Fred Drakee28d8ae2001-03-22 16:30:17 +00005777 0, /* tp_doc */
5778 (traverseproc)my_traverse, /* tp_traverse */
5779 (inquiry)my_clear, /* tp_clear */
5780 0, /* tp_richcompare */
5781 0, /* tp_weaklistoffset */
5782};
5783
5784/* This constructor should be made accessible from Python. */
5785static PyObject *
5786new_object(PyObject *unused, PyObject *args)
5787{
5788 PyObject *container = NULL;
5789 MyObject *result = NULL;
5790
5791 if (PyArg_ParseTuple(args, "|O:new_object", &container)) {
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005792 result = PyObject_GC_New(MyObject, &MyObject_Type);
Fred Drakee28d8ae2001-03-22 16:30:17 +00005793 if (result != NULL) {
5794 result->container = container;
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005795 PyObject_GC_Track(result);
Fred Drakee28d8ae2001-03-22 16:30:17 +00005796 }
5797 }
5798 return (PyObject *) result;
5799}
5800\end{verbatim}
5801
5802
Fred Drake659ebfa2000-04-03 15:42:13 +00005803% \chapter{Debugging \label{debugging}}
5804%
5805% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00005806
5807
Fred Drakeed773ef2000-09-21 21:35:22 +00005808\appendix
5809\chapter{Reporting Bugs}
5810\input{reportingbugs}
5811
Fred Drake490d34d2001-06-20 21:39:12 +00005812\chapter{History and License}
5813\input{license}
5814
Marc-André Lemburga544ea22001-01-17 18:04:31 +00005815\input{api.ind} % Index -- must be last
Guido van Rossum9231c8f1997-05-15 21:43:21 +00005816
5817\end{document}