blob: b3a32d140d636fc30cd4a19dc2f6fc5830f46c66 [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).
Guido van Rossum580aa8d1997-11-25 15:34:51 +000079
80All user visible names defined by Python.h (except those defined by
Fred Drakee058b4f1998-02-16 06:15:35 +000081the included standard headers) have one of the prefixes \samp{Py} or
Fred Drake659ebfa2000-04-03 15:42:13 +000082\samp{_Py}. Names beginning with \samp{_Py} are for internal use by
83the Python implementation and should not be used by extension writers.
84Structure member names do not have a reserved prefix.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000085
Fred Drakee058b4f1998-02-16 06:15:35 +000086\strong{Important:} user code should never define names that begin
87with \samp{Py} or \samp{_Py}. This confuses the reader, and
88jeopardizes the portability of the user code to future Python
89versions, which may define additional names beginning with one of
90these prefixes.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000091
Fred Drake659ebfa2000-04-03 15:42:13 +000092The header files are typically installed with Python. On \UNIX, these
93are located in the directories
94\file{\envvar{prefix}/include/python\var{version}/} and
95\file{\envvar{exec_prefix}/include/python\var{version}/}, where
96\envvar{prefix} and \envvar{exec_prefix} are defined by the
97corresponding parameters to Python's \program{configure} script and
98\var{version} is \code{sys.version[:3]}. On Windows, the headers are
99installed in \file{\envvar{prefix}/include}, where \envvar{prefix} is
100the installation directory specified to the installer.
101
102To include the headers, place both directories (if different) on your
103compiler's search path for includes. Do \emph{not} place the parent
104directories on the search path and then use
Fred Draked5d04352000-09-14 20:24:17 +0000105\samp{\#include <python\shortversion/Python.h>}; this will break on
Fred Drake659ebfa2000-04-03 15:42:13 +0000106multi-platform builds since the platform independent headers under
107\envvar{prefix} include the platform specific headers from
108\envvar{exec_prefix}.
109
Fred Drakebab29652001-07-10 16:10:08 +0000110\Cpp{} users should note that though the API is defined entirely using
111C, the header files do properly declare the entry points to be
112\code{extern "C"}, so there is no need to do anything special to use
113the API from \Cpp.
114
Fred Drakeefd146c1999-02-15 15:30:45 +0000115
116\section{Objects, Types and Reference Counts \label{objects}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000117
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000118Most Python/C API functions have one or more arguments as well as a
Fred Drake659ebfa2000-04-03 15:42:13 +0000119return value of type \ctype{PyObject*}. This type is a pointer
Fred Drakee058b4f1998-02-16 06:15:35 +0000120to an opaque data type representing an arbitrary Python
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000121object. Since all Python object types are treated the same way by the
122Python language in most situations (e.g., assignments, scope rules,
123and argument passing), it is only fitting that they should be
Fred Drake659ebfa2000-04-03 15:42:13 +0000124represented by a single C type. Almost all Python objects live on the
125heap: you never declare an automatic or static variable of type
126\ctype{PyObject}, only pointer variables of type \ctype{PyObject*} can
127be declared. The sole exception are the type objects\obindex{type};
128since these must never be deallocated, they are typically static
129\ctype{PyTypeObject} objects.
Guido van Rossum59a61351997-08-14 20:34:33 +0000130
Fred Drakee058b4f1998-02-16 06:15:35 +0000131All Python objects (even Python integers) have a \dfn{type} and a
132\dfn{reference count}. An object's type determines what kind of object
Guido van Rossum4a944d71997-08-14 20:35:38 +0000133it is (e.g., an integer, a list, or a user-defined function; there are
Fred Drakebe486461999-11-09 17:03:03 +0000134many more as explained in the \citetitle[../ref/ref.html]{Python
135Reference Manual}). For each of the well-known types there is a macro
136to check whether an object is of that type; for instance,
Fred Drake659ebfa2000-04-03 15:42:13 +0000137\samp{PyList_Check(\var{a})} is true if (and only if) the object
138pointed to by \var{a} is a Python list.
Guido van Rossum59a61351997-08-14 20:34:33 +0000139
Fred Drakeefd146c1999-02-15 15:30:45 +0000140
141\subsection{Reference Counts \label{refcounts}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000142
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000143The reference count is important because today's computers have a
Fred Drake003d8da1998-04-13 00:53:42 +0000144finite (and often severely limited) memory size; it counts how many
Guido van Rossum4a944d71997-08-14 20:35:38 +0000145different places there are that have a reference to an object. Such a
Fred Drake659ebfa2000-04-03 15:42:13 +0000146place could be another object, or a global (or static) C variable, or
147a local variable in some C function. When an object's reference count
Guido van Rossum4a944d71997-08-14 20:35:38 +0000148becomes zero, the object is deallocated. If it contains references to
149other objects, their reference count is decremented. Those other
150objects may be deallocated in turn, if this decrement makes their
151reference count become zero, and so on. (There's an obvious problem
152with objects that reference each other here; for now, the solution is
Fred Drake659ebfa2000-04-03 15:42:13 +0000153``don't do that.'')
Guido van Rossum59a61351997-08-14 20:34:33 +0000154
Guido van Rossum4a944d71997-08-14 20:35:38 +0000155Reference counts are always manipulated explicitly. The normal way is
Fred Drake659ebfa2000-04-03 15:42:13 +0000156to use the macro \cfunction{Py_INCREF()}\ttindex{Py_INCREF()} to
157increment an object's reference count by one, and
158\cfunction{Py_DECREF()}\ttindex{Py_DECREF()} to decrement it by
159one. The \cfunction{Py_DECREF()} macro is considerably more complex
160than the incref one, since it must check whether the reference count
161becomes zero and then cause the object's deallocator to be called.
162The deallocator is a function pointer contained in the object's type
163structure. The type-specific deallocator takes care of decrementing
164the reference counts for other objects contained in the object if this
165is a compound object type, such as a list, as well as performing any
166additional finalization that's needed. There's no chance that the
167reference count can overflow; at least as many bits are used to hold
168the reference count as there are distinct memory locations in virtual
169memory (assuming \code{sizeof(long) >= sizeof(char*)}). Thus, the
170reference count increment is a simple operation.
Guido van Rossum59a61351997-08-14 20:34:33 +0000171
Guido van Rossum4a944d71997-08-14 20:35:38 +0000172It is not necessary to increment an object's reference count for every
173local variable that contains a pointer to an object. In theory, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000174object's reference count goes up by one when the variable is made to
Guido van Rossum4a944d71997-08-14 20:35:38 +0000175point to it and it goes down by one when the variable goes out of
176scope. However, these two cancel each other out, so at the end the
177reference count hasn't changed. The only real reason to use the
178reference count is to prevent the object from being deallocated as
179long as our variable is pointing to it. If we know that there is at
180least one other reference to the object that lives at least as long as
181our variable, there is no need to increment the reference count
182temporarily. An important situation where this arises is in objects
Fred Drake659ebfa2000-04-03 15:42:13 +0000183that are passed as arguments to C functions in an extension module
Guido van Rossum4a944d71997-08-14 20:35:38 +0000184that are called from Python; the call mechanism guarantees to hold a
Guido van Rossum59a61351997-08-14 20:34:33 +0000185reference to every argument for the duration of the call.
186
Fred Drakee058b4f1998-02-16 06:15:35 +0000187However, a common pitfall is to extract an object from a list and
188hold on to it for a while without incrementing its reference count.
189Some other operation might conceivably remove the object from the
190list, decrementing its reference count and possible deallocating it.
191The real danger is that innocent-looking operations may invoke
192arbitrary Python code which could do this; there is a code path which
193allows control to flow back to the user from a \cfunction{Py_DECREF()},
194so almost any operation is potentially dangerous.
Guido van Rossum59a61351997-08-14 20:34:33 +0000195
Guido van Rossum4a944d71997-08-14 20:35:38 +0000196A safe approach is to always use the generic operations (functions
Fred Drake659ebfa2000-04-03 15:42:13 +0000197whose name begins with \samp{PyObject_}, \samp{PyNumber_},
198\samp{PySequence_} or \samp{PyMapping_}). These operations always
199increment the reference count of the object they return. This leaves
200the caller with the responsibility to call
201\cfunction{Py_DECREF()} when they are done with the result; this soon
202becomes second nature.
Guido van Rossum59a61351997-08-14 20:34:33 +0000203
Fred Drakeefd146c1999-02-15 15:30:45 +0000204
205\subsubsection{Reference Count Details \label{refcountDetails}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000206
207The reference count behavior of functions in the Python/C API is best
Fred Drake659ebfa2000-04-03 15:42:13 +0000208explained in terms of \emph{ownership of references}. Note that we
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000209talk of owning references, never of owning objects; objects are always
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000210shared! When a function owns a reference, it has to dispose of it
Fred Drakee058b4f1998-02-16 06:15:35 +0000211properly --- either by passing ownership on (usually to its caller) or
212by calling \cfunction{Py_DECREF()} or \cfunction{Py_XDECREF()}. When
213a function passes ownership of a reference on to its caller, the
214caller is said to receive a \emph{new} reference. When no ownership
215is transferred, the caller is said to \emph{borrow} the reference.
216Nothing needs to be done for a borrowed reference.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000217
Fred Drakea8455ab2000-06-16 19:58:42 +0000218Conversely, when a calling function passes it a reference to an
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000219object, there are two possibilities: the function \emph{steals} a
220reference to the object, or it does not. Few functions steal
Fred Drakee058b4f1998-02-16 06:15:35 +0000221references; the two notable exceptions are
Fred Drake659ebfa2000-04-03 15:42:13 +0000222\cfunction{PyList_SetItem()}\ttindex{PyList_SetItem()} and
223\cfunction{PyTuple_SetItem()}\ttindex{PyTuple_SetItem()}, which
Fred Drakee058b4f1998-02-16 06:15:35 +0000224steal a reference to the item (but not to the tuple or list into which
Fred Drake003d8da1998-04-13 00:53:42 +0000225the item is put!). These functions were designed to steal a reference
Fred Drakee058b4f1998-02-16 06:15:35 +0000226because of a common idiom for populating a tuple or list with newly
227created objects; for example, the code to create the tuple \code{(1,
2282, "three")} could look like this (forgetting about error handling for
Fred Drake659ebfa2000-04-03 15:42:13 +0000229the moment; a better way to code this is shown below):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000230
231\begin{verbatim}
232PyObject *t;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000233
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000234t = PyTuple_New(3);
235PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
236PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
237PyTuple_SetItem(t, 2, PyString_FromString("three"));
238\end{verbatim}
239
Fred Drakee058b4f1998-02-16 06:15:35 +0000240Incidentally, \cfunction{PyTuple_SetItem()} is the \emph{only} way to
241set tuple items; \cfunction{PySequence_SetItem()} and
242\cfunction{PyObject_SetItem()} refuse to do this since tuples are an
243immutable data type. You should only use
244\cfunction{PyTuple_SetItem()} for tuples that you are creating
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000245yourself.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000246
247Equivalent code for populating a list can be written using
Fred Drakee058b4f1998-02-16 06:15:35 +0000248\cfunction{PyList_New()} and \cfunction{PyList_SetItem()}. Such code
249can also use \cfunction{PySequence_SetItem()}; this illustrates the
250difference between the two (the extra \cfunction{Py_DECREF()} calls):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000251
252\begin{verbatim}
253PyObject *l, *x;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000254
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000255l = PyList_New(3);
256x = PyInt_FromLong(1L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000257PySequence_SetItem(l, 0, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000258x = PyInt_FromLong(2L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000259PySequence_SetItem(l, 1, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000260x = PyString_FromString("three");
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000261PySequence_SetItem(l, 2, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000262\end{verbatim}
263
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000264You might find it strange that the ``recommended'' approach takes more
265code. However, in practice, you will rarely use these ways of
266creating and populating a tuple or list. There's a generic function,
Fred Drakee058b4f1998-02-16 06:15:35 +0000267\cfunction{Py_BuildValue()}, that can create most common objects from
Fred Drake659ebfa2000-04-03 15:42:13 +0000268C values, directed by a \dfn{format string}. For example, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000269above two blocks of code could be replaced by the following (which
270also takes care of the error checking):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000271
272\begin{verbatim}
273PyObject *t, *l;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000274
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000275t = Py_BuildValue("(iis)", 1, 2, "three");
276l = Py_BuildValue("[iis]", 1, 2, "three");
277\end{verbatim}
278
Fred Drakee058b4f1998-02-16 06:15:35 +0000279It is much more common to use \cfunction{PyObject_SetItem()} and
280friends with items whose references you are only borrowing, like
281arguments that were passed in to the function you are writing. In
282that case, their behaviour regarding reference counts is much saner,
283since you don't have to increment a reference count so you can give a
284reference away (``have it be stolen''). For example, this function
285sets all items of a list (actually, any mutable sequence) to a given
286item:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000287
288\begin{verbatim}
289int set_all(PyObject *target, PyObject *item)
290{
291 int i, n;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000292
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000293 n = PyObject_Length(target);
294 if (n < 0)
295 return -1;
296 for (i = 0; i < n; i++) {
297 if (PyObject_SetItem(target, i, item) < 0)
298 return -1;
299 }
300 return 0;
301}
302\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000303\ttindex{set_all()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000304
305The situation is slightly different for function return values.
306While passing a reference to most functions does not change your
307ownership responsibilities for that reference, many functions that
308return a referece to an object give you ownership of the reference.
309The reason is simple: in many cases, the returned object is created
310on the fly, and the reference you get is the only reference to the
Fred Drakee058b4f1998-02-16 06:15:35 +0000311object. Therefore, the generic functions that return object
312references, like \cfunction{PyObject_GetItem()} and
Fred Drakebab29652001-07-10 16:10:08 +0000313\cfunction{PySequence_GetItem()}, always return a new reference (the
314caller becomes the owner of the reference).
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000315
316It is important to realize that whether you own a reference returned
Fred Drakee058b4f1998-02-16 06:15:35 +0000317by a function depends on which function you call only --- \emph{the
Fred Drakebab29652001-07-10 16:10:08 +0000318plumage} (the type of the type of the object passed as an
Fred Drakee058b4f1998-02-16 06:15:35 +0000319argument to the function) \emph{doesn't enter into it!} Thus, if you
320extract an item from a list using \cfunction{PyList_GetItem()}, you
321don't own the reference --- but if you obtain the same item from the
322same list using \cfunction{PySequence_GetItem()} (which happens to
323take exactly the same arguments), you do own a reference to the
324returned object.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000325
Fred Drakee058b4f1998-02-16 06:15:35 +0000326Here is an example of how you could write a function that computes the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000327sum of the items in a list of integers; once using
Fred Drake659ebfa2000-04-03 15:42:13 +0000328\cfunction{PyList_GetItem()}\ttindex{PyList_GetItem()}, and once using
329\cfunction{PySequence_GetItem()}\ttindex{PySequence_GetItem()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000330
331\begin{verbatim}
332long sum_list(PyObject *list)
333{
334 int i, n;
335 long total = 0;
336 PyObject *item;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000337
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000338 n = PyList_Size(list);
339 if (n < 0)
340 return -1; /* Not a list */
341 for (i = 0; i < n; i++) {
342 item = PyList_GetItem(list, i); /* Can't fail */
343 if (!PyInt_Check(item)) continue; /* Skip non-integers */
344 total += PyInt_AsLong(item);
345 }
346 return total;
347}
348\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000349\ttindex{sum_list()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000350
351\begin{verbatim}
352long sum_sequence(PyObject *sequence)
353{
354 int i, n;
355 long total = 0;
356 PyObject *item;
Fred Drake659ebfa2000-04-03 15:42:13 +0000357 n = PySequence_Length(sequence);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000358 if (n < 0)
359 return -1; /* Has no length */
360 for (i = 0; i < n; i++) {
Fred Drake659ebfa2000-04-03 15:42:13 +0000361 item = PySequence_GetItem(sequence, i);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000362 if (item == NULL)
363 return -1; /* Not a sequence, or other failure */
364 if (PyInt_Check(item))
365 total += PyInt_AsLong(item);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000366 Py_DECREF(item); /* Discard reference ownership */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000367 }
368 return total;
369}
370\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000371\ttindex{sum_sequence()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000372
Fred Drakeefd146c1999-02-15 15:30:45 +0000373
374\subsection{Types \label{types}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000375
376There are few other data types that play a significant role in
Fred Drake659ebfa2000-04-03 15:42:13 +0000377the Python/C API; most are simple C types such as \ctype{int},
378\ctype{long}, \ctype{double} and \ctype{char*}. A few structure types
Guido van Rossum4a944d71997-08-14 20:35:38 +0000379are used to describe static tables used to list the functions exported
Fred Drake659ebfa2000-04-03 15:42:13 +0000380by a module or the data attributes of a new object type, and another
381is used to describe the value of a complex number. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000382be discussed together with the functions that use them.
383
Fred Drakeefd146c1999-02-15 15:30:45 +0000384
385\section{Exceptions \label{exceptions}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000386
Guido van Rossum4a944d71997-08-14 20:35:38 +0000387The Python programmer only needs to deal with exceptions if specific
388error handling is required; unhandled exceptions are automatically
Fred Drake659ebfa2000-04-03 15:42:13 +0000389propagated to the caller, then to the caller's caller, and so on, until
Guido van Rossum4a944d71997-08-14 20:35:38 +0000390they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000391user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000392
Fred Drake659ebfa2000-04-03 15:42:13 +0000393For C programmers, however, error checking always has to be explicit.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000394All functions in the Python/C API can raise exceptions, unless an
395explicit claim is made otherwise in a function's documentation. In
396general, when a function encounters an error, it sets an exception,
397discards any object references that it owns, and returns an
Fred Drakee058b4f1998-02-16 06:15:35 +0000398error indicator --- usually \NULL{} or \code{-1}. A few functions
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000399return a Boolean true/false result, with false indicating an error.
400Very few functions return no explicit error indicator or have an
401ambiguous return value, and require explicit testing for errors with
Fred Drake659ebfa2000-04-03 15:42:13 +0000402\cfunction{PyErr_Occurred()}\ttindex{PyErr_Occurred()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000403
404Exception state is maintained in per-thread storage (this is
405equivalent to using global storage in an unthreaded application). A
Fred Drakec6fa34e1998-04-02 06:47:24 +0000406thread can be in one of two states: an exception has occurred, or not.
Fred Drakee058b4f1998-02-16 06:15:35 +0000407The function \cfunction{PyErr_Occurred()} can be used to check for
408this: it returns a borrowed reference to the exception type object
409when an exception has occurred, and \NULL{} otherwise. There are a
410number of functions to set the exception state:
Fred Drake659ebfa2000-04-03 15:42:13 +0000411\cfunction{PyErr_SetString()}\ttindex{PyErr_SetString()} is the most
412common (though not the most general) function to set the exception
413state, and \cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} clears the
414exception state.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000415
416The full exception state consists of three objects (all of which can
Fred Drakee058b4f1998-02-16 06:15:35 +0000417be \NULL{}): the exception type, the corresponding exception
Fred Drake659ebfa2000-04-03 15:42:13 +0000418value, and the traceback. These have the same meanings as the Python
419\withsubitem{(in module sys)}{
420 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
421objects \code{sys.exc_type}, \code{sys.exc_value}, and
422\code{sys.exc_traceback}; however, they are not the same: the Python
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000423objects represent the last exception being handled by a Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000424\keyword{try} \ldots\ \keyword{except} statement, while the C level
Fred Drakee058b4f1998-02-16 06:15:35 +0000425exception state only exists while an exception is being passed on
Fred Drake659ebfa2000-04-03 15:42:13 +0000426between C functions until it reaches the Python bytecode interpreter's
427main loop, which takes care of transferring it to \code{sys.exc_type}
428and friends.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000429
Fred Drakec6fa34e1998-04-02 06:47:24 +0000430Note that starting with Python 1.5, the preferred, thread-safe way to
Fred Drake659ebfa2000-04-03 15:42:13 +0000431access the exception state from Python code is to call the function
432\withsubitem{(in module sys)}{\ttindex{exc_info()}}
Fred Drakee058b4f1998-02-16 06:15:35 +0000433\function{sys.exc_info()}, which returns the per-thread exception state
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000434for Python code. Also, the semantics of both ways to access the
435exception state have changed so that a function which catches an
436exception will save and restore its thread's exception state so as to
437preserve the exception state of its caller. This prevents common bugs
438in exception handling code caused by an innocent-looking function
439overwriting the exception being handled; it also reduces the often
440unwanted lifetime extension for objects that are referenced by the
Fred Drakec6fa34e1998-04-02 06:47:24 +0000441stack frames in the traceback.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000442
443As a general principle, a function that calls another function to
444perform some task should check whether the called function raised an
445exception, and if so, pass the exception state on to its caller. It
Fred Drake659ebfa2000-04-03 15:42:13 +0000446should discard any object references that it owns, and return an
Fred Drakee058b4f1998-02-16 06:15:35 +0000447error indicator, but it should \emph{not} set another exception ---
448that would overwrite the exception that was just raised, and lose
449important information about the exact cause of the error.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000450
Fred Drake659ebfa2000-04-03 15:42:13 +0000451A simple example of detecting exceptions and passing them on is shown
452in the \cfunction{sum_sequence()}\ttindex{sum_sequence()} example
453above. It so happens that that example doesn't need to clean up any
454owned references when it detects an error. The following example
455function shows some error cleanup. First, to remind you why you like
456Python, we show the equivalent Python code:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000457
458\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000459def incr_item(dict, key):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000460 try:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000461 item = dict[key]
462 except KeyError:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000463 item = 0
Fred Drake6b3f3f22000-11-29 15:48:22 +0000464 dict[key] = item + 1
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000465\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000466\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000467
Fred Drake659ebfa2000-04-03 15:42:13 +0000468Here is the corresponding C code, in all its glory:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000469
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000470\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000471int incr_item(PyObject *dict, PyObject *key)
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000472{
473 /* Objects all initialized to NULL for Py_XDECREF */
474 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000475 int rv = -1; /* Return value initialized to -1 (failure) */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000476
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000477 item = PyObject_GetItem(dict, key);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000478 if (item == NULL) {
Fred Drakec6fa34e1998-04-02 06:47:24 +0000479 /* Handle KeyError only: */
Fred Drake6b3f3f22000-11-29 15:48:22 +0000480 if (!PyErr_ExceptionMatches(PyExc_KeyError))
481 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000482
483 /* Clear the error and use zero: */
484 PyErr_Clear();
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000485 item = PyInt_FromLong(0L);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000486 if (item == NULL)
487 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000488 }
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000489 const_one = PyInt_FromLong(1L);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000490 if (const_one == NULL)
491 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000492
493 incremented_item = PyNumber_Add(item, const_one);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000494 if (incremented_item == NULL)
495 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000496
Fred Drake6b3f3f22000-11-29 15:48:22 +0000497 if (PyObject_SetItem(dict, key, incremented_item) < 0)
498 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000499 rv = 0; /* Success */
500 /* Continue with cleanup code */
501
502 error:
503 /* Cleanup code, shared by success and failure path */
504
505 /* Use Py_XDECREF() to ignore NULL references */
506 Py_XDECREF(item);
507 Py_XDECREF(const_one);
508 Py_XDECREF(incremented_item);
509
510 return rv; /* -1 for error, 0 for success */
511}
512\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000513\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000514
Fred Drakef8830d11998-04-23 14:06:01 +0000515This example represents an endorsed use of the \keyword{goto} statement
Fred Drake659ebfa2000-04-03 15:42:13 +0000516in C! It illustrates the use of
517\cfunction{PyErr_ExceptionMatches()}\ttindex{PyErr_ExceptionMatches()} and
518\cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} to
519handle specific exceptions, and the use of
520\cfunction{Py_XDECREF()}\ttindex{Py_XDECREF()} to
521dispose of owned references that may be \NULL{} (note the
522\character{X} in the name; \cfunction{Py_DECREF()} would crash when
523confronted with a \NULL{} reference). It is important that the
524variables used to hold owned references are initialized to \NULL{} for
525this to work; likewise, the proposed return value is initialized to
526\code{-1} (failure) and only set to success after the final call made
527is successful.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000528
Guido van Rossum59a61351997-08-14 20:34:33 +0000529
Fred Drakeefd146c1999-02-15 15:30:45 +0000530\section{Embedding Python \label{embedding}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000531
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000532The one important task that only embedders (as opposed to extension
533writers) of the Python interpreter have to worry about is the
534initialization, and possibly the finalization, of the Python
535interpreter. Most functionality of the interpreter can only be used
536after the interpreter has been initialized.
Guido van Rossum59a61351997-08-14 20:34:33 +0000537
Fred Drake659ebfa2000-04-03 15:42:13 +0000538The basic initialization function is
539\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Fred Drakee058b4f1998-02-16 06:15:35 +0000540This initializes the table of loaded modules, and creates the
Fred Drake4de05a91998-02-16 14:25:26 +0000541fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake680cabb2001-08-14 15:32:16 +0000542\module{__main__}\refbimodindex{__main__}, \module{sys}\refbimodindex{sys},
543and \module{exceptions}.\refbimodindex{exceptions} It also initializes
544the module search path (\code{sys.path}).%
Fred Drakec6fa34e1998-04-02 06:47:24 +0000545\indexiii{module}{search}{path}
Fred Drake659ebfa2000-04-03 15:42:13 +0000546\withsubitem{(in module sys)}{\ttindex{path}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000547
Fred Drakee058b4f1998-02-16 06:15:35 +0000548\cfunction{Py_Initialize()} does not set the ``script argument list''
Guido van Rossum4a944d71997-08-14 20:35:38 +0000549(\code{sys.argv}). If this variable is needed by Python code that
550will be executed later, it must be set explicitly with a call to
Fred Drake659ebfa2000-04-03 15:42:13 +0000551\code{PySys_SetArgv(\var{argc},
552\var{argv})}\ttindex{PySys_SetArgv()} subsequent to the call to
553\cfunction{Py_Initialize()}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000554
Fred Drakeb0a78731998-01-13 18:51:10 +0000555On most systems (in particular, on \UNIX{} and Windows, although the
Fred Drake659ebfa2000-04-03 15:42:13 +0000556details are slightly different),
557\cfunction{Py_Initialize()} calculates the module search path based
558upon its best guess for the location of the standard Python
559interpreter executable, assuming that the Python library is found in a
560fixed location relative to the Python interpreter executable. In
561particular, it looks for a directory named
Fred Draked5d04352000-09-14 20:24:17 +0000562\file{lib/python\shortversion} relative to the parent directory where
563the executable named \file{python} is found on the shell command
564search path (the environment variable \envvar{PATH}).
Guido van Rossum42cefd01997-10-05 15:27:29 +0000565
566For instance, if the Python executable is found in
Fred Drakee058b4f1998-02-16 06:15:35 +0000567\file{/usr/local/bin/python}, it will assume that the libraries are in
Fred Draked5d04352000-09-14 20:24:17 +0000568\file{/usr/local/lib/python\shortversion}. (In fact, this particular path
Fred Drakee058b4f1998-02-16 06:15:35 +0000569is also the ``fallback'' location, used when no executable file named
Fred Drakec6fa34e1998-04-02 06:47:24 +0000570\file{python} is found along \envvar{PATH}.) The user can override
571this behavior by setting the environment variable \envvar{PYTHONHOME},
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000572or insert additional directories in front of the standard path by
Fred Drakec6fa34e1998-04-02 06:47:24 +0000573setting \envvar{PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000574
Guido van Rossum4a944d71997-08-14 20:35:38 +0000575The embedding application can steer the search by calling
Fred Drake659ebfa2000-04-03 15:42:13 +0000576\code{Py_SetProgramName(\var{file})}\ttindex{Py_SetProgramName()} \emph{before} calling
Fred Drakec6fa34e1998-04-02 06:47:24 +0000577\cfunction{Py_Initialize()}. Note that \envvar{PYTHONHOME} still
578overrides this and \envvar{PYTHONPATH} is still inserted in front of
Fred Drakee058b4f1998-02-16 06:15:35 +0000579the standard path. An application that requires total control has to
Fred Drake659ebfa2000-04-03 15:42:13 +0000580provide its own implementation of
581\cfunction{Py_GetPath()}\ttindex{Py_GetPath()},
582\cfunction{Py_GetPrefix()}\ttindex{Py_GetPrefix()},
583\cfunction{Py_GetExecPrefix()}\ttindex{Py_GetExecPrefix()}, and
584\cfunction{Py_GetProgramFullPath()}\ttindex{Py_GetProgramFullPath()} (all
585defined in \file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000586
Guido van Rossum4a944d71997-08-14 20:35:38 +0000587Sometimes, it is desirable to ``uninitialize'' Python. For instance,
588the application may want to start over (make another call to
Fred Drakee058b4f1998-02-16 06:15:35 +0000589\cfunction{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000590use of Python and wants to free all memory allocated by Python. This
Fred Drakee058b4f1998-02-16 06:15:35 +0000591can be accomplished by calling \cfunction{Py_Finalize()}. The function
Fred Drake659ebfa2000-04-03 15:42:13 +0000592\cfunction{Py_IsInitialized()}\ttindex{Py_IsInitialized()} returns
593true if Python is currently in the initialized state. More
594information about these functions is given in a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000595
Guido van Rossum4a944d71997-08-14 20:35:38 +0000596
Fred Drakeefd146c1999-02-15 15:30:45 +0000597\chapter{The Very High Level Layer \label{veryhigh}}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000598
Fred Drakee5bf8b21998-02-12 21:22:28 +0000599The functions in this chapter will let you execute Python source code
600given in a file or a buffer, but they will not let you interact in a
601more detailed way with the interpreter.
Guido van Rossum4a944d71997-08-14 20:35:38 +0000602
Fred Drake659ebfa2000-04-03 15:42:13 +0000603Several of these functions accept a start symbol from the grammar as a
604parameter. The available start symbols are \constant{Py_eval_input},
605\constant{Py_file_input}, and \constant{Py_single_input}. These are
606described following the functions which accept them as parameters.
607
Fred Drake510d08b2000-08-14 02:50:21 +0000608Note also that several of these functions take \ctype{FILE*}
609parameters. On particular issue which needs to be handled carefully
610is that the \ctype{FILE} structure for different C libraries can be
611different and incompatible. Under Windows (at least), it is possible
612for dynamically linked extensions to actually use different libraries,
613so care should be taken that \ctype{FILE*} parameters are only passed
614to these functions if it is certain that they were created by the same
615library that the Python runtime is using.
616
Fred Drake24e62192001-05-21 15:56:55 +0000617\begin{cfuncdesc}{int}{Py_Main}{int argc, char **argv}
618 The main program for the standard interpreter. This is made
619 available for programs which embed Python. The \var{argc} and
620 \var{argv} parameters should be prepared exactly as those which are
621 passed to a C program's \cfunction{main()} function. It is
622 important to note that the argument list may be modified (but the
623 contents of the strings pointed to by the argument list are not).
624 The return value will be the integer passed to the
625 \function{sys.exit()} function, \code{1} if the interpreter exits
626 due to an exception, or \code{2} if the parameter list does not
627 represent a valid Python command line.
628\end{cfuncdesc}
629
Fred Drakec6fa34e1998-04-02 06:47:24 +0000630\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000631 If \var{fp} refers to a file associated with an interactive device
632 (console or terminal input or \UNIX{} pseudo-terminal), return the
633 value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
634 result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
Fred Drakea8d73412000-08-11 20:39:29 +0000635 \NULL{}, this function uses \code{"???"} as the filename.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000636\end{cfuncdesc}
637
Fred Drakec6fa34e1998-04-02 06:47:24 +0000638\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
Fred Drake0041a941999-04-29 04:20:46 +0000639 Executes the Python source code from \var{command} in the
640 \module{__main__} module. If \module{__main__} does not already
641 exist, it is created. Returns \code{0} on success or \code{-1} if
642 an exception was raised. If there was an error, there is no way to
643 get the exception information.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000644\end{cfuncdesc}
645
Fred Drakec6fa34e1998-04-02 06:47:24 +0000646\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000647 Similar to \cfunction{PyRun_SimpleString()}, but the Python source
648 code is read from \var{fp} instead of an in-memory string.
649 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000650\end{cfuncdesc}
651
Fred Drakec6fa34e1998-04-02 06:47:24 +0000652\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000653 Read and execute a single statement from a file associated with an
654 interactive device. If \var{filename} is \NULL, \code{"???"} is
655 used instead. The user will be prompted using \code{sys.ps1} and
656 \code{sys.ps2}. Returns \code{0} when the input was executed
657 successfully, \code{-1} if there was an exception, or an error code
658 from the \file{errcode.h} include file distributed as part of Python
659 in case of a parse error. (Note that \file{errcode.h} is not
660 included by \file{Python.h}, so must be included specifically if
661 needed.)
Fred Drakee5bf8b21998-02-12 21:22:28 +0000662\end{cfuncdesc}
663
Fred Drakec6fa34e1998-04-02 06:47:24 +0000664\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000665 Read and execute statements from a file associated with an
666 interactive device until \EOF{} is reached. If \var{filename} is
667 \NULL, \code{"???"} is used instead. The user will be prompted
668 using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000669\end{cfuncdesc}
670
Fred Drakec6fa34e1998-04-02 06:47:24 +0000671\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
672 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000673 Parse Python source code from \var{str} using the start token
674 \var{start}. The result can be used to create a code object which
675 can be evaluated efficiently. This is useful if a code fragment
676 must be evaluated many times.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000677\end{cfuncdesc}
678
Fred Drakec6fa34e1998-04-02 06:47:24 +0000679\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
680 char *filename, int start}
Fred Drake0041a941999-04-29 04:20:46 +0000681 Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
682 source code is read from \var{fp} instead of an in-memory string.
683 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000684\end{cfuncdesc}
685
Fred Drakec6fa34e1998-04-02 06:47:24 +0000686\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
687 PyObject *globals,
688 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000689 Execute Python source code from \var{str} in the context specified
690 by the dictionaries \var{globals} and \var{locals}. The parameter
691 \var{start} specifies the start token that should be used to parse
692 the source code.
693
694 Returns the result of executing the code as a Python object, or
695 \NULL{} if an exception was raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000696\end{cfuncdesc}
697
Fred Drakec6fa34e1998-04-02 06:47:24 +0000698\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
699 int start, PyObject *globals,
700 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000701 Similar to \cfunction{PyRun_String()}, but the Python source code is
Fred Drake659ebfa2000-04-03 15:42:13 +0000702 read from \var{fp} instead of an in-memory string.
703 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000704\end{cfuncdesc}
705
Fred Drakec6fa34e1998-04-02 06:47:24 +0000706\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
707 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000708 Parse and compile the Python source code in \var{str}, returning the
709 resulting code object. The start token is given by \var{start};
Fred Drakec924b8d1999-08-23 18:57:25 +0000710 this can be used to constrain the code which can be compiled and should
711 be \constant{Py_eval_input}, \constant{Py_file_input}, or
712 \constant{Py_single_input}. The filename specified by
713 \var{filename} is used to construct the code object and may appear
714 in tracebacks or \exception{SyntaxError} exception messages. This
715 returns \NULL{} if the code cannot be parsed or compiled.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000716\end{cfuncdesc}
717
Fred Drakec924b8d1999-08-23 18:57:25 +0000718\begin{cvardesc}{int}{Py_eval_input}
719 The start symbol from the Python grammar for isolated expressions;
Fred Drake659ebfa2000-04-03 15:42:13 +0000720 for use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
Fred Drakec924b8d1999-08-23 18:57:25 +0000721\end{cvardesc}
722
723\begin{cvardesc}{int}{Py_file_input}
724 The start symbol from the Python grammar for sequences of statements
725 as read from a file or other source; for use with
Fred Drake659ebfa2000-04-03 15:42:13 +0000726 \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
727 the symbol to use when compiling arbitrarily long Python source code.
Fred Drakec924b8d1999-08-23 18:57:25 +0000728\end{cvardesc}
729
730\begin{cvardesc}{int}{Py_single_input}
731 The start symbol from the Python grammar for a single statement; for
Fred Drake659ebfa2000-04-03 15:42:13 +0000732 use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
733 This is the symbol used for the interactive interpreter loop.
Fred Drakec924b8d1999-08-23 18:57:25 +0000734\end{cvardesc}
735
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000736
Fred Drakeefd146c1999-02-15 15:30:45 +0000737\chapter{Reference Counting \label{countingRefs}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000738
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000739The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000740of Python objects.
741
742\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
Fred Drakec6fa34e1998-04-02 06:47:24 +0000743Increment the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000744not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000745\cfunction{Py_XINCREF()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000746\end{cfuncdesc}
747
748\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000749Increment the reference count for object \var{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000750\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000751\end{cfuncdesc}
752
753\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000754Decrement the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000755not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000756\cfunction{Py_XDECREF()}. If the reference count reaches zero, the
757object's type's deallocation function (which must not be \NULL{}) is
758invoked.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000759
760\strong{Warning:} The deallocation function can cause arbitrary Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000761code to be invoked (e.g. when a class instance with a
762\method{__del__()} method is deallocated). While exceptions in such
763code are not propagated, the executed code has free access to all
764Python global variables. This means that any object that is reachable
765from a global variable should be in a consistent state before
766\cfunction{Py_DECREF()} is invoked. For example, code to delete an
767object from a list should copy a reference to the deleted object in a
768temporary variable, update the list data structure, and then call
769\cfunction{Py_DECREF()} for the temporary variable.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000770\end{cfuncdesc}
771
772\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000773Decrement the reference count for object \var{o}. The object may be
774\NULL{}, in which case the macro has no effect; otherwise the effect
775is the same as for \cfunction{Py_DECREF()}, and the same warning
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000776applies.
777\end{cfuncdesc}
778
Fred Drake659ebfa2000-04-03 15:42:13 +0000779The following functions or macros are only for use within the
780interpreter core: \cfunction{_Py_Dealloc()},
781\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
782well as the global variable \cdata{_Py_RefTotal}.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000783
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000784
Fred Drakeefd146c1999-02-15 15:30:45 +0000785\chapter{Exception Handling \label{exceptionHandling}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000786
Fred Drake659ebfa2000-04-03 15:42:13 +0000787The functions described in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000788exceptions. It is important to understand some of the basics of
Fred Drake659ebfa2000-04-03 15:42:13 +0000789Python exception handling. It works somewhat like the
790\UNIX{} \cdata{errno} variable: there is a global indicator (per
791thread) of the last error that occurred. Most functions don't clear
792this on success, but will set it to indicate the cause of the error on
793failure. Most functions also return an error indicator, usually
794\NULL{} if they are supposed to return a pointer, or \code{-1} if they
795return an integer (exception: the \cfunction{PyArg_Parse*()} functions
796return \code{1} for success and \code{0} for failure). When a
797function must fail because some function it called failed, it
798generally doesn't set the error indicator; the function it called
799already set it.
Guido van Rossumae110af1997-05-22 20:11:52 +0000800
801The error indicator consists of three Python objects corresponding to
Fred Drake659ebfa2000-04-03 15:42:13 +0000802\withsubitem{(in module sys)}{
803 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000804the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
805\code{sys.exc_traceback}. API functions exist to interact with the
806error indicator in various ways. There is a separate error indicator
807for each thread.
808
809% XXX Order of these should be more thoughtful.
810% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000811
812\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000813Print a standard traceback to \code{sys.stderr} and clear the error
814indicator. Call this function only when the error indicator is set.
815(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000816\end{cfuncdesc}
817
Fred Drakec6fa34e1998-04-02 06:47:24 +0000818\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000819Test whether the error indicator is set. If set, return the exception
Fred Drakee058b4f1998-02-16 06:15:35 +0000820\emph{type} (the first argument to the last call to one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000821\cfunction{PyErr_Set*()} functions or to \cfunction{PyErr_Restore()}). If
Fred Drakee058b4f1998-02-16 06:15:35 +0000822not set, return \NULL{}. You do not own a reference to the return
823value, so you do not need to \cfunction{Py_DECREF()} it.
Fred Drake659ebfa2000-04-03 15:42:13 +0000824\strong{Note:} Do not compare the return value to a specific
Fred Drakee058b4f1998-02-16 06:15:35 +0000825exception; use \cfunction{PyErr_ExceptionMatches()} instead, shown
Fred Drake659ebfa2000-04-03 15:42:13 +0000826below. (The comparison could easily fail since the exception may be
827an instance instead of a class, in the case of a class exception, or
828it may the a subclass of the expected exception.)
Guido van Rossum42cefd01997-10-05 15:27:29 +0000829\end{cfuncdesc}
830
831\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000832Equivalent to
Fred Drakee058b4f1998-02-16 06:15:35 +0000833\samp{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
Fred Drake659ebfa2000-04-03 15:42:13 +0000834This should only be called when an exception is actually set; a memory
835access violation will occur if no exception has been raised.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000836\end{cfuncdesc}
837
838\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000839Return true if the \var{given} exception matches the exception in
840\var{exc}. If \var{exc} is a class object, this also returns true
Fred Drake659ebfa2000-04-03 15:42:13 +0000841when \var{given} is an instance of a subclass. If \var{exc} is a tuple, all
Guido van Rossum42cefd01997-10-05 15:27:29 +0000842exceptions in the tuple (and recursively in subtuples) are searched
Fred Drake659ebfa2000-04-03 15:42:13 +0000843for a match. If \var{given} is \NULL, a memory access violation will
844occur.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000845\end{cfuncdesc}
846
847\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000848Under certain circumstances, the values returned by
Fred Drakee058b4f1998-02-16 06:15:35 +0000849\cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning that
850\code{*\var{exc}} is a class object but \code{*\var{val}} is not an
851instance of the same class. This function can be used to instantiate
852the class in that case. If the values are already normalized, nothing
Fred Drake659ebfa2000-04-03 15:42:13 +0000853happens. The delayed normalization is implemented to improve
854performance.
Guido van Rossumae110af1997-05-22 20:11:52 +0000855\end{cfuncdesc}
856
857\begin{cfuncdesc}{void}{PyErr_Clear}{}
858Clear the error indicator. If the error indicator is not set, there
859is no effect.
860\end{cfuncdesc}
861
Fred Drake659ebfa2000-04-03 15:42:13 +0000862\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
863 PyObject **ptraceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000864Retrieve the error indicator into three variables whose addresses are
865passed. If the error indicator is not set, set all three variables to
866\NULL{}. If it is set, it will be cleared and you own a reference to
Fred Drake659ebfa2000-04-03 15:42:13 +0000867each object retrieved. The value and traceback object may be
868\NULL{} even when the type object is not. \strong{Note:} This
869function is normally only used by code that needs to handle exceptions
870or by code that needs to save and restore the error indicator
871temporarily.
Guido van Rossumae110af1997-05-22 20:11:52 +0000872\end{cfuncdesc}
873
Fred Drake17e63432000-08-31 05:50:40 +0000874\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
875 PyObject *traceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000876Set the error indicator from the three objects. If the error
877indicator is already set, it is cleared first. If the objects are
878\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
879and non-\NULL{} value or traceback. The exception type should be a
880string or class; if it is a class, the value should be an instance of
881that class. Do not pass an invalid exception type or value.
882(Violating these rules will cause subtle problems later.) This call
Fred Drakebab29652001-07-10 16:10:08 +0000883takes away a reference to each object: you must own a reference
Guido van Rossumae110af1997-05-22 20:11:52 +0000884to each object before the call and after the call you no longer own
885these references. (If you don't understand this, don't use this
Fred Drake659ebfa2000-04-03 15:42:13 +0000886function. I warned you.) \strong{Note:} This function is normally
Guido van Rossumae110af1997-05-22 20:11:52 +0000887only used by code that needs to save and restore the error indicator
888temporarily.
889\end{cfuncdesc}
890
891\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
892This is the most common way to set the error indicator. The first
893argument specifies the exception type; it is normally one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000894standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
Guido van Rossumae110af1997-05-22 20:11:52 +0000895increment its reference count. The second argument is an error
896message; it is converted to a string object.
897\end{cfuncdesc}
898
899\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +0000900This function is similar to \cfunction{PyErr_SetString()} but lets you
Guido van Rossumae110af1997-05-22 20:11:52 +0000901specify an arbitrary Python object for the ``value'' of the exception.
902You need not increment its reference count.
903\end{cfuncdesc}
904
Fred Drake73577702000-04-10 18:50:14 +0000905\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
Moshe Zadka57a59322000-09-01 09:47:20 +0000906 const char *format, \moreargs}
Fred Drake89fb0352000-10-14 05:49:30 +0000907This function sets the error indicator. \var{exception} should be a
908Python exception (string or class, not an instance).
Fred Drake5566c1c2001-01-19 22:48:33 +0000909\var{format} should be a string, containing format codes, similar to
Moshe Zadka57a59322000-09-01 09:47:20 +0000910\cfunction{printf}. The \code{width.precision} before a format code
911is parsed, but the width part is ignored.
912
913\begin{tableii}{c|l}{character}{Character}{Meaning}
914 \lineii{c}{Character, as an \ctype{int} parameter}
915 \lineii{d}{Number in decimal, as an \ctype{int} parameter}
916 \lineii{x}{Number in hexadecimal, as an \ctype{int} parameter}
917 \lineii{x}{A string, as a \ctype{char *} parameter}
918\end{tableii}
919
920An unrecognized format character causes all the rest of
921the format string to be copied as-is to the result string,
922and any extra arguments discarded.
923
924A new reference is returned, which is owned by the caller.
Jeremy Hylton98605b52000-04-10 18:40:57 +0000925\end{cfuncdesc}
926
Guido van Rossumae110af1997-05-22 20:11:52 +0000927\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +0000928This is a shorthand for \samp{PyErr_SetObject(\var{type}, Py_None)}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000929\end{cfuncdesc}
930
931\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000932This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000933\var{message})}, where \var{message} indicates that a built-in operation
934was invoked with an illegal argument. It is mostly for internal use.
935\end{cfuncdesc}
936
Fred Drakec6fa34e1998-04-02 06:47:24 +0000937\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000938This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
Guido van Rossumae110af1997-05-22 20:11:52 +0000939returns \NULL{} so an object allocation function can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000940\samp{return PyErr_NoMemory();} when it runs out of memory.
Guido van Rossumae110af1997-05-22 20:11:52 +0000941\end{cfuncdesc}
942
Fred Drakec6fa34e1998-04-02 06:47:24 +0000943\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
Fred Drake659ebfa2000-04-03 15:42:13 +0000944This is a convenience function to raise an exception when a C library
945function has returned an error and set the C variable \cdata{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000946It constructs a tuple object whose first item is the integer
Fred Drakef8830d11998-04-23 14:06:01 +0000947\cdata{errno} value and whose second item is the corresponding error
Fred Drake659ebfa2000-04-03 15:42:13 +0000948message (gotten from \cfunction{strerror()}\ttindex{strerror()}), and
949then calls
Fred Drakee058b4f1998-02-16 06:15:35 +0000950\samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
Fred Drakef8830d11998-04-23 14:06:01 +0000951the \cdata{errno} value is \constant{EINTR}, indicating an interrupted
Fred Drakee058b4f1998-02-16 06:15:35 +0000952system call, this calls \cfunction{PyErr_CheckSignals()}, and if that set
Guido van Rossumae110af1997-05-22 20:11:52 +0000953the error indicator, leaves it set to that. The function always
954returns \NULL{}, so a wrapper function around a system call can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000955\samp{return PyErr_SetFromErrno();} when the system call returns an
956error.
Guido van Rossumae110af1997-05-22 20:11:52 +0000957\end{cfuncdesc}
958
Fred Drake490d34d2001-06-20 21:39:12 +0000959\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrnoWithFilename}{PyObject *type,
960 char *filename}
961Similar to \cfunction{PyErr_SetFromErrno()}, with the additional
962behavior that if \var{filename} is not \NULL, it is passed to the
963constructor of \var{type} as a third parameter. In the case of
964exceptions such as \exception{IOError} and \exception{OSError}, this
965is used to define the \member{filename} attribute of the exception
966instance.
967\end{cfuncdesc}
968
Guido van Rossumae110af1997-05-22 20:11:52 +0000969\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000970This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000971\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000972operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000973argument. It is mostly for internal use.
974\end{cfuncdesc}
975
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000976\begin{cfuncdesc}{int}{PyErr_Warn}{PyObject *category, char *message}
977Issue a warning message. The \var{category} argument is a warning
Fred Drake5566c1c2001-01-19 22:48:33 +0000978category (see below) or \NULL; the \var{message} argument is a message
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000979string.
980
981This function normally prints a warning message to \var{sys.stderr};
982however, it is also possible that the user has specified that warnings
983are to be turned into errors, and in that case this will raise an
984exception. It is also possible that the function raises an exception
985because of a problem with the warning machinery (the implementation
986imports the \module{warnings} module to do the heavy lifting). The
987return value is \code{0} if no exception is raised, or \code{-1} if
988an exception is raised. (It is not possible to determine whether a
989warning message is actually printed, nor what the reason is for the
990exception; this is intentional.) If an exception is raised, the
Fred Drake5566c1c2001-01-19 22:48:33 +0000991caller should do its normal exception handling
992(e.g. \cfunction{Py_DECREF()} owned references and return an error
993value).
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000994
995Warning categories must be subclasses of \cdata{Warning}; the default
996warning category is \cdata{RuntimeWarning}. The standard Python
997warning categories are available as global variables whose names are
998\samp{PyExc_} followed by the Python exception name. These have the
999type \ctype{PyObject*}; they are all class objects. Their names are
1000\cdata{PyExc_Warning}, \cdata{PyExc_UserWarning},
1001\cdata{PyExc_DeprecationWarning}, \cdata{PyExc_SyntaxWarning}, and
1002\cdata{PyExc_RuntimeWarning}. \cdata{PyExc_Warning} is a subclass of
1003\cdata{PyExc_Exception}; the other warning categories are subclasses
1004of \cdata{PyExc_Warning}.
1005
1006For information about warning control, see the documentation for the
Fred Drake316ef7c2001-01-04 05:56:34 +00001007\module{warnings} module and the \programopt{-W} option in the command
1008line documentation. There is no C API for warning control.
Guido van Rossum3dbb4062000-12-19 03:53:01 +00001009\end{cfuncdesc}
1010
Guido van Rossum1874c8f2001-02-28 23:46:44 +00001011\begin{cfuncdesc}{int}{PyErr_WarnExplicit}{PyObject *category, char *message,
1012char *filename, int lineno, char *module, PyObject *registry}
1013Issue a warning message with explicit control over all warning
1014attributes. This is a straightforward wrapper around the Python
1015function \function{warnings.warn_explicit()}, see there for more
1016information. The \var{module} and \var{registry} arguments may be
1017set to \code{NULL} to get the default effect described there.
1018\end{cfuncdesc}
1019
Guido van Rossumae110af1997-05-22 20:11:52 +00001020\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
1021This function interacts with Python's signal handling. It checks
1022whether a signal has been sent to the processes and if so, invokes the
Fred Drake4de05a91998-02-16 14:25:26 +00001023corresponding signal handler. If the
1024\module{signal}\refbimodindex{signal} module is supported, this can
1025invoke a signal handler written in Python. In all cases, the default
Fred Drake659ebfa2000-04-03 15:42:13 +00001026effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
1027\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
1028\exception{KeyboardInterrupt} exception. If an exception is raised the
Fred Drakee058b4f1998-02-16 06:15:35 +00001029error indicator is set and the function returns \code{1}; otherwise
1030the function returns \code{0}. The error indicator may or may not be
1031cleared if it was previously set.
Guido van Rossumae110af1997-05-22 20:11:52 +00001032\end{cfuncdesc}
1033
1034\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001035This function is obsolete. It simulates the effect of a
1036\constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
Fred Drakee058b4f1998-02-16 06:15:35 +00001037\cfunction{PyErr_CheckSignals()} is called,
Fred Drake659ebfa2000-04-03 15:42:13 +00001038\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
1039\exception{KeyboardInterrupt} will be raised.
1040It may be called without holding the interpreter lock.
Guido van Rossumae110af1997-05-22 20:11:52 +00001041\end{cfuncdesc}
1042
Fred Drakec6fa34e1998-04-02 06:47:24 +00001043\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
1044 PyObject *base,
1045 PyObject *dict}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001046This utility function creates and returns a new exception object. The
Fred Drake659ebfa2000-04-03 15:42:13 +00001047\var{name} argument must be the name of the new exception, a C string
1048of the form \code{module.class}. The \var{base} and
Fred Draked04038d2000-06-29 20:15:14 +00001049\var{dict} arguments are normally \NULL{}. This creates a
Fred Drake659ebfa2000-04-03 15:42:13 +00001050class object derived from the root for all exceptions, the built-in
1051name \exception{Exception} (accessible in C as
Fred Draked04038d2000-06-29 20:15:14 +00001052\cdata{PyExc_Exception}). The \member{__module__} attribute of the
1053new class is set to the first part (up to the last dot) of the
1054\var{name} argument, and the class name is set to the last part (after
1055the last dot). The \var{base} argument can be used to specify an
1056alternate base class. The \var{dict} argument can be used to specify
1057a dictionary of class variables and methods.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001058\end{cfuncdesc}
1059
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001060\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
1061This utility function prints a warning message to \var{sys.stderr}
1062when an exception has been set but it is impossible for the
1063interpreter to actually raise the exception. It is used, for example,
1064when an exception occurs in an \member{__del__} method.
1065
1066The function is called with a single argument \var{obj} that
1067identifies where the context in which the unraisable exception
1068occurred. The repr of \var{obj} will be printed in the warning
1069message.
1070\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001071
Fred Drakeefd146c1999-02-15 15:30:45 +00001072\section{Standard Exceptions \label{standardExceptions}}
Guido van Rossumae110af1997-05-22 20:11:52 +00001073
1074All standard Python exceptions are available as global variables whose
Fred Drake659ebfa2000-04-03 15:42:13 +00001075names are \samp{PyExc_} followed by the Python exception name. These
1076have the type \ctype{PyObject*}; they are all class objects. For
1077completeness, here are all the variables:
1078
1079\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
1080 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
1081 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
1082 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
1083 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
1084 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
1085 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
1086 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
1087 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
1088 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
1089 \lineiii{PyExc_IOError}{\exception{IOError}}{}
1090 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
1091 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
1092 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
1093 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
1094 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
1095 \lineiii{PyExc_NameError}{\exception{NameError}}{}
1096 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
1097 \lineiii{PyExc_OSError}{\exception{OSError}}{}
1098 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
1099 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
1100 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
1101 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
1102 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
1103 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
1104 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
Fred Drakea8d73412000-08-11 20:39:29 +00001105 \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(2)}
Fred Drake659ebfa2000-04-03 15:42:13 +00001106 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
1107\end{tableiii}
1108
1109\noindent
Fred Drakea8d73412000-08-11 20:39:29 +00001110Notes:
Fred Drake659ebfa2000-04-03 15:42:13 +00001111\begin{description}
1112\item[(1)]
Fred Draked04038d2000-06-29 20:15:14 +00001113 This is a base class for other standard exceptions.
Fred Drakea8d73412000-08-11 20:39:29 +00001114
1115\item[(2)]
1116 Only defined on Windows; protect code that uses this by testing that
1117 the preprocessor macro \code{MS_WINDOWS} is defined.
Fred Drake659ebfa2000-04-03 15:42:13 +00001118\end{description}
1119
1120
1121\section{Deprecation of String Exceptions}
1122
Fred Draked04038d2000-06-29 20:15:14 +00001123All exceptions built into Python or provided in the standard library
1124are derived from \exception{Exception}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001125\withsubitem{(built-in exception)}{\ttindex{Exception}}
Fred Drake659ebfa2000-04-03 15:42:13 +00001126
Fred Draked04038d2000-06-29 20:15:14 +00001127String exceptions are still supported in the interpreter to allow
Fred Drake659ebfa2000-04-03 15:42:13 +00001128existing code to run unmodified, but this will also change in a future
1129release.
Guido van Rossumae110af1997-05-22 20:11:52 +00001130
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001131
Fred Drakeefd146c1999-02-15 15:30:45 +00001132\chapter{Utilities \label{utilities}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001133
Fred Drake88fdaa72001-07-20 20:56:11 +00001134The functions in this chapter perform various utility tasks, ranging
1135from helping C code be more portable across platforms, using Python
1136modules from C, and parsing function arguments and constructing Python
1137values from C values.
1138
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001139
Fred Drake377fb1e2001-07-14 03:01:48 +00001140\section{Operating System Utilities \label{os}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001141
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001142\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001143Return true (nonzero) if the standard I/O file \var{fp} with name
1144\var{filename} is deemed interactive. This is the case for files for
1145which \samp{isatty(fileno(\var{fp}))} is true. If the global flag
Fred Drakef8830d11998-04-23 14:06:01 +00001146\cdata{Py_InteractiveFlag} is true, this function also returns true if
Fred Drake5566c1c2001-01-19 22:48:33 +00001147the \var{filename} pointer is \NULL{} or if the name is equal to one of
Fred Drakea8455ab2000-06-16 19:58:42 +00001148the strings \code{'<stdin>'} or \code{'???'}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001149\end{cfuncdesc}
1150
1151\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001152Return the time of last modification of the file \var{filename}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001153The result is encoded in the same way as the timestamp returned by
Fred Drake659ebfa2000-04-03 15:42:13 +00001154the standard C library function \cfunction{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001155\end{cfuncdesc}
1156
Fred Drakecabbc3b2000-06-28 15:53:13 +00001157\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
1158Function to update some internal state after a process fork; this
1159should be called in the new process if the Python interpreter will
1160continue to be used. If a new executable is loaded into the new
1161process, this function does not need to be called.
1162\end{cfuncdesc}
1163
Fred Drake17e63432000-08-31 05:50:40 +00001164\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
1165Return true when the interpreter runs out of stack space. This is a
1166reliable check, but is only available when \code{USE_STACKCHECK} is
1167defined (currently on Windows using the Microsoft Visual C++ compiler
1168and on the Macintosh). \code{USE_CHECKSTACK} will be defined
1169automatically; you should never change the definition in your own
1170code.
1171\end{cfuncdesc}
1172
Guido van Rossumc96ec6e2000-09-16 16:30:48 +00001173\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i}
1174Return the current signal handler for signal \var{i}.
1175This is a thin wrapper around either \cfunction{sigaction} or
1176\cfunction{signal}. Do not call those functions directly!
1177\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1178\end{cfuncdesc}
1179
1180\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h}
1181Set the signal handler for signal \var{i} to be \var{h};
1182return the old signal handler.
1183This is a thin wrapper around either \cfunction{sigaction} or
1184\cfunction{signal}. Do not call those functions directly!
1185\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1186\end{cfuncdesc}
1187
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001188
Fred Drakeefd146c1999-02-15 15:30:45 +00001189\section{Process Control \label{processControl}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001190
1191\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
1192Print a fatal error message and kill the process. No cleanup is
1193performed. This function should only be invoked when a condition is
1194detected that would make it dangerous to continue using the Python
1195interpreter; e.g., when the object administration appears to be
Fred Drake659ebfa2000-04-03 15:42:13 +00001196corrupted. On \UNIX{}, the standard C library function
1197\cfunction{abort()}\ttindex{abort()} is called which will attempt to
1198produce a \file{core} file.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001199\end{cfuncdesc}
1200
1201\begin{cfuncdesc}{void}{Py_Exit}{int status}
Fred Drake659ebfa2000-04-03 15:42:13 +00001202Exit the current process. This calls
1203\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
1204then calls the standard C library function
1205\code{exit(\var{status})}\ttindex{exit()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001206\end{cfuncdesc}
1207
1208\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drake659ebfa2000-04-03 15:42:13 +00001209Register a cleanup function to be called by
1210\cfunction{Py_Finalize()}\ttindex{Py_Finalize()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001211The cleanup function will be called with no arguments and should
Fred Drake659ebfa2000-04-03 15:42:13 +00001212return no value. At most 32 \index{cleanup functions}cleanup
1213functions can be registered.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001214When the registration is successful, \cfunction{Py_AtExit()} returns
1215\code{0}; on failure, it returns \code{-1}. The cleanup function
1216registered last is called first. Each cleanup function will be called
1217at most once. Since Python's internal finallization will have
1218completed before the cleanup function, no Python APIs should be called
1219by \var{func}.
1220\end{cfuncdesc}
1221
1222
Fred Drakeefd146c1999-02-15 15:30:45 +00001223\section{Importing Modules \label{importing}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001224
Fred Drakec6fa34e1998-04-02 06:47:24 +00001225\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00001226This is a simplified interface to
1227\cfunction{PyImport_ImportModuleEx()} below, leaving the
1228\var{globals} and \var{locals} arguments set to \NULL{}. When the
Fred Drakebab29652001-07-10 16:10:08 +00001229\var{name} argument contains a dot (when it specifies a
Fred Drake659ebfa2000-04-03 15:42:13 +00001230submodule of a package), the \var{fromlist} argument is set to the
1231list \code{['*']} so that the return value is the named module rather
1232than the top-level package containing it as would otherwise be the
1233case. (Unfortunately, this has an additional side effect when
1234\var{name} in fact specifies a subpackage instead of a submodule: the
1235submodules specified in the package's \code{__all__} variable are
1236\index{package variable!\code{__all__}}
1237\withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a
1238new reference to the imported module, or
1239\NULL{} with an exception set on failure (the module may still be
1240created in this case --- examine \code{sys.modules} to find out).
1241\withsubitem{(in module sys)}{\ttindex{modules}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001242\end{cfuncdesc}
1243
Fred Drake01978582001-08-08 19:14:53 +00001244\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name,
1245 PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001246Import a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001247Python function \function{__import__()}\bifuncindex{__import__}, as
1248the standard \function{__import__()} function calls this function
1249directly.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001250
Guido van Rossum42cefd01997-10-05 15:27:29 +00001251The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001252top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001253(the module may still be created in this case). Like for
Fred Drakee058b4f1998-02-16 06:15:35 +00001254\function{__import__()}, the return value when a submodule of a
1255package was requested is normally the top-level package, unless a
1256non-empty \var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001257\end{cfuncdesc}
1258
Fred Drakec6fa34e1998-04-02 06:47:24 +00001259\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001260This is a higher-level interface that calls the current ``import hook
Fred Drakee058b4f1998-02-16 06:15:35 +00001261function''. It invokes the \function{__import__()} function from the
Guido van Rossum42cefd01997-10-05 15:27:29 +00001262\code{__builtins__} of the current globals. This means that the
1263import is done using whatever import hooks are installed in the
Fred Drake4de05a91998-02-16 14:25:26 +00001264current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
1265\module{ihooks}\refstmodindex{ihooks}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001266\end{cfuncdesc}
1267
Fred Drakec6fa34e1998-04-02 06:47:24 +00001268\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001269Reload a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001270Python function \function{reload()}\bifuncindex{reload}, as the standard
Fred Drakee058b4f1998-02-16 06:15:35 +00001271\function{reload()} function calls this function directly. Return a
1272new reference to the reloaded module, or \NULL{} with an exception set
1273on failure (the module still exists in this case).
Guido van Rossum42cefd01997-10-05 15:27:29 +00001274\end{cfuncdesc}
1275
Fred Drakec6fa34e1998-04-02 06:47:24 +00001276\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001277Return the module object corresponding to a module name. The
1278\var{name} argument may be of the form \code{package.module}). First
1279check the modules dictionary if there's one there, and if not, create
Fred Drake659ebfa2000-04-03 15:42:13 +00001280a new one and insert in in the modules dictionary.
Guido van Rossuma096a2e1998-11-02 17:02:42 +00001281Warning: this function does not load or import the module; if the
1282module wasn't already loaded, you will get an empty module object.
1283Use \cfunction{PyImport_ImportModule()} or one of its variants to
1284import a module.
Fred Drake659ebfa2000-04-03 15:42:13 +00001285Return \NULL{} with an exception set on failure.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001286\end{cfuncdesc}
1287
Fred Drakec6fa34e1998-04-02 06:47:24 +00001288\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001289Given a module name (possibly of the form \code{package.module}) and a
1290code object read from a Python bytecode file or obtained from the
Fred Drake53fb7721998-02-16 06:23:20 +00001291built-in function \function{compile()}\bifuncindex{compile}, load the
1292module. Return a new reference to the module object, or \NULL{} with
1293an exception set if an error occurred (the module may still be created
1294in this case). (This function would reload the module if it was
1295already imported.)
Guido van Rossum42cefd01997-10-05 15:27:29 +00001296\end{cfuncdesc}
1297
1298\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001299Return the magic number for Python bytecode files (a.k.a.
1300\file{.pyc} and \file{.pyo} files). The magic number should be
1301present in the first four bytes of the bytecode file, in little-endian
1302byte order.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001303\end{cfuncdesc}
1304
Fred Drakec6fa34e1998-04-02 06:47:24 +00001305\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001306Return the dictionary used for the module administration
1307(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1308variable.
1309\end{cfuncdesc}
1310
1311\begin{cfuncdesc}{void}{_PyImport_Init}{}
1312Initialize the import mechanism. For internal use only.
1313\end{cfuncdesc}
1314
1315\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1316Empty the module table. For internal use only.
1317\end{cfuncdesc}
1318
1319\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1320Finalize the import mechanism. For internal use only.
1321\end{cfuncdesc}
1322
Fred Drakec6fa34e1998-04-02 06:47:24 +00001323\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001324For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001325\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001326
Fred Drakec6fa34e1998-04-02 06:47:24 +00001327\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001328For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001329\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001330
Fred Drake1d158692000-06-18 05:21:21 +00001331\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
1332Load a frozen module named \var{name}. Return \code{1} for success,
1333\code{0} if the module is not found, and \code{-1} with an exception
1334set if the initialization failed. To access the imported module on a
1335successful load, use \cfunction{PyImport_ImportModule()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00001336(Note the misnomer --- this function would reload the module if it was
Guido van Rossum42cefd01997-10-05 15:27:29 +00001337already imported.)
1338\end{cfuncdesc}
1339
Fred Drake659ebfa2000-04-03 15:42:13 +00001340\begin{ctypedesc}[_frozen]{struct _frozen}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001341This is the structure type definition for frozen module descriptors,
Fred Drakec6fa34e1998-04-02 06:47:24 +00001342as generated by the \program{freeze}\index{freeze utility} utility
1343(see \file{Tools/freeze/} in the Python source distribution). Its
Fred Drakee0d9a832000-09-01 05:30:00 +00001344definition, found in \file{Include/import.h}, is:
Fred Drakec6fa34e1998-04-02 06:47:24 +00001345
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001346\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001347struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001348 char *name;
1349 unsigned char *code;
1350 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001351};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001352\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001353\end{ctypedesc}
1354
Fred Drakec6fa34e1998-04-02 06:47:24 +00001355\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
Fred Drakef8830d11998-04-23 14:06:01 +00001356This pointer is initialized to point to an array of \ctype{struct
Fred Drake659ebfa2000-04-03 15:42:13 +00001357_frozen} records, terminated by one whose members are all
1358\NULL{} or zero. When a frozen module is imported, it is searched in
1359this table. Third-party code could play tricks with this to provide a
Guido van Rossum42cefd01997-10-05 15:27:29 +00001360dynamically created collection of frozen modules.
1361\end{cvardesc}
1362
Fred Drakee0d9a832000-09-01 05:30:00 +00001363\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
1364 void (*initfunc)(void)}
1365Add a single module to the existing table of built-in modules. This
1366is a convenience wrapper around \cfunction{PyImport_ExtendInittab()},
1367returning \code{-1} if the table could not be extended. The new
1368module can be imported by the name \var{name}, and uses the function
1369\var{initfunc} as the initialization function called on the first
1370attempted import. This should be called before
1371\cfunction{Py_Initialize()}.
1372\end{cfuncdesc}
1373
1374\begin{ctypedesc}[_inittab]{struct _inittab}
1375Structure describing a single entry in the list of built-in modules.
1376Each of these structures gives the name and initialization function
1377for a module built into the interpreter. Programs which embed Python
1378may use an array of these structures in conjunction with
1379\cfunction{PyImport_ExtendInittab()} to provide additional built-in
1380modules. The structure is defined in \file{Include/import.h} as:
1381
1382\begin{verbatim}
1383struct _inittab {
1384 char *name;
1385 void (*initfunc)(void);
1386};
1387\end{verbatim}
1388\end{ctypedesc}
1389
1390\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
1391Add a collection of modules to the table of built-in modules. The
1392\var{newtab} array must end with a sentinel entry which contains
1393\NULL{} for the \member{name} field; failure to provide the sentinel
1394value can result in a memory fault. Returns \code{0} on success or
1395\code{-1} if insufficient memory could be allocated to extend the
1396internal table. In the event of failure, no modules are added to the
1397internal table. This should be called before
1398\cfunction{Py_Initialize()}.
1399\end{cfuncdesc}
1400
Guido van Rossum42cefd01997-10-05 15:27:29 +00001401
Fred Drake88fdaa72001-07-20 20:56:11 +00001402\section{Parsing arguements and building values
1403 \label{arg-parsing}}
1404
1405These functions are useful when creating your own extensions functions
1406and methods. Additional information and examples are available in
1407\citetitle[../ext/ext.html]{Extending and Embedding the Python
1408Interpreter}.
1409
1410\begin{cfuncdesc}{int}{PyArg_ParseTuple}{PyObject *args, char *format,
1411 \moreargs}
1412 Parse the parameters of a function that takes only positional
1413 parameters into local variables. Returns true on success; on
1414 failure, it returns false and raises the appropriate exception. See
1415 \citetitle[../ext/parseTuple.html]{Extending and Embedding the
1416 Python Interpreter} for more information.
1417\end{cfuncdesc}
1418
1419\begin{cfuncdesc}{int}{PyArg_ParseTupleAndKeywords}{PyObject *args,
1420 PyObject *kw, char *format, char *keywords[],
1421 \moreargs}
1422 Parse the parameters of a function that takes both positional and
1423 keyword parameters into local variables. Returns true on success;
1424 on failure, it returns false and raises the appropriate exception.
1425 See \citetitle[../ext/parseTupleAndKeywords.html]{Extending and
1426 Embedding the Python Interpreter} for more information.
1427\end{cfuncdesc}
1428
1429\begin{cfuncdesc}{int}{PyArg_Parse}{PyObject *args, char *format,
1430 \moreargs}
1431 Function used to deconstruct the argument lists of ``old-style''
1432 functions --- these are functions which use the
1433 \constant{METH_OLDARGS} parameter parsing method. This is not
1434 recommended for use in parameter parsing in new code, and most code
1435 in the standard interpreter has been modified to no longer use this
1436 for that purpose. It does remain a convenient way to decompose
1437 other tuples, however, and may continue to be used for that
1438 purpose.
1439\end{cfuncdesc}
1440
1441\begin{cfuncdesc}{PyObject*}{Py_BuildValue}{char *format,
1442 \moreargs}
1443 Create a new value based on a format string similar to those
1444 accepted by the \cfunction{PyArg_Parse*()} family of functions and a
1445 sequence of values. Returns the value or \NULL{} in the case of an
1446 error; an exception will be raised if \NULL{} is returned. For more
1447 information on the format string and additional parameters, see
1448 \citetitle[../ext/buildValue.html]{Extending and Embedding the
1449 Python Interpreter}.
1450\end{cfuncdesc}
1451
1452
1453
Fred Drakeefd146c1999-02-15 15:30:45 +00001454\chapter{Abstract Objects Layer \label{abstract}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001455
1456The functions in this chapter interact with Python objects regardless
1457of their type, or with wide classes of object types (e.g. all
1458numerical types, or all sequence types). When used on object types
Fred Drake659ebfa2000-04-03 15:42:13 +00001459for which they do not apply, they will raise a Python exception.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001460
Fred Drakeefd146c1999-02-15 15:30:45 +00001461\section{Object Protocol \label{object}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001462
1463\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00001464Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error.
1465The flags argument is used to enable certain printing options. The
1466only option currently supported is \constant{Py_PRINT_RAW}; if given,
1467the \function{str()} of the object is written instead of the
1468\function{repr()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001469\end{cfuncdesc}
1470
1471\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001472Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1473\code{0} otherwise. This is equivalent to the Python expression
1474\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001475This function always succeeds.
1476\end{cfuncdesc}
1477
Fred Drake659ebfa2000-04-03 15:42:13 +00001478\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
1479 char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001480Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001481Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001482This is the equivalent of the Python expression
1483\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001484\end{cfuncdesc}
1485
1486
1487\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001488Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1489\code{0} otherwise. This is equivalent to the Python expression
1490\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001491This function always succeeds.
1492\end{cfuncdesc}
1493
1494
Fred Drake659ebfa2000-04-03 15:42:13 +00001495\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
1496 PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001497Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001498Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001499This is the equivalent of the Python expression
1500\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001501\end{cfuncdesc}
1502
1503
Fred Drake01978582001-08-08 19:14:53 +00001504\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o,
1505 char *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001506Set the value of the attribute named \var{attr_name}, for object
1507\var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1508the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1509\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001510\end{cfuncdesc}
1511
1512
Fred Drake01978582001-08-08 19:14:53 +00001513\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o,
1514 PyObject *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001515Set the value of the attribute named \var{attr_name}, for
1516object \var{o},
1517to the value \var{v}. Returns \code{-1} on failure. This is
1518the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1519\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001520\end{cfuncdesc}
1521
1522
1523\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001524Delete attribute named \var{attr_name}, for object \var{o}. Returns
1525\code{-1} on failure. This is the equivalent of the Python
1526statement: \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001527\end{cfuncdesc}
1528
1529
1530\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001531Delete attribute named \var{attr_name}, for object \var{o}. Returns
1532\code{-1} on failure. This is the equivalent of the Python
1533statement \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001534\end{cfuncdesc}
1535
1536
1537\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
Fred Drakee058b4f1998-02-16 06:15:35 +00001538Compare the values of \var{o1} and \var{o2} using a routine provided
1539by \var{o1}, if one exists, otherwise with a routine provided by
1540\var{o2}. The result of the comparison is returned in \var{result}.
1541Returns \code{-1} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001542statement\bifuncindex{cmp} \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001543\end{cfuncdesc}
1544
1545
1546\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001547Compare the values of \var{o1} and \var{o2} using a routine provided
1548by \var{o1}, if one exists, otherwise with a routine provided by
1549\var{o2}. Returns the result of the comparison on success. On error,
1550the value returned is undefined; use \cfunction{PyErr_Occurred()} to
Fred Drake659ebfa2000-04-03 15:42:13 +00001551detect an error. This is equivalent to the Python
1552expression\bifuncindex{cmp} \samp{cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001553\end{cfuncdesc}
1554
1555
1556\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001557Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001558string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001559the equivalent of the Python expression \samp{repr(\var{o})}.
1560Called by the \function{repr()}\bifuncindex{repr} built-in function
1561and by reverse quotes.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001562\end{cfuncdesc}
1563
1564
1565\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001566Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001567string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001568the equivalent of the Python expression \samp{str(\var{o})}.
1569Called by the \function{str()}\bifuncindex{str} built-in function and
1570by the \keyword{print} statement.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001571\end{cfuncdesc}
1572
1573
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001574\begin{cfuncdesc}{PyObject*}{PyObject_Unicode}{PyObject *o}
1575Compute a Unicode string representation of object \var{o}. Returns the
1576Unicode string representation on success, \NULL{} on failure. This is
1577the equivalent of the Python expression \samp{unistr(\var{o})}.
1578Called by the \function{unistr()}\bifuncindex{unistr} built-in function.
1579\end{cfuncdesc}
1580
Fred Drake58c8f9f2001-03-28 21:14:32 +00001581\begin{cfuncdesc}{int}{PyObject_IsInstance}{PyObject *inst, PyObject *cls}
1582Return \code{1} if \var{inst} is an instance of the class \var{cls} or
1583a subclass of \var{cls}. If \var{cls} is a type object rather than a
1584class object, \cfunction{PyObject_IsInstance()} returns \code{1} if
1585\var{inst} is of type \var{cls}. If \var{inst} is not a class
1586instance and \var{cls} is neither a type object or class object,
1587\var{inst} must have a \member{__class__} attribute --- the class
1588relationship of the value of that attribute with \var{cls} will be
1589used to determine the result of this function.
1590\versionadded{2.1}
1591\end{cfuncdesc}
1592
1593Subclass determination is done in a fairly straightforward way, but
1594includes a wrinkle that implementors of extensions to the class system
1595may want to be aware of. If \class{A} and \class{B} are class
1596objects, \class{B} is a subclass of \class{A} if it inherits from
1597\class{A} either directly or indirectly. If either is not a class
1598object, a more general mechanism is used to determine the class
1599relationship of the two objects. When testing if \var{B} is a
1600subclass of \var{A}, if \var{A} is \var{B},
1601\cfunction{PyObject_IsSubclass()} returns true. If \var{A} and
1602\var{B} are different objects, \var{B}'s \member{__bases__} attribute
1603is searched in a depth-first fashion for \var{A} --- the presence of
1604the \member{__bases__} attribute is considered sufficient for this
1605determination.
1606
1607\begin{cfuncdesc}{int}{PyObject_IsSubclass}{PyObject *derived,
1608 PyObject *cls}
1609Returns \code{1} if the class \var{derived} is identical to or derived
1610from the class \var{cls}, otherwise returns \code{0}. In case of an
1611error, returns \code{-1}. If either \var{derived} or \var{cls} is not
1612an actual class object, this function uses the generic algorithm
1613described above.
1614\versionadded{2.1}
1615\end{cfuncdesc}
1616
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001617
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001618\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001619Determine if the object \var{o} is callable. Return \code{1} if the
Fred Drakee058b4f1998-02-16 06:15:35 +00001620object is callable and \code{0} otherwise.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001621This function always succeeds.
1622\end{cfuncdesc}
1623
1624
Fred Drake659ebfa2000-04-03 15:42:13 +00001625\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
1626 PyObject *args}
Fred Drakee058b4f1998-02-16 06:15:35 +00001627Call a callable Python object \var{callable_object}, with
1628arguments given by the tuple \var{args}. If no arguments are
Fred Drake659ebfa2000-04-03 15:42:13 +00001629needed, then \var{args} may be \NULL{}. Returns the result of the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001630call on success, or \NULL{} on failure. This is the equivalent
Fred Drakef90490e2001-08-02 18:00:28 +00001631of the Python expression \samp{apply(\var{callable_object},
1632\var{args})} or \samp{\var{callable_object}(*\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001633\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001634\end{cfuncdesc}
1635
Fred Drake5566c1c2001-01-19 22:48:33 +00001636\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object,
1637 char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001638Call a callable Python object \var{callable_object}, with a
Fred Drake659ebfa2000-04-03 15:42:13 +00001639variable number of C arguments. The C arguments are described
Fred Drakee058b4f1998-02-16 06:15:35 +00001640using a \cfunction{Py_BuildValue()} style format string. The format may
1641be \NULL{}, indicating that no arguments are provided. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001642result of the call on success, or \NULL{} on failure. This is
Fred Drakef90490e2001-08-02 18:00:28 +00001643the equivalent of the Python expression
1644\samp{apply(\var{callable_object}\var{args})} or
1645\samp{\var{callable_object}(*\var{args})}.
1646\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001647\end{cfuncdesc}
1648
1649
Fred Drake5566c1c2001-01-19 22:48:33 +00001650\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o,
1651 char *method, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001652Call the method named \var{m} of object \var{o} with a variable number
Fred Drake659ebfa2000-04-03 15:42:13 +00001653of C arguments. The C arguments are described by a
Fred Drakee058b4f1998-02-16 06:15:35 +00001654\cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1655indicating that no arguments are provided. Returns the result of the
1656call on success, or \NULL{} on failure. This is the equivalent of the
1657Python expression \samp{\var{o}.\var{method}(\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001658Note that special method names, such as \method{__add__()},
1659\method{__getitem__()}, and so on are not supported. The specific
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001660abstract-object routines for these must be used.
1661\end{cfuncdesc}
1662
1663
1664\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001665Compute and return the hash value of an object \var{o}. On
1666failure, return \code{-1}. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001667expression \samp{hash(\var{o})}.\bifuncindex{hash}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001668\end{cfuncdesc}
1669
1670
1671\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001672Returns \code{1} if the object \var{o} is considered to be true, and
1673\code{0} otherwise. This is equivalent to the Python expression
1674\samp{not not \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001675This function always succeeds.
1676\end{cfuncdesc}
1677
1678
1679\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1680On success, returns a type object corresponding to the object
Fred Drakee058b4f1998-02-16 06:15:35 +00001681type of object \var{o}. On failure, returns \NULL{}. This is
1682equivalent to the Python expression \samp{type(\var{o})}.
Fred Drake53fb7721998-02-16 06:23:20 +00001683\bifuncindex{type}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001684\end{cfuncdesc}
1685
1686\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001687Return the length of object \var{o}. If the object \var{o} provides
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001688both sequence and mapping protocols, the sequence length is
Fred Drake659ebfa2000-04-03 15:42:13 +00001689returned. On error, \code{-1} is returned. This is the equivalent
1690to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001691\end{cfuncdesc}
1692
1693
1694\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001695Return element of \var{o} corresponding to the object \var{key} or
1696\NULL{} on failure. This is the equivalent of the Python expression
1697\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001698\end{cfuncdesc}
1699
1700
Fred Drake01978582001-08-08 19:14:53 +00001701\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o,
1702 PyObject *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001703Map the object \var{key} to the value \var{v}.
1704Returns \code{-1} on failure. This is the equivalent
1705of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001706\end{cfuncdesc}
1707
1708
Guido van Rossumd1dbf631999-01-22 20:10:49 +00001709\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001710Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1711failure. This is the equivalent of the Python statement \samp{del
1712\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001713\end{cfuncdesc}
1714
Andrew M. Kuchling8c46b302000-07-13 23:58:16 +00001715\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
1716Derives a file-descriptor from a Python object. If the object
1717is an integer or long integer, its value is returned. If not, the
1718object's \method{fileno()} method is called if it exists; the method
1719must return an integer or long integer, which is returned as the file
1720descriptor value. Returns \code{-1} on failure.
1721\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001722
Tim Peters7eea37e2001-09-04 22:08:56 +00001723\begin{cfuncdesc}{PyObject*}{PyObject_Dir}{PyObject *o}
1724This is equivalent to the Python expression \samp{dir(\var{o})},
1725returning a (possibly empty) list of strings appropriate for the
1726object argument, or \NULL{} in case of error.
1727If the argument is \NULL{}, this is like the Python \samp{dir()},
1728returning the names of the current locals; in this case, if no
1729execution frame is active then \NULL{} is returned but
1730\cfunction{PyErr_Occurred()} will return false.
1731\end{cfuncdesc}
1732
Fred Drake01978582001-08-08 19:14:53 +00001733
Fred Drakeefd146c1999-02-15 15:30:45 +00001734\section{Number Protocol \label{number}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001735
1736\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001737Returns \code{1} if the object \var{o} provides numeric protocols, and
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001738false otherwise.
1739This function always succeeds.
1740\end{cfuncdesc}
1741
1742
1743\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001744Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1745failure. This is the equivalent of the Python expression
1746\samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001747\end{cfuncdesc}
1748
1749
1750\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
Fred Drake659ebfa2000-04-03 15:42:13 +00001751Returns the result of subtracting \var{o2} from \var{o1}, or
1752\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001753\samp{\var{o1} - \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001754\end{cfuncdesc}
1755
1756
1757\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001758Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1759failure. This is the equivalent of the Python expression
1760\samp{\var{o1} * \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001761\end{cfuncdesc}
1762
1763
1764\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001765Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1766failure.
1767This is the equivalent of the Python expression \samp{\var{o1} /
1768\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001769\end{cfuncdesc}
1770
1771
Fred Drake01978582001-08-08 19:14:53 +00001772\begin{cfuncdesc}{PyObject*}{PyNumber_FloorDivide}{PyObject *o1, PyObject *o2}
1773Return the floor of \var{o1} divided by \var{o2}, or \NULL{} on
1774failure. This is equivalent to the ``classic'' division of integers.
1775\versionadded{2.2}
1776\end{cfuncdesc}
1777
1778
1779\begin{cfuncdesc}{PyObject*}{PyNumber_TrueDivide}{PyObject *o1, PyObject *o2}
1780Return a reasonable approximation for the mathematical value of
1781\var{o1} divided by \var{o2}, or \NULL{} on failure. The return value
1782is ``approximate'' because binary floating point numbers are
1783approximate; it is not possible to represent all real numbers in base
1784two. This function can return a floating point value when passed two
1785integers.
1786\versionadded{2.2}
1787\end{cfuncdesc}
1788
1789
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001790\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001791Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1792failure. This is the equivalent of the Python expression
Fred Drake659ebfa2000-04-03 15:42:13 +00001793\samp{\var{o1} \%\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001794\end{cfuncdesc}
1795
1796
1797\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
Fred Drake53fb7721998-02-16 06:23:20 +00001798See the built-in function \function{divmod()}\bifuncindex{divmod}.
1799Returns \NULL{} on failure. This is the equivalent of the Python
1800expression \samp{divmod(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001801\end{cfuncdesc}
1802
1803
Fred Drake01978582001-08-08 19:14:53 +00001804\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1,
1805 PyObject *o2, PyObject *o3}
Fred Drake53fb7721998-02-16 06:23:20 +00001806See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1807\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001808\samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
Fred Drake659ebfa2000-04-03 15:42:13 +00001809If \var{o3} is to be ignored, pass \cdata{Py_None} in its place
1810(passing \NULL{} for \var{o3} would cause an illegal memory access).
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001811\end{cfuncdesc}
1812
1813
1814\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001815Returns the negation of \var{o} on success, or \NULL{} on failure.
1816This is the equivalent of the Python expression \samp{-\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001817\end{cfuncdesc}
1818
1819
1820\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001821Returns \var{o} on success, or \NULL{} on failure.
1822This is the equivalent of the Python expression \samp{+\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001823\end{cfuncdesc}
1824
1825
1826\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001827Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1828the equivalent of the Python expression \samp{abs(\var{o})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001829\bifuncindex{abs}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001830\end{cfuncdesc}
1831
1832
1833\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001834Returns the bitwise negation of \var{o} on success, or \NULL{} on
1835failure. This is the equivalent of the Python expression
1836\samp{\~\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001837\end{cfuncdesc}
1838
1839
1840\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001841Returns the result of left shifting \var{o1} by \var{o2} on success,
1842or \NULL{} on failure. This is the equivalent of the Python
Fred Draked20d8b32001-04-13 14:52:39 +00001843expression \samp{\var{o1} <\code{<} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001844\end{cfuncdesc}
1845
1846
1847\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001848Returns the result of right shifting \var{o1} by \var{o2} on success,
1849or \NULL{} on failure. This is the equivalent of the Python
Fred Draked20d8b32001-04-13 14:52:39 +00001850expression \samp{\var{o1} >\code{>} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001851\end{cfuncdesc}
1852
1853
1854\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001855Returns the ``bitwise and'' of \var{o2} and \var{o2} on success and
1856\NULL{} on failure. This is the equivalent of the Python expression
Fred Drake5566c1c2001-01-19 22:48:33 +00001857\samp{\var{o1} \&\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001858\end{cfuncdesc}
1859
1860
1861\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001862Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success,
Fred Drakee058b4f1998-02-16 06:15:35 +00001863or \NULL{} on failure. This is the equivalent of the Python
Fred Drake755c23d2001-07-14 03:05:53 +00001864expression \samp{\var{o1} \textasciicircum{} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001865\end{cfuncdesc}
1866
1867\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001868Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
1869\NULL{} on failure. This is the equivalent of the Python expression
1870\samp{\var{o1} | \var{o2}}.
1871\end{cfuncdesc}
1872
1873
1874\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAdd}{PyObject *o1, PyObject *o2}
Fred Drake01978582001-08-08 19:14:53 +00001875Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1876failure. The operation is done \emph{in-place} when \var{o1} supports
1877it. This is the equivalent of the Python statement \samp{\var{o1} +=
1878\var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001879\end{cfuncdesc}
1880
1881
Fred Drake01978582001-08-08 19:14:53 +00001882\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceSubtract}{PyObject *o1,
1883 PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001884Returns the result of subtracting \var{o2} from \var{o1}, or
Fred Drake01978582001-08-08 19:14:53 +00001885\NULL{} on failure. The operation is done \emph{in-place} when
1886\var{o1} supports it. This is the equivalent of the Python statement
1887\samp{\var{o1} -= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001888\end{cfuncdesc}
1889
1890
Fred Drake01978582001-08-08 19:14:53 +00001891\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceMultiply}{PyObject *o1,
1892 PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001893Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1894failure. The operation is done \emph{in-place} when \var{o1} supports it.
Fred Drake01978582001-08-08 19:14:53 +00001895This is the equivalent of the Python statement \samp{\var{o1} *= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001896\end{cfuncdesc}
1897
1898
Fred Drake01978582001-08-08 19:14:53 +00001899\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceDivide}{PyObject *o1,
1900 PyObject *o2}
1901Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1902failure. The operation is done \emph{in-place} when \var{o1} supports
1903it. This is the equivalent of the Python statement \samp{\var{o1} /=
1904\var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001905\end{cfuncdesc}
1906
1907
Fred Drake01978582001-08-08 19:14:53 +00001908\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceFloorDivide}{PyObject *o1,
1909 PyObject *o2}
1910Returns the mathematical of dividing \var{o1} by \var{o2}, or \NULL{}
1911on failure. The operation is done \emph{in-place} when \var{o1}
1912supports it. This is the equivalent of the Python statement
1913\samp{\var{o1} //= \var{o2}}.
1914\versionadded{2.2}
1915\end{cfuncdesc}
1916
1917
1918\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceTrueDivide}{PyObject *o1,
1919 PyObject *o2}
1920Return a reasonable approximation for the mathematical value of
1921\var{o1} divided by \var{o2}, or \NULL{} on failure. The return value
1922is ``approximate'' because binary floating point numbers are
1923approximate; it is not possible to represent all real numbers in base
1924two. This function can return a floating point value when passed two
1925integers. The operation is done \emph{in-place} when \var{o1}
1926supports it.
1927\versionadded{2.2}
1928\end{cfuncdesc}
1929
1930
1931\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRemainder}{PyObject *o1,
1932 PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001933Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1934failure. The operation is done \emph{in-place} when \var{o1} supports it.
Fred Drake01978582001-08-08 19:14:53 +00001935This is the equivalent of the Python statement \samp{\var{o1} \%= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001936\end{cfuncdesc}
1937
1938
Fred Drake01978582001-08-08 19:14:53 +00001939\begin{cfuncdesc}{PyObject*}{PyNumber_InPlacePower}{PyObject *o1,
1940 PyObject *o2, PyObject *o3}
1941See the built-in function \function{pow()}.\bifuncindex{pow} Returns
1942\NULL{} on failure. The operation is done \emph{in-place} when
1943\var{o1} supports it. This is the equivalent of the Python statement
1944\samp{\var{o1} **= \var{o2}} when o3 is \cdata{Py_None}, or an
1945in-place variant of \samp{pow(\var{o1}, \var{o2}, \var{o3})}
1946otherwise. If \var{o3} is to be ignored, pass \cdata{Py_None} in its
1947place (passing \NULL{} for \var{o3} would cause an illegal memory
1948access).
Fred Drake7740a012000-09-12 20:27:05 +00001949\end{cfuncdesc}
1950
Fred Drake01978582001-08-08 19:14:53 +00001951\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceLshift}{PyObject *o1,
1952 PyObject *o2}
1953Returns the result of left shifting \var{o1} by \var{o2} on success,
1954or \NULL{} on failure. The operation is done \emph{in-place} when
1955\var{o1} supports it. This is the equivalent of the Python statement
1956\samp{\var{o1} <\code{<=} \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001957\end{cfuncdesc}
1958
1959
Fred Drake01978582001-08-08 19:14:53 +00001960\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRshift}{PyObject *o1,
1961 PyObject *o2}
1962Returns the result of right shifting \var{o1} by \var{o2} on success,
1963or \NULL{} on failure. The operation is done \emph{in-place} when
1964\var{o1} supports it. This is the equivalent of the Python statement
1965\samp{\var{o1} >\code{>=} \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001966\end{cfuncdesc}
1967
1968
1969\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAnd}{PyObject *o1, PyObject *o2}
Fred Drake5566c1c2001-01-19 22:48:33 +00001970Returns the ``bitwise and'' of \var{o1} and \var{o2} on success
1971and \NULL{} on failure. The operation is done \emph{in-place} when
Fred Drake01978582001-08-08 19:14:53 +00001972\var{o1} supports it. This is the equivalent of the Python statement
Fred Drake5566c1c2001-01-19 22:48:33 +00001973\samp{\var{o1} \&= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001974\end{cfuncdesc}
1975
1976
1977\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceXor}{PyObject *o1, PyObject *o2}
Fred Drake01978582001-08-08 19:14:53 +00001978Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on
1979success, or \NULL{} on failure. The operation is done \emph{in-place}
1980when \var{o1} supports it. This is the equivalent of the Python
1981statement \samp{\var{o1} \textasciicircum= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001982\end{cfuncdesc}
1983
1984\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2}
Fred Drake01978582001-08-08 19:14:53 +00001985Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
1986\NULL{} on failure. The operation is done \emph{in-place} when
1987\var{o1} supports it. This is the equivalent of the Python statement
1988\samp{\var{o1} |= \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001989\end{cfuncdesc}
1990
Fred Drakec0e6c5b2000-09-22 18:17:49 +00001991\begin{cfuncdesc}{int}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001992This function takes the addresses of two variables of type
Fred Drake659ebfa2000-04-03 15:42:13 +00001993\ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} and
1994\code{*\var{p2}} have the same type, increment their reference count
1995and return \code{0} (success). If the objects can be converted to a
1996common numeric type, replace \code{*p1} and \code{*p2} by their
1997converted value (with 'new' reference counts), and return \code{0}.
1998If no conversion is possible, or if some other error occurs, return
1999\code{-1} (failure) and don't increment the reference counts. The
2000call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
2001statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
2002\bifuncindex{coerce}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002003\end{cfuncdesc}
2004
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002005\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002006Returns the \var{o} converted to an integer object on success, or
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002007\NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00002008expression \samp{int(\var{o})}.\bifuncindex{int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002009\end{cfuncdesc}
2010
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002011\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002012Returns the \var{o} converted to a long integer object on success,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002013or \NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00002014expression \samp{long(\var{o})}.\bifuncindex{long}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002015\end{cfuncdesc}
2016
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002017\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002018Returns the \var{o} converted to a float object on success, or
2019\NULL{} on failure. This is the equivalent of the Python expression
2020\samp{float(\var{o})}.\bifuncindex{float}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002021\end{cfuncdesc}
2022
2023
Fred Drakeefd146c1999-02-15 15:30:45 +00002024\section{Sequence Protocol \label{sequence}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002025
2026\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002027Return \code{1} if the object provides sequence protocol, and
2028\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002029\end{cfuncdesc}
2030
Fred Drakec6a3cb42001-04-04 01:25:17 +00002031\begin{cfuncdesc}{int}{PySequence_Size}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002032Returns the number of objects in sequence \var{o} on success, and
2033\code{-1} on failure. For objects that do not provide sequence
2034protocol, this is equivalent to the Python expression
2035\samp{len(\var{o})}.\bifuncindex{len}
2036\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002037
Fred Drakec6a3cb42001-04-04 01:25:17 +00002038\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
2039Alternate name for \cfunction{PySequence_Size()}.
2040\end{cfuncdesc}
2041
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002042\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00002043Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002044failure. This is the equivalent of the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002045expression \samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002046\end{cfuncdesc}
2047
2048
2049\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Fred Drake659ebfa2000-04-03 15:42:13 +00002050Return the result of repeating sequence object
2051\var{o} \var{count} times, or \NULL{} on failure. This is the
2052equivalent of the Python expression \samp{\var{o} * \var{count}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002053\end{cfuncdesc}
2054
Fred Drake01978582001-08-08 19:14:53 +00002055\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceConcat}{PyObject *o1,
2056 PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00002057Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
2058failure. The operation is done \emph{in-place} when \var{o1} supports it.
2059This is the equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
2060\end{cfuncdesc}
2061
2062
2063\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceRepeat}{PyObject *o, int count}
2064Return the result of repeating sequence object \var{o} \var{count} times, or
2065\NULL{} on failure. The operation is done \emph{in-place} when \var{o}
2066supports it. This is the equivalent of the Python expression \samp{\var{o}
2067*= \var{count}}.
2068\end{cfuncdesc}
2069
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002070
2071\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00002072Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
2073is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002074\end{cfuncdesc}
2075
2076
2077\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00002078Return the slice of sequence object \var{o} between \var{i1} and
2079\var{i2}, or \NULL{} on failure. This is the equivalent of the Python
2080expression \samp{\var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002081\end{cfuncdesc}
2082
2083
2084\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00002085Assign object \var{v} to the \var{i}th element of \var{o}.
2086Returns \code{-1} on failure. This is the equivalent of the Python
2087statement \samp{\var{o}[\var{i}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002088\end{cfuncdesc}
2089
2090\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
Fred Drake5566c1c2001-01-19 22:48:33 +00002091Delete the \var{i}th element of object \var{o}. Returns
Fred Drakee058b4f1998-02-16 06:15:35 +00002092\code{-1} on failure. This is the equivalent of the Python
2093statement \samp{del \var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002094\end{cfuncdesc}
2095
Fred Drake659ebfa2000-04-03 15:42:13 +00002096\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
2097 int i2, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00002098Assign the sequence object \var{v} to the slice in sequence
2099object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
2100the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002101\end{cfuncdesc}
2102
2103\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00002104Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
2105Returns \code{-1} on failure. This is the equivalent of the Python
2106statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002107\end{cfuncdesc}
2108
2109\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002110Returns the \var{o} as a tuple on success, and \NULL{} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00002111This is equivalent to the Python expression \samp{tuple(\var{o})}.
2112\bifuncindex{tuple}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002113\end{cfuncdesc}
2114
2115\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00002116Return the number of occurrences of \var{value} in \var{o}, that is,
2117return the number of keys for which \code{\var{o}[\var{key}] ==
2118\var{value}}. On failure, return \code{-1}. This is equivalent to
2119the Python expression \samp{\var{o}.count(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002120\end{cfuncdesc}
2121
Fred Drake659ebfa2000-04-03 15:42:13 +00002122\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00002123Determine if \var{o} contains \var{value}. If an item in \var{o} is
2124equal to \var{value}, return \code{1}, otherwise return \code{0}. On
2125error, return \code{-1}. This is equivalent to the Python expression
2126\samp{\var{value} in \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002127\end{cfuncdesc}
2128
2129\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00002130Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
2131\var{value}}. On error, return \code{-1}. This is equivalent to
2132the Python expression \samp{\var{o}.index(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002133\end{cfuncdesc}
2134
Fred Drakea8455ab2000-06-16 19:58:42 +00002135\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
2136Return a list object with the same contents as the arbitrary sequence
2137\var{o}. The returned list is guaranteed to be new.
2138\end{cfuncdesc}
2139
2140\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
2141Return a tuple object with the same contents as the arbitrary sequence
2142\var{o}. If \var{o} is a tuple, a new reference will be returned,
2143otherwise a tuple will be constructed with the appropriate contents.
2144\end{cfuncdesc}
2145
Fred Drakef39ed671998-02-26 22:01:23 +00002146
Fred Drake81cccb72000-09-12 15:22:05 +00002147\begin{cfuncdesc}{PyObject*}{PySequence_Fast}{PyObject *o, const char *m}
2148Returns the sequence \var{o} as a tuple, unless it is already a
2149tuple or list, in which case \var{o} is returned. Use
2150\cfunction{PySequence_Fast_GET_ITEM()} to access the members of the
2151result. Returns \NULL{} on failure. If the object is not a sequence,
2152raises \exception{TypeError} with \var{m} as the message text.
2153\end{cfuncdesc}
2154
2155\begin{cfuncdesc}{PyObject*}{PySequence_Fast_GET_ITEM}{PyObject *o, int i}
2156Return the \var{i}th element of \var{o}, assuming that \var{o} was
2157returned by \cfunction{PySequence_Fast()}, and that \var{i} is within
2158bounds. The caller is expected to get the length of the sequence by
Fred Drake96a2a802001-05-29 18:51:41 +00002159calling \cfunction{PySequence_Size()} on \var{o}, since lists and tuples
Fred Drake81cccb72000-09-12 15:22:05 +00002160are guaranteed to always return their true length.
2161\end{cfuncdesc}
2162
2163
Fred Drakeefd146c1999-02-15 15:30:45 +00002164\section{Mapping Protocol \label{mapping}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002165
2166\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002167Return \code{1} if the object provides mapping protocol, and
2168\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002169\end{cfuncdesc}
2170
2171
2172\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002173Returns the number of keys in object \var{o} on success, and
2174\code{-1} on failure. For objects that do not provide mapping
2175protocol, this is equivalent to the Python expression
2176\samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002177\end{cfuncdesc}
2178
2179
2180\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002181Remove the mapping for object \var{key} from the object \var{o}.
2182Return \code{-1} on failure. This is equivalent to
2183the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002184\end{cfuncdesc}
2185
2186
2187\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002188Remove the mapping for object \var{key} from the object \var{o}.
2189Return \code{-1} on failure. This is equivalent to
2190the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002191\end{cfuncdesc}
2192
2193
2194\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
Fred Drake659ebfa2000-04-03 15:42:13 +00002195On success, return \code{1} if the mapping object has the key
2196\var{key} and \code{0} otherwise. This is equivalent to the Python
2197expression \samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002198This function always succeeds.
2199\end{cfuncdesc}
2200
2201
2202\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002203Return \code{1} if the mapping object has the key \var{key} and
2204\code{0} otherwise. This is equivalent to the Python expression
2205\samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002206This function always succeeds.
2207\end{cfuncdesc}
2208
2209
2210\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002211On success, return a list of the keys in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002212failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002213expression \samp{\var{o}.keys()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002214\end{cfuncdesc}
2215
2216
2217\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002218On success, return a list of the values in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002219failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002220expression \samp{\var{o}.values()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002221\end{cfuncdesc}
2222
2223
2224\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002225On success, return a list of the items in object \var{o}, where
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002226each item is a tuple containing a key-value pair. On
2227failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002228expression \samp{\var{o}.items()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002229\end{cfuncdesc}
2230
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002231
2232\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002233Return element of \var{o} corresponding to the object \var{key} or
2234\NULL{} on failure. This is the equivalent of the Python expression
2235\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002236\end{cfuncdesc}
2237
Fred Drakedbcaeda2001-05-07 17:42:18 +00002238\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key,
2239 PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00002240Map the object \var{key} to the value \var{v} in object \var{o}.
2241Returns \code{-1} on failure. This is the equivalent of the Python
2242statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002243\end{cfuncdesc}
2244
2245
Fred Drakedbcaeda2001-05-07 17:42:18 +00002246\section{Iterator Protocol \label{iterator}}
2247
Fred Drakea8e08272001-05-07 17:47:07 +00002248\versionadded{2.2}
2249
Fred Drakedbcaeda2001-05-07 17:42:18 +00002250There are only a couple of functions specifically for working with
2251iterators.
2252
2253\begin{cfuncdesc}{int}{PyIter_Check}{PyObject *o}
2254 Return true if the object \var{o} supports the iterator protocol.
2255\end{cfuncdesc}
2256
2257\begin{cfuncdesc}{PyObject*}{PyIter_Next}{PyObject *o}
2258 Return the next value from the iteration \var{o}. If the object is
2259 an iterator, this retrieves the next value from the iteration, and
2260 returns \NULL{} with no exception set if there are no remaining
2261 items. If the object is not an iterator, \exception{TypeError} is
2262 raised, or if there is an error in retrieving the item, returns
2263 \NULL{} and passes along the exception.
2264\end{cfuncdesc}
2265
2266To write a loop which iterates over an iterator, the C code should
2267look something like this:
2268
2269\begin{verbatim}
2270PyObject *iterator = ...;
2271PyObject *item;
2272
2273while (item = PyIter_Next(iter)) {
2274 /* do something with item */
2275}
2276if (PyErr_Occurred()) {
2277 /* propogate error */
2278}
2279else {
2280 /* continue doing useful work */
2281}
2282\end{verbatim}
2283
2284
Fred Drakeefd146c1999-02-15 15:30:45 +00002285\chapter{Concrete Objects Layer \label{concrete}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002286
2287The functions in this chapter are specific to certain Python object
2288types. Passing them an object of the wrong type is not a good idea;
2289if you receive an object from a Python program and you are not sure
2290that it has the right type, you must perform a type check first;
Fred Drake5566c1c2001-01-19 22:48:33 +00002291for example, to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00002292\cfunction{PyDict_Check()}. The chapter is structured like the
2293``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002294
Fred Drake89024422000-10-23 16:00:54 +00002295\strong{Warning:}
2296While the functions described in this chapter carefully check the type
2297of the objects which are passed in, many of them do not check for
2298\NULL{} being passed instead of a valid object. Allowing \NULL{} to
2299be passed in can cause memory access violations and immediate
2300termination of the interpreter.
2301
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002302
Fred Drakeefd146c1999-02-15 15:30:45 +00002303\section{Fundamental Objects \label{fundamental}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002304
Fred Drakee5bf8b21998-02-12 21:22:28 +00002305This section describes Python type objects and the singleton object
2306\code{None}.
2307
2308
Fred Drakeefd146c1999-02-15 15:30:45 +00002309\subsection{Type Objects \label{typeObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002310
Fred Drake659ebfa2000-04-03 15:42:13 +00002311\obindex{type}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002312\begin{ctypedesc}{PyTypeObject}
Fred Drake659ebfa2000-04-03 15:42:13 +00002313The C structure of the objects used to describe built-in types.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002314\end{ctypedesc}
2315
Fred Drake659ebfa2000-04-03 15:42:13 +00002316\begin{cvardesc}{PyObject*}{PyType_Type}
Fred Drakeefd146c1999-02-15 15:30:45 +00002317This is the type object for type objects; it is the same object as
2318\code{types.TypeType} in the Python layer.
Fred Drake659ebfa2000-04-03 15:42:13 +00002319\withsubitem{(in module types)}{\ttindex{TypeType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002320\end{cvardesc}
2321
Fred Drake659ebfa2000-04-03 15:42:13 +00002322\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
2323Returns true is the object \var{o} is a type object.
2324\end{cfuncdesc}
2325
2326\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
2327Returns true if the type object \var{o} sets the feature
Fred Drakef0e08ef2001-02-03 01:11:26 +00002328\var{feature}. Type features are denoted by single bit flags.
Fred Drake659ebfa2000-04-03 15:42:13 +00002329\end{cfuncdesc}
2330
Fred Drakee5bf8b21998-02-12 21:22:28 +00002331
Fred Drakeefd146c1999-02-15 15:30:45 +00002332\subsection{The None Object \label{noneObject}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002333
Fred Drake659ebfa2000-04-03 15:42:13 +00002334\obindex{None@\texttt{None}}
2335Note that the \ctype{PyTypeObject} for \code{None} is not directly
2336exposed in the Python/C API. Since \code{None} is a singleton,
2337testing for object identity (using \samp{==} in C) is sufficient.
2338There is no \cfunction{PyNone_Check()} function for the same reason.
2339
2340\begin{cvardesc}{PyObject*}{Py_None}
Guido van Rossum44475131998-04-21 15:30:01 +00002341The Python \code{None} object, denoting lack of value. This object has
2342no methods.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002343\end{cvardesc}
2344
2345
Fred Drakefa774872001-07-11 20:35:37 +00002346\section{Numeric Objects \label{numericObjects}}
2347
2348\obindex{numeric}
2349
2350
2351\subsection{Plain Integer Objects \label{intObjects}}
2352
2353\obindex{integer}
2354\begin{ctypedesc}{PyIntObject}
2355This subtype of \ctype{PyObject} represents a Python integer object.
2356\end{ctypedesc}
2357
2358\begin{cvardesc}{PyTypeObject}{PyInt_Type}
2359This instance of \ctype{PyTypeObject} represents the Python plain
2360integer type. This is the same object as \code{types.IntType}.
2361\withsubitem{(in modules types)}{\ttindex{IntType}}
2362\end{cvardesc}
2363
2364\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
2365Returns true if \var{o} is of type \cdata{PyInt_Type}.
2366\end{cfuncdesc}
2367
2368\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
2369Creates a new integer object with a value of \var{ival}.
2370
2371The current implementation keeps an array of integer objects for all
2372integers between \code{-1} and \code{100}, when you create an int in
2373that range you actually just get back a reference to the existing
2374object. So it should be possible to change the value of \code{1}. I
2375suspect the behaviour of Python in this case is undefined. :-)
2376\end{cfuncdesc}
2377
2378\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
2379Will first attempt to cast the object to a \ctype{PyIntObject}, if
2380it is not already one, and then return its value.
2381\end{cfuncdesc}
2382
2383\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
2384Returns the value of the object \var{io}. No error checking is
2385performed.
2386\end{cfuncdesc}
2387
2388\begin{cfuncdesc}{long}{PyInt_GetMax}{}
2389Returns the system's idea of the largest integer it can handle
2390(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
2391header files).
2392\end{cfuncdesc}
2393
2394
2395\subsection{Long Integer Objects \label{longObjects}}
2396
2397\obindex{long integer}
2398\begin{ctypedesc}{PyLongObject}
2399This subtype of \ctype{PyObject} represents a Python long integer
2400object.
2401\end{ctypedesc}
2402
2403\begin{cvardesc}{PyTypeObject}{PyLong_Type}
2404This instance of \ctype{PyTypeObject} represents the Python long
2405integer type. This is the same object as \code{types.LongType}.
2406\withsubitem{(in modules types)}{\ttindex{LongType}}
2407\end{cvardesc}
2408
2409\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
2410Returns true if its argument is a \ctype{PyLongObject}.
2411\end{cfuncdesc}
2412
2413\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
2414Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on
2415failure.
2416\end{cfuncdesc}
2417
2418\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
2419Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
2420long}, or \NULL{} on failure.
2421\end{cfuncdesc}
2422
2423\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
2424Returns a new \ctype{PyLongObject} object from the integer part of
2425\var{v}, or \NULL{} on failure.
2426\end{cfuncdesc}
2427
2428\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
2429Returns a C \ctype{long} representation of the contents of
2430\var{pylong}. If \var{pylong} is greater than
2431\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is
2432raised.\withsubitem{(built-in exception)}{\ttindex{OverflowError}}
2433\end{cfuncdesc}
2434
2435\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
2436Returns a C \ctype{unsigned long} representation of the contents of
2437\var{pylong}. If \var{pylong} is greater than
2438\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError}
2439is raised.\withsubitem{(built-in exception)}{\ttindex{OverflowError}}
2440\end{cfuncdesc}
2441
2442\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
2443Returns a C \ctype{double} representation of the contents of \var{pylong}.
2444\end{cfuncdesc}
2445
2446\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
2447 int base}
2448Return a new \ctype{PyLongObject} based on the string value in
2449\var{str}, which is interpreted according to the radix in \var{base}.
2450If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first
2451character in \var{str} which follows the representation of the
2452number. If \var{base} is \code{0}, the radix will be determined base
2453on the leading characters of \var{str}: if \var{str} starts with
2454\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts
2455with \code{'0'}, radix 8 will be used; otherwise radix 10 will be
2456used. If \var{base} is not \code{0}, it must be between \code{2} and
2457\code{36}, inclusive. Leading spaces are ignored. If there are no
2458digits, \exception{ValueError} will be raised.
2459\end{cfuncdesc}
2460
2461
2462\subsection{Floating Point Objects \label{floatObjects}}
2463
2464\obindex{floating point}
2465\begin{ctypedesc}{PyFloatObject}
2466This subtype of \ctype{PyObject} represents a Python floating point
2467object.
2468\end{ctypedesc}
2469
2470\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2471This instance of \ctype{PyTypeObject} represents the Python floating
2472point type. This is the same object as \code{types.FloatType}.
2473\withsubitem{(in modules types)}{\ttindex{FloatType}}
2474\end{cvardesc}
2475
2476\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2477Returns true if its argument is a \ctype{PyFloatObject}.
2478\end{cfuncdesc}
2479
2480\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
2481Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
2482failure.
2483\end{cfuncdesc}
2484
2485\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
2486Returns a C \ctype{double} representation of the contents of \var{pyfloat}.
2487\end{cfuncdesc}
2488
2489\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
2490Returns a C \ctype{double} representation of the contents of
2491\var{pyfloat}, but without error checking.
2492\end{cfuncdesc}
2493
2494
2495\subsection{Complex Number Objects \label{complexObjects}}
2496
2497\obindex{complex number}
2498Python's complex number objects are implemented as two distinct types
2499when viewed from the C API: one is the Python object exposed to
2500Python programs, and the other is a C structure which represents the
2501actual complex number value. The API provides functions for working
2502with both.
2503
2504\subsubsection{Complex Numbers as C Structures}
2505
2506Note that the functions which accept these structures as parameters
2507and return them as results do so \emph{by value} rather than
2508dereferencing them through pointers. This is consistent throughout
2509the API.
2510
2511\begin{ctypedesc}{Py_complex}
2512The C structure which corresponds to the value portion of a Python
2513complex number object. Most of the functions for dealing with complex
2514number objects use structures of this type as input or output values,
2515as appropriate. It is defined as:
2516
2517\begin{verbatim}
2518typedef struct {
2519 double real;
2520 double imag;
2521} Py_complex;
2522\end{verbatim}
2523\end{ctypedesc}
2524
2525\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
2526Return the sum of two complex numbers, using the C
2527\ctype{Py_complex} representation.
2528\end{cfuncdesc}
2529
2530\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
2531Return the difference between two complex numbers, using the C
2532\ctype{Py_complex} representation.
2533\end{cfuncdesc}
2534
2535\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
2536Return the negation of the complex number \var{complex}, using the C
2537\ctype{Py_complex} representation.
2538\end{cfuncdesc}
2539
2540\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
2541Return the product of two complex numbers, using the C
2542\ctype{Py_complex} representation.
2543\end{cfuncdesc}
2544
2545\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
2546 Py_complex divisor}
2547Return the quotient of two complex numbers, using the C
2548\ctype{Py_complex} representation.
2549\end{cfuncdesc}
2550
2551\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
2552Return the exponentiation of \var{num} by \var{exp}, using the C
2553\ctype{Py_complex} representation.
2554\end{cfuncdesc}
2555
2556
2557\subsubsection{Complex Numbers as Python Objects}
2558
2559\begin{ctypedesc}{PyComplexObject}
2560This subtype of \ctype{PyObject} represents a Python complex number object.
2561\end{ctypedesc}
2562
2563\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2564This instance of \ctype{PyTypeObject} represents the Python complex
2565number type.
2566\end{cvardesc}
2567
2568\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2569Returns true if its argument is a \ctype{PyComplexObject}.
2570\end{cfuncdesc}
2571
2572\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
2573Create a new Python complex number object from a C
2574\ctype{Py_complex} value.
2575\end{cfuncdesc}
2576
2577\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
2578Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
2579\end{cfuncdesc}
2580
2581\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2582Returns the real part of \var{op} as a C \ctype{double}.
2583\end{cfuncdesc}
2584
2585\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2586Returns the imaginary part of \var{op} as a C \ctype{double}.
2587\end{cfuncdesc}
2588
2589\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2590Returns the \ctype{Py_complex} value of the complex number \var{op}.
2591\end{cfuncdesc}
2592
2593
2594
Fred Drakeefd146c1999-02-15 15:30:45 +00002595\section{Sequence Objects \label{sequenceObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002596
Fred Drake659ebfa2000-04-03 15:42:13 +00002597\obindex{sequence}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002598Generic operations on sequence objects were discussed in the previous
2599chapter; this section deals with the specific kinds of sequence
2600objects that are intrinsic to the Python language.
2601
2602
Fred Drakeefd146c1999-02-15 15:30:45 +00002603\subsection{String Objects \label{stringObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002604
Fred Drake89024422000-10-23 16:00:54 +00002605These functions raise \exception{TypeError} when expecting a string
2606parameter and are called with a non-string parameter.
2607
Fred Drake659ebfa2000-04-03 15:42:13 +00002608\obindex{string}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002609\begin{ctypedesc}{PyStringObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002610This subtype of \ctype{PyObject} represents a Python string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002611\end{ctypedesc}
2612
2613\begin{cvardesc}{PyTypeObject}{PyString_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002614This instance of \ctype{PyTypeObject} represents the Python string
2615type; it is the same object as \code{types.TypeType} in the Python
2616layer.\withsubitem{(in module types)}{\ttindex{StringType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002617\end{cvardesc}
2618
2619\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002620Returns true if the object \var{o} is a string object.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002621\end{cfuncdesc}
2622
Fred Drakec6fa34e1998-04-02 06:47:24 +00002623\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002624Returns a new string object with the value \var{v} on success, and
2625\NULL{} on failure.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002626\end{cfuncdesc}
2627
Fred Drake659ebfa2000-04-03 15:42:13 +00002628\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
2629 int len}
2630Returns a new string object with the value \var{v} and length
2631\var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
2632the contents of the string are uninitialized.
2633\end{cfuncdesc}
2634
Barry Warsawc86aa572001-08-28 02:31:28 +00002635\begin{cfuncdesc}{PyObject*}{PyString_FromFormat}{const char *format, ...}
2636Takes a C \code{printf}-style \var{format} string and a variable
2637number of arguments, calculates the size of the resulting Python
2638string and returns a string with the values formatted into it. The
2639variable arguments must be C types and must correspond exactly to the
2640format characters in the \var{format} string. The following format
2641characters are allowed:
2642\begin{tableiii}{l|l|l}{member}{Format Characters}{Type}{Comment}
2643 \lineiii{\%\%}{\emph{n/a}}{The literal \% character.}
2644 \lineiii{\%c}{int}{A single character, represented as an C int.}
2645 \lineiii{\%d}{int}{Exactly equivalent to \code{printf("\%d")}.}
2646 \lineiii{\%ld}{long}{Exactly equivalent to \code{printf("\%ld")}.}
2647 \lineiii{\%i}{int}{Exactly equivalent to \code{printf("\%i")}.}
2648 \lineiii{\%x}{int}{Exactly equivalent to \code{printf("\%x")}.}
2649 \lineiii{\%s}{char*}{A null-terminated C character array.}
2650 \lineiii{\%p}{void*}{The hex representation of a C pointer.
2651 Mostly equivalent to \code{printf("\%p")} except that it is
2652 guaranteed to start with the literal \code{0x} regardless of
2653 what the platform's \code{printf} yields.}
2654\end{tableiii}
2655\end{cfuncdesc}
2656
2657\begin{cfuncdesc}{PyObject*}{PyString_FromFormatV}{const char *format,
2658 va_list vargs}
2659Identical to \function{PyString_FromFormat()} except that it takes
2660exactly two arguments.
2661\end{cfuncdesc}
2662
Fred Drakec6fa34e1998-04-02 06:47:24 +00002663\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002664Returns the length of the string in string object \var{string}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002665\end{cfuncdesc}
2666
Fred Drake659ebfa2000-04-03 15:42:13 +00002667\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
Fred Drake5d644212000-10-07 12:31:50 +00002668Macro form of \cfunction{PyString_Size()} but without error
Fred Drake659ebfa2000-04-03 15:42:13 +00002669checking.
2670\end{cfuncdesc}
2671
Fred Drakec6fa34e1998-04-02 06:47:24 +00002672\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
Fred Drake659ebfa2000-04-03 15:42:13 +00002673Returns a null-terminated representation of the contents of
2674\var{string}. The pointer refers to the internal buffer of
Fred Drake89024422000-10-23 16:00:54 +00002675\var{string}, not a copy. The data must not be modified in any way,
2676unless the string was just created using
2677\code{PyString_FromStringAndSize(NULL, \var{size})}.
2678It must not be deallocated.
Fred Drake659ebfa2000-04-03 15:42:13 +00002679\end{cfuncdesc}
2680
2681\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
2682Macro form of \cfunction{PyString_AsString()} but without error
2683checking.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002684\end{cfuncdesc}
2685
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002686\begin{cfuncdesc}{int}{PyString_AsStringAndSize}{PyObject *obj,
2687 char **buffer,
2688 int *length}
2689Returns a null-terminated representation of the contents of the object
2690\var{obj} through the output variables \var{buffer} and \var{length}.
2691
2692The function accepts both string and Unicode objects as input. For
2693Unicode objects it returns the default encoded version of the object.
2694If \var{length} is set to \NULL{}, the resulting buffer may not contain
2695null characters; if it does, the function returns -1 and a
2696TypeError is raised.
2697
2698The buffer refers to an internal string buffer of \var{obj}, not a
Fred Drake89024422000-10-23 16:00:54 +00002699copy. The data must not be modified in any way, unless the string was
2700just created using \code{PyString_FromStringAndSize(NULL,
2701\var{size})}. It must not be deallocated.
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002702\end{cfuncdesc}
2703
Fred Drakec6fa34e1998-04-02 06:47:24 +00002704\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
2705 PyObject *newpart}
Fred Drake66b989c1999-02-15 20:15:39 +00002706Creates a new string object in \var{*string} containing the
Fred Drakeddc6c272000-03-31 18:22:38 +00002707contents of \var{newpart} appended to \var{string}; the caller will
2708own the new reference. The reference to the old value of \var{string}
2709will be stolen. If the new string
Fred Drake66b989c1999-02-15 20:15:39 +00002710cannot be created, the old reference to \var{string} will still be
2711discarded and the value of \var{*string} will be set to
2712\NULL{}; the appropriate exception will be set.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002713\end{cfuncdesc}
2714
2715\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
2716 PyObject *newpart}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002717Creates a new string object in \var{*string} containing the contents
Guido van Rossum44475131998-04-21 15:30:01 +00002718of \var{newpart} appended to \var{string}. This version decrements
2719the reference count of \var{newpart}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002720\end{cfuncdesc}
2721
2722\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
Guido van Rossum44475131998-04-21 15:30:01 +00002723A way to resize a string object even though it is ``immutable''.
2724Only use this to build up a brand new string object; don't use this if
2725the string may already be known in other parts of the code.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002726\end{cfuncdesc}
2727
2728\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
2729 PyObject *args}
Guido van Rossum44475131998-04-21 15:30:01 +00002730Returns a new string object from \var{format} and \var{args}. Analogous
Fred Drake659ebfa2000-04-03 15:42:13 +00002731to \code{\var{format} \%\ \var{args}}. The \var{args} argument must be
Guido van Rossum44475131998-04-21 15:30:01 +00002732a tuple.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002733\end{cfuncdesc}
2734
2735\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
Guido van Rossum44475131998-04-21 15:30:01 +00002736Intern the argument \var{*string} in place. The argument must be the
2737address of a pointer variable pointing to a Python string object.
2738If there is an existing interned string that is the same as
2739\var{*string}, it sets \var{*string} to it (decrementing the reference
2740count of the old string object and incrementing the reference count of
2741the interned string object), otherwise it leaves \var{*string} alone
2742and interns it (incrementing its reference count). (Clarification:
2743even though there is a lot of talk about reference counts, think of
Fred Drakef8830d11998-04-23 14:06:01 +00002744this function as reference-count-neutral; you own the object after
2745the call if and only if you owned it before the call.)
Fred Drakec6fa34e1998-04-02 06:47:24 +00002746\end{cfuncdesc}
2747
2748\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
Fred Drakef8830d11998-04-23 14:06:01 +00002749A combination of \cfunction{PyString_FromString()} and
2750\cfunction{PyString_InternInPlace()}, returning either a new string object
Guido van Rossum44475131998-04-21 15:30:01 +00002751that has been interned, or a new (``owned'') reference to an earlier
2752interned string object with the same value.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002753\end{cfuncdesc}
2754
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002755\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
2756 int size,
2757 const char *encoding,
2758 const char *errors}
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002759Creates an object by decoding \var{size} bytes of the encoded
2760buffer \var{s} using the codec registered
2761for \var{encoding}. \var{encoding} and \var{errors} have the same meaning
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002762as the parameters of the same name in the unicode() builtin
2763function. The codec to be used is looked up using the Python codec
2764registry. Returns \NULL{} in case an exception was raised by the
2765codec.
2766\end{cfuncdesc}
2767
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002768\begin{cfuncdesc}{PyObject*}{PyString_AsDecodedObject}{PyObject *str,
2769 const char *encoding,
2770 const char *errors}
2771Decodes a string object by passing it to the codec registered
2772for \var{encoding} and returns the result as Python
2773object. \var{encoding} and \var{errors} have the same meaning as the
2774parameters of the same name in the string .encode() method. The codec
2775to be used is looked up using the Python codec registry. Returns
2776\NULL{} in case an exception was raised by the codec.
2777\end{cfuncdesc}
2778
2779\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const char *s,
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002780 int size,
2781 const char *encoding,
2782 const char *errors}
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002783Encodes the \ctype{char} buffer of the given size by passing it to
2784the codec registered for \var{encoding} and returns a Python object.
2785\var{encoding} and \var{errors} have the same
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002786meaning as the parameters of the same name in the string .encode()
2787method. The codec to be used is looked up using the Python codec
2788registry. Returns \NULL{} in case an exception was raised by the
2789codec.
2790\end{cfuncdesc}
2791
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002792\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedObject}{PyObject *str,
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002793 const char *encoding,
2794 const char *errors}
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002795Encodes a string object using the codec registered
2796for \var{encoding} and returns the result as Python
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002797object. \var{encoding} and \var{errors} have the same meaning as the
2798parameters of the same name in the string .encode() method. The codec
2799to be used is looked up using the Python codec registry. Returns
2800\NULL{} in case an exception was raised by the codec.
2801\end{cfuncdesc}
2802
Fred Drakee5bf8b21998-02-12 21:22:28 +00002803
Fred Drakea4cd2612000-04-06 14:10:29 +00002804\subsection{Unicode Objects \label{unicodeObjects}}
2805\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
2806
2807%--- Unicode Type -------------------------------------------------------
2808
2809These are the basic Unicode object types used for the Unicode
2810implementation in Python:
2811
2812\begin{ctypedesc}{Py_UNICODE}
2813This type represents a 16-bit unsigned storage type which is used by
2814Python internally as basis for holding Unicode ordinals. On platforms
2815where \ctype{wchar_t} is available and also has 16-bits,
2816\ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
2817native platform compatibility. On all other platforms,
2818\ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
2819\end{ctypedesc}
2820
2821\begin{ctypedesc}{PyUnicodeObject}
2822This subtype of \ctype{PyObject} represents a Python Unicode object.
2823\end{ctypedesc}
2824
2825\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
2826This instance of \ctype{PyTypeObject} represents the Python Unicode type.
2827\end{cvardesc}
2828
2829%--- These are really C macros... is there a macrodesc TeX macro ?
2830
2831The following APIs are really C macros and can be used to do fast
2832checks and to access internal read-only data of Unicode objects:
2833
2834\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
2835Returns true if the object \var{o} is a Unicode object.
2836\end{cfuncdesc}
2837
2838\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
2839Returns the size of the object. o has to be a
2840PyUnicodeObject (not checked).
2841\end{cfuncdesc}
2842
2843\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
2844Returns the size of the object's internal buffer in bytes. o has to be
2845a PyUnicodeObject (not checked).
2846\end{cfuncdesc}
2847
Fred Drake992fe5a2000-06-16 21:04:15 +00002848\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002849Returns a pointer to the internal Py_UNICODE buffer of the object. o
2850has to be a PyUnicodeObject (not checked).
2851\end{cfuncdesc}
2852
Fred Drake992fe5a2000-06-16 21:04:15 +00002853\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002854Returns a (const char *) pointer to the internal buffer of the object.
2855o has to be a PyUnicodeObject (not checked).
2856\end{cfuncdesc}
2857
2858% --- Unicode character properties ---------------------------------------
2859
2860Unicode provides many different character properties. The most often
2861needed ones are available through these macros which are mapped to C
2862functions depending on the Python configuration.
2863
2864\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
2865Returns 1/0 depending on whether \var{ch} is a whitespace character.
2866\end{cfuncdesc}
2867
2868\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
2869Returns 1/0 depending on whether \var{ch} is a lowercase character.
2870\end{cfuncdesc}
2871
2872\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
Fred Drakeae96aab2000-07-03 13:38:10 +00002873Returns 1/0 depending on whether \var{ch} is an uppercase character.
Fred Drakea4cd2612000-04-06 14:10:29 +00002874\end{cfuncdesc}
2875
2876\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
2877Returns 1/0 depending on whether \var{ch} is a titlecase character.
2878\end{cfuncdesc}
2879
2880\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
2881Returns 1/0 depending on whether \var{ch} is a linebreak character.
2882\end{cfuncdesc}
2883
2884\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
2885Returns 1/0 depending on whether \var{ch} is a decimal character.
2886\end{cfuncdesc}
2887
2888\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
2889Returns 1/0 depending on whether \var{ch} is a digit character.
2890\end{cfuncdesc}
2891
2892\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
2893Returns 1/0 depending on whether \var{ch} is a numeric character.
2894\end{cfuncdesc}
2895
Fred Drakeae96aab2000-07-03 13:38:10 +00002896\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
2897Returns 1/0 depending on whether \var{ch} is an alphabetic character.
2898\end{cfuncdesc}
2899
2900\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
2901Returns 1/0 depending on whether \var{ch} is an alphanumeric character.
2902\end{cfuncdesc}
2903
Fred Drakea4cd2612000-04-06 14:10:29 +00002904These APIs can be used for fast direct character conversions:
2905
2906\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
2907Returns the character \var{ch} converted to lower case.
2908\end{cfuncdesc}
2909
2910\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
2911Returns the character \var{ch} converted to upper case.
2912\end{cfuncdesc}
2913
2914\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
2915Returns the character \var{ch} converted to title case.
2916\end{cfuncdesc}
2917
2918\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
2919Returns the character \var{ch} converted to a decimal positive integer.
2920Returns -1 in case this is not possible. Does not raise exceptions.
2921\end{cfuncdesc}
2922
2923\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
2924Returns the character \var{ch} converted to a single digit integer.
2925Returns -1 in case this is not possible. Does not raise exceptions.
2926\end{cfuncdesc}
2927
2928\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
2929Returns the character \var{ch} converted to a (positive) double.
2930Returns -1.0 in case this is not possible. Does not raise exceptions.
2931\end{cfuncdesc}
2932
2933% --- Plain Py_UNICODE ---------------------------------------------------
2934
2935To create Unicode objects and access their basic sequence properties,
2936use these APIs:
2937
2938\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
2939 int size}
2940
2941Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
2942given size. \var{u} may be \NULL{} which causes the contents to be
2943undefined. It is the user's responsibility to fill in the needed data.
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002944The buffer is copied into the new object. If the buffer is not \NULL{},
2945the return value might be a shared object. Therefore, modification of
2946the resulting Unicode Object is only allowed when \var{u} is \NULL{}.
Fred Drakea4cd2612000-04-06 14:10:29 +00002947\end{cfuncdesc}
2948
Fred Drake1d158692000-06-18 05:21:21 +00002949\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002950Return a read-only pointer to the Unicode object's internal
2951\ctype{Py_UNICODE} buffer.
2952\end{cfuncdesc}
2953
2954\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
2955Return the length of the Unicode object.
2956\end{cfuncdesc}
2957
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002958\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
2959 const char *encoding,
2960 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002961
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002962Coerce an encoded object obj to an Unicode object and return a
2963reference with incremented refcount.
Fred Drakea4cd2612000-04-06 14:10:29 +00002964
2965Coercion is done in the following way:
2966\begin{enumerate}
2967\item Unicode objects are passed back as-is with incremented
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002968 refcount. Note: these cannot be decoded; passing a non-NULL
2969 value for encoding will result in a TypeError.
Fred Drakea4cd2612000-04-06 14:10:29 +00002970
2971\item String and other char buffer compatible objects are decoded
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002972 according to the given encoding and using the error handling
2973 defined by errors. Both can be NULL to have the interface use
2974 the default values (see the next section for details).
Fred Drakea4cd2612000-04-06 14:10:29 +00002975
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002976\item All other objects cause an exception.
Fred Drakea4cd2612000-04-06 14:10:29 +00002977\end{enumerate}
2978The API returns NULL in case of an error. The caller is responsible
2979for decref'ing the returned objects.
2980\end{cfuncdesc}
2981
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002982\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
2983
2984Shortcut for PyUnicode_FromEncodedObject(obj, NULL, ``strict'')
2985which is used throughout the interpreter whenever coercion to
2986Unicode is needed.
2987\end{cfuncdesc}
2988
Fred Drakea4cd2612000-04-06 14:10:29 +00002989% --- wchar_t support for platforms which support it ---------------------
2990
2991If the platform supports \ctype{wchar_t} and provides a header file
2992wchar.h, Python can interface directly to this type using the
2993following functions. Support is optimized if Python's own
2994\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
2995
2996\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
2997 int size}
2998Create a Unicode Object from the \ctype{whcar_t} buffer \var{w} of the
2999given size. Returns \NULL{} on failure.
3000\end{cfuncdesc}
3001
3002\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
3003 wchar_t *w,
3004 int size}
Fred Drakea4cd2612000-04-06 14:10:29 +00003005Copies the Unicode Object contents into the \ctype{whcar_t} buffer
3006\var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
3007Returns the number of \ctype{whcar_t} characters copied or -1 in case
3008of an error.
3009\end{cfuncdesc}
3010
3011
3012\subsubsection{Builtin Codecs \label{builtinCodecs}}
3013
3014Python provides a set of builtin codecs which are written in C
3015for speed. All of these codecs are directly usable via the
3016following functions.
3017
3018Many of the following APIs take two arguments encoding and
3019errors. These parameters encoding and errors have the same semantics
3020as the ones of the builtin unicode() Unicode object constructor.
3021
3022Setting encoding to NULL causes the default encoding to be used which
Martin v. Löwis7c82a3e02001-09-05 17:09:48 +00003023is \ASCII{}. The file system calls should use
3024\var{Py_FileSystemDefaultEncoding} as the encoding for file
3025names. This variable should be treated as read-only: On some systems,
3026it will be a pointer to a static string, on others, it will change at
3027run-time, e.g. when the application invokes setlocale.
Fred Drakea4cd2612000-04-06 14:10:29 +00003028
3029Error handling is set by errors which may also be set to NULL meaning
3030to use the default handling defined for the codec. Default error
3031handling for all builtin codecs is ``strict'' (ValueErrors are raised).
3032
3033The codecs all use a similar interface. Only deviation from the
3034following generic ones are documented for simplicity.
3035
3036% --- Generic Codecs -----------------------------------------------------
3037
3038These are the generic codec APIs:
3039
3040\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
3041 int size,
3042 const char *encoding,
3043 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003044Create a Unicode object by decoding \var{size} bytes of the encoded
3045string \var{s}. \var{encoding} and \var{errors} have the same meaning
3046as the parameters of the same name in the unicode() builtin
3047function. The codec to be used is looked up using the Python codec
3048registry. Returns \NULL{} in case an exception was raised by the
3049codec.
3050\end{cfuncdesc}
3051
3052\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
3053 int size,
3054 const char *encoding,
3055 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003056Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
3057Python string object. \var{encoding} and \var{errors} have the same
3058meaning as the parameters of the same name in the Unicode .encode()
3059method. The codec to be used is looked up using the Python codec
3060registry. Returns \NULL{} in case an exception was raised by the
3061codec.
3062\end{cfuncdesc}
3063
3064\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
3065 const char *encoding,
3066 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003067Encodes a Unicode object and returns the result as Python string
3068object. \var{encoding} and \var{errors} have the same meaning as the
3069parameters of the same name in the Unicode .encode() method. The codec
3070to be used is looked up using the Python codec registry. Returns
3071\NULL{} in case an exception was raised by the codec.
3072\end{cfuncdesc}
3073
3074% --- UTF-8 Codecs -------------------------------------------------------
3075
3076These are the UTF-8 codec APIs:
3077
3078\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
3079 int size,
3080 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003081Creates a Unicode object by decoding \var{size} bytes of the UTF-8
3082encoded string \var{s}. Returns \NULL{} in case an exception was
3083raised by the codec.
3084\end{cfuncdesc}
3085
3086\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
3087 int size,
3088 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003089Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
3090and returns a Python string object. Returns \NULL{} in case an
3091exception was raised by the codec.
3092\end{cfuncdesc}
3093
3094\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003095Encodes a Unicode objects using UTF-8 and returns the result as Python
3096string object. Error handling is ``strict''. Returns
3097\NULL{} in case an exception was raised by the codec.
3098\end{cfuncdesc}
3099
3100% --- UTF-16 Codecs ------------------------------------------------------ */
3101
3102These are the UTF-16 codec APIs:
3103
3104\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
3105 int size,
3106 const char *errors,
3107 int *byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00003108Decodes \var{length} bytes from a UTF-16 encoded buffer string and
3109returns the corresponding Unicode object.
3110
3111\var{errors} (if non-NULL) defines the error handling. It defaults
3112to ``strict''.
3113
3114If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
3115the given byte order:
3116
3117\begin{verbatim}
3118 *byteorder == -1: little endian
3119 *byteorder == 0: native order
3120 *byteorder == 1: big endian
3121\end{verbatim}
3122
3123and then switches according to all byte order marks (BOM) it finds in
3124the input data. BOM marks are not copied into the resulting Unicode
3125string. After completion, \var{*byteorder} is set to the current byte
3126order at the end of input data.
3127
3128If \var{byteorder} is \NULL{}, the codec starts in native order mode.
3129
3130Returns \NULL{} in case an exception was raised by the codec.
3131\end{cfuncdesc}
3132
3133\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
3134 int size,
3135 const char *errors,
3136 int byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00003137Returns a Python string object holding the UTF-16 encoded value of the
3138Unicode data in \var{s}.
3139
Fred Drakea8455ab2000-06-16 19:58:42 +00003140If \var{byteorder} is not \code{0}, output is written according to the
Fred Drakea4cd2612000-04-06 14:10:29 +00003141following byte order:
3142
3143\begin{verbatim}
3144 byteorder == -1: little endian
3145 byteorder == 0: native byte order (writes a BOM mark)
3146 byteorder == 1: big endian
3147\end{verbatim}
3148
Fred Drakea8455ab2000-06-16 19:58:42 +00003149If byteorder is \code{0}, the output string will always start with the
Fred Drakea4cd2612000-04-06 14:10:29 +00003150Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
3151prepended.
3152
3153Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
3154reduced to UCS-2. This trick makes it possible to add full UTF-16
3155capabilities at a later point without comprimising the APIs.
3156
3157Returns \NULL{} in case an exception was raised by the codec.
3158\end{cfuncdesc}
3159
3160\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003161Returns a Python string using the UTF-16 encoding in native byte
3162order. The string always starts with a BOM mark. Error handling is
3163``strict''. Returns \NULL{} in case an exception was raised by the
3164codec.
3165\end{cfuncdesc}
3166
3167% --- Unicode-Escape Codecs ----------------------------------------------
3168
3169These are the ``Unicode Esacpe'' codec APIs:
3170
3171\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
3172 int size,
3173 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003174Creates a Unicode object by decoding \var{size} bytes of the Unicode-Esacpe
3175encoded string \var{s}. Returns \NULL{} in case an exception was
3176raised by the codec.
3177\end{cfuncdesc}
3178
3179\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
3180 int size,
3181 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003182Encodes the \ctype{Py_UNICODE} buffer of the given size using Unicode-Escape
3183and returns a Python string object. Returns \NULL{} in case an
3184exception was raised by the codec.
3185\end{cfuncdesc}
3186
3187\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003188Encodes a Unicode objects using Unicode-Escape and returns the result
3189as Python string object. Error handling is ``strict''. Returns
3190\NULL{} in case an exception was raised by the codec.
3191\end{cfuncdesc}
3192
3193% --- Raw-Unicode-Escape Codecs ------------------------------------------
3194
3195These are the ``Raw Unicode Esacpe'' codec APIs:
3196
3197\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
3198 int size,
3199 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003200Creates a Unicode object by decoding \var{size} bytes of the Raw-Unicode-Esacpe
3201encoded string \var{s}. Returns \NULL{} in case an exception was
3202raised by the codec.
3203\end{cfuncdesc}
3204
3205\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
3206 int size,
3207 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003208Encodes the \ctype{Py_UNICODE} buffer of the given size using Raw-Unicode-Escape
3209and returns a Python string object. Returns \NULL{} in case an
3210exception was raised by the codec.
3211\end{cfuncdesc}
3212
3213\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003214Encodes a Unicode objects using Raw-Unicode-Escape and returns the result
3215as Python string object. Error handling is ``strict''. Returns
3216\NULL{} in case an exception was raised by the codec.
3217\end{cfuncdesc}
3218
3219% --- Latin-1 Codecs -----------------------------------------------------
3220
3221These are the Latin-1 codec APIs:
3222
3223Latin-1 corresponds to the first 256 Unicode ordinals and only these
3224are accepted by the codecs during encoding.
3225
3226\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00003227 int size,
3228 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003229Creates a Unicode object by decoding \var{size} bytes of the Latin-1
3230encoded string \var{s}. Returns \NULL{} in case an exception was
3231raised by the codec.
3232\end{cfuncdesc}
3233
3234\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00003235 int size,
3236 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003237Encodes the \ctype{Py_UNICODE} buffer of the given size using Latin-1
3238and returns a Python string object. Returns \NULL{} in case an
3239exception was raised by the codec.
3240\end{cfuncdesc}
3241
3242\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003243Encodes a Unicode objects using Latin-1 and returns the result as
3244Python string object. Error handling is ``strict''. Returns
3245\NULL{} in case an exception was raised by the codec.
3246\end{cfuncdesc}
3247
3248% --- ASCII Codecs -------------------------------------------------------
3249
Fred Drake1d158692000-06-18 05:21:21 +00003250These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
3251accepted. All other codes generate errors.
Fred Drakea4cd2612000-04-06 14:10:29 +00003252
3253\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00003254 int size,
3255 const char *errors}
3256Creates a Unicode object by decoding \var{size} bytes of the
3257\ASCII{} encoded string \var{s}. Returns \NULL{} in case an exception
3258was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003259\end{cfuncdesc}
3260
3261\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00003262 int size,
3263 const char *errors}
3264Encodes the \ctype{Py_UNICODE} buffer of the given size using
3265\ASCII{} and returns a Python string object. Returns \NULL{} in case
3266an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003267\end{cfuncdesc}
3268
3269\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
Fred Drake1d158692000-06-18 05:21:21 +00003270Encodes a Unicode objects using \ASCII{} and returns the result as Python
Fred Drakea4cd2612000-04-06 14:10:29 +00003271string object. Error handling is ``strict''. Returns
3272\NULL{} in case an exception was raised by the codec.
3273\end{cfuncdesc}
3274
3275% --- Character Map Codecs -----------------------------------------------
3276
3277These are the mapping codec APIs:
3278
3279This codec is special in that it can be used to implement many
3280different codecs (and this is in fact what was done to obtain most of
3281the standard codecs included in the \module{encodings} package). The
3282codec uses mapping to encode and decode characters.
3283
3284Decoding mappings must map single string characters to single Unicode
3285characters, integers (which are then interpreted as Unicode ordinals)
3286or None (meaning "undefined mapping" and causing an error).
3287
3288Encoding mappings must map single Unicode characters to single string
3289characters, integers (which are then interpreted as Latin-1 ordinals)
3290or None (meaning "undefined mapping" and causing an error).
3291
3292The mapping objects provided must only support the __getitem__ mapping
3293interface.
3294
3295If a character lookup fails with a LookupError, the character is
3296copied as-is meaning that its ordinal value will be interpreted as
3297Unicode or Latin-1 ordinal resp. Because of this, mappings only need
3298to contain those mappings which map characters to different code
3299points.
3300
3301\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
3302 int size,
3303 PyObject *mapping,
3304 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003305Creates a Unicode object by decoding \var{size} bytes of the encoded
3306string \var{s} using the given \var{mapping} object. Returns \NULL{}
3307in case an exception was raised by the codec.
3308\end{cfuncdesc}
3309
3310\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
3311 int size,
3312 PyObject *mapping,
3313 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003314Encodes the \ctype{Py_UNICODE} buffer of the given size using the
3315given \var{mapping} object and returns a Python string object.
3316Returns \NULL{} in case an exception was raised by the codec.
3317\end{cfuncdesc}
3318
3319\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
3320 PyObject *mapping}
Fred Drakea4cd2612000-04-06 14:10:29 +00003321Encodes a Unicode objects using the given \var{mapping} object and
3322returns the result as Python string object. Error handling is
3323``strict''. Returns \NULL{} in case an exception was raised by the
3324codec.
3325\end{cfuncdesc}
3326
3327The following codec API is special in that maps Unicode to Unicode.
3328
3329\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
3330 int size,
3331 PyObject *table,
3332 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003333Translates a \ctype{Py_UNICODE} buffer of the given length by applying
3334a character mapping \var{table} to it and returns the resulting
Fred Drake1d158692000-06-18 05:21:21 +00003335Unicode object. Returns \NULL{} when an exception was raised by the
3336codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003337
3338The \var{mapping} table must map Unicode ordinal integers to Unicode
3339ordinal integers or None (causing deletion of the character).
3340
3341Mapping tables must only provide the __getitem__ interface,
3342e.g. dictionaries or sequences. Unmapped character ordinals (ones
3343which cause a LookupError) are left untouched and are copied as-is.
Fred Drakea4cd2612000-04-06 14:10:29 +00003344\end{cfuncdesc}
3345
3346% --- MBCS codecs for Windows --------------------------------------------
3347
Fred Drake1d158692000-06-18 05:21:21 +00003348These are the MBCS codec APIs. They are currently only available on
Fred Drakea4cd2612000-04-06 14:10:29 +00003349Windows and use the Win32 MBCS converters to implement the
Fred Drake1d158692000-06-18 05:21:21 +00003350conversions. Note that MBCS (or DBCS) is a class of encodings, not
3351just one. The target encoding is defined by the user settings on the
3352machine running the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003353
3354\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
3355 int size,
3356 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003357Creates a Unicode object by decoding \var{size} bytes of the MBCS
Fred Drake1d158692000-06-18 05:21:21 +00003358encoded string \var{s}. Returns \NULL{} in case an exception was
Fred Drakea4cd2612000-04-06 14:10:29 +00003359raised by the codec.
3360\end{cfuncdesc}
3361
3362\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
3363 int size,
3364 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003365Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
3366and returns a Python string object. Returns \NULL{} in case an
3367exception was raised by the codec.
3368\end{cfuncdesc}
3369
3370\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00003371Encodes a Unicode objects using MBCS and returns the result as Python
Fred Drake1d158692000-06-18 05:21:21 +00003372string object. Error handling is ``strict''. Returns \NULL{} in case
3373an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00003374\end{cfuncdesc}
3375
3376% --- Methods & Slots ----------------------------------------------------
3377
3378\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
3379
3380The following APIs are capable of handling Unicode objects and strings
3381on input (we refer to them as strings in the descriptions) and return
3382Unicode objects or integers as apporpriate.
3383
3384They all return \NULL{} or -1 in case an exception occurrs.
3385
3386\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
3387 PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00003388Concat two strings giving a new Unicode string.
3389\end{cfuncdesc}
3390
3391\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
3392 PyObject *sep,
3393 int maxsplit}
Fred Drakea4cd2612000-04-06 14:10:29 +00003394Split a string giving a list of Unicode strings.
3395
3396If sep is NULL, splitting will be done at all whitespace
3397substrings. Otherwise, splits occur at the given separator.
3398
3399At most maxsplit splits will be done. If negative, no limit is set.
3400
3401Separators are not included in the resulting list.
3402\end{cfuncdesc}
3403
3404\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
3405 int maxsplit}
Fred Drake1d158692000-06-18 05:21:21 +00003406Split a Unicode string at line breaks, returning a list of Unicode
3407strings. CRLF is considered to be one line break. The Line break
3408characters are not included in the resulting strings.
Fred Drakea4cd2612000-04-06 14:10:29 +00003409\end{cfuncdesc}
3410
3411\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
3412 PyObject *table,
3413 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00003414Translate a string by applying a character mapping table to it and
3415return the resulting Unicode object.
3416
3417The mapping table must map Unicode ordinal integers to Unicode ordinal
3418integers or None (causing deletion of the character).
3419
3420Mapping tables must only provide the __getitem__ interface,
3421e.g. dictionaries or sequences. Unmapped character ordinals (ones
3422which cause a LookupError) are left untouched and are copied as-is.
3423
3424\var{errors} has the usual meaning for codecs. It may be \NULL{}
3425which indicates to use the default error handling.
Fred Drakea4cd2612000-04-06 14:10:29 +00003426\end{cfuncdesc}
3427
3428\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
3429 PyObject *seq}
Fred Drakea4cd2612000-04-06 14:10:29 +00003430Join a sequence of strings using the given separator and return
3431the resulting Unicode string.
3432\end{cfuncdesc}
3433
3434\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
3435 PyObject *substr,
3436 int start,
3437 int end,
3438 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00003439Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
3440the given tail end (\var{direction} == -1 means to do a prefix match,
3441\var{direction} == 1 a suffix match), 0 otherwise.
3442\end{cfuncdesc}
3443
3444\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
3445 PyObject *substr,
3446 int start,
3447 int end,
3448 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00003449Return the first position of \var{substr} in
3450\var{str}[\var{start}:\var{end}] using the given \var{direction}
3451(\var{direction} == 1 means to do a forward search,
3452\var{direction} == -1 a backward search), 0 otherwise.
3453\end{cfuncdesc}
3454
3455\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
3456 PyObject *substr,
3457 int start,
3458 int end}
Fred Drakea4cd2612000-04-06 14:10:29 +00003459Count the number of occurrences of \var{substr} in
3460\var{str}[\var{start}:\var{end}]
3461\end{cfuncdesc}
3462
3463\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
3464 PyObject *substr,
3465 PyObject *replstr,
3466 int maxcount}
Fred Drakea4cd2612000-04-06 14:10:29 +00003467Replace at most \var{maxcount} occurrences of \var{substr} in
3468\var{str} with \var{replstr} and return the resulting Unicode object.
3469\var{maxcount} == -1 means: replace all occurrences.
3470\end{cfuncdesc}
3471
Fred Drake1d158692000-06-18 05:21:21 +00003472\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00003473Compare two strings and return -1, 0, 1 for less than, equal,
3474greater than resp.
3475\end{cfuncdesc}
3476
3477\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
3478 PyObject *args}
Fred Drake1d158692000-06-18 05:21:21 +00003479Returns a new string object from \var{format} and \var{args}; this is
3480analogous to \code{\var{format} \%\ \var{args}}. The
3481\var{args} argument must be a tuple.
Fred Drakea4cd2612000-04-06 14:10:29 +00003482\end{cfuncdesc}
3483
3484\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
3485 PyObject *element}
Fred Drakea4cd2612000-04-06 14:10:29 +00003486Checks whether \var{element} is contained in \var{container} and
Fred Drake1d158692000-06-18 05:21:21 +00003487returns true or false accordingly.
Fred Drakea4cd2612000-04-06 14:10:29 +00003488
Fred Drake1d158692000-06-18 05:21:21 +00003489\var{element} has to coerce to a one element Unicode string. \code{-1} is
Fred Drakea4cd2612000-04-06 14:10:29 +00003490returned in case of an error.
3491\end{cfuncdesc}
3492
3493
Fred Drake58c5a2a1999-08-04 13:13:24 +00003494\subsection{Buffer Objects \label{bufferObjects}}
Fred Drake659ebfa2000-04-03 15:42:13 +00003495\sectionauthor{Greg Stein}{gstein@lyra.org}
Fred Drake58c5a2a1999-08-04 13:13:24 +00003496
Fred Drake659ebfa2000-04-03 15:42:13 +00003497\obindex{buffer}
3498Python objects implemented in C can export a group of functions called
3499the ``buffer\index{buffer interface} interface.'' These functions can
3500be used by an object to expose its data in a raw, byte-oriented
3501format. Clients of the object can use the buffer interface to access
3502the object data directly, without needing to copy it first.
3503
3504Two examples of objects that support
3505the buffer interface are strings and arrays. The string object exposes
3506the character contents in the buffer interface's byte-oriented
3507form. An array can also expose its contents, but it should be noted
3508that array elements may be multi-byte values.
3509
3510An example user of the buffer interface is the file object's
3511\method{write()} method. Any object that can export a series of bytes
3512through the buffer interface can be written to a file. There are a
Fred Drake88fdaa72001-07-20 20:56:11 +00003513number of format codes to \cfunction{PyArg_ParseTuple()} that operate
Fred Drake659ebfa2000-04-03 15:42:13 +00003514against an object's buffer interface, returning data from the target
3515object.
3516
3517More information on the buffer interface is provided in the section
3518``Buffer Object Structures'' (section \ref{buffer-structs}), under
3519the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
3520
3521A ``buffer object'' is defined in the \file{bufferobject.h} header
3522(included by \file{Python.h}). These objects look very similar to
3523string objects at the Python programming level: they support slicing,
3524indexing, concatenation, and some other standard string
3525operations. However, their data can come from one of two sources: from
3526a block of memory, or from another object which exports the buffer
3527interface.
3528
3529Buffer objects are useful as a way to expose the data from another
3530object's buffer interface to the Python programmer. They can also be
3531used as a zero-copy slicing mechanism. Using their ability to
3532reference a block of memory, it is possible to expose any data to the
3533Python programmer quite easily. The memory could be a large, constant
3534array in a C extension, it could be a raw block of memory for
3535manipulation before passing to an operating system library, or it
3536could be used to pass around structured data in its native, in-memory
3537format.
3538
3539\begin{ctypedesc}{PyBufferObject}
3540This subtype of \ctype{PyObject} represents a buffer object.
3541\end{ctypedesc}
Fred Drake58c5a2a1999-08-04 13:13:24 +00003542
3543\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
3544The instance of \ctype{PyTypeObject} which represents the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00003545buffer type; it is the same object as \code{types.BufferType} in the
3546Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003547\end{cvardesc}
3548
3549\begin{cvardesc}{int}{Py_END_OF_BUFFER}
Fred Drake659ebfa2000-04-03 15:42:13 +00003550This constant may be passed as the \var{size} parameter to
3551\cfunction{PyBuffer_FromObject()} or
3552\cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the new
3553\ctype{PyBufferObject} should refer to \var{base} object from the
3554specified \var{offset} to the end of its exported buffer. Using this
3555enables the caller to avoid querying the \var{base} object for its
3556length.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003557\end{cvardesc}
3558
3559\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
3560Return true if the argument has type \cdata{PyBuffer_Type}.
3561\end{cfuncdesc}
3562
3563\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
3564 int offset, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003565Return a new read-only buffer object. This raises
3566\exception{TypeError} if \var{base} doesn't support the read-only
3567buffer protocol or doesn't provide exactly one buffer segment, or it
3568raises \exception{ValueError} if \var{offset} is less than zero. The
3569buffer will hold a reference to the \var{base} object, and the
3570buffer's contents will refer to the \var{base} object's buffer
3571interface, starting as position \var{offset} and extending for
3572\var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
3573the new buffer's contents extend to the length of the
3574\var{base} object's exported buffer data.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003575\end{cfuncdesc}
3576
3577\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
3578 int offset,
3579 int size}
3580Return a new writable buffer object. Parameters and exceptions are
3581similar to those for \cfunction{PyBuffer_FromObject()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003582If the \var{base} object does not export the writeable buffer
3583protocol, then \exception{TypeError} is raised.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003584\end{cfuncdesc}
3585
3586\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003587Return a new read-only buffer object that reads from a specified
3588location in memory, with a specified size.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003589The caller is responsible for ensuring that the memory buffer, passed
3590in as \var{ptr}, is not deallocated while the returned buffer object
3591exists. Raises \exception{ValueError} if \var{size} is less than
Fred Drake659ebfa2000-04-03 15:42:13 +00003592zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be passed
3593for the \var{size} parameter; \exception{ValueError} will be raised in
3594that case.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003595\end{cfuncdesc}
3596
3597\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003598Similar to \cfunction{PyBuffer_FromMemory()}, but the returned buffer
3599is writable.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003600\end{cfuncdesc}
3601
3602\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
3603Returns a new writable buffer object that maintains its own memory
Fred Drake659ebfa2000-04-03 15:42:13 +00003604buffer of \var{size} bytes. \exception{ValueError} is returned if
3605\var{size} is not zero or positive.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003606\end{cfuncdesc}
3607
Guido van Rossum44475131998-04-21 15:30:01 +00003608
Fred Drakeefd146c1999-02-15 15:30:45 +00003609\subsection{Tuple Objects \label{tupleObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003610
Fred Drake659ebfa2000-04-03 15:42:13 +00003611\obindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003612\begin{ctypedesc}{PyTupleObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003613This subtype of \ctype{PyObject} represents a Python tuple object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003614\end{ctypedesc}
3615
3616\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003617This instance of \ctype{PyTypeObject} represents the Python tuple
3618type; it is the same object as \code{types.TupleType} in the Python
3619layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003620\end{cvardesc}
3621
3622\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
3623Return true if the argument is a tuple object.
3624\end{cfuncdesc}
3625
Fred Drake659ebfa2000-04-03 15:42:13 +00003626\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
3627Return a new tuple object of size \var{len}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003628\end{cfuncdesc}
3629
Fred Drakea05460c2001-02-12 17:38:18 +00003630\begin{cfuncdesc}{int}{PyTuple_Size}{PyObject *p}
Fred Drakee058b4f1998-02-16 06:15:35 +00003631Takes a pointer to a tuple object, and returns the size
Fred Drakee5bf8b21998-02-12 21:22:28 +00003632of that tuple.
3633\end{cfuncdesc}
3634
Fred Drake0e40c3d2001-08-20 16:48:59 +00003635\begin{cfuncdesc}{int}{PyTuple_GET_SIZE}{PyObject *p}
3636Return the size of the tuple \var{p}, which must be non-\NULL{} and
3637point to a tuple; no error checking is performed.
3638\end{cfuncdesc}
3639
Fred Drakea05460c2001-02-12 17:38:18 +00003640\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003641Returns the object at position \var{pos} in the tuple pointed
3642to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003643sets an \exception{IndexError} exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003644\end{cfuncdesc}
3645
Fred Drakea05460c2001-02-12 17:38:18 +00003646\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyObject *p, int pos}
Fred Drakefac312f2001-05-29 15:13:00 +00003647Like \cfunction{PyTuple_GetItem()}, but does no checking of its
3648arguments.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003649\end{cfuncdesc}
3650
Fred Drakea05460c2001-02-12 17:38:18 +00003651\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyObject *p,
3652 int low, int high}
Fred Drakee058b4f1998-02-16 06:15:35 +00003653Takes a slice of the tuple pointed to by \var{p} from
3654\var{low} to \var{high} and returns it as a new tuple.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003655\end{cfuncdesc}
3656
Fred Drake659ebfa2000-04-03 15:42:13 +00003657\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
3658 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003659Inserts a reference to object \var{o} at position \var{pos} of
3660the tuple pointed to by \var{p}. It returns \code{0} on success.
Fred Drake659ebfa2000-04-03 15:42:13 +00003661\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003662\end{cfuncdesc}
3663
Fred Drake659ebfa2000-04-03 15:42:13 +00003664\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
3665 int pos, PyObject *o}
Fred Drakefac312f2001-05-29 15:13:00 +00003666Like \cfunction{PyTuple_SetItem()}, but does no error checking, and
Fred Drakee5bf8b21998-02-12 21:22:28 +00003667should \emph{only} be used to fill in brand new tuples.
Fred Drake659ebfa2000-04-03 15:42:13 +00003668\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003669\end{cfuncdesc}
3670
Fred Drakefac312f2001-05-29 15:13:00 +00003671\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyObject **p, int newsize}
Fred Drake659ebfa2000-04-03 15:42:13 +00003672Can be used to resize a tuple. \var{newsize} will be the new length
3673of the tuple. Because tuples are \emph{supposed} to be immutable,
3674this should only be used if there is only one reference to the object.
3675Do \emph{not} use this if the tuple may already be known to some other
Fred Drakefac312f2001-05-29 15:13:00 +00003676part of the code. The tuple will always grow or shrink at the end.
3677Think of this as destroying the old tuple and creating a new one, only
3678more efficiently. Returns \code{0} on success. Client code should
3679never assume that the resulting value of \code{*\var{p}} will be the
3680same as before calling this function. If the object referenced by
3681\code{*\var{p}} is replaced, the original \code{*\var{p}} is
3682destroyed. On failure, returns \code{-1} and sets \code{*\var{p}} to
3683\NULL, and raises \exception{MemoryError} or \exception{SystemError}.
3684\versionchanged[Removed unused third parameter, \var{last_is_sticky}]{2.2}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003685\end{cfuncdesc}
3686
3687
Fred Drakeefd146c1999-02-15 15:30:45 +00003688\subsection{List Objects \label{listObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003689
Fred Drake659ebfa2000-04-03 15:42:13 +00003690\obindex{list}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003691\begin{ctypedesc}{PyListObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003692This subtype of \ctype{PyObject} represents a Python list object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003693\end{ctypedesc}
3694
3695\begin{cvardesc}{PyTypeObject}{PyList_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003696This instance of \ctype{PyTypeObject} represents the Python list
3697type. This is the same object as \code{types.ListType}.
3698\withsubitem{(in module types)}{\ttindex{ListType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003699\end{cvardesc}
3700
3701\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003702Returns true if its argument is a \ctype{PyListObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003703\end{cfuncdesc}
3704
Fred Drake659ebfa2000-04-03 15:42:13 +00003705\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
3706Returns a new list of length \var{len} on success, or \NULL{} on
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003707failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003708\end{cfuncdesc}
3709
Fred Drakec6fa34e1998-04-02 06:47:24 +00003710\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003711Returns the length of the list object in \var{list}; this is
3712equivalent to \samp{len(\var{list})} on a list object.
3713\bifuncindex{len}
3714\end{cfuncdesc}
3715
3716\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
Fred Drake5d644212000-10-07 12:31:50 +00003717Macro form of \cfunction{PyList_Size()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003718\end{cfuncdesc}
3719
Fred Drakec6fa34e1998-04-02 06:47:24 +00003720\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
Guido van Rossum44475131998-04-21 15:30:01 +00003721Returns the object at position \var{pos} in the list pointed
3722to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003723sets an \exception{IndexError} exception.
3724\end{cfuncdesc}
3725
3726\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
3727Macro form of \cfunction{PyList_GetItem()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003728\end{cfuncdesc}
3729
Fred Drakec6fa34e1998-04-02 06:47:24 +00003730\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
3731 PyObject *item}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003732Sets the item at index \var{index} in list to \var{item}.
Fred Drakebab29652001-07-10 16:10:08 +00003733Returns \code{0} on success or \code{-1} on failure.
Fred Drake00d0cb62001-06-03 03:12:57 +00003734\strong{Note:} This function ``steals'' a reference to \var{item} and
3735discards a reference to an item already in the list at the affected
3736position.
Fred Drake659ebfa2000-04-03 15:42:13 +00003737\end{cfuncdesc}
3738
Fred Drakebab29652001-07-10 16:10:08 +00003739\begin{cfuncdesc}{void}{PyList_SET_ITEM}{PyObject *list, int i,
Fred Drake659ebfa2000-04-03 15:42:13 +00003740 PyObject *o}
3741Macro form of \cfunction{PyList_SetItem()} without error checking.
Fred Drake00d0cb62001-06-03 03:12:57 +00003742\strong{Note:} This function ``steals'' a reference to \var{item},
3743and, unlike \cfunction{PyList_SetItem()}, does \emph{not} discard a
Fred Drakebab29652001-07-10 16:10:08 +00003744reference to any item that it being replaced; any reference in
3745\var{list} at position \var{i} will be leaked. This is normally only
3746used to fill in new lists where there is no previous content.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003747\end{cfuncdesc}
3748
Fred Drakec6fa34e1998-04-02 06:47:24 +00003749\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
Guido van Rossum44475131998-04-21 15:30:01 +00003750 PyObject *item}
3751Inserts the item \var{item} into list \var{list} in front of index
Fred Drake659ebfa2000-04-03 15:42:13 +00003752\var{index}. Returns \code{0} if successful; returns \code{-1} and
3753raises an exception if unsuccessful. Analogous to
3754\code{\var{list}.insert(\var{index}, \var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003755\end{cfuncdesc}
3756
Fred Drakec6fa34e1998-04-02 06:47:24 +00003757\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
Guido van Rossum44475131998-04-21 15:30:01 +00003758Appends the object \var{item} at the end of list \var{list}. Returns
Fred Drake659ebfa2000-04-03 15:42:13 +00003759\code{0} if successful; returns \code{-1} and sets an exception if
3760unsuccessful. Analogous to \code{\var{list}.append(\var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003761\end{cfuncdesc}
3762
Fred Drakec6fa34e1998-04-02 06:47:24 +00003763\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
3764 int low, int high}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003765Returns a list of the objects in \var{list} containing the objects
Guido van Rossum44475131998-04-21 15:30:01 +00003766\emph{between} \var{low} and \var{high}. Returns NULL and sets an
3767exception if unsuccessful.
Fred Drake659ebfa2000-04-03 15:42:13 +00003768Analogous to \code{\var{list}[\var{low}:\var{high}]}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003769\end{cfuncdesc}
3770
Fred Drakec6fa34e1998-04-02 06:47:24 +00003771\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
3772 int low, int high,
3773 PyObject *itemlist}
Fred Drake659ebfa2000-04-03 15:42:13 +00003774Sets the slice of \var{list} between \var{low} and \var{high} to the
3775contents of \var{itemlist}. Analogous to
3776\code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
3777\code{0} on success, \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003778\end{cfuncdesc}
3779
Fred Drakec6fa34e1998-04-02 06:47:24 +00003780\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003781Sorts the items of \var{list} in place. Returns \code{0} on success,
3782\code{-1} on failure. This is equivalent to
3783\samp{\var{list}.sort()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003784\end{cfuncdesc}
3785
Fred Drakec6fa34e1998-04-02 06:47:24 +00003786\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003787Reverses the items of \var{list} in place. Returns \code{0} on
3788success, \code{-1} on failure. This is the equivalent of
3789\samp{\var{list}.reverse()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003790\end{cfuncdesc}
3791
Fred Drakec6fa34e1998-04-02 06:47:24 +00003792\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003793Returns a new tuple object containing the contents of \var{list};
3794equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003795\end{cfuncdesc}
3796
3797
Fred Drakeefd146c1999-02-15 15:30:45 +00003798\section{Mapping Objects \label{mapObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003799
Fred Drake659ebfa2000-04-03 15:42:13 +00003800\obindex{mapping}
3801
3802
Fred Drakeefd146c1999-02-15 15:30:45 +00003803\subsection{Dictionary Objects \label{dictObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003804
Fred Drake659ebfa2000-04-03 15:42:13 +00003805\obindex{dictionary}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003806\begin{ctypedesc}{PyDictObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003807This subtype of \ctype{PyObject} represents a Python dictionary object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003808\end{ctypedesc}
3809
3810\begin{cvardesc}{PyTypeObject}{PyDict_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003811This instance of \ctype{PyTypeObject} represents the Python dictionary
3812type. This is exposed to Python programs as \code{types.DictType} and
3813\code{types.DictionaryType}.
3814\withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003815\end{cvardesc}
3816
3817\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003818Returns true if its argument is a \ctype{PyDictObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003819\end{cfuncdesc}
3820
Fred Drakec6fa34e1998-04-02 06:47:24 +00003821\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003822Returns a new empty dictionary, or \NULL{} on failure.
3823\end{cfuncdesc}
3824
3825\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
3826Empties an existing dictionary of all key-value pairs.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003827\end{cfuncdesc}
3828
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003829\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
Fred Drake0e40c3d2001-08-20 16:48:59 +00003830Returns a new dictionary that contains the same key-value pairs as
3831\var{p}.
Fred Drake11ee9022001-08-10 21:31:12 +00003832\versionadded{1.6}
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003833\end{cfuncdesc}
3834
Fred Drake659ebfa2000-04-03 15:42:13 +00003835\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
3836 PyObject *val}
Fred Drakebab29652001-07-10 16:10:08 +00003837Inserts \var{value} into the dictionary \var{p} with a key of \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003838\var{key} must be hashable; if it isn't, \exception{TypeError} will be
3839raised.
Fred Drakebab29652001-07-10 16:10:08 +00003840Returns \code{0} on success or \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003841\end{cfuncdesc}
3842
Fred Drake83e01bf2001-03-16 15:41:29 +00003843\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p,
Fred Drakee5bf8b21998-02-12 21:22:28 +00003844 char *key,
3845 PyObject *val}
Fred Drakebab29652001-07-10 16:10:08 +00003846Inserts \var{value} into the dictionary \var{p} using \var{key}
Fred Drake1d158692000-06-18 05:21:21 +00003847as a key. \var{key} should be a \ctype{char*}. The key object is
Fred Drakee058b4f1998-02-16 06:15:35 +00003848created using \code{PyString_FromString(\var{key})}.
Fred Drakebab29652001-07-10 16:10:08 +00003849Returns \code{0} on success or \code{-1} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00003850\ttindex{PyString_FromString()}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003851\end{cfuncdesc}
3852
Fred Drake659ebfa2000-04-03 15:42:13 +00003853\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003854Removes the entry in dictionary \var{p} with key \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003855\var{key} must be hashable; if it isn't, \exception{TypeError} is
3856raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003857\end{cfuncdesc}
3858
Fred Drake659ebfa2000-04-03 15:42:13 +00003859\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003860Removes the entry in dictionary \var{p} which has a key
Fred Drake659ebfa2000-04-03 15:42:13 +00003861specified by the string \var{key}.
Fred Drakebab29652001-07-10 16:10:08 +00003862Returns \code{0} on success or \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003863\end{cfuncdesc}
3864
Fred Drake659ebfa2000-04-03 15:42:13 +00003865\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003866Returns the object from dictionary \var{p} which has a key
Guido van Rossum44475131998-04-21 15:30:01 +00003867\var{key}. Returns \NULL{} if the key \var{key} is not present, but
Fred Drake659ebfa2000-04-03 15:42:13 +00003868\emph{without} setting an exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003869\end{cfuncdesc}
3870
Fred Drake659ebfa2000-04-03 15:42:13 +00003871\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
Fred Drakef8830d11998-04-23 14:06:01 +00003872This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
Fred Drake659ebfa2000-04-03 15:42:13 +00003873specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003874\end{cfuncdesc}
3875
Fred Drake659ebfa2000-04-03 15:42:13 +00003876\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003877Returns a \ctype{PyListObject} containing all the items
Guido van Rossum44475131998-04-21 15:30:01 +00003878from the dictionary, as in the dictinoary method \method{items()} (see
Fred Drakebe486461999-11-09 17:03:03 +00003879the \citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003880\end{cfuncdesc}
3881
Fred Drake659ebfa2000-04-03 15:42:13 +00003882\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003883Returns a \ctype{PyListObject} containing all the keys
Guido van Rossum44475131998-04-21 15:30:01 +00003884from the dictionary, as in the dictionary method \method{keys()} (see the
Fred Drakebe486461999-11-09 17:03:03 +00003885\citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003886\end{cfuncdesc}
3887
Fred Drake659ebfa2000-04-03 15:42:13 +00003888\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003889Returns a \ctype{PyListObject} containing all the values
Guido van Rossum44475131998-04-21 15:30:01 +00003890from the dictionary \var{p}, as in the dictionary method
Fred Drakebe486461999-11-09 17:03:03 +00003891\method{values()} (see the \citetitle[../lib/lib.html]{Python Library
3892Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003893\end{cfuncdesc}
3894
Fred Drake659ebfa2000-04-03 15:42:13 +00003895\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
3896Returns the number of items in the dictionary. This is equivalent to
3897\samp{len(\var{p})} on a dictionary.\bifuncindex{len}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003898\end{cfuncdesc}
3899
Fred Drake83e01bf2001-03-16 15:41:29 +00003900\begin{cfuncdesc}{int}{PyDict_Next}{PyObject *p, int *ppos,
Fred Drake7d45d342000-08-11 17:07:32 +00003901 PyObject **pkey, PyObject **pvalue}
Fred Drake83e01bf2001-03-16 15:41:29 +00003902Iterate over all key-value pairs in the dictionary \var{p}. The
3903\ctype{int} referred to by \var{ppos} must be initialized to \code{0}
3904prior to the first call to this function to start the iteration; the
3905function returns true for each pair in the dictionary, and false once
3906all pairs have been reported. The parameters \var{pkey} and
3907\var{pvalue} should either point to \ctype{PyObject*} variables that
3908will be filled in with each key and value, respectively, or may be
Fred Drake8d00a0f2001-04-13 17:55:02 +00003909\NULL.
3910
Fred Drake83e01bf2001-03-16 15:41:29 +00003911For example:
Fred Drakee5bf8b21998-02-12 21:22:28 +00003912
Fred Drake83e01bf2001-03-16 15:41:29 +00003913\begin{verbatim}
3914PyObject *key, *value;
3915int pos = 0;
3916
3917while (PyDict_Next(self->dict, &pos, &key, &value)) {
3918 /* do something interesting with the values... */
3919 ...
3920}
3921\end{verbatim}
Fred Drake8d00a0f2001-04-13 17:55:02 +00003922
3923The dictionary \var{p} should not be mutated during iteration. It is
3924safe (since Python 2.1) to modify the values of the keys as you
Fred Drake11ee9022001-08-10 21:31:12 +00003925iterate over the dictionary, but only so long as the set of keys does
3926not change. For example:
Fred Drake8d00a0f2001-04-13 17:55:02 +00003927
3928\begin{verbatim}
3929PyObject *key, *value;
3930int pos = 0;
3931
3932while (PyDict_Next(self->dict, &pos, &key, &value)) {
3933 int i = PyInt_AS_LONG(value) + 1;
3934 PyObject *o = PyInt_FromLong(i);
3935 if (o == NULL)
3936 return -1;
3937 if (PyDict_SetItem(self->dict, key, o) < 0) {
3938 Py_DECREF(o);
3939 return -1;
3940 }
3941 Py_DECREF(o);
3942}
3943\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003944\end{cfuncdesc}
3945
Fred Drake11ee9022001-08-10 21:31:12 +00003946\begin{cfuncdesc}{int}{PyDict_Merge}{PyObject *a, PyObject *b, int override}
3947Iterate over dictionary \var{b} adding key-value pairs to dictionary
3948\var{a}. If \var{override} is true, existing pairs in \var{a} will be
3949replaced if a matching key is found in \var{b}, otherwise pairs will
3950only be added if there is not a matching key in \var{a}. Returns
3951\code{0} on success or \code{-1} if an exception was raised.
3952\versionadded{2.2}
3953\end{cfuncdesc}
3954
3955\begin{cfuncdesc}{int}{PyDict_Update}{PyObject *a, PyObject *b}
3956This is the same as \code{PyDict_Merge(\var{a}, \var{b}, 1)} in C, or
3957\code{\var{a}.update(\var{b})} in Python. Returns \code{0} on success
3958or \code{-1} if an exception was raised.
3959\versionadded{2.2}
3960\end{cfuncdesc}
3961
Fred Drakee5bf8b21998-02-12 21:22:28 +00003962
Fred Drakeefd146c1999-02-15 15:30:45 +00003963\section{Other Objects \label{otherObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003964
Fred Drakeefd146c1999-02-15 15:30:45 +00003965\subsection{File Objects \label{fileObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003966
Fred Drake659ebfa2000-04-03 15:42:13 +00003967\obindex{file}
3968Python's built-in file objects are implemented entirely on the
3969\ctype{FILE*} support from the C standard library. This is an
3970implementation detail and may change in future releases of Python.
3971
Fred Drakee5bf8b21998-02-12 21:22:28 +00003972\begin{ctypedesc}{PyFileObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003973This subtype of \ctype{PyObject} represents a Python file object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003974\end{ctypedesc}
3975
3976\begin{cvardesc}{PyTypeObject}{PyFile_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003977This instance of \ctype{PyTypeObject} represents the Python file
3978type. This is exposed to Python programs as \code{types.FileType}.
3979\withsubitem{(in module types)}{\ttindex{FileType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003980\end{cvardesc}
3981
3982\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003983Returns true if its argument is a \ctype{PyFileObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003984\end{cfuncdesc}
3985
Fred Drake659ebfa2000-04-03 15:42:13 +00003986\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
3987On success, returns a new file object that is opened on the
3988file given by \var{filename}, with a file mode given by \var{mode},
3989where \var{mode} has the same semantics as the standard C routine
3990\cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003991\end{cfuncdesc}
3992
Fred Drakec6fa34e1998-04-02 06:47:24 +00003993\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
Fred Drake659ebfa2000-04-03 15:42:13 +00003994 char *name, char *mode,
3995 int (*close)(FILE*)}
3996Creates a new \ctype{PyFileObject} from the already-open standard C
3997file pointer, \var{fp}. The function \var{close} will be called when
3998the file should be closed. Returns \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003999\end{cfuncdesc}
4000
Fred Drake659ebfa2000-04-03 15:42:13 +00004001\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
4002Returns the file object associated with \var{p} as a \ctype{FILE*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004003\end{cfuncdesc}
4004
Fred Drakec6fa34e1998-04-02 06:47:24 +00004005\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004006Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
4007function reads one line from the object \var{p}. \var{p} may be a
4008file object or any object with a \method{readline()} method. If
4009\var{n} is \code{0}, exactly one line is read, regardless of the
4010length of the line. If \var{n} is greater than \code{0}, no more than
4011\var{n} bytes will be read from the file; a partial line can be
4012returned. In both cases, an empty string is returned if the end of
4013the file is reached immediately. If \var{n} is less than \code{0},
4014however, one line is read regardless of length, but
4015\exception{EOFError} is raised if the end of the file is reached
4016immediately.
4017\withsubitem{(built-in exception)}{\ttindex{EOFError}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00004018\end{cfuncdesc}
4019
Fred Drakec6fa34e1998-04-02 06:47:24 +00004020\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004021Returns the name of the file specified by \var{p} as a string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004022\end{cfuncdesc}
4023
4024\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004025Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
4026only. This should only be called immediately after file object
4027creation.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004028\end{cfuncdesc}
4029
Fred Drake659ebfa2000-04-03 15:42:13 +00004030\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
4031This function exists for internal use by the interpreter.
4032Sets the \member{softspace} attribute of \var{p} to \var{newflag} and
4033\withsubitem{(file attribute)}{\ttindex{softspace}}returns the
4034previous value. \var{p} does not have to be a file object
4035for this function to work properly; any object is supported (thought
4036its only interesting if the \member{softspace} attribute can be set).
4037This function clears any errors, and will return \code{0} as the
4038previous value if the attribute either does not exist or if there were
4039errors in retrieving it. There is no way to detect errors from this
4040function, but doing so should not be needed.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004041\end{cfuncdesc}
4042
Fred Drakec6fa34e1998-04-02 06:47:24 +00004043\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
4044 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00004045Writes object \var{obj} to file object \var{p}. The only supported
4046flag for \var{flags} is \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW};
4047if given, the \function{str()} of the object is written instead of the
4048\function{repr()}. Returns \code{0} on success or \code{-1} on
4049failure; the appropriate exception will be set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004050\end{cfuncdesc}
4051
Fred Drake024ef6f2001-08-10 14:27:38 +00004052\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004053Writes string \var{s} to file object \var{p}. Returns \code{0} on
4054success or \code{-1} on failure; the appropriate exception will be
4055set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00004056\end{cfuncdesc}
4057
4058
Fred Drake5838d0f2001-01-28 06:39:35 +00004059\subsection{Instance Objects \label{instanceObjects}}
4060
4061\obindex{instance}
4062There are very few functions specific to instance objects.
4063
4064\begin{cvardesc}{PyTypeObject}{PyInstance_Type}
4065 Type object for class instances.
4066\end{cvardesc}
4067
4068\begin{cfuncdesc}{int}{PyInstance_Check}{PyObject *obj}
4069 Returns true if \var{obj} is an instance.
4070\end{cfuncdesc}
4071
4072\begin{cfuncdesc}{PyObject*}{PyInstance_New}{PyObject *class,
4073 PyObject *arg,
4074 PyObject *kw}
4075 Create a new instance of a specific class. The parameters \var{arg}
4076 and \var{kw} are used as the positional and keyword parameters to
4077 the object's constructor.
4078\end{cfuncdesc}
4079
4080\begin{cfuncdesc}{PyObject*}{PyInstance_NewRaw}{PyObject *class,
4081 PyObject *dict}
4082 Create a new instance of a specific class without calling it's
4083 constructor. \var{class} is the class of new object. The
4084 \var{dict} parameter will be used as the object's \member{__dict__};
4085 if \NULL, a new dictionary will be created for the instance.
4086\end{cfuncdesc}
4087
4088
Fred Drakeefd146c1999-02-15 15:30:45 +00004089\subsection{Module Objects \label{moduleObjects}}
4090
4091\obindex{module}
4092There are only a few functions special to module objects.
4093
Fred Drake659ebfa2000-04-03 15:42:13 +00004094\begin{cvardesc}{PyTypeObject}{PyModule_Type}
4095This instance of \ctype{PyTypeObject} represents the Python module
4096type. This is exposed to Python programs as \code{types.ModuleType}.
4097\withsubitem{(in module types)}{\ttindex{ModuleType}}
4098\end{cvardesc}
4099
4100\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
4101Returns true if its argument is a module object.
Fred Drakeefd146c1999-02-15 15:30:45 +00004102\end{cfuncdesc}
4103
Fred Drake659ebfa2000-04-03 15:42:13 +00004104\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
4105Return a new module object with the \member{__name__} attribute set to
4106\var{name}. Only the module's \member{__doc__} and
4107\member{__name__} attributes are filled in; the caller is responsible
4108for providing a \member{__file__} attribute.
4109\withsubitem{(module attribute)}{
4110 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
4111\end{cfuncdesc}
4112
4113\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00004114Return the dictionary object that implements \var{module}'s namespace;
4115this object is the same as the \member{__dict__} attribute of the
4116module object. This function never fails.
Fred Drake659ebfa2000-04-03 15:42:13 +00004117\withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakeefd146c1999-02-15 15:30:45 +00004118\end{cfuncdesc}
4119
Fred Drake659ebfa2000-04-03 15:42:13 +00004120\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00004121Return \var{module}'s \member{__name__} value. If the module does not
Fred Drake659ebfa2000-04-03 15:42:13 +00004122provide one, or if it is not a string, \exception{SystemError} is
4123raised and \NULL{} is returned.
4124\withsubitem{(module attribute)}{\ttindex{__name__}}
4125\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00004126\end{cfuncdesc}
4127
Fred Drake659ebfa2000-04-03 15:42:13 +00004128\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00004129Return the name of the file from which \var{module} was loaded using
4130\var{module}'s \member{__file__} attribute. If this is not defined,
Fred Drake659ebfa2000-04-03 15:42:13 +00004131or if it is not a string, raise \exception{SystemError} and return
4132\NULL.
4133\withsubitem{(module attribute)}{\ttindex{__file__}}
4134\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00004135\end{cfuncdesc}
4136
Fred Drake891150b2000-09-23 03:25:42 +00004137\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
4138 char *name, PyObject *value}
4139Add an object to \var{module} as \var{name}. This is a convenience
4140function which can be used from the module's initialization function.
4141This steals a reference to \var{value}. Returns \code{-1} on error,
4142\code{0} on success.
4143\versionadded{2.0}
4144\end{cfuncdesc}
4145
4146\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
4147 char *name, int value}
4148Add an integer constant to \var{module} as \var{name}. This convenience
4149function can be used from the module's initialization function.
4150Returns \code{-1} on error, \code{0} on success.
4151\versionadded{2.0}
4152\end{cfuncdesc}
4153
4154\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
4155 char *name, char *value}
4156Add a string constant to \var{module} as \var{name}. This convenience
4157function can be used from the module's initialization function. The
4158string \var{value} must be null-terminated. Returns \code{-1} on
4159error, \code{0} on success.
4160\versionadded{2.0}
4161\end{cfuncdesc}
4162
Fred Drakeefd146c1999-02-15 15:30:45 +00004163
4164\subsection{CObjects \label{cObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00004165
Fred Drake659ebfa2000-04-03 15:42:13 +00004166\obindex{CObject}
4167Refer to \emph{Extending and Embedding the Python Interpreter},
4168section 1.12 (``Providing a C API for an Extension Module''), for more
4169information on using these objects.
4170
4171
Guido van Rossum44475131998-04-21 15:30:01 +00004172\begin{ctypedesc}{PyCObject}
Fred Drakef8830d11998-04-23 14:06:01 +00004173This subtype of \ctype{PyObject} represents an opaque value, useful for
Fred Drake659ebfa2000-04-03 15:42:13 +00004174C extension modules who need to pass an opaque value (as a
4175\ctype{void*} pointer) through Python code to other C code. It is
Guido van Rossum44475131998-04-21 15:30:01 +00004176often used to make a C function pointer defined in one module
4177available to other modules, so the regular import mechanism can be
4178used to access C APIs defined in dynamically loaded modules.
4179\end{ctypedesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00004180
Fred Drake659ebfa2000-04-03 15:42:13 +00004181\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
4182Returns true if its argument is a \ctype{PyCObject}.
4183\end{cfuncdesc}
4184
4185\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00004186 void (*destr)(void *)}
Fred Drake1d158692000-06-18 05:21:21 +00004187Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drakedab44681999-05-13 18:41:14 +00004188\var{destr} function will be called when the object is reclaimed, unless
4189it is \NULL.
Guido van Rossum44475131998-04-21 15:30:01 +00004190\end{cfuncdesc}
4191
Fred Drake659ebfa2000-04-03 15:42:13 +00004192\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00004193 void* desc, void (*destr)(void *, void *) }
Fred Drakef8830d11998-04-23 14:06:01 +00004194Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
4195\var{destr} function will be called when the object is reclaimed. The
4196\var{desc} argument can be used to pass extra callback data for the
4197destructor function.
Guido van Rossum44475131998-04-21 15:30:01 +00004198\end{cfuncdesc}
4199
Fred Drake659ebfa2000-04-03 15:42:13 +00004200\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
4201Returns the object \ctype{void *} that the
4202\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00004203\end{cfuncdesc}
4204
Fred Drake659ebfa2000-04-03 15:42:13 +00004205\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
4206Returns the description \ctype{void *} that the
4207\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00004208\end{cfuncdesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00004209
Fred Drake659ebfa2000-04-03 15:42:13 +00004210
Fred Drakeefd146c1999-02-15 15:30:45 +00004211\chapter{Initialization, Finalization, and Threads
4212 \label{initialization}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004213
Guido van Rossum4a944d71997-08-14 20:35:38 +00004214\begin{cfuncdesc}{void}{Py_Initialize}{}
4215Initialize the Python interpreter. In an application embedding
4216Python, this should be called before using any other Python/C API
Fred Drake659ebfa2000-04-03 15:42:13 +00004217functions; with the exception of
4218\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
4219\cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
4220\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
4221and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
4222This initializes the table of loaded modules (\code{sys.modules}), and
4223\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}creates the
4224fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake4de05a91998-02-16 14:25:26 +00004225\module{__main__}\refbimodindex{__main__} and
4226\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drake659ebfa2000-04-03 15:42:13 +00004227search\indexiii{module}{search}{path} path (\code{sys.path}).
4228It does not set \code{sys.argv}; use
4229\cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
4230is a no-op when called for a second time (without calling
4231\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is no
4232return value; it is a fatal error if the initialization fails.
Guido van Rossum42cefd01997-10-05 15:27:29 +00004233\end{cfuncdesc}
4234
4235\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00004236Return true (nonzero) when the Python interpreter has been
Fred Drakee058b4f1998-02-16 06:15:35 +00004237initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
4238called, this returns false until \cfunction{Py_Initialize()} is called
Guido van Rossum42cefd01997-10-05 15:27:29 +00004239again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004240\end{cfuncdesc}
4241
4242\begin{cfuncdesc}{void}{Py_Finalize}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004243Undo all initializations made by \cfunction{Py_Initialize()} and
4244subsequent use of Python/C API functions, and destroy all
4245sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
4246created and not yet destroyed since the last call to
4247\cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
4248by the Python interpreter. This is a no-op when called for a second
4249time (without calling \cfunction{Py_Initialize()} again first). There
4250is no return value; errors during finalization are ignored.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004251
4252This function is provided for a number of reasons. An embedding
4253application might want to restart Python without having to restart the
4254application itself. An application that has loaded the Python
4255interpreter from a dynamically loadable library (or DLL) might want to
4256free all memory allocated by Python before unloading the DLL. During a
4257hunt for memory leaks in an application a developer might want to free
4258all memory allocated by Python before exiting from the application.
4259
Fred Drakee058b4f1998-02-16 06:15:35 +00004260\strong{Bugs and caveats:} The destruction of modules and objects in
Guido van Rossum4a944d71997-08-14 20:35:38 +00004261modules is done in random order; this may cause destructors
Fred Drakee058b4f1998-02-16 06:15:35 +00004262(\method{__del__()} methods) to fail when they depend on other objects
Guido van Rossum4a944d71997-08-14 20:35:38 +00004263(even functions) or modules. Dynamically loaded extension modules
4264loaded by Python are not unloaded. Small amounts of memory allocated
4265by the Python interpreter may not be freed (if you find a leak, please
4266report it). Memory tied up in circular references between objects is
4267not freed. Some memory allocated by extension modules may not be
4268freed. Some extension may not work properly if their initialization
4269routine is called more than once; this can happen if an applcation
Fred Drakee058b4f1998-02-16 06:15:35 +00004270calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
4271than once.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004272\end{cfuncdesc}
4273
Fred Drakec6fa34e1998-04-02 06:47:24 +00004274\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
Fred Drake4de05a91998-02-16 14:25:26 +00004275Create a new sub-interpreter. This is an (almost) totally separate
4276environment for the execution of Python code. In particular, the new
4277interpreter has separate, independent versions of all imported
4278modules, including the fundamental modules
4279\module{__builtin__}\refbimodindex{__builtin__},
4280\module{__main__}\refbimodindex{__main__} and
4281\module{sys}\refbimodindex{sys}. The table of loaded modules
4282(\code{sys.modules}) and the module search path (\code{sys.path}) are
4283also separate. The new environment has no \code{sys.argv} variable.
4284It has new standard I/O stream file objects \code{sys.stdin},
4285\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drake659ebfa2000-04-03 15:42:13 +00004286same underlying \ctype{FILE} structures in the C library).
4287\withsubitem{(in module sys)}{
4288 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004289
4290The return value points to the first thread state created in the new
4291sub-interpreter. This thread state is made the current thread state.
4292Note that no actual thread is created; see the discussion of thread
4293states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004294\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00004295is stored in the current thread state and there may not be a current
4296thread state. (Like all other Python/C API functions, the global
4297interpreter lock must be held before calling this function and is
4298still held when it returns; however, unlike most other Python/C API
4299functions, there needn't be a current thread state on entry.)
4300
4301Extension modules are shared between (sub-)interpreters as follows:
4302the first time a particular extension is imported, it is initialized
4303normally, and a (shallow) copy of its module's dictionary is
4304squirreled away. When the same extension is imported by another
4305(sub-)interpreter, a new module is initialized and filled with the
Fred Drakee058b4f1998-02-16 06:15:35 +00004306contents of this copy; the extension's \code{init} function is not
4307called. Note that this is different from what happens when an
4308extension is imported after the interpreter has been completely
Fred Drake659ebfa2000-04-03 15:42:13 +00004309re-initialized by calling
4310\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
4311\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
4312the extension's \code{init\var{module}} function \emph{is} called
4313again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004314
Fred Drakee058b4f1998-02-16 06:15:35 +00004315\strong{Bugs and caveats:} Because sub-interpreters (and the main
Guido van Rossum4a944d71997-08-14 20:35:38 +00004316interpreter) are part of the same process, the insulation between them
Fred Drakee058b4f1998-02-16 06:15:35 +00004317isn't perfect --- for example, using low-level file operations like
Fred Drake659ebfa2000-04-03 15:42:13 +00004318\withsubitem{(in module os)}{\ttindex{close()}}
Fred Drakef8830d11998-04-23 14:06:01 +00004319\function{os.close()} they can (accidentally or maliciously) affect each
Guido van Rossum4a944d71997-08-14 20:35:38 +00004320other's open files. Because of the way extensions are shared between
4321(sub-)interpreters, some extensions may not work properly; this is
4322especially likely when the extension makes use of (static) global
4323variables, or when the extension manipulates its module's dictionary
4324after its initialization. It is possible to insert objects created in
4325one sub-interpreter into a namespace of another sub-interpreter; this
4326should be done with great care to avoid sharing user-defined
4327functions, methods, instances or classes between sub-interpreters,
4328since import operations executed by such objects may affect the
4329wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
4330a hard-to-fix bug that will be addressed in a future release.)
4331\end{cfuncdesc}
4332
4333\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
4334Destroy the (sub-)interpreter represented by the given thread state.
4335The given thread state must be the current thread state. See the
4336discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004337thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00004338interpreted are destroyed. (The global interpreter lock must be held
4339before calling this function and is still held when it returns.)
Fred Drake659ebfa2000-04-03 15:42:13 +00004340\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will destroy all
4341sub-interpreters that haven't been explicitly destroyed at that point.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004342\end{cfuncdesc}
4343
4344\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00004345This function should be called before
4346\cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
Guido van Rossum4a944d71997-08-14 20:35:38 +00004347for the first time, if it is called at all. It tells the interpreter
Fred Drake659ebfa2000-04-03 15:42:13 +00004348the value of the \code{argv[0]} argument to the
4349\cfunction{main()}\ttindex{main()} function of the program. This is
4350used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some other
Guido van Rossum4a944d71997-08-14 20:35:38 +00004351functions below to find the Python run-time libraries relative to the
Fred Drakea8455ab2000-06-16 19:58:42 +00004352interpreter executable. The default value is \code{'python'}. The
Guido van Rossum4a944d71997-08-14 20:35:38 +00004353argument should point to a zero-terminated character string in static
4354storage whose contents will not change for the duration of the
4355program's execution. No code in the Python interpreter will change
4356the contents of this storage.
4357\end{cfuncdesc}
4358
Fred Drakec6fa34e1998-04-02 06:47:24 +00004359\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00004360Return the program name set with
4361\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
Guido van Rossum4a944d71997-08-14 20:35:38 +00004362default. The returned string points into static storage; the caller
4363should not modify its value.
4364\end{cfuncdesc}
4365
Fred Drakec6fa34e1998-04-02 06:47:24 +00004366\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004367Return the \emph{prefix} for installed platform-independent files. This
Guido van Rossum4a944d71997-08-14 20:35:38 +00004368is derived through a number of complicated rules from the program name
Fred Drakee058b4f1998-02-16 06:15:35 +00004369set with \cfunction{Py_SetProgramName()} and some environment variables;
Fred Drakea8455ab2000-06-16 19:58:42 +00004370for example, if the program name is \code{'/usr/local/bin/python'},
4371the prefix is \code{'/usr/local'}. The returned string points into
Guido van Rossum4a944d71997-08-14 20:35:38 +00004372static storage; the caller should not modify its value. This
Fred Drakec94d9341998-04-12 02:39:13 +00004373corresponds to the \makevar{prefix} variable in the top-level
Fred Drakea8455ab2000-06-16 19:58:42 +00004374\file{Makefile} and the \longprogramopt{prefix} argument to the
Fred Drakee058b4f1998-02-16 06:15:35 +00004375\program{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00004376Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00004377also the next function.
4378\end{cfuncdesc}
4379
Fred Drakec6fa34e1998-04-02 06:47:24 +00004380\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004381Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
Guido van Rossum4a944d71997-08-14 20:35:38 +00004382files. This is derived through a number of complicated rules from the
Fred Drakee058b4f1998-02-16 06:15:35 +00004383program name set with \cfunction{Py_SetProgramName()} and some environment
Guido van Rossum4a944d71997-08-14 20:35:38 +00004384variables; for example, if the program name is
Fred Drakea8455ab2000-06-16 19:58:42 +00004385\code{'/usr/local/bin/python'}, the exec-prefix is
4386\code{'/usr/local'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00004387the caller should not modify its value. This corresponds to the
Fred Drakec94d9341998-04-12 02:39:13 +00004388\makevar{exec_prefix} variable in the top-level \file{Makefile} and the
Fred Drakea8455ab2000-06-16 19:58:42 +00004389\longprogramopt{exec-prefix} argument to the
Fred Drake310ee611999-11-09 17:31:42 +00004390\program{configure} script at build time. The value is available to
4391Python code as \code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004392
4393Background: The exec-prefix differs from the prefix when platform
4394dependent files (such as executables and shared libraries) are
4395installed in a different directory tree. In a typical installation,
4396platform dependent files may be installed in the
Fred Drakea8455ab2000-06-16 19:58:42 +00004397\file{/usr/local/plat} subtree while platform independent may be
4398installed in \file{/usr/local}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004399
4400Generally speaking, a platform is a combination of hardware and
4401software families, e.g. Sparc machines running the Solaris 2.x
4402operating system are considered the same platform, but Intel machines
4403running Solaris 2.x are another platform, and Intel machines running
4404Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00004405operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004406operating systems are a different story; the installation strategies
4407on those systems are so different that the prefix and exec-prefix are
4408meaningless, and set to the empty string. Note that compiled Python
4409bytecode files are platform independent (but not independent from the
4410Python version by which they were compiled!).
4411
Fred Drakee058b4f1998-02-16 06:15:35 +00004412System administrators will know how to configure the \program{mount} or
Fred Drakea8455ab2000-06-16 19:58:42 +00004413\program{automount} programs to share \file{/usr/local} between platforms
4414while having \file{/usr/local/plat} be a different filesystem for each
Guido van Rossum4a944d71997-08-14 20:35:38 +00004415platform.
4416\end{cfuncdesc}
4417
Fred Drakec6fa34e1998-04-02 06:47:24 +00004418\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004419Return the full program name of the Python executable; this is
4420computed as a side-effect of deriving the default module search path
Fred Drake659ebfa2000-04-03 15:42:13 +00004421from the program name (set by
4422\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
4423The returned string points into static storage; the caller should not
Guido van Rossum4a944d71997-08-14 20:35:38 +00004424modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00004425\code{sys.executable}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004426\withsubitem{(in module sys)}{\ttindex{executable}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004427\end{cfuncdesc}
4428
Fred Drakec6fa34e1998-04-02 06:47:24 +00004429\begin{cfuncdesc}{char*}{Py_GetPath}{}
Fred Drake4de05a91998-02-16 14:25:26 +00004430\indexiii{module}{search}{path}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004431Return the default module search path; this is computed from the
Fred Drakee058b4f1998-02-16 06:15:35 +00004432program name (set by \cfunction{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00004433environment variables. The returned string consists of a series of
4434directory names separated by a platform dependent delimiter character.
Fred Drakef8830d11998-04-23 14:06:01 +00004435The delimiter character is \character{:} on \UNIX{}, \character{;} on
Fred Drake659ebfa2000-04-03 15:42:13 +00004436DOS/Windows, and \character{\e n} (the \ASCII{} newline character) on
Fred Drakee5bc4971998-02-12 23:36:49 +00004437Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00004438should not modify its value. The value is available to Python code
Fred Drake659ebfa2000-04-03 15:42:13 +00004439as the list \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}},
4440which may be modified to change the future search path for loaded
4441modules.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004442
4443% XXX should give the exact rules
4444\end{cfuncdesc}
4445
Fred Drakec6fa34e1998-04-02 06:47:24 +00004446\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004447Return the version of this Python interpreter. This is a string that
4448looks something like
4449
Guido van Rossum09270b51997-08-15 18:57:32 +00004450\begin{verbatim}
Fred Drakee058b4f1998-02-16 06:15:35 +00004451"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
Guido van Rossum09270b51997-08-15 18:57:32 +00004452\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004453
4454The first word (up to the first space character) is the current Python
4455version; the first three characters are the major and minor version
4456separated by a period. The returned string points into static storage;
4457the caller should not modify its value. The value is available to
4458Python code as the list \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004459\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004460\end{cfuncdesc}
4461
Fred Drakec6fa34e1998-04-02 06:47:24 +00004462\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00004463Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00004464this is formed from the ``official'' name of the operating system,
4465converted to lower case, followed by the major revision number; e.g.,
4466for Solaris 2.x, which is also known as SunOS 5.x, the value is
Fred Drakea8455ab2000-06-16 19:58:42 +00004467\code{'sunos5'}. On Macintosh, it is \code{'mac'}. On Windows, it
4468is \code{'win'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00004469the caller should not modify its value. The value is available to
4470Python code as \code{sys.platform}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004471\withsubitem{(in module sys)}{\ttindex{platform}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004472\end{cfuncdesc}
4473
Fred Drakec6fa34e1998-04-02 06:47:24 +00004474\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004475Return the official copyright string for the current Python version,
4476for example
4477
Fred Drakea8455ab2000-06-16 19:58:42 +00004478\code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004479
4480The returned string points into static storage; the caller should not
4481modify its value. The value is available to Python code as the list
4482\code{sys.copyright}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004483\withsubitem{(in module sys)}{\ttindex{copyright}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004484\end{cfuncdesc}
4485
Fred Drakec6fa34e1998-04-02 06:47:24 +00004486\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004487Return an indication of the compiler used to build the current Python
Fred Drakee058b4f1998-02-16 06:15:35 +00004488version, in square brackets, for example:
Guido van Rossum4a944d71997-08-14 20:35:38 +00004489
Fred Drakee058b4f1998-02-16 06:15:35 +00004490\begin{verbatim}
4491"[GCC 2.7.2.2]"
4492\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004493
4494The returned string points into static storage; the caller should not
4495modify its value. The value is available to Python code as part of
4496the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004497\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004498\end{cfuncdesc}
4499
Fred Drakec6fa34e1998-04-02 06:47:24 +00004500\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004501Return information about the sequence number and build date and time
4502of the current Python interpreter instance, for example
4503
Guido van Rossum09270b51997-08-15 18:57:32 +00004504\begin{verbatim}
4505"#67, Aug 1 1997, 22:34:28"
4506\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004507
4508The returned string points into static storage; the caller should not
4509modify its value. The value is available to Python code as part of
4510the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004511\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004512\end{cfuncdesc}
4513
4514\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
Fred Drake659ebfa2000-04-03 15:42:13 +00004515Set \code{sys.argv} based on \var{argc} and \var{argv}. These
4516parameters are similar to those passed to the program's
4517\cfunction{main()}\ttindex{main()} function with the difference that
4518the first entry should refer to the script file to be executed rather
4519than the executable hosting the Python interpreter. If there isn't a
4520script that will be run, the first entry in \var{argv} can be an empty
4521string. If this function fails to initialize \code{sys.argv}, a fatal
4522condition is signalled using
4523\cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
4524\withsubitem{(in module sys)}{\ttindex{argv}}
4525% XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
4526% check w/ Guido.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004527\end{cfuncdesc}
4528
4529% XXX Other PySys thingies (doesn't really belong in this chapter)
4530
Fred Drakeefd146c1999-02-15 15:30:45 +00004531\section{Thread State and the Global Interpreter Lock
4532 \label{threads}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004533
Fred Drake659ebfa2000-04-03 15:42:13 +00004534\index{global interpreter lock}
4535\index{interpreter lock}
4536\index{lock, interpreter}
4537
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004538The Python interpreter is not fully thread safe. In order to support
4539multi-threaded Python programs, there's a global lock that must be
4540held by the current thread before it can safely access Python objects.
4541Without the lock, even the simplest operations could cause problems in
Fred Drake7baf3d41998-02-20 00:45:52 +00004542a multi-threaded program: for example, when two threads simultaneously
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004543increment the reference count of the same object, the reference count
4544could end up being incremented only once instead of twice.
4545
4546Therefore, the rule exists that only the thread that has acquired the
4547global interpreter lock may operate on Python objects or call Python/C
4548API functions. In order to support multi-threaded Python programs,
Fred Drake659ebfa2000-04-03 15:42:13 +00004549the interpreter regularly releases and reacquires the lock --- by
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004550default, every ten bytecode instructions (this can be changed with
Fred Drake659ebfa2000-04-03 15:42:13 +00004551\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
Fred Drakee058b4f1998-02-16 06:15:35 +00004552\function{sys.setcheckinterval()}). The lock is also released and
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004553reacquired around potentially blocking I/O operations like reading or
4554writing a file, so that other threads can run while the thread that
4555requests the I/O is waiting for the I/O operation to complete.
4556
4557The Python interpreter needs to keep some bookkeeping information
Fred Drakee058b4f1998-02-16 06:15:35 +00004558separate per thread --- for this it uses a data structure called
Fred Drake659ebfa2000-04-03 15:42:13 +00004559\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
45601.5; in earlier versions, such state was stored in global variables,
4561and switching threads could cause problems. In particular, exception
4562handling is now thread safe, when the application uses
4563\withsubitem{(in module sys)}{\ttindex{exc_info()}}
4564\function{sys.exc_info()} to access the exception last raised in the
4565current thread.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004566
4567There's one global variable left, however: the pointer to the current
Fred Drake659ebfa2000-04-03 15:42:13 +00004568\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
4569thread packages have a way to store ``per-thread global data,''
4570Python's internal platform independent thread abstraction doesn't
4571support this yet. Therefore, the current thread state must be
4572manipulated explicitly.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004573
4574This is easy enough in most cases. Most code manipulating the global
4575interpreter lock has the following simple structure:
4576
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004577\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004578Save the thread state in a local variable.
4579Release the interpreter lock.
4580...Do some blocking I/O operation...
4581Reacquire the interpreter lock.
4582Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004583\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004584
4585This is so common that a pair of macros exists to simplify it:
4586
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004587\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004588Py_BEGIN_ALLOW_THREADS
4589...Do some blocking I/O operation...
4590Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004591\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004592
Fred Drake659ebfa2000-04-03 15:42:13 +00004593The \code{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS} macro
4594opens a new block and declares a hidden local variable; the
4595\code{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS} macro closes
Fred Drakee058b4f1998-02-16 06:15:35 +00004596the block. Another advantage of using these two macros is that when
4597Python is compiled without thread support, they are defined empty,
4598thus saving the thread state and lock manipulations.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004599
4600When thread support is enabled, the block above expands to the
4601following code:
4602
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004603\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004604 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004605
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004606 _save = PyEval_SaveThread();
4607 ...Do some blocking I/O operation...
4608 PyEval_RestoreThread(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004609\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004610
4611Using even lower level primitives, we can get roughly the same effect
4612as follows:
4613
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004614\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004615 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004616
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004617 _save = PyThreadState_Swap(NULL);
4618 PyEval_ReleaseLock();
4619 ...Do some blocking I/O operation...
4620 PyEval_AcquireLock();
4621 PyThreadState_Swap(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004622\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004623
4624There are some subtle differences; in particular,
Fred Drake659ebfa2000-04-03 15:42:13 +00004625\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
4626and restores the value of the global variable
4627\cdata{errno}\ttindex{errno}, since the lock manipulation does not
Fred Drakef8830d11998-04-23 14:06:01 +00004628guarantee that \cdata{errno} is left alone. Also, when thread support
Fred Drake659ebfa2000-04-03 15:42:13 +00004629is disabled,
4630\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
Fred Drakee058b4f1998-02-16 06:15:35 +00004631\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
Fred Drake659ebfa2000-04-03 15:42:13 +00004632case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
4633\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
4634available. This is done so that dynamically loaded extensions
4635compiled with thread support enabled can be loaded by an interpreter
4636that was compiled with disabled thread support.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004637
4638The global interpreter lock is used to protect the pointer to the
4639current thread state. When releasing the lock and saving the thread
4640state, the current thread state pointer must be retrieved before the
4641lock is released (since another thread could immediately acquire the
4642lock and store its own thread state in the global variable).
Fred Drakeffe58ca2000-09-29 17:31:54 +00004643Conversely, when acquiring the lock and restoring the thread state,
4644the lock must be acquired before storing the thread state pointer.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004645
4646Why am I going on with so much detail about this? Because when
Fred Drake659ebfa2000-04-03 15:42:13 +00004647threads are created from C, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004648lock, nor is there a thread state data structure for them. Such
4649threads must bootstrap themselves into existence, by first creating a
4650thread state data structure, then acquiring the lock, and finally
4651storing their thread state pointer, before they can start using the
4652Python/C API. When they are done, they should reset the thread state
4653pointer, release the lock, and finally free their thread state data
4654structure.
4655
4656When creating a thread data structure, you need to provide an
4657interpreter state data structure. The interpreter state data
4658structure hold global data that is shared by all threads in an
4659interpreter, for example the module administration
4660(\code{sys.modules}). Depending on your needs, you can either create
4661a new interpreter state data structure, or share the interpreter state
4662data structure used by the Python main thread (to access the latter,
Fred Drakef8830d11998-04-23 14:06:01 +00004663you must obtain the thread state and access its \member{interp} member;
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004664this must be done by a thread that is created by Python or by the main
4665thread after Python is initialized).
4666
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004667
4668\begin{ctypedesc}{PyInterpreterState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004669This data structure represents the state shared by a number of
4670cooperating threads. Threads belonging to the same interpreter
4671share their module administration and a few other internal items.
4672There are no public members in this structure.
4673
4674Threads belonging to different interpreters initially share nothing,
4675except process state like available memory, open file descriptors and
4676such. The global interpreter lock is also shared by all threads,
4677regardless of to which interpreter they belong.
4678\end{ctypedesc}
4679
4680\begin{ctypedesc}{PyThreadState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004681This data structure represents the state of a single thread. The only
Fred Drakef8830d11998-04-23 14:06:01 +00004682public data member is \ctype{PyInterpreterState *}\member{interp},
4683which points to this thread's interpreter state.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004684\end{ctypedesc}
4685
4686\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
4687Initialize and acquire the global interpreter lock. It should be
4688called in the main thread before creating a second thread or engaging
Fred Drakee058b4f1998-02-16 06:15:35 +00004689in any other thread operations such as
Fred Drake659ebfa2000-04-03 15:42:13 +00004690\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
4691\code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
4692It is not needed before calling
4693\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
4694\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004695
4696This is a no-op when called for a second time. It is safe to call
Fred Drake659ebfa2000-04-03 15:42:13 +00004697this function before calling
4698\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004699
4700When only the main thread exists, no lock operations are needed. This
4701is a common situation (most Python programs do not use threads), and
4702the lock operations slow the interpreter down a bit. Therefore, the
4703lock is not created initially. This situation is equivalent to having
4704acquired the lock: when there is only a single thread, all object
4705accesses are safe. Therefore, when this function initializes the
Fred Drake4de05a91998-02-16 14:25:26 +00004706lock, it also acquires it. Before the Python
4707\module{thread}\refbimodindex{thread} module creates a new thread,
4708knowing that either it has the lock or the lock hasn't been created
4709yet, it calls \cfunction{PyEval_InitThreads()}. When this call
4710returns, it is guaranteed that the lock has been created and that it
4711has acquired it.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004712
4713It is \strong{not} safe to call this function when it is unknown which
4714thread (if any) currently has the global interpreter lock.
4715
4716This function is not available when thread support is disabled at
4717compile time.
4718\end{cfuncdesc}
4719
Guido van Rossum4a944d71997-08-14 20:35:38 +00004720\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004721Acquire the global interpreter lock. The lock must have been created
4722earlier. If this thread already has the lock, a deadlock ensues.
4723This function is not available when thread support is disabled at
4724compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004725\end{cfuncdesc}
4726
4727\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004728Release the global interpreter lock. The lock must have been created
4729earlier. This function is not available when thread support is
Fred Drakee058b4f1998-02-16 06:15:35 +00004730disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004731\end{cfuncdesc}
4732
4733\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004734Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004735state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004736have been created earlier. If this thread already has the lock,
4737deadlock ensues. This function is not available when thread support
Fred Drakee058b4f1998-02-16 06:15:35 +00004738is disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004739\end{cfuncdesc}
4740
4741\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004742Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004743interpreter lock. The lock must have been created earlier and must be
4744held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004745be \NULL{}, is only used to check that it represents the current
Fred Drakee058b4f1998-02-16 06:15:35 +00004746thread state --- if it isn't, a fatal error is reported. This
4747function is not available when thread support is disabled at compile
4748time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004749\end{cfuncdesc}
4750
Fred Drakec6fa34e1998-04-02 06:47:24 +00004751\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004752Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004753support is enabled) and reset the thread state to \NULL{},
4754returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004755the lock has been created, the current thread must have acquired it.
4756(This function is available even when thread support is disabled at
4757compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004758\end{cfuncdesc}
4759
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004760\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004761Acquire the interpreter lock (if it has been created and thread
4762support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004763must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004764thread must not have acquired it, otherwise deadlock ensues. (This
4765function is available even when thread support is disabled at compile
4766time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004767\end{cfuncdesc}
4768
Fred Drake659ebfa2000-04-03 15:42:13 +00004769The following macros are normally used without a trailing semicolon;
4770look for example usage in the Python source distribution.
4771
4772\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004773This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004774\samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004775Note that it contains an opening brace; it must be matched with a
4776following \code{Py_END_ALLOW_THREADS} macro. See above for further
4777discussion of this macro. It is a no-op when thread support is
4778disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004779\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004780
Fred Drake659ebfa2000-04-03 15:42:13 +00004781\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004782This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004783\samp{PyEval_RestoreThread(_save); \}}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004784Note that it contains a closing brace; it must be matched with an
4785earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
4786discussion of this macro. It is a no-op when thread support is
4787disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004788\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004789
Thomas Wouterse30ac572001-07-09 14:35:01 +00004790\begin{csimplemacrodesc}{Py_BLOCK_THREADS}
Fred Drakebab29652001-07-10 16:10:08 +00004791This macro expands to \samp{PyEval_RestoreThread(_save);}: it
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004792is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
4793brace. It is a no-op when thread support is disabled at compile
4794time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004795\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004796
Thomas Wouterse30ac572001-07-09 14:35:01 +00004797\begin{csimplemacrodesc}{Py_UNBLOCK_THREADS}
Fred Drakebab29652001-07-10 16:10:08 +00004798This macro expands to \samp{_save = PyEval_SaveThread();}: it is
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004799equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
4800and variable declaration. It is a no-op when thread support is
4801disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004802\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004803
4804All of the following functions are only available when thread support
4805is enabled at compile time, and must be called only when the
Fred Drake9d20ac31998-02-16 15:27:08 +00004806interpreter lock has been created.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004807
Fred Drakec6fa34e1998-04-02 06:47:24 +00004808\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004809Create a new interpreter state object. The interpreter lock need not
4810be held, but may be held if it is necessary to serialize calls to this
4811function.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004812\end{cfuncdesc}
4813
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004814\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
4815Reset all information in an interpreter state object. The interpreter
4816lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004817\end{cfuncdesc}
4818
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004819\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
4820Destroy an interpreter state object. The interpreter lock need not be
4821held. The interpreter state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004822call to \cfunction{PyInterpreterState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004823\end{cfuncdesc}
4824
Fred Drakec6fa34e1998-04-02 06:47:24 +00004825\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004826Create a new thread state object belonging to the given interpreter
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004827object. The interpreter lock need not be held, but may be held if it
4828is necessary to serialize calls to this function.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004829\end{cfuncdesc}
4830
4831\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
4832Reset all information in a thread state object. The interpreter lock
4833must be held.
4834\end{cfuncdesc}
4835
4836\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
4837Destroy a thread state object. The interpreter lock need not be
4838held. The thread state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004839call to \cfunction{PyThreadState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004840\end{cfuncdesc}
4841
Fred Drakec6fa34e1998-04-02 06:47:24 +00004842\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004843Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004844When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004845error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004846\end{cfuncdesc}
4847
Fred Drakec6fa34e1998-04-02 06:47:24 +00004848\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004849Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004850argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004851must be held.
4852\end{cfuncdesc}
4853
Fred Drake24e62192001-05-21 15:56:55 +00004854\begin{cfuncdesc}{PyObject*}{PyThreadState_GetDict}{}
4855Return a dictionary in which extensions can store thread-specific
4856state information. Each extension should use a unique key to use to
4857store state in the dictionary. If this function returns \NULL, an
4858exception has been raised and the caller should allow it to
4859propogate.
4860\end{cfuncdesc}
4861
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004862
Fred Drake68db7302001-07-17 19:48:30 +00004863\section{Profiling and Tracing \label{profiling}}
4864
4865\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
4866
4867The Python interpreter provides some low-level support for attaching
4868profiling and execution tracing facilities. These are used for
4869profiling, debugging, and coverage analysis tools.
4870
4871Starting with Python 2.2, the implementation of this facility was
4872substantially revised, and an interface from C was added. This C
4873interface allows the profiling or tracing code to avoid the overhead
4874of calling through Python-level callable objects, making a direct C
4875function call instead. The essential attributes of the facility have
4876not changed; the interface allows trace functions to be installed
4877per-thread, and the basic events reported to the trace function are
4878the same as had been reported to the Python-level trace functions in
4879previous versions.
4880
4881\begin{ctypedesc}[Py_tracefunc]{int (*Py_tracefunc)(PyObject *obj,
4882 PyFrameObject *frame, int what,
4883 PyObject *arg)}
4884 The type of the trace function registered using
4885 \cfunction{PyEval_SetProfile()} and \cfunction{PyEval_SetTrace()}.
4886 The first parameter is the object passed to the registration
4887 function,
4888\end{ctypedesc}
4889
4890\begin{cvardesc}{int}{PyTrace_CALL}
4891 The value of the \var{what} parameter to a \ctype{Py_tracefunc}
4892 function when a new function or method call is being reported.
4893\end{cvardesc}
4894
4895\begin{cvardesc}{int}{PyTrace_EXCEPT}
4896\end{cvardesc}
4897
4898\begin{cvardesc}{int}{PyTrace_LINE}
4899 The value passed as the \var{what} parameter to a trace function
4900 (but not a profiling function) when a line-number event is being
4901 reported.
4902\end{cvardesc}
4903
4904\begin{cvardesc}{int}{PyTrace_RETURN}
4905 The value for the \var{what} parameter to \ctype{Py_tracefunc}
4906 functions when a call is returning without propogating an exception.
4907\end{cvardesc}
4908
4909\begin{cfuncdesc}{void}{PyEval_SetProfile}{Py_tracefunc func, PyObject *obj}
Fred Drakef90490e2001-08-02 18:00:28 +00004910 Set the profiler function to \var{func}. The \var{obj} parameter is
4911 passed to the function as its first parameter, and may be any Python
4912 object, or \NULL. If the profile function needs to maintain state,
4913 using a different value for \var{obj} for each thread provides a
4914 convenient and thread-safe place to store it. The profile function
4915 is called for all monitored events except the line-number events.
Fred Drake68db7302001-07-17 19:48:30 +00004916\end{cfuncdesc}
4917
4918\begin{cfuncdesc}{void}{PyEval_SetTrace}{Py_tracefunc func, PyObject *obj}
Fred Drakef90490e2001-08-02 18:00:28 +00004919 Set the the tracing function to \var{func}. This is similar to
4920 \cfunction{PyEval_SetProfile()}, except the tracing function does
4921 receive line-number events.
Fred Drake68db7302001-07-17 19:48:30 +00004922\end{cfuncdesc}
4923
4924
Fred Drake01978582001-08-08 19:14:53 +00004925\section{Advanced Debugger Support \label{advanced-debugging}}
4926\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
4927
4928These functions are only intended to be used by advanced debugging
4929tools.
4930
4931\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Head}{}
4932Return the interpreter state object at the head of the list of all
4933such objects.
4934\versionadded{2.2}
4935\end{cfuncdesc}
4936
4937\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Next}{PyInterpreterState *interp}
4938Return the next interpreter state object after \var{interp} from the
4939list of all such objects.
4940\versionadded{2.2}
4941\end{cfuncdesc}
4942
4943\begin{cfuncdesc}{PyThreadState *}{PyInterpreterState_ThreadHead}{PyInterpreterState *interp}
4944Return the a pointer to the first \ctype{PyThreadState} object in the
4945list of threads associated with the interpreter \var{interp}.
4946\versionadded{2.2}
4947\end{cfuncdesc}
4948
4949\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Next}{PyThreadState *tstate}
4950Return the next thread state object after \var{tstate} from the list
4951of all such objects belonging to the same \ctype{PyInterpreterState}
4952object.
4953\versionadded{2.2}
4954\end{cfuncdesc}
4955
4956
Fred Drake659ebfa2000-04-03 15:42:13 +00004957\chapter{Memory Management \label{memory}}
4958\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
4959
4960
4961\section{Overview \label{memoryOverview}}
4962
4963Memory management in Python involves a private heap containing all
4964Python objects and data structures. The management of this private
4965heap is ensured internally by the \emph{Python memory manager}. The
4966Python memory manager has different components which deal with various
4967dynamic storage management aspects, like sharing, segmentation,
4968preallocation or caching.
4969
4970At the lowest level, a raw memory allocator ensures that there is
4971enough room in the private heap for storing all Python-related data
4972by interacting with the memory manager of the operating system. On top
4973of the raw memory allocator, several object-specific allocators
4974operate on the same heap and implement distinct memory management
4975policies adapted to the peculiarities of every object type. For
4976example, integer objects are managed differently within the heap than
4977strings, tuples or dictionaries because integers imply different
4978storage requirements and speed/space tradeoffs. The Python memory
4979manager thus delegates some of the work to the object-specific
4980allocators, but ensures that the latter operate within the bounds of
4981the private heap.
4982
4983It is important to understand that the management of the Python heap
4984is performed by the interpreter itself and that the user has no
4985control on it, even if she regularly manipulates object pointers to
4986memory blocks inside that heap. The allocation of heap space for
4987Python objects and other internal buffers is performed on demand by
4988the Python memory manager through the Python/C API functions listed in
4989this document.
4990
4991To avoid memory corruption, extension writers should never try to
4992operate on Python objects with the functions exported by the C
4993library: \cfunction{malloc()}\ttindex{malloc()},
4994\cfunction{calloc()}\ttindex{calloc()},
4995\cfunction{realloc()}\ttindex{realloc()} and
4996\cfunction{free()}\ttindex{free()}. This will result in
4997mixed calls between the C allocator and the Python memory manager
4998with fatal consequences, because they implement different algorithms
4999and operate on different heaps. However, one may safely allocate and
5000release memory blocks with the C library allocator for individual
5001purposes, as shown in the following example:
5002
5003\begin{verbatim}
5004 PyObject *res;
5005 char *buf = (char *) malloc(BUFSIZ); /* for I/O */
5006
5007 if (buf == NULL)
5008 return PyErr_NoMemory();
5009 ...Do some I/O operation involving buf...
5010 res = PyString_FromString(buf);
5011 free(buf); /* malloc'ed */
5012 return res;
5013\end{verbatim}
5014
5015In this example, the memory request for the I/O buffer is handled by
5016the C library allocator. The Python memory manager is involved only
5017in the allocation of the string object returned as a result.
5018
5019In most situations, however, it is recommended to allocate memory from
5020the Python heap specifically because the latter is under control of
5021the Python memory manager. For example, this is required when the
5022interpreter is extended with new object types written in C. Another
5023reason for using the Python heap is the desire to \emph{inform} the
5024Python memory manager about the memory needs of the extension module.
5025Even when the requested memory is used exclusively for internal,
5026highly-specific purposes, delegating all memory requests to the Python
5027memory manager causes the interpreter to have a more accurate image of
5028its memory footprint as a whole. Consequently, under certain
5029circumstances, the Python memory manager may or may not trigger
5030appropriate actions, like garbage collection, memory compaction or
5031other preventive procedures. Note that by using the C library
5032allocator as shown in the previous example, the allocated memory for
5033the I/O buffer escapes completely the Python memory manager.
5034
5035
5036\section{Memory Interface \label{memoryInterface}}
5037
5038The following function sets, modeled after the ANSI C standard, are
5039available for allocating and releasing memory from the Python heap:
5040
5041
Fred Drake7d45d342000-08-11 17:07:32 +00005042\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
5043Allocates \var{n} bytes and returns a pointer of type \ctype{void*} to
Fred Drakebab29652001-07-10 16:10:08 +00005044the allocated memory, or \NULL{} if the request fails. Requesting zero
Fred Drake659ebfa2000-04-03 15:42:13 +00005045bytes returns a non-\NULL{} pointer.
Fred Drakebab29652001-07-10 16:10:08 +00005046The memory will not have been initialized in any way.
Fred Drake659ebfa2000-04-03 15:42:13 +00005047\end{cfuncdesc}
5048
Fred Drake7d45d342000-08-11 17:07:32 +00005049\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00005050Resizes the memory block pointed to by \var{p} to \var{n} bytes. The
5051contents will be unchanged to the minimum of the old and the new
5052sizes. If \var{p} is \NULL{}, the call is equivalent to
Fred Drakebab29652001-07-10 16:10:08 +00005053\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the
5054memory block is resized but is not freed, and the returned pointer is
5055non-\NULL{}. Unless \var{p} is \NULL{}, it must have been returned by
5056a previous call to \cfunction{PyMem_Malloc()} or
5057\cfunction{PyMem_Realloc()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00005058\end{cfuncdesc}
5059
Fred Drake7d45d342000-08-11 17:07:32 +00005060\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00005061Frees the memory block pointed to by \var{p}, which must have been
5062returned by a previous call to \cfunction{PyMem_Malloc()} or
5063\cfunction{PyMem_Realloc()}. Otherwise, or if
5064\cfunction{PyMem_Free(p)} has been called before, undefined behaviour
5065occurs. If \var{p} is \NULL{}, no operation is performed.
5066\end{cfuncdesc}
5067
Fred Drake659ebfa2000-04-03 15:42:13 +00005068The following type-oriented macros are provided for convenience. Note
5069that \var{TYPE} refers to any C type.
5070
Fred Drakef913e542000-09-12 20:17:17 +00005071\begin{cfuncdesc}{\var{TYPE}*}{PyMem_New}{TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00005072Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
5073sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
5074\ctype{\var{TYPE}*}.
Fred Drakebab29652001-07-10 16:10:08 +00005075The memory will not have been initialized in any way.
Fred Drake659ebfa2000-04-03 15:42:13 +00005076\end{cfuncdesc}
5077
Fred Drakef913e542000-09-12 20:17:17 +00005078\begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00005079Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
5080to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
5081cast to \ctype{\var{TYPE}*}.
5082\end{cfuncdesc}
5083
Fred Drakef913e542000-09-12 20:17:17 +00005084\begin{cfuncdesc}{void}{PyMem_Del}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00005085Same as \cfunction{PyMem_Free()}.
5086\end{cfuncdesc}
5087
Fred Drakef913e542000-09-12 20:17:17 +00005088In addition, the following macro sets are provided for calling the
5089Python memory allocator directly, without involving the C API functions
5090listed above. However, note that their use does not preserve binary
5091compatibility accross Python versions and is therefore deprecated in
5092extension modules.
5093
5094\cfunction{PyMem_MALLOC()}, \cfunction{PyMem_REALLOC()}, \cfunction{PyMem_FREE()}.
5095
5096\cfunction{PyMem_NEW()}, \cfunction{PyMem_RESIZE()}, \cfunction{PyMem_DEL()}.
5097
Fred Drake659ebfa2000-04-03 15:42:13 +00005098
5099\section{Examples \label{memoryExamples}}
5100
5101Here is the example from section \ref{memoryOverview}, rewritten so
5102that the I/O buffer is allocated from the Python heap by using the
5103first function set:
5104
5105\begin{verbatim}
5106 PyObject *res;
5107 char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
5108
5109 if (buf == NULL)
5110 return PyErr_NoMemory();
5111 /* ...Do some I/O operation involving buf... */
5112 res = PyString_FromString(buf);
5113 PyMem_Free(buf); /* allocated with PyMem_Malloc */
5114 return res;
5115\end{verbatim}
5116
Fred Drakef913e542000-09-12 20:17:17 +00005117The same code using the type-oriented function set:
Fred Drake659ebfa2000-04-03 15:42:13 +00005118
5119\begin{verbatim}
5120 PyObject *res;
Fred Drakef913e542000-09-12 20:17:17 +00005121 char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
Fred Drake659ebfa2000-04-03 15:42:13 +00005122
5123 if (buf == NULL)
5124 return PyErr_NoMemory();
5125 /* ...Do some I/O operation involving buf... */
5126 res = PyString_FromString(buf);
Fred Drakef913e542000-09-12 20:17:17 +00005127 PyMem_Del(buf); /* allocated with PyMem_New */
Fred Drake659ebfa2000-04-03 15:42:13 +00005128 return res;
5129\end{verbatim}
5130
Fred Drakef913e542000-09-12 20:17:17 +00005131Note that in the two examples above, the buffer is always
5132manipulated via functions belonging to the same set. Indeed, it
Fred Drake659ebfa2000-04-03 15:42:13 +00005133is required to use the same memory API family for a given
5134memory block, so that the risk of mixing different allocators is
5135reduced to a minimum. The following code sequence contains two errors,
5136one of which is labeled as \emph{fatal} because it mixes two different
5137allocators operating on different heaps.
5138
5139\begin{verbatim}
Fred Drakef913e542000-09-12 20:17:17 +00005140char *buf1 = PyMem_New(char, BUFSIZ);
Fred Drake659ebfa2000-04-03 15:42:13 +00005141char *buf2 = (char *) malloc(BUFSIZ);
5142char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
5143...
Fred Drakef913e542000-09-12 20:17:17 +00005144PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
Fred Drake659ebfa2000-04-03 15:42:13 +00005145free(buf2); /* Right -- allocated via malloc() */
Fred Drakef913e542000-09-12 20:17:17 +00005146free(buf1); /* Fatal -- should be PyMem_Del() */
Fred Drake659ebfa2000-04-03 15:42:13 +00005147\end{verbatim}
5148
5149In addition to the functions aimed at handling raw memory blocks from
5150the Python heap, objects in Python are allocated and released with
Fred Drakef913e542000-09-12 20:17:17 +00005151\cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()} and
5152\cfunction{PyObject_Del()}, or with their corresponding macros
5153\cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()} and
Fred Drakee06f0f92000-06-30 15:52:39 +00005154\cfunction{PyObject_DEL()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00005155
Fred Drakee06f0f92000-06-30 15:52:39 +00005156These will be explained in the next chapter on defining and
5157implementing new object types in C.
Fred Drake659ebfa2000-04-03 15:42:13 +00005158
5159
Fred Drakeefd146c1999-02-15 15:30:45 +00005160\chapter{Defining New Object Types \label{newTypes}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00005161
Fred Drake88fdaa72001-07-20 20:56:11 +00005162
5163\section{Allocating Objects on the Heap
5164 \label{allocating-objects}}
5165
Fred Drakec6fa34e1998-04-02 06:47:24 +00005166\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00005167\end{cfuncdesc}
5168
Fred Drakef913e542000-09-12 20:17:17 +00005169\begin{cfuncdesc}{PyVarObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00005170\end{cfuncdesc}
5171
Fred Drakef913e542000-09-12 20:17:17 +00005172\begin{cfuncdesc}{void}{_PyObject_Del}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00005173\end{cfuncdesc}
5174
Fred Drakef913e542000-09-12 20:17:17 +00005175\begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op,
Fred Drakebab29652001-07-10 16:10:08 +00005176 PyTypeObject *type}
5177 Initialize a newly-allocated object \var{op} with its type and
5178 initial reference. Returns the initialized object. If \var{type}
5179 indicates that the object participates in the cyclic garbage
5180 detector, it it added to the detector's set of observed objects.
5181 Other fields of the object are not affected.
Fred Drakef913e542000-09-12 20:17:17 +00005182\end{cfuncdesc}
5183
5184\begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op,
Fred Drakebab29652001-07-10 16:10:08 +00005185 PyTypeObject *type, int size}
5186 This does everything \cfunction{PyObject_Init()} does, and also
5187 initializes the length information for a variable-size object.
Fred Drakef913e542000-09-12 20:17:17 +00005188\end{cfuncdesc}
5189
5190\begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type}
Fred Drakebab29652001-07-10 16:10:08 +00005191 Allocate a new Python object using the C structure type \var{TYPE}
5192 and the Python type object \var{type}. Fields not defined by the
5193 Python object header are not initialized; the object's reference
5194 count will be one. The size of the memory
5195 allocation is determined from the \member{tp_basicsize} field of the
5196 type object.
Fred Drakef913e542000-09-12 20:17:17 +00005197\end{cfuncdesc}
5198
5199\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type,
5200 int size}
Fred Drakebab29652001-07-10 16:10:08 +00005201 Allocate a new Python object using the C structure type \var{TYPE}
5202 and the Python type object \var{type}. Fields not defined by the
5203 Python object header are not initialized. The allocated memory
5204 allows for the \var{TYPE} structure plus \var{size} fields of the
5205 size given by the \member{tp_itemsize} field of \var{type}. This is
5206 useful for implementing objects like tuples, which are able to
5207 determine their size at construction time. Embedding the array of
5208 fields into the same allocation decreases the number of allocations,
5209 improving the memory management efficiency.
Fred Drakef913e542000-09-12 20:17:17 +00005210\end{cfuncdesc}
5211
5212\begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op}
Fred Drakebab29652001-07-10 16:10:08 +00005213 Releases memory allocated to an object using
5214 \cfunction{PyObject_New()} or \cfunction{PyObject_NewVar()}. This
5215 is normally called from the \member{tp_dealloc} handler specified in
5216 the object's type. The fields of the object should not be accessed
5217 after this call as the memory is no longer a valid Python object.
Fred Drakef913e542000-09-12 20:17:17 +00005218\end{cfuncdesc}
5219
5220\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW}{TYPE, PyTypeObject *type}
Fred Drakebab29652001-07-10 16:10:08 +00005221 Macro version of \cfunction{PyObject_New()}, to gain performance at
5222 the expense of safety. This does not check \var{type} for a \NULL{}
5223 value.
Fred Drakef913e542000-09-12 20:17:17 +00005224\end{cfuncdesc}
5225
5226\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
5227 int size}
Fred Drakebab29652001-07-10 16:10:08 +00005228 Macro version of \cfunction{PyObject_NewVar()}, to gain performance
5229 at the expense of safety. This does not check \var{type} for a
5230 \NULL{} value.
Fred Drakef913e542000-09-12 20:17:17 +00005231\end{cfuncdesc}
5232
5233\begin{cfuncdesc}{void}{PyObject_DEL}{PyObject *op}
Fred Drakebab29652001-07-10 16:10:08 +00005234 Macro version of \cfunction{PyObject_Del()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00005235\end{cfuncdesc}
5236
Fred Drakeee814bf2000-11-28 22:34:32 +00005237\begin{cfuncdesc}{PyObject*}{Py_InitModule}{char *name,
5238 PyMethodDef *methods}
5239 Create a new module object based on a name and table of functions,
5240 returning the new module object.
5241\end{cfuncdesc}
5242
5243\begin{cfuncdesc}{PyObject*}{Py_InitModule3}{char *name,
5244 PyMethodDef *methods,
5245 char *doc}
5246 Create a new module object based on a name and table of functions,
5247 returning the new module object. If \var{doc} is non-\NULL, it will
5248 be used to define the docstring for the module.
5249\end{cfuncdesc}
5250
5251\begin{cfuncdesc}{PyObject*}{Py_InitModule4}{char *name,
5252 PyMethodDef *methods,
5253 char *doc, PyObject *self,
5254 int apiver}
5255 Create a new module object based on a name and table of functions,
5256 returning the new module object. If \var{doc} is non-\NULL, it will
5257 be used to define the docstring for the module. If \var{self} is
5258 non-\NULL, it will passed to the functions of the module as their
5259 (otherwise \NULL) first parameter. (This was added as an
5260 experimental feature, and there are no known uses in the current
5261 version of Python.) For \var{apiver}, the only value which should
5262 be passed is defined by the constant \constant{PYTHON_API_VERSION}.
5263
5264 \strong{Note:} Most uses of this function should probably be using
5265 the \cfunction{Py_InitModule3()} instead; only use this if you are
5266 sure you need it.
5267\end{cfuncdesc}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00005268
Fred Drake659ebfa2000-04-03 15:42:13 +00005269DL_IMPORT
5270
Fred Drakebab29652001-07-10 16:10:08 +00005271\begin{cvardesc}{PyObject}{_Py_NoneStruct}
5272 Object which is visible in Python as \code{None}. This should only
5273 be accessed using the \code{Py_None} macro, which evaluates to a
5274 pointer to this object.
5275\end{cvardesc}
Fred Drake659ebfa2000-04-03 15:42:13 +00005276
5277
5278\section{Common Object Structures \label{common-structs}}
5279
Guido van Rossumae110af1997-05-22 20:11:52 +00005280PyObject, PyVarObject
5281
5282PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
5283
5284Typedefs:
5285unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
5286intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
Guido van Rossumae110af1997-05-22 20:11:52 +00005287destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
5288setattrofunc, cmpfunc, reprfunc, hashfunc
5289
Fred Drakea8455ab2000-06-16 19:58:42 +00005290\begin{ctypedesc}{PyCFunction}
5291Type of the functions used to implement most Python callables in C.
5292\end{ctypedesc}
5293
5294\begin{ctypedesc}{PyMethodDef}
5295Structure used to describe a method of an extension type. This
5296structure has four fields:
5297
5298\begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
5299 \lineiii{ml_name}{char *}{name of the method}
5300 \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
5301 \lineiii{ml_flags}{int}{flag bits indicating how the call should be
5302 constructed}
5303 \lineiii{ml_doc}{char *}{points to the contents of the docstring}
5304\end{tableiii}
5305\end{ctypedesc}
5306
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00005307The \var{ml_meth} is a C function pointer. The functions may be of
5308different types, but they always return \ctype{PyObject*}. If the
5309function is not of the \ctype{PyCFunction}, the compiler will require
5310a cast in the method table. Even though \ctype{PyCFunction} defines
5311the first parameter as \ctype{PyObject*}, it is common that the method
5312implementation uses a the specific C type of the \var{self} object.
5313
5314The flags can have the following values. Only METH_VARARGS and
5315METH_KEYWORDS can be combined; the others can't.
5316
5317\begin{datadesc}{METH_VARARGS}
5318
5319This is the typical calling convention, where the methods have the
5320type \ctype{PyMethodDef}. The function expects two \ctype{PyObject*}.
5321The first one is the \var{self} object for methods; for module
5322functions, it has the value given to \cfunction{PyInitModule4} (or
5323\NULL{} if \cfunction{PyInitModule} was used). The second parameter
5324(often called \var{args}) is a tuple object representing all
5325arguments. This parameter is typically processed using
5326\cfunction{PyArg_ParseTuple}.
5327
5328\end{datadesc}
5329
5330\begin{datadesc}{METH_KEYWORDS}
5331
5332Methods with these flags must be of type
5333\ctype{PyCFunctionWithKeywords}. The function expects three
5334parameters: \var{self}, \var{args}, and a dictionary of all the keyword
5335arguments. The flag is typically combined with METH_VARARGS, and the
5336parameters are typically processed using
5337\cfunction{PyArg_ParseTupleAndKeywords}.
5338
5339\end{datadesc}
5340
5341\begin{datadesc}{METH_NOARGS}
5342
5343Methods without parameters don't need to check whether arguments are
5344given if they are listed with the \code{METH_NOARGS} flag. They need
5345to be of type \ctype{PyNoArgsFunction}, i.e. they expect a single
5346\var{self} parameter.
5347
5348\end{datadesc}
5349
5350\begin{datadesc}{METH_O}
5351
5352Methods with a single object argument can be listed with the
5353\code{METH_O} flag, instead of invoking \cfunction{PyArg_ParseTuple}
5354with a \code{``O''} argument. They have the type \ctype{PyCFunction},
5355with the \var{self} parameter, and a \ctype{PyObject*} parameter
5356representing the single argument.
5357
5358\end{datadesc}
5359
5360\begin{datadesc}{METH_OLDARGS}
5361
5362This calling convention is deprecated. The method must be of type
5363\ctype{PyCFunction}. The second argument is \NULL{} if no arguments
5364are given, a single object if exactly one argument is given, and a
5365tuple of objects if more than one argument is given.
5366
5367\end{datadesc}
5368
Fred Drakea8455ab2000-06-16 19:58:42 +00005369\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef[] table,
5370 PyObject *ob, char *name}
5371Return a bound method object for an extension type implemented in C.
5372This function also handles the special attribute \member{__methods__},
5373returning a list of all the method names defined in \var{table}.
5374\end{cfuncdesc}
5375
Fred Drake659ebfa2000-04-03 15:42:13 +00005376
5377\section{Mapping Object Structures \label{mapping-structs}}
5378
5379\begin{ctypedesc}{PyMappingMethods}
5380Structure used to hold pointers to the functions used to implement the
5381mapping protocol for an extension type.
5382\end{ctypedesc}
5383
5384
5385\section{Number Object Structures \label{number-structs}}
5386
5387\begin{ctypedesc}{PyNumberMethods}
5388Structure used to hold pointers to the functions an extension type
5389uses to implement the number protocol.
5390\end{ctypedesc}
5391
5392
5393\section{Sequence Object Structures \label{sequence-structs}}
5394
5395\begin{ctypedesc}{PySequenceMethods}
5396Structure used to hold pointers to the functions which an object uses
5397to implement the sequence protocol.
5398\end{ctypedesc}
5399
5400
5401\section{Buffer Object Structures \label{buffer-structs}}
5402\sectionauthor{Greg J. Stein}{greg@lyra.org}
5403
5404The buffer interface exports a model where an object can expose its
5405internal data as a set of chunks of data, where each chunk is
5406specified as a pointer/length pair. These chunks are called
5407\dfn{segments} and are presumed to be non-contiguous in memory.
5408
5409If an object does not export the buffer interface, then its
5410\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
5411should be \NULL{}. Otherwise, the \member{tp_as_buffer} will point to
5412a \ctype{PyBufferProcs} structure.
5413
5414\strong{Note:} It is very important that your
Fred Drakec392b572001-03-21 22:15:01 +00005415\ctype{PyTypeObject} structure uses \constant{Py_TPFLAGS_DEFAULT} for
5416the value of the \member{tp_flags} member rather than \code{0}. This
Fred Drake659ebfa2000-04-03 15:42:13 +00005417tells the Python runtime that your \ctype{PyBufferProcs} structure
5418contains the \member{bf_getcharbuffer} slot. Older versions of Python
5419did not have this member, so a new Python interpreter using an old
5420extension needs to be able to test for its presence before using it.
5421
5422\begin{ctypedesc}{PyBufferProcs}
5423Structure used to hold the function pointers which define an
5424implementation of the buffer protocol.
5425
5426The first slot is \member{bf_getreadbuffer}, of type
5427\ctype{getreadbufferproc}. If this slot is \NULL{}, then the object
5428does not support reading from the internal data. This is
5429non-sensical, so implementors should fill this in, but callers should
5430test that the slot contains a non-\NULL{} value.
5431
5432The next slot is \member{bf_getwritebuffer} having type
5433\ctype{getwritebufferproc}. This slot may be \NULL{} if the object
5434does not allow writing into its returned buffers.
5435
5436The third slot is \member{bf_getsegcount}, with type
5437\ctype{getsegcountproc}. This slot must not be \NULL{} and is used to
5438inform the caller how many segments the object contains. Simple
5439objects such as \ctype{PyString_Type} and
5440\ctype{PyBuffer_Type} objects contain a single segment.
5441
5442The last slot is \member{bf_getcharbuffer}, of type
5443\ctype{getcharbufferproc}. This slot will only be present if the
Fred Drakec392b572001-03-21 22:15:01 +00005444\constant{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
Fred Drake659ebfa2000-04-03 15:42:13 +00005445\member{tp_flags} field of the object's \ctype{PyTypeObject}. Before using
5446this slot, the caller should test whether it is present by using the
5447\cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()} function.
5448If present, it may be \NULL, indicating that the object's contents
5449cannot be used as \emph{8-bit characters}.
5450The slot function may also raise an error if the object's contents
5451cannot be interpreted as 8-bit characters. For example, if the object
5452is an array which is configured to hold floating point values, an
5453exception may be raised if a caller attempts to use
5454\member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
5455This notion of exporting the internal buffers as ``text'' is used to
5456distinguish between objects that are binary in nature, and those which
5457have character-based content.
5458
5459\strong{Note:} The current policy seems to state that these characters
5460may be multi-byte characters. This implies that a buffer size of
5461\var{N} does not mean there are \var{N} characters present.
5462\end{ctypedesc}
5463
5464\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
5465Flag bit set in the type structure to indicate that the
5466\member{bf_getcharbuffer} slot is known. This being set does not
5467indicate that the object supports the buffer interface or that the
5468\member{bf_getcharbuffer} slot is non-\NULL.
5469\end{datadesc}
5470
5471\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
5472 (PyObject *self, int segment, void **ptrptr)}
5473Return a pointer to a readable segment of the buffer. This function
5474is allowed to raise an exception, in which case it must return
5475\code{-1}. The \var{segment} which is passed must be zero or
5476positive, and strictly less than the number of segments returned by
Greg Stein4d4d0032001-04-07 16:14:49 +00005477the \member{bf_getsegcount} slot function. On success, it returns the
5478length of the buffer memory, and sets \code{*\var{ptrptr}} to a
5479pointer to that memory.
Fred Drake659ebfa2000-04-03 15:42:13 +00005480\end{ctypedesc}
5481
5482\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
5483 (PyObject *self, int segment, void **ptrptr)}
Greg Stein4d4d0032001-04-07 16:14:49 +00005484Return a pointer to a writable memory buffer in \code{*\var{ptrptr}},
5485and the length of that segment as the function return value.
5486The memory buffer must correspond to buffer segment \var{segment}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00005487Must return \code{-1} and set an exception on error.
5488\exception{TypeError} should be raised if the object only supports
5489read-only buffers, and \exception{SystemError} should be raised when
5490\var{segment} specifies a segment that doesn't exist.
5491% Why doesn't it raise ValueError for this one?
Fred Drake659ebfa2000-04-03 15:42:13 +00005492% GJS: because you shouldn't be calling it with an invalid
5493% segment. That indicates a blatant programming error in the C
5494% code.
Fred Drake58c5a2a1999-08-04 13:13:24 +00005495\end{ctypedesc}
5496
Fred Drake659ebfa2000-04-03 15:42:13 +00005497\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
5498 (PyObject *self, int *lenp)}
5499Return the number of memory segments which comprise the buffer. If
5500\var{lenp} is not \NULL, the implementation must report the sum of the
5501sizes (in bytes) of all segments in \code{*\var{lenp}}.
5502The function cannot fail.
5503\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00005504
Fred Drake659ebfa2000-04-03 15:42:13 +00005505\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
5506 (PyObject *self, int segment, const char **ptrptr)}
5507\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00005508
Guido van Rossumae110af1997-05-22 20:11:52 +00005509
Fred Drakef90490e2001-08-02 18:00:28 +00005510\section{Supporting the Iterator Protocol
5511 \label{supporting-iteration}}
5512
5513
Fred Drakec392b572001-03-21 22:15:01 +00005514\section{Supporting Cyclic Garbarge Collection
5515 \label{supporting-cycle-detection}}
5516
5517Python's support for detecting and collecting garbage which involves
5518circular references requires support from object types which are
5519``containers'' for other objects which may also be containers. Types
5520which do not store references to other objects, or which only store
5521references to atomic types (such as numbers or strings), do not need
5522to provide any explicit support for garbage collection.
5523
5524To create a container type, the \member{tp_flags} field of the type
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005525object must include the \constant{Py_TPFLAGS_HAVE_GC} and provide an
5526implementation of the \member{tp_traverse} handler. If instances of the
5527type are mutable, a \member{tp_clear} implementation must also be
5528provided.
Fred Drakec392b572001-03-21 22:15:01 +00005529
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005530\begin{datadesc}{Py_TPFLAGS_HAVE_GC}
Fred Drakec392b572001-03-21 22:15:01 +00005531 Objects with a type with this flag set must conform with the rules
5532 documented here. For convenience these objects will be referred to
5533 as container objects.
5534\end{datadesc}
5535
Fred Drakee28d8ae2001-03-22 16:30:17 +00005536Constructors for container types must conform to two rules:
5537
5538\begin{enumerate}
5539\item The memory for the object must be allocated using
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005540 \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_VarNew()}.
Fred Drakee28d8ae2001-03-22 16:30:17 +00005541
5542\item Once all the fields which may contain references to other
5543 containers are initialized, it must call
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005544 \cfunction{PyObject_GC_Track()}.
Fred Drakee28d8ae2001-03-22 16:30:17 +00005545\end{enumerate}
5546
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005547\begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_New}{TYPE, PyTypeObject *type}
5548 Analogous to \cfunction{PyObject_New()} but for container objects with
5549 the \constant{Py_TPFLAGS_HAVE_GC} flag set.
5550\end{cfuncdesc}
5551
5552\begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_NewVar}{TYPE, PyTypeObject *type,
5553 int size}
5554 Analogous to \cfunction{PyObject_NewVar()} but for container objects
5555 with the \constant{Py_TPFLAGS_HAVE_GC} flag set.
5556\end{cfuncdesc}
5557
5558\begin{cfuncdesc}{PyVarObject *}{PyObject_GC_Resize}{PyVarObject *op, int}
5559 Resize an object allocated by \cfunction{PyObject_NewVar()}. Returns
5560 the resized object or \NULL{} on failure.
5561\end{cfuncdesc}
5562
5563\begin{cfuncdesc}{void}{PyObject_GC_Track}{PyObject *op}
Fred Drakec392b572001-03-21 22:15:01 +00005564 Adds the object \var{op} to the set of container objects tracked by
5565 the collector. The collector can run at unexpected times so objects
5566 must be valid while being tracked. This should be called once all
5567 the fields followed by the \member{tp_traverse} handler become valid,
5568 usually near the end of the constructor.
5569\end{cfuncdesc}
5570
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005571\begin{cfuncdesc}{void}{_PyObject_GC_TRACK}{PyObject *op}
5572 A macro version of \cfunction{PyObject_GC_Track()}. It should not be
5573 used for extension modules.
5574\end{cfuncdesc}
5575
Fred Drakee28d8ae2001-03-22 16:30:17 +00005576Similarly, the deallocator for the object must conform to a similar
5577pair of rules:
5578
5579\begin{enumerate}
5580\item Before fields which refer to other containers are invalidated,
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005581 \cfunction{PyObject_GC_UnTrack()} must be called.
Fred Drakee28d8ae2001-03-22 16:30:17 +00005582
5583\item The object's memory must be deallocated using
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005584 \cfunction{PyObject_GC_Del()}.
Fred Drakee28d8ae2001-03-22 16:30:17 +00005585\end{enumerate}
5586
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005587\begin{cfuncdesc}{void}{PyObject_GC_Del}{PyObject *op}
5588 Releases memory allocated to an object using
5589 \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_NewVar()}.
5590\end{cfuncdesc}
5591
5592\begin{cfuncdesc}{void}{PyObject_GC_UnTrack}{PyObject *op}
Fred Drakec392b572001-03-21 22:15:01 +00005593 Remove the object \var{op} from the set of container objects tracked
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005594 by the collector. Note that \cfunction{PyObject_GC_Track()} can be
Fred Drakec392b572001-03-21 22:15:01 +00005595 called again on this object to add it back to the set of tracked
5596 objects. The deallocator (\member{tp_dealloc} handler) should call
5597 this for the object before any of the fields used by the
5598 \member{tp_traverse} handler become invalid.
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005599\end{cfuncdesc}
Fred Drake8f6df462001-03-23 17:42:09 +00005600
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005601\begin{cfuncdesc}{void}{_PyObject_GC_UNTRACK}{PyObject *op}
5602 A macro version of \cfunction{PyObject_GC_UnTrack()}. It should not be
5603 used for extension modules.
Fred Drakec392b572001-03-21 22:15:01 +00005604\end{cfuncdesc}
5605
5606The \member{tp_traverse} handler accepts a function parameter of this
5607type:
5608
5609\begin{ctypedesc}[visitproc]{int (*visitproc)(PyObject *object, void *arg)}
5610 Type of the visitor function passed to the \member{tp_traverse}
5611 handler. The function should be called with an object to traverse
5612 as \var{object} and the third parameter to the \member{tp_traverse}
5613 handler as \var{arg}.
5614\end{ctypedesc}
5615
5616The \member{tp_traverse} handler must have the following type:
5617
5618\begin{ctypedesc}[traverseproc]{int (*traverseproc)(PyObject *self,
5619 visitproc visit, void *arg)}
5620 Traversal function for a container object. Implementations must
5621 call the \var{visit} function for each object directly contained by
5622 \var{self}, with the parameters to \var{visit} being the contained
5623 object and the \var{arg} value passed to the handler. If
5624 \var{visit} returns a non-zero value then an error has occurred and
5625 that value should be returned immediately.
5626\end{ctypedesc}
5627
5628The \member{tp_clear} handler must be of the \ctype{inquiry} type, or
5629\NULL{} if the object is immutable.
5630
5631\begin{ctypedesc}[inquiry]{int (*inquiry)(PyObject *self)}
5632 Drop references that may have created reference cycles. Immutable
5633 objects do not have to define this method since they can never
5634 directly create reference cycles. Note that the object must still
Fred Drakebab29652001-07-10 16:10:08 +00005635 be valid after calling this method (don't just call
Fred Drakec392b572001-03-21 22:15:01 +00005636 \cfunction{Py_DECREF()} on a reference). The collector will call
5637 this method if it detects that this object is involved in a
5638 reference cycle.
5639\end{ctypedesc}
5640
5641
Fred Drakee28d8ae2001-03-22 16:30:17 +00005642\subsection{Example Cycle Collector Support
5643 \label{example-cycle-support}}
5644
5645This example shows only enough of the implementation of an extension
5646type to show how the garbage collector support needs to be added. It
5647shows the definition of the object structure, the
5648\member{tp_traverse}, \member{tp_clear} and \member{tp_dealloc}
5649implementations, the type structure, and a constructor --- the module
5650initialization needed to export the constructor to Python is not shown
5651as there are no special considerations there for the collector. To
5652make this interesting, assume that the module exposes ways for the
5653\member{container} field of the object to be modified. Note that
5654since no checks are made on the type of the object used to initialize
5655\member{container}, we have to assume that it may be a container.
5656
5657\begin{verbatim}
5658#include "Python.h"
5659
5660typedef struct {
5661 PyObject_HEAD
5662 PyObject *container;
5663} MyObject;
5664
5665static int
5666my_traverse(MyObject *self, visitproc visit, void *arg)
5667{
5668 if (self->container != NULL)
5669 return visit(self->container, arg);
5670 else
5671 return 0;
5672}
5673
5674static int
5675my_clear(MyObject *self)
5676{
5677 Py_XDECREF(self->container);
5678 self->container = NULL;
5679
5680 return 0;
5681}
5682
5683static void
5684my_dealloc(MyObject *self)
5685{
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005686 PyObject_GC_UnTrack((PyObject *) self);
Fred Drakee28d8ae2001-03-22 16:30:17 +00005687 Py_XDECREF(self->container);
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005688 PyObject_GC_Del(self);
Fred Drakee28d8ae2001-03-22 16:30:17 +00005689}
5690\end{verbatim}
5691
5692\begin{verbatim}
5693statichere PyTypeObject
5694MyObject_Type = {
5695 PyObject_HEAD_INIT(NULL)
5696 0,
5697 "MyObject",
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005698 sizeof(MyObject),
Fred Drakee28d8ae2001-03-22 16:30:17 +00005699 0,
5700 (destructor)my_dealloc, /* tp_dealloc */
5701 0, /* tp_print */
5702 0, /* tp_getattr */
5703 0, /* tp_setattr */
5704 0, /* tp_compare */
5705 0, /* tp_repr */
5706 0, /* tp_as_number */
5707 0, /* tp_as_sequence */
5708 0, /* tp_as_mapping */
5709 0, /* tp_hash */
5710 0, /* tp_call */
5711 0, /* tp_str */
5712 0, /* tp_getattro */
5713 0, /* tp_setattro */
5714 0, /* tp_as_buffer */
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005715 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
Fred Drakee28d8ae2001-03-22 16:30:17 +00005716 0, /* tp_doc */
5717 (traverseproc)my_traverse, /* tp_traverse */
5718 (inquiry)my_clear, /* tp_clear */
5719 0, /* tp_richcompare */
5720 0, /* tp_weaklistoffset */
5721};
5722
5723/* This constructor should be made accessible from Python. */
5724static PyObject *
5725new_object(PyObject *unused, PyObject *args)
5726{
5727 PyObject *container = NULL;
5728 MyObject *result = NULL;
5729
5730 if (PyArg_ParseTuple(args, "|O:new_object", &container)) {
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005731 result = PyObject_GC_New(MyObject, &MyObject_Type);
Fred Drakee28d8ae2001-03-22 16:30:17 +00005732 if (result != NULL) {
5733 result->container = container;
Neil Schemenauer55cdc882001-08-30 15:24:17 +00005734 PyObject_GC_Track(result);
Fred Drakee28d8ae2001-03-22 16:30:17 +00005735 }
5736 }
5737 return (PyObject *) result;
5738}
5739\end{verbatim}
5740
5741
Fred Drake659ebfa2000-04-03 15:42:13 +00005742% \chapter{Debugging \label{debugging}}
5743%
5744% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00005745
5746
Fred Drakeed773ef2000-09-21 21:35:22 +00005747\appendix
5748\chapter{Reporting Bugs}
5749\input{reportingbugs}
5750
Fred Drake490d34d2001-06-20 21:39:12 +00005751\chapter{History and License}
5752\input{license}
5753
Marc-André Lemburga544ea22001-01-17 18:04:31 +00005754\input{api.ind} % Index -- must be last
Guido van Rossum9231c8f1997-05-15 21:43:21 +00005755
5756\end{document}