blob: 8e7efcb84c1b09b21e60d467e68c18438cd60bca [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
58embedding Python is less straightforward that 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 Drakeefd146c1999-02-15 15:30:45 +0000110
111\section{Objects, Types and Reference Counts \label{objects}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000112
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000113Most Python/C API functions have one or more arguments as well as a
Fred Drake659ebfa2000-04-03 15:42:13 +0000114return value of type \ctype{PyObject*}. This type is a pointer
Fred Drakee058b4f1998-02-16 06:15:35 +0000115to an opaque data type representing an arbitrary Python
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000116object. Since all Python object types are treated the same way by the
117Python language in most situations (e.g., assignments, scope rules,
118and argument passing), it is only fitting that they should be
Fred Drake659ebfa2000-04-03 15:42:13 +0000119represented by a single C type. Almost all Python objects live on the
120heap: you never declare an automatic or static variable of type
121\ctype{PyObject}, only pointer variables of type \ctype{PyObject*} can
122be declared. The sole exception are the type objects\obindex{type};
123since these must never be deallocated, they are typically static
124\ctype{PyTypeObject} objects.
Guido van Rossum59a61351997-08-14 20:34:33 +0000125
Fred Drakee058b4f1998-02-16 06:15:35 +0000126All Python objects (even Python integers) have a \dfn{type} and a
127\dfn{reference count}. An object's type determines what kind of object
Guido van Rossum4a944d71997-08-14 20:35:38 +0000128it is (e.g., an integer, a list, or a user-defined function; there are
Fred Drakebe486461999-11-09 17:03:03 +0000129many more as explained in the \citetitle[../ref/ref.html]{Python
130Reference Manual}). For each of the well-known types there is a macro
131to check whether an object is of that type; for instance,
Fred Drake659ebfa2000-04-03 15:42:13 +0000132\samp{PyList_Check(\var{a})} is true if (and only if) the object
133pointed to by \var{a} is a Python list.
Guido van Rossum59a61351997-08-14 20:34:33 +0000134
Fred Drakeefd146c1999-02-15 15:30:45 +0000135
136\subsection{Reference Counts \label{refcounts}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000137
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000138The reference count is important because today's computers have a
Fred Drake003d8da1998-04-13 00:53:42 +0000139finite (and often severely limited) memory size; it counts how many
Guido van Rossum4a944d71997-08-14 20:35:38 +0000140different places there are that have a reference to an object. Such a
Fred Drake659ebfa2000-04-03 15:42:13 +0000141place could be another object, or a global (or static) C variable, or
142a local variable in some C function. When an object's reference count
Guido van Rossum4a944d71997-08-14 20:35:38 +0000143becomes zero, the object is deallocated. If it contains references to
144other objects, their reference count is decremented. Those other
145objects may be deallocated in turn, if this decrement makes their
146reference count become zero, and so on. (There's an obvious problem
147with objects that reference each other here; for now, the solution is
Fred Drake659ebfa2000-04-03 15:42:13 +0000148``don't do that.'')
Guido van Rossum59a61351997-08-14 20:34:33 +0000149
Guido van Rossum4a944d71997-08-14 20:35:38 +0000150Reference counts are always manipulated explicitly. The normal way is
Fred Drake659ebfa2000-04-03 15:42:13 +0000151to use the macro \cfunction{Py_INCREF()}\ttindex{Py_INCREF()} to
152increment an object's reference count by one, and
153\cfunction{Py_DECREF()}\ttindex{Py_DECREF()} to decrement it by
154one. The \cfunction{Py_DECREF()} macro is considerably more complex
155than the incref one, since it must check whether the reference count
156becomes zero and then cause the object's deallocator to be called.
157The deallocator is a function pointer contained in the object's type
158structure. The type-specific deallocator takes care of decrementing
159the reference counts for other objects contained in the object if this
160is a compound object type, such as a list, as well as performing any
161additional finalization that's needed. There's no chance that the
162reference count can overflow; at least as many bits are used to hold
163the reference count as there are distinct memory locations in virtual
164memory (assuming \code{sizeof(long) >= sizeof(char*)}). Thus, the
165reference count increment is a simple operation.
Guido van Rossum59a61351997-08-14 20:34:33 +0000166
Guido van Rossum4a944d71997-08-14 20:35:38 +0000167It is not necessary to increment an object's reference count for every
168local variable that contains a pointer to an object. In theory, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000169object's reference count goes up by one when the variable is made to
Guido van Rossum4a944d71997-08-14 20:35:38 +0000170point to it and it goes down by one when the variable goes out of
171scope. However, these two cancel each other out, so at the end the
172reference count hasn't changed. The only real reason to use the
173reference count is to prevent the object from being deallocated as
174long as our variable is pointing to it. If we know that there is at
175least one other reference to the object that lives at least as long as
176our variable, there is no need to increment the reference count
177temporarily. An important situation where this arises is in objects
Fred Drake659ebfa2000-04-03 15:42:13 +0000178that are passed as arguments to C functions in an extension module
Guido van Rossum4a944d71997-08-14 20:35:38 +0000179that are called from Python; the call mechanism guarantees to hold a
Guido van Rossum59a61351997-08-14 20:34:33 +0000180reference to every argument for the duration of the call.
181
Fred Drakee058b4f1998-02-16 06:15:35 +0000182However, a common pitfall is to extract an object from a list and
183hold on to it for a while without incrementing its reference count.
184Some other operation might conceivably remove the object from the
185list, decrementing its reference count and possible deallocating it.
186The real danger is that innocent-looking operations may invoke
187arbitrary Python code which could do this; there is a code path which
188allows control to flow back to the user from a \cfunction{Py_DECREF()},
189so almost any operation is potentially dangerous.
Guido van Rossum59a61351997-08-14 20:34:33 +0000190
Guido van Rossum4a944d71997-08-14 20:35:38 +0000191A safe approach is to always use the generic operations (functions
Fred Drake659ebfa2000-04-03 15:42:13 +0000192whose name begins with \samp{PyObject_}, \samp{PyNumber_},
193\samp{PySequence_} or \samp{PyMapping_}). These operations always
194increment the reference count of the object they return. This leaves
195the caller with the responsibility to call
196\cfunction{Py_DECREF()} when they are done with the result; this soon
197becomes second nature.
Guido van Rossum59a61351997-08-14 20:34:33 +0000198
Fred Drakeefd146c1999-02-15 15:30:45 +0000199
200\subsubsection{Reference Count Details \label{refcountDetails}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000201
202The reference count behavior of functions in the Python/C API is best
Fred Drake659ebfa2000-04-03 15:42:13 +0000203explained in terms of \emph{ownership of references}. Note that we
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000204talk of owning references, never of owning objects; objects are always
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000205shared! When a function owns a reference, it has to dispose of it
Fred Drakee058b4f1998-02-16 06:15:35 +0000206properly --- either by passing ownership on (usually to its caller) or
207by calling \cfunction{Py_DECREF()} or \cfunction{Py_XDECREF()}. When
208a function passes ownership of a reference on to its caller, the
209caller is said to receive a \emph{new} reference. When no ownership
210is transferred, the caller is said to \emph{borrow} the reference.
211Nothing needs to be done for a borrowed reference.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000212
Fred Drakea8455ab2000-06-16 19:58:42 +0000213Conversely, when a calling function passes it a reference to an
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000214object, there are two possibilities: the function \emph{steals} a
215reference to the object, or it does not. Few functions steal
Fred Drakee058b4f1998-02-16 06:15:35 +0000216references; the two notable exceptions are
Fred Drake659ebfa2000-04-03 15:42:13 +0000217\cfunction{PyList_SetItem()}\ttindex{PyList_SetItem()} and
218\cfunction{PyTuple_SetItem()}\ttindex{PyTuple_SetItem()}, which
Fred Drakee058b4f1998-02-16 06:15:35 +0000219steal a reference to the item (but not to the tuple or list into which
Fred Drake003d8da1998-04-13 00:53:42 +0000220the item is put!). These functions were designed to steal a reference
Fred Drakee058b4f1998-02-16 06:15:35 +0000221because of a common idiom for populating a tuple or list with newly
222created objects; for example, the code to create the tuple \code{(1,
2232, "three")} could look like this (forgetting about error handling for
Fred Drake659ebfa2000-04-03 15:42:13 +0000224the moment; a better way to code this is shown below):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000225
226\begin{verbatim}
227PyObject *t;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000228
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000229t = PyTuple_New(3);
230PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
231PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
232PyTuple_SetItem(t, 2, PyString_FromString("three"));
233\end{verbatim}
234
Fred Drakee058b4f1998-02-16 06:15:35 +0000235Incidentally, \cfunction{PyTuple_SetItem()} is the \emph{only} way to
236set tuple items; \cfunction{PySequence_SetItem()} and
237\cfunction{PyObject_SetItem()} refuse to do this since tuples are an
238immutable data type. You should only use
239\cfunction{PyTuple_SetItem()} for tuples that you are creating
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000240yourself.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000241
242Equivalent code for populating a list can be written using
Fred Drakee058b4f1998-02-16 06:15:35 +0000243\cfunction{PyList_New()} and \cfunction{PyList_SetItem()}. Such code
244can also use \cfunction{PySequence_SetItem()}; this illustrates the
245difference between the two (the extra \cfunction{Py_DECREF()} calls):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000246
247\begin{verbatim}
248PyObject *l, *x;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000249
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000250l = PyList_New(3);
251x = PyInt_FromLong(1L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000252PySequence_SetItem(l, 0, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000253x = PyInt_FromLong(2L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000254PySequence_SetItem(l, 1, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000255x = PyString_FromString("three");
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000256PySequence_SetItem(l, 2, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000257\end{verbatim}
258
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000259You might find it strange that the ``recommended'' approach takes more
260code. However, in practice, you will rarely use these ways of
261creating and populating a tuple or list. There's a generic function,
Fred Drakee058b4f1998-02-16 06:15:35 +0000262\cfunction{Py_BuildValue()}, that can create most common objects from
Fred Drake659ebfa2000-04-03 15:42:13 +0000263C values, directed by a \dfn{format string}. For example, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000264above two blocks of code could be replaced by the following (which
265also takes care of the error checking):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000266
267\begin{verbatim}
268PyObject *t, *l;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000269
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000270t = Py_BuildValue("(iis)", 1, 2, "three");
271l = Py_BuildValue("[iis]", 1, 2, "three");
272\end{verbatim}
273
Fred Drakee058b4f1998-02-16 06:15:35 +0000274It is much more common to use \cfunction{PyObject_SetItem()} and
275friends with items whose references you are only borrowing, like
276arguments that were passed in to the function you are writing. In
277that case, their behaviour regarding reference counts is much saner,
278since you don't have to increment a reference count so you can give a
279reference away (``have it be stolen''). For example, this function
280sets all items of a list (actually, any mutable sequence) to a given
281item:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000282
283\begin{verbatim}
284int set_all(PyObject *target, PyObject *item)
285{
286 int i, n;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000287
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000288 n = PyObject_Length(target);
289 if (n < 0)
290 return -1;
291 for (i = 0; i < n; i++) {
292 if (PyObject_SetItem(target, i, item) < 0)
293 return -1;
294 }
295 return 0;
296}
297\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000298\ttindex{set_all()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000299
300The situation is slightly different for function return values.
301While passing a reference to most functions does not change your
302ownership responsibilities for that reference, many functions that
303return a referece to an object give you ownership of the reference.
304The reason is simple: in many cases, the returned object is created
305on the fly, and the reference you get is the only reference to the
Fred Drakee058b4f1998-02-16 06:15:35 +0000306object. Therefore, the generic functions that return object
307references, like \cfunction{PyObject_GetItem()} and
308\cfunction{PySequence_GetItem()}, always return a new reference (i.e.,
309the caller becomes the owner of the reference).
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000310
311It is important to realize that whether you own a reference returned
Fred Drakee058b4f1998-02-16 06:15:35 +0000312by a function depends on which function you call only --- \emph{the
313plumage} (i.e., the type of the type of the object passed as an
314argument to the function) \emph{doesn't enter into it!} Thus, if you
315extract an item from a list using \cfunction{PyList_GetItem()}, you
316don't own the reference --- but if you obtain the same item from the
317same list using \cfunction{PySequence_GetItem()} (which happens to
318take exactly the same arguments), you do own a reference to the
319returned object.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000320
Fred Drakee058b4f1998-02-16 06:15:35 +0000321Here is an example of how you could write a function that computes the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000322sum of the items in a list of integers; once using
Fred Drake659ebfa2000-04-03 15:42:13 +0000323\cfunction{PyList_GetItem()}\ttindex{PyList_GetItem()}, and once using
324\cfunction{PySequence_GetItem()}\ttindex{PySequence_GetItem()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000325
326\begin{verbatim}
327long sum_list(PyObject *list)
328{
329 int i, n;
330 long total = 0;
331 PyObject *item;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000332
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000333 n = PyList_Size(list);
334 if (n < 0)
335 return -1; /* Not a list */
336 for (i = 0; i < n; i++) {
337 item = PyList_GetItem(list, i); /* Can't fail */
338 if (!PyInt_Check(item)) continue; /* Skip non-integers */
339 total += PyInt_AsLong(item);
340 }
341 return total;
342}
343\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000344\ttindex{sum_list()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000345
346\begin{verbatim}
347long sum_sequence(PyObject *sequence)
348{
349 int i, n;
350 long total = 0;
351 PyObject *item;
Fred Drake659ebfa2000-04-03 15:42:13 +0000352 n = PySequence_Length(sequence);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000353 if (n < 0)
354 return -1; /* Has no length */
355 for (i = 0; i < n; i++) {
Fred Drake659ebfa2000-04-03 15:42:13 +0000356 item = PySequence_GetItem(sequence, i);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000357 if (item == NULL)
358 return -1; /* Not a sequence, or other failure */
359 if (PyInt_Check(item))
360 total += PyInt_AsLong(item);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000361 Py_DECREF(item); /* Discard reference ownership */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000362 }
363 return total;
364}
365\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000366\ttindex{sum_sequence()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000367
Fred Drakeefd146c1999-02-15 15:30:45 +0000368
369\subsection{Types \label{types}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000370
371There are few other data types that play a significant role in
Fred Drake659ebfa2000-04-03 15:42:13 +0000372the Python/C API; most are simple C types such as \ctype{int},
373\ctype{long}, \ctype{double} and \ctype{char*}. A few structure types
Guido van Rossum4a944d71997-08-14 20:35:38 +0000374are used to describe static tables used to list the functions exported
Fred Drake659ebfa2000-04-03 15:42:13 +0000375by a module or the data attributes of a new object type, and another
376is used to describe the value of a complex number. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000377be discussed together with the functions that use them.
378
Fred Drakeefd146c1999-02-15 15:30:45 +0000379
380\section{Exceptions \label{exceptions}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000381
Guido van Rossum4a944d71997-08-14 20:35:38 +0000382The Python programmer only needs to deal with exceptions if specific
383error handling is required; unhandled exceptions are automatically
Fred Drake659ebfa2000-04-03 15:42:13 +0000384propagated to the caller, then to the caller's caller, and so on, until
Guido van Rossum4a944d71997-08-14 20:35:38 +0000385they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000386user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000387
Fred Drake659ebfa2000-04-03 15:42:13 +0000388For C programmers, however, error checking always has to be explicit.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000389All functions in the Python/C API can raise exceptions, unless an
390explicit claim is made otherwise in a function's documentation. In
391general, when a function encounters an error, it sets an exception,
392discards any object references that it owns, and returns an
Fred Drakee058b4f1998-02-16 06:15:35 +0000393error indicator --- usually \NULL{} or \code{-1}. A few functions
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000394return a Boolean true/false result, with false indicating an error.
395Very few functions return no explicit error indicator or have an
396ambiguous return value, and require explicit testing for errors with
Fred Drake659ebfa2000-04-03 15:42:13 +0000397\cfunction{PyErr_Occurred()}\ttindex{PyErr_Occurred()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000398
399Exception state is maintained in per-thread storage (this is
400equivalent to using global storage in an unthreaded application). A
Fred Drakec6fa34e1998-04-02 06:47:24 +0000401thread can be in one of two states: an exception has occurred, or not.
Fred Drakee058b4f1998-02-16 06:15:35 +0000402The function \cfunction{PyErr_Occurred()} can be used to check for
403this: it returns a borrowed reference to the exception type object
404when an exception has occurred, and \NULL{} otherwise. There are a
405number of functions to set the exception state:
Fred Drake659ebfa2000-04-03 15:42:13 +0000406\cfunction{PyErr_SetString()}\ttindex{PyErr_SetString()} is the most
407common (though not the most general) function to set the exception
408state, and \cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} clears the
409exception state.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000410
411The full exception state consists of three objects (all of which can
Fred Drakee058b4f1998-02-16 06:15:35 +0000412be \NULL{}): the exception type, the corresponding exception
Fred Drake659ebfa2000-04-03 15:42:13 +0000413value, and the traceback. These have the same meanings as the Python
414\withsubitem{(in module sys)}{
415 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
416objects \code{sys.exc_type}, \code{sys.exc_value}, and
417\code{sys.exc_traceback}; however, they are not the same: the Python
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000418objects represent the last exception being handled by a Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000419\keyword{try} \ldots\ \keyword{except} statement, while the C level
Fred Drakee058b4f1998-02-16 06:15:35 +0000420exception state only exists while an exception is being passed on
Fred Drake659ebfa2000-04-03 15:42:13 +0000421between C functions until it reaches the Python bytecode interpreter's
422main loop, which takes care of transferring it to \code{sys.exc_type}
423and friends.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000424
Fred Drakec6fa34e1998-04-02 06:47:24 +0000425Note that starting with Python 1.5, the preferred, thread-safe way to
Fred Drake659ebfa2000-04-03 15:42:13 +0000426access the exception state from Python code is to call the function
427\withsubitem{(in module sys)}{\ttindex{exc_info()}}
Fred Drakee058b4f1998-02-16 06:15:35 +0000428\function{sys.exc_info()}, which returns the per-thread exception state
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000429for Python code. Also, the semantics of both ways to access the
430exception state have changed so that a function which catches an
431exception will save and restore its thread's exception state so as to
432preserve the exception state of its caller. This prevents common bugs
433in exception handling code caused by an innocent-looking function
434overwriting the exception being handled; it also reduces the often
435unwanted lifetime extension for objects that are referenced by the
Fred Drakec6fa34e1998-04-02 06:47:24 +0000436stack frames in the traceback.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000437
438As a general principle, a function that calls another function to
439perform some task should check whether the called function raised an
440exception, and if so, pass the exception state on to its caller. It
Fred Drake659ebfa2000-04-03 15:42:13 +0000441should discard any object references that it owns, and return an
Fred Drakee058b4f1998-02-16 06:15:35 +0000442error indicator, but it should \emph{not} set another exception ---
443that would overwrite the exception that was just raised, and lose
444important information about the exact cause of the error.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000445
Fred Drake659ebfa2000-04-03 15:42:13 +0000446A simple example of detecting exceptions and passing them on is shown
447in the \cfunction{sum_sequence()}\ttindex{sum_sequence()} example
448above. It so happens that that example doesn't need to clean up any
449owned references when it detects an error. The following example
450function shows some error cleanup. First, to remind you why you like
451Python, we show the equivalent Python code:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000452
453\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000454def incr_item(dict, key):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000455 try:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000456 item = dict[key]
457 except KeyError:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000458 item = 0
Fred Drake6b3f3f22000-11-29 15:48:22 +0000459 dict[key] = item + 1
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000460\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000461\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000462
Fred Drake659ebfa2000-04-03 15:42:13 +0000463Here is the corresponding C code, in all its glory:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000464
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000465\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000466int incr_item(PyObject *dict, PyObject *key)
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000467{
468 /* Objects all initialized to NULL for Py_XDECREF */
469 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000470 int rv = -1; /* Return value initialized to -1 (failure) */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000471
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000472 item = PyObject_GetItem(dict, key);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000473 if (item == NULL) {
Fred Drakec6fa34e1998-04-02 06:47:24 +0000474 /* Handle KeyError only: */
Fred Drake6b3f3f22000-11-29 15:48:22 +0000475 if (!PyErr_ExceptionMatches(PyExc_KeyError))
476 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000477
478 /* Clear the error and use zero: */
479 PyErr_Clear();
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000480 item = PyInt_FromLong(0L);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000481 if (item == NULL)
482 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000483 }
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000484 const_one = PyInt_FromLong(1L);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000485 if (const_one == NULL)
486 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000487
488 incremented_item = PyNumber_Add(item, const_one);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000489 if (incremented_item == NULL)
490 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000491
Fred Drake6b3f3f22000-11-29 15:48:22 +0000492 if (PyObject_SetItem(dict, key, incremented_item) < 0)
493 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000494 rv = 0; /* Success */
495 /* Continue with cleanup code */
496
497 error:
498 /* Cleanup code, shared by success and failure path */
499
500 /* Use Py_XDECREF() to ignore NULL references */
501 Py_XDECREF(item);
502 Py_XDECREF(const_one);
503 Py_XDECREF(incremented_item);
504
505 return rv; /* -1 for error, 0 for success */
506}
507\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000508\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000509
Fred Drakef8830d11998-04-23 14:06:01 +0000510This example represents an endorsed use of the \keyword{goto} statement
Fred Drake659ebfa2000-04-03 15:42:13 +0000511in C! It illustrates the use of
512\cfunction{PyErr_ExceptionMatches()}\ttindex{PyErr_ExceptionMatches()} and
513\cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} to
514handle specific exceptions, and the use of
515\cfunction{Py_XDECREF()}\ttindex{Py_XDECREF()} to
516dispose of owned references that may be \NULL{} (note the
517\character{X} in the name; \cfunction{Py_DECREF()} would crash when
518confronted with a \NULL{} reference). It is important that the
519variables used to hold owned references are initialized to \NULL{} for
520this to work; likewise, the proposed return value is initialized to
521\code{-1} (failure) and only set to success after the final call made
522is successful.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000523
Guido van Rossum59a61351997-08-14 20:34:33 +0000524
Fred Drakeefd146c1999-02-15 15:30:45 +0000525\section{Embedding Python \label{embedding}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000526
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000527The one important task that only embedders (as opposed to extension
528writers) of the Python interpreter have to worry about is the
529initialization, and possibly the finalization, of the Python
530interpreter. Most functionality of the interpreter can only be used
531after the interpreter has been initialized.
Guido van Rossum59a61351997-08-14 20:34:33 +0000532
Fred Drake659ebfa2000-04-03 15:42:13 +0000533The basic initialization function is
534\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Fred Drakee058b4f1998-02-16 06:15:35 +0000535This initializes the table of loaded modules, and creates the
Fred Drake4de05a91998-02-16 14:25:26 +0000536fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
537\module{__main__}\refbimodindex{__main__} and
538\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drakec6fa34e1998-04-02 06:47:24 +0000539search path (\code{sys.path}).%
540\indexiii{module}{search}{path}
Fred Drake659ebfa2000-04-03 15:42:13 +0000541\withsubitem{(in module sys)}{\ttindex{path}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000542
Fred Drakee058b4f1998-02-16 06:15:35 +0000543\cfunction{Py_Initialize()} does not set the ``script argument list''
Guido van Rossum4a944d71997-08-14 20:35:38 +0000544(\code{sys.argv}). If this variable is needed by Python code that
545will be executed later, it must be set explicitly with a call to
Fred Drake659ebfa2000-04-03 15:42:13 +0000546\code{PySys_SetArgv(\var{argc},
547\var{argv})}\ttindex{PySys_SetArgv()} subsequent to the call to
548\cfunction{Py_Initialize()}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000549
Fred Drakeb0a78731998-01-13 18:51:10 +0000550On most systems (in particular, on \UNIX{} and Windows, although the
Fred Drake659ebfa2000-04-03 15:42:13 +0000551details are slightly different),
552\cfunction{Py_Initialize()} calculates the module search path based
553upon its best guess for the location of the standard Python
554interpreter executable, assuming that the Python library is found in a
555fixed location relative to the Python interpreter executable. In
556particular, it looks for a directory named
Fred Draked5d04352000-09-14 20:24:17 +0000557\file{lib/python\shortversion} relative to the parent directory where
558the executable named \file{python} is found on the shell command
559search path (the environment variable \envvar{PATH}).
Guido van Rossum42cefd01997-10-05 15:27:29 +0000560
561For instance, if the Python executable is found in
Fred Drakee058b4f1998-02-16 06:15:35 +0000562\file{/usr/local/bin/python}, it will assume that the libraries are in
Fred Draked5d04352000-09-14 20:24:17 +0000563\file{/usr/local/lib/python\shortversion}. (In fact, this particular path
Fred Drakee058b4f1998-02-16 06:15:35 +0000564is also the ``fallback'' location, used when no executable file named
Fred Drakec6fa34e1998-04-02 06:47:24 +0000565\file{python} is found along \envvar{PATH}.) The user can override
566this behavior by setting the environment variable \envvar{PYTHONHOME},
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000567or insert additional directories in front of the standard path by
Fred Drakec6fa34e1998-04-02 06:47:24 +0000568setting \envvar{PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000569
Guido van Rossum4a944d71997-08-14 20:35:38 +0000570The embedding application can steer the search by calling
Fred Drake659ebfa2000-04-03 15:42:13 +0000571\code{Py_SetProgramName(\var{file})}\ttindex{Py_SetProgramName()} \emph{before} calling
Fred Drakec6fa34e1998-04-02 06:47:24 +0000572\cfunction{Py_Initialize()}. Note that \envvar{PYTHONHOME} still
573overrides this and \envvar{PYTHONPATH} is still inserted in front of
Fred Drakee058b4f1998-02-16 06:15:35 +0000574the standard path. An application that requires total control has to
Fred Drake659ebfa2000-04-03 15:42:13 +0000575provide its own implementation of
576\cfunction{Py_GetPath()}\ttindex{Py_GetPath()},
577\cfunction{Py_GetPrefix()}\ttindex{Py_GetPrefix()},
578\cfunction{Py_GetExecPrefix()}\ttindex{Py_GetExecPrefix()}, and
579\cfunction{Py_GetProgramFullPath()}\ttindex{Py_GetProgramFullPath()} (all
580defined in \file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000581
Guido van Rossum4a944d71997-08-14 20:35:38 +0000582Sometimes, it is desirable to ``uninitialize'' Python. For instance,
583the application may want to start over (make another call to
Fred Drakee058b4f1998-02-16 06:15:35 +0000584\cfunction{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000585use of Python and wants to free all memory allocated by Python. This
Fred Drakee058b4f1998-02-16 06:15:35 +0000586can be accomplished by calling \cfunction{Py_Finalize()}. The function
Fred Drake659ebfa2000-04-03 15:42:13 +0000587\cfunction{Py_IsInitialized()}\ttindex{Py_IsInitialized()} returns
588true if Python is currently in the initialized state. More
589information about these functions is given in a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000590
Guido van Rossum4a944d71997-08-14 20:35:38 +0000591
Fred Drakeefd146c1999-02-15 15:30:45 +0000592\chapter{The Very High Level Layer \label{veryhigh}}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000593
Fred Drakee5bf8b21998-02-12 21:22:28 +0000594The functions in this chapter will let you execute Python source code
595given in a file or a buffer, but they will not let you interact in a
596more detailed way with the interpreter.
Guido van Rossum4a944d71997-08-14 20:35:38 +0000597
Fred Drake659ebfa2000-04-03 15:42:13 +0000598Several of these functions accept a start symbol from the grammar as a
599parameter. The available start symbols are \constant{Py_eval_input},
600\constant{Py_file_input}, and \constant{Py_single_input}. These are
601described following the functions which accept them as parameters.
602
Fred Drake510d08b2000-08-14 02:50:21 +0000603Note also that several of these functions take \ctype{FILE*}
604parameters. On particular issue which needs to be handled carefully
605is that the \ctype{FILE} structure for different C libraries can be
606different and incompatible. Under Windows (at least), it is possible
607for dynamically linked extensions to actually use different libraries,
608so care should be taken that \ctype{FILE*} parameters are only passed
609to these functions if it is certain that they were created by the same
610library that the Python runtime is using.
611
Fred Drakec6fa34e1998-04-02 06:47:24 +0000612\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000613 If \var{fp} refers to a file associated with an interactive device
614 (console or terminal input or \UNIX{} pseudo-terminal), return the
615 value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
616 result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
Fred Drakea8d73412000-08-11 20:39:29 +0000617 \NULL{}, this function uses \code{"???"} as the filename.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000618\end{cfuncdesc}
619
Fred Drakec6fa34e1998-04-02 06:47:24 +0000620\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
Fred Drake0041a941999-04-29 04:20:46 +0000621 Executes the Python source code from \var{command} in the
622 \module{__main__} module. If \module{__main__} does not already
623 exist, it is created. Returns \code{0} on success or \code{-1} if
624 an exception was raised. If there was an error, there is no way to
625 get the exception information.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000626\end{cfuncdesc}
627
Fred Drakec6fa34e1998-04-02 06:47:24 +0000628\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000629 Similar to \cfunction{PyRun_SimpleString()}, but the Python source
630 code is read from \var{fp} instead of an in-memory string.
631 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000632\end{cfuncdesc}
633
Fred Drakec6fa34e1998-04-02 06:47:24 +0000634\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000635 Read and execute a single statement from a file associated with an
636 interactive device. If \var{filename} is \NULL, \code{"???"} is
637 used instead. The user will be prompted using \code{sys.ps1} and
638 \code{sys.ps2}. Returns \code{0} when the input was executed
639 successfully, \code{-1} if there was an exception, or an error code
640 from the \file{errcode.h} include file distributed as part of Python
641 in case of a parse error. (Note that \file{errcode.h} is not
642 included by \file{Python.h}, so must be included specifically if
643 needed.)
Fred Drakee5bf8b21998-02-12 21:22:28 +0000644\end{cfuncdesc}
645
Fred Drakec6fa34e1998-04-02 06:47:24 +0000646\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000647 Read and execute statements from a file associated with an
648 interactive device until \EOF{} is reached. If \var{filename} is
649 \NULL, \code{"???"} is used instead. The user will be prompted
650 using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000651\end{cfuncdesc}
652
Fred Drakec6fa34e1998-04-02 06:47:24 +0000653\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
654 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000655 Parse Python source code from \var{str} using the start token
656 \var{start}. The result can be used to create a code object which
657 can be evaluated efficiently. This is useful if a code fragment
658 must be evaluated many times.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000659\end{cfuncdesc}
660
Fred Drakec6fa34e1998-04-02 06:47:24 +0000661\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
662 char *filename, int start}
Fred Drake0041a941999-04-29 04:20:46 +0000663 Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
664 source code is read from \var{fp} instead of an in-memory string.
665 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000666\end{cfuncdesc}
667
Fred Drakec6fa34e1998-04-02 06:47:24 +0000668\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
669 PyObject *globals,
670 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000671 Execute Python source code from \var{str} in the context specified
672 by the dictionaries \var{globals} and \var{locals}. The parameter
673 \var{start} specifies the start token that should be used to parse
674 the source code.
675
676 Returns the result of executing the code as a Python object, or
677 \NULL{} if an exception was raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000678\end{cfuncdesc}
679
Fred Drakec6fa34e1998-04-02 06:47:24 +0000680\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
681 int start, PyObject *globals,
682 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000683 Similar to \cfunction{PyRun_String()}, but the Python source code is
Fred Drake659ebfa2000-04-03 15:42:13 +0000684 read from \var{fp} instead of an in-memory string.
685 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000686\end{cfuncdesc}
687
Fred Drakec6fa34e1998-04-02 06:47:24 +0000688\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
689 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000690 Parse and compile the Python source code in \var{str}, returning the
691 resulting code object. The start token is given by \var{start};
Fred Drakec924b8d1999-08-23 18:57:25 +0000692 this can be used to constrain the code which can be compiled and should
693 be \constant{Py_eval_input}, \constant{Py_file_input}, or
694 \constant{Py_single_input}. The filename specified by
695 \var{filename} is used to construct the code object and may appear
696 in tracebacks or \exception{SyntaxError} exception messages. This
697 returns \NULL{} if the code cannot be parsed or compiled.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000698\end{cfuncdesc}
699
Fred Drakec924b8d1999-08-23 18:57:25 +0000700\begin{cvardesc}{int}{Py_eval_input}
701 The start symbol from the Python grammar for isolated expressions;
Fred Drake659ebfa2000-04-03 15:42:13 +0000702 for use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
Fred Drakec924b8d1999-08-23 18:57:25 +0000703\end{cvardesc}
704
705\begin{cvardesc}{int}{Py_file_input}
706 The start symbol from the Python grammar for sequences of statements
707 as read from a file or other source; for use with
Fred Drake659ebfa2000-04-03 15:42:13 +0000708 \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
709 the symbol to use when compiling arbitrarily long Python source code.
Fred Drakec924b8d1999-08-23 18:57:25 +0000710\end{cvardesc}
711
712\begin{cvardesc}{int}{Py_single_input}
713 The start symbol from the Python grammar for a single statement; for
Fred Drake659ebfa2000-04-03 15:42:13 +0000714 use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
715 This is the symbol used for the interactive interpreter loop.
Fred Drakec924b8d1999-08-23 18:57:25 +0000716\end{cvardesc}
717
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000718
Fred Drakeefd146c1999-02-15 15:30:45 +0000719\chapter{Reference Counting \label{countingRefs}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000720
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000721The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000722of Python objects.
723
724\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
Fred Drakec6fa34e1998-04-02 06:47:24 +0000725Increment the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000726not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000727\cfunction{Py_XINCREF()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000728\end{cfuncdesc}
729
730\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000731Increment the reference count for object \var{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000732\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000733\end{cfuncdesc}
734
735\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000736Decrement the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000737not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000738\cfunction{Py_XDECREF()}. If the reference count reaches zero, the
739object's type's deallocation function (which must not be \NULL{}) is
740invoked.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000741
742\strong{Warning:} The deallocation function can cause arbitrary Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000743code to be invoked (e.g. when a class instance with a
744\method{__del__()} method is deallocated). While exceptions in such
745code are not propagated, the executed code has free access to all
746Python global variables. This means that any object that is reachable
747from a global variable should be in a consistent state before
748\cfunction{Py_DECREF()} is invoked. For example, code to delete an
749object from a list should copy a reference to the deleted object in a
750temporary variable, update the list data structure, and then call
751\cfunction{Py_DECREF()} for the temporary variable.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000752\end{cfuncdesc}
753
754\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000755Decrement the reference count for object \var{o}. The object may be
756\NULL{}, in which case the macro has no effect; otherwise the effect
757is the same as for \cfunction{Py_DECREF()}, and the same warning
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000758applies.
759\end{cfuncdesc}
760
Fred Drake659ebfa2000-04-03 15:42:13 +0000761The following functions or macros are only for use within the
762interpreter core: \cfunction{_Py_Dealloc()},
763\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
764well as the global variable \cdata{_Py_RefTotal}.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000765
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000766
Fred Drakeefd146c1999-02-15 15:30:45 +0000767\chapter{Exception Handling \label{exceptionHandling}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000768
Fred Drake659ebfa2000-04-03 15:42:13 +0000769The functions described in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000770exceptions. It is important to understand some of the basics of
Fred Drake659ebfa2000-04-03 15:42:13 +0000771Python exception handling. It works somewhat like the
772\UNIX{} \cdata{errno} variable: there is a global indicator (per
773thread) of the last error that occurred. Most functions don't clear
774this on success, but will set it to indicate the cause of the error on
775failure. Most functions also return an error indicator, usually
776\NULL{} if they are supposed to return a pointer, or \code{-1} if they
777return an integer (exception: the \cfunction{PyArg_Parse*()} functions
778return \code{1} for success and \code{0} for failure). When a
779function must fail because some function it called failed, it
780generally doesn't set the error indicator; the function it called
781already set it.
Guido van Rossumae110af1997-05-22 20:11:52 +0000782
783The error indicator consists of three Python objects corresponding to
Fred Drake659ebfa2000-04-03 15:42:13 +0000784\withsubitem{(in module sys)}{
785 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000786the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
787\code{sys.exc_traceback}. API functions exist to interact with the
788error indicator in various ways. There is a separate error indicator
789for each thread.
790
791% XXX Order of these should be more thoughtful.
792% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000793
794\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000795Print a standard traceback to \code{sys.stderr} and clear the error
796indicator. Call this function only when the error indicator is set.
797(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000798\end{cfuncdesc}
799
Fred Drakec6fa34e1998-04-02 06:47:24 +0000800\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000801Test whether the error indicator is set. If set, return the exception
Fred Drakee058b4f1998-02-16 06:15:35 +0000802\emph{type} (the first argument to the last call to one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000803\cfunction{PyErr_Set*()} functions or to \cfunction{PyErr_Restore()}). If
Fred Drakee058b4f1998-02-16 06:15:35 +0000804not set, return \NULL{}. You do not own a reference to the return
805value, so you do not need to \cfunction{Py_DECREF()} it.
Fred Drake659ebfa2000-04-03 15:42:13 +0000806\strong{Note:} Do not compare the return value to a specific
Fred Drakee058b4f1998-02-16 06:15:35 +0000807exception; use \cfunction{PyErr_ExceptionMatches()} instead, shown
Fred Drake659ebfa2000-04-03 15:42:13 +0000808below. (The comparison could easily fail since the exception may be
809an instance instead of a class, in the case of a class exception, or
810it may the a subclass of the expected exception.)
Guido van Rossum42cefd01997-10-05 15:27:29 +0000811\end{cfuncdesc}
812
813\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000814Equivalent to
Fred Drakee058b4f1998-02-16 06:15:35 +0000815\samp{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
Fred Drake659ebfa2000-04-03 15:42:13 +0000816This should only be called when an exception is actually set; a memory
817access violation will occur if no exception has been raised.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000818\end{cfuncdesc}
819
820\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000821Return true if the \var{given} exception matches the exception in
822\var{exc}. If \var{exc} is a class object, this also returns true
Fred Drake659ebfa2000-04-03 15:42:13 +0000823when \var{given} is an instance of a subclass. If \var{exc} is a tuple, all
Guido van Rossum42cefd01997-10-05 15:27:29 +0000824exceptions in the tuple (and recursively in subtuples) are searched
Fred Drake659ebfa2000-04-03 15:42:13 +0000825for a match. If \var{given} is \NULL, a memory access violation will
826occur.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000827\end{cfuncdesc}
828
829\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000830Under certain circumstances, the values returned by
Fred Drakee058b4f1998-02-16 06:15:35 +0000831\cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning that
832\code{*\var{exc}} is a class object but \code{*\var{val}} is not an
833instance of the same class. This function can be used to instantiate
834the class in that case. If the values are already normalized, nothing
Fred Drake659ebfa2000-04-03 15:42:13 +0000835happens. The delayed normalization is implemented to improve
836performance.
Guido van Rossumae110af1997-05-22 20:11:52 +0000837\end{cfuncdesc}
838
839\begin{cfuncdesc}{void}{PyErr_Clear}{}
840Clear the error indicator. If the error indicator is not set, there
841is no effect.
842\end{cfuncdesc}
843
Fred Drake659ebfa2000-04-03 15:42:13 +0000844\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
845 PyObject **ptraceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000846Retrieve the error indicator into three variables whose addresses are
847passed. If the error indicator is not set, set all three variables to
848\NULL{}. If it is set, it will be cleared and you own a reference to
Fred Drake659ebfa2000-04-03 15:42:13 +0000849each object retrieved. The value and traceback object may be
850\NULL{} even when the type object is not. \strong{Note:} This
851function is normally only used by code that needs to handle exceptions
852or by code that needs to save and restore the error indicator
853temporarily.
Guido van Rossumae110af1997-05-22 20:11:52 +0000854\end{cfuncdesc}
855
Fred Drake17e63432000-08-31 05:50:40 +0000856\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
857 PyObject *traceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000858Set the error indicator from the three objects. If the error
859indicator is already set, it is cleared first. If the objects are
860\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
861and non-\NULL{} value or traceback. The exception type should be a
862string or class; if it is a class, the value should be an instance of
863that class. Do not pass an invalid exception type or value.
864(Violating these rules will cause subtle problems later.) This call
Fred Drake17e63432000-08-31 05:50:40 +0000865takes away a reference to each object, i.e.\ you must own a reference
Guido van Rossumae110af1997-05-22 20:11:52 +0000866to each object before the call and after the call you no longer own
867these references. (If you don't understand this, don't use this
Fred Drake659ebfa2000-04-03 15:42:13 +0000868function. I warned you.) \strong{Note:} This function is normally
Guido van Rossumae110af1997-05-22 20:11:52 +0000869only used by code that needs to save and restore the error indicator
870temporarily.
871\end{cfuncdesc}
872
873\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
874This is the most common way to set the error indicator. The first
875argument specifies the exception type; it is normally one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000876standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
Guido van Rossumae110af1997-05-22 20:11:52 +0000877increment its reference count. The second argument is an error
878message; it is converted to a string object.
879\end{cfuncdesc}
880
881\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +0000882This function is similar to \cfunction{PyErr_SetString()} but lets you
Guido van Rossumae110af1997-05-22 20:11:52 +0000883specify an arbitrary Python object for the ``value'' of the exception.
884You need not increment its reference count.
885\end{cfuncdesc}
886
Fred Drake73577702000-04-10 18:50:14 +0000887\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
Moshe Zadka57a59322000-09-01 09:47:20 +0000888 const char *format, \moreargs}
Fred Drake89fb0352000-10-14 05:49:30 +0000889This function sets the error indicator. \var{exception} should be a
890Python exception (string or class, not an instance).
Fred Drake5566c1c2001-01-19 22:48:33 +0000891\var{format} should be a string, containing format codes, similar to
Moshe Zadka57a59322000-09-01 09:47:20 +0000892\cfunction{printf}. The \code{width.precision} before a format code
893is parsed, but the width part is ignored.
894
895\begin{tableii}{c|l}{character}{Character}{Meaning}
896 \lineii{c}{Character, as an \ctype{int} parameter}
897 \lineii{d}{Number in decimal, as an \ctype{int} parameter}
898 \lineii{x}{Number in hexadecimal, as an \ctype{int} parameter}
899 \lineii{x}{A string, as a \ctype{char *} parameter}
900\end{tableii}
901
902An unrecognized format character causes all the rest of
903the format string to be copied as-is to the result string,
904and any extra arguments discarded.
905
906A new reference is returned, which is owned by the caller.
Jeremy Hylton98605b52000-04-10 18:40:57 +0000907\end{cfuncdesc}
908
Guido van Rossumae110af1997-05-22 20:11:52 +0000909\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +0000910This is a shorthand for \samp{PyErr_SetObject(\var{type}, Py_None)}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000911\end{cfuncdesc}
912
913\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000914This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000915\var{message})}, where \var{message} indicates that a built-in operation
916was invoked with an illegal argument. It is mostly for internal use.
917\end{cfuncdesc}
918
Fred Drakec6fa34e1998-04-02 06:47:24 +0000919\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000920This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
Guido van Rossumae110af1997-05-22 20:11:52 +0000921returns \NULL{} so an object allocation function can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000922\samp{return PyErr_NoMemory();} when it runs out of memory.
Guido van Rossumae110af1997-05-22 20:11:52 +0000923\end{cfuncdesc}
924
Fred Drakec6fa34e1998-04-02 06:47:24 +0000925\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
Fred Drake659ebfa2000-04-03 15:42:13 +0000926This is a convenience function to raise an exception when a C library
927function has returned an error and set the C variable \cdata{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000928It constructs a tuple object whose first item is the integer
Fred Drakef8830d11998-04-23 14:06:01 +0000929\cdata{errno} value and whose second item is the corresponding error
Fred Drake659ebfa2000-04-03 15:42:13 +0000930message (gotten from \cfunction{strerror()}\ttindex{strerror()}), and
931then calls
Fred Drakee058b4f1998-02-16 06:15:35 +0000932\samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
Fred Drakef8830d11998-04-23 14:06:01 +0000933the \cdata{errno} value is \constant{EINTR}, indicating an interrupted
Fred Drakee058b4f1998-02-16 06:15:35 +0000934system call, this calls \cfunction{PyErr_CheckSignals()}, and if that set
Guido van Rossumae110af1997-05-22 20:11:52 +0000935the error indicator, leaves it set to that. The function always
936returns \NULL{}, so a wrapper function around a system call can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000937\samp{return PyErr_SetFromErrno();} when the system call returns an
938error.
Guido van Rossumae110af1997-05-22 20:11:52 +0000939\end{cfuncdesc}
940
941\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000942This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000943\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000944operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000945argument. It is mostly for internal use.
946\end{cfuncdesc}
947
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000948\begin{cfuncdesc}{int}{PyErr_Warn}{PyObject *category, char *message}
949Issue a warning message. The \var{category} argument is a warning
Fred Drake5566c1c2001-01-19 22:48:33 +0000950category (see below) or \NULL; the \var{message} argument is a message
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000951string.
952
953This function normally prints a warning message to \var{sys.stderr};
954however, it is also possible that the user has specified that warnings
955are to be turned into errors, and in that case this will raise an
956exception. It is also possible that the function raises an exception
957because of a problem with the warning machinery (the implementation
958imports the \module{warnings} module to do the heavy lifting). The
959return value is \code{0} if no exception is raised, or \code{-1} if
960an exception is raised. (It is not possible to determine whether a
961warning message is actually printed, nor what the reason is for the
962exception; this is intentional.) If an exception is raised, the
Fred Drake5566c1c2001-01-19 22:48:33 +0000963caller should do its normal exception handling
964(e.g. \cfunction{Py_DECREF()} owned references and return an error
965value).
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000966
967Warning categories must be subclasses of \cdata{Warning}; the default
968warning category is \cdata{RuntimeWarning}. The standard Python
969warning categories are available as global variables whose names are
970\samp{PyExc_} followed by the Python exception name. These have the
971type \ctype{PyObject*}; they are all class objects. Their names are
972\cdata{PyExc_Warning}, \cdata{PyExc_UserWarning},
973\cdata{PyExc_DeprecationWarning}, \cdata{PyExc_SyntaxWarning}, and
974\cdata{PyExc_RuntimeWarning}. \cdata{PyExc_Warning} is a subclass of
975\cdata{PyExc_Exception}; the other warning categories are subclasses
976of \cdata{PyExc_Warning}.
977
978For information about warning control, see the documentation for the
Fred Drake316ef7c2001-01-04 05:56:34 +0000979\module{warnings} module and the \programopt{-W} option in the command
980line documentation. There is no C API for warning control.
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000981\end{cfuncdesc}
982
Guido van Rossum1874c8f2001-02-28 23:46:44 +0000983\begin{cfuncdesc}{int}{PyErr_WarnExplicit}{PyObject *category, char *message,
984char *filename, int lineno, char *module, PyObject *registry}
985Issue a warning message with explicit control over all warning
986attributes. This is a straightforward wrapper around the Python
987function \function{warnings.warn_explicit()}, see there for more
988information. The \var{module} and \var{registry} arguments may be
989set to \code{NULL} to get the default effect described there.
990\end{cfuncdesc}
991
Guido van Rossumae110af1997-05-22 20:11:52 +0000992\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
993This function interacts with Python's signal handling. It checks
994whether a signal has been sent to the processes and if so, invokes the
Fred Drake4de05a91998-02-16 14:25:26 +0000995corresponding signal handler. If the
996\module{signal}\refbimodindex{signal} module is supported, this can
997invoke a signal handler written in Python. In all cases, the default
Fred Drake659ebfa2000-04-03 15:42:13 +0000998effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
999\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
1000\exception{KeyboardInterrupt} exception. If an exception is raised the
Fred Drakee058b4f1998-02-16 06:15:35 +00001001error indicator is set and the function returns \code{1}; otherwise
1002the function returns \code{0}. The error indicator may or may not be
1003cleared if it was previously set.
Guido van Rossumae110af1997-05-22 20:11:52 +00001004\end{cfuncdesc}
1005
1006\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001007This function is obsolete. It simulates the effect of a
1008\constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
Fred Drakee058b4f1998-02-16 06:15:35 +00001009\cfunction{PyErr_CheckSignals()} is called,
Fred Drake659ebfa2000-04-03 15:42:13 +00001010\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
1011\exception{KeyboardInterrupt} will be raised.
1012It may be called without holding the interpreter lock.
Guido van Rossumae110af1997-05-22 20:11:52 +00001013\end{cfuncdesc}
1014
Fred Drakec6fa34e1998-04-02 06:47:24 +00001015\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
1016 PyObject *base,
1017 PyObject *dict}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001018This utility function creates and returns a new exception object. The
Fred Drake659ebfa2000-04-03 15:42:13 +00001019\var{name} argument must be the name of the new exception, a C string
1020of the form \code{module.class}. The \var{base} and
Fred Draked04038d2000-06-29 20:15:14 +00001021\var{dict} arguments are normally \NULL{}. This creates a
Fred Drake659ebfa2000-04-03 15:42:13 +00001022class object derived from the root for all exceptions, the built-in
1023name \exception{Exception} (accessible in C as
Fred Draked04038d2000-06-29 20:15:14 +00001024\cdata{PyExc_Exception}). The \member{__module__} attribute of the
1025new class is set to the first part (up to the last dot) of the
1026\var{name} argument, and the class name is set to the last part (after
1027the last dot). The \var{base} argument can be used to specify an
1028alternate base class. The \var{dict} argument can be used to specify
1029a dictionary of class variables and methods.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001030\end{cfuncdesc}
1031
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001032\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
1033This utility function prints a warning message to \var{sys.stderr}
1034when an exception has been set but it is impossible for the
1035interpreter to actually raise the exception. It is used, for example,
1036when an exception occurs in an \member{__del__} method.
1037
1038The function is called with a single argument \var{obj} that
1039identifies where the context in which the unraisable exception
1040occurred. The repr of \var{obj} will be printed in the warning
1041message.
1042\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001043
Fred Drakeefd146c1999-02-15 15:30:45 +00001044\section{Standard Exceptions \label{standardExceptions}}
Guido van Rossumae110af1997-05-22 20:11:52 +00001045
1046All standard Python exceptions are available as global variables whose
Fred Drake659ebfa2000-04-03 15:42:13 +00001047names are \samp{PyExc_} followed by the Python exception name. These
1048have the type \ctype{PyObject*}; they are all class objects. For
1049completeness, here are all the variables:
1050
1051\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
1052 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
1053 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
1054 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
1055 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
1056 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
1057 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
1058 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
1059 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
1060 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
1061 \lineiii{PyExc_IOError}{\exception{IOError}}{}
1062 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
1063 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
1064 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
1065 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
1066 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
1067 \lineiii{PyExc_NameError}{\exception{NameError}}{}
1068 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
1069 \lineiii{PyExc_OSError}{\exception{OSError}}{}
1070 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
1071 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
1072 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
1073 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
1074 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
1075 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
1076 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
Fred Drakea8d73412000-08-11 20:39:29 +00001077 \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(2)}
Fred Drake659ebfa2000-04-03 15:42:13 +00001078 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
1079\end{tableiii}
1080
1081\noindent
Fred Drakea8d73412000-08-11 20:39:29 +00001082Notes:
Fred Drake659ebfa2000-04-03 15:42:13 +00001083\begin{description}
1084\item[(1)]
Fred Draked04038d2000-06-29 20:15:14 +00001085 This is a base class for other standard exceptions.
Fred Drakea8d73412000-08-11 20:39:29 +00001086
1087\item[(2)]
1088 Only defined on Windows; protect code that uses this by testing that
1089 the preprocessor macro \code{MS_WINDOWS} is defined.
Fred Drake659ebfa2000-04-03 15:42:13 +00001090\end{description}
1091
1092
1093\section{Deprecation of String Exceptions}
1094
Fred Draked04038d2000-06-29 20:15:14 +00001095All exceptions built into Python or provided in the standard library
1096are derived from \exception{Exception}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001097\withsubitem{(built-in exception)}{\ttindex{Exception}}
Fred Drake659ebfa2000-04-03 15:42:13 +00001098
Fred Draked04038d2000-06-29 20:15:14 +00001099String exceptions are still supported in the interpreter to allow
Fred Drake659ebfa2000-04-03 15:42:13 +00001100existing code to run unmodified, but this will also change in a future
1101release.
Guido van Rossumae110af1997-05-22 20:11:52 +00001102
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001103
Fred Drakeefd146c1999-02-15 15:30:45 +00001104\chapter{Utilities \label{utilities}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001105
1106The functions in this chapter perform various utility tasks, such as
Fred Drake659ebfa2000-04-03 15:42:13 +00001107parsing function arguments and constructing Python values from C
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001108values.
1109
Fred Drakeefd146c1999-02-15 15:30:45 +00001110\section{OS Utilities \label{os}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001111
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001112\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001113Return true (nonzero) if the standard I/O file \var{fp} with name
1114\var{filename} is deemed interactive. This is the case for files for
1115which \samp{isatty(fileno(\var{fp}))} is true. If the global flag
Fred Drakef8830d11998-04-23 14:06:01 +00001116\cdata{Py_InteractiveFlag} is true, this function also returns true if
Fred Drake5566c1c2001-01-19 22:48:33 +00001117the \var{filename} pointer is \NULL{} or if the name is equal to one of
Fred Drakea8455ab2000-06-16 19:58:42 +00001118the strings \code{'<stdin>'} or \code{'???'}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001119\end{cfuncdesc}
1120
1121\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001122Return the time of last modification of the file \var{filename}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001123The result is encoded in the same way as the timestamp returned by
Fred Drake659ebfa2000-04-03 15:42:13 +00001124the standard C library function \cfunction{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001125\end{cfuncdesc}
1126
Fred Drakecabbc3b2000-06-28 15:53:13 +00001127\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
1128Function to update some internal state after a process fork; this
1129should be called in the new process if the Python interpreter will
1130continue to be used. If a new executable is loaded into the new
1131process, this function does not need to be called.
1132\end{cfuncdesc}
1133
Fred Drake17e63432000-08-31 05:50:40 +00001134\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
1135Return true when the interpreter runs out of stack space. This is a
1136reliable check, but is only available when \code{USE_STACKCHECK} is
1137defined (currently on Windows using the Microsoft Visual C++ compiler
1138and on the Macintosh). \code{USE_CHECKSTACK} will be defined
1139automatically; you should never change the definition in your own
1140code.
1141\end{cfuncdesc}
1142
Guido van Rossumc96ec6e2000-09-16 16:30:48 +00001143\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i}
1144Return the current signal handler for signal \var{i}.
1145This is a thin wrapper around either \cfunction{sigaction} or
1146\cfunction{signal}. Do not call those functions directly!
1147\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1148\end{cfuncdesc}
1149
1150\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h}
1151Set the signal handler for signal \var{i} to be \var{h};
1152return the old signal handler.
1153This is a thin wrapper around either \cfunction{sigaction} or
1154\cfunction{signal}. Do not call those functions directly!
1155\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1156\end{cfuncdesc}
1157
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001158
Fred Drakeefd146c1999-02-15 15:30:45 +00001159\section{Process Control \label{processControl}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001160
1161\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
1162Print a fatal error message and kill the process. No cleanup is
1163performed. This function should only be invoked when a condition is
1164detected that would make it dangerous to continue using the Python
1165interpreter; e.g., when the object administration appears to be
Fred Drake659ebfa2000-04-03 15:42:13 +00001166corrupted. On \UNIX{}, the standard C library function
1167\cfunction{abort()}\ttindex{abort()} is called which will attempt to
1168produce a \file{core} file.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001169\end{cfuncdesc}
1170
1171\begin{cfuncdesc}{void}{Py_Exit}{int status}
Fred Drake659ebfa2000-04-03 15:42:13 +00001172Exit the current process. This calls
1173\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
1174then calls the standard C library function
1175\code{exit(\var{status})}\ttindex{exit()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001176\end{cfuncdesc}
1177
1178\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drake659ebfa2000-04-03 15:42:13 +00001179Register a cleanup function to be called by
1180\cfunction{Py_Finalize()}\ttindex{Py_Finalize()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001181The cleanup function will be called with no arguments and should
Fred Drake659ebfa2000-04-03 15:42:13 +00001182return no value. At most 32 \index{cleanup functions}cleanup
1183functions can be registered.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001184When the registration is successful, \cfunction{Py_AtExit()} returns
1185\code{0}; on failure, it returns \code{-1}. The cleanup function
1186registered last is called first. Each cleanup function will be called
1187at most once. Since Python's internal finallization will have
1188completed before the cleanup function, no Python APIs should be called
1189by \var{func}.
1190\end{cfuncdesc}
1191
1192
Fred Drakeefd146c1999-02-15 15:30:45 +00001193\section{Importing Modules \label{importing}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001194
Fred Drakec6fa34e1998-04-02 06:47:24 +00001195\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00001196This is a simplified interface to
1197\cfunction{PyImport_ImportModuleEx()} below, leaving the
1198\var{globals} and \var{locals} arguments set to \NULL{}. When the
1199\var{name} argument contains a dot (i.e., when it specifies a
1200submodule of a package), the \var{fromlist} argument is set to the
1201list \code{['*']} so that the return value is the named module rather
1202than the top-level package containing it as would otherwise be the
1203case. (Unfortunately, this has an additional side effect when
1204\var{name} in fact specifies a subpackage instead of a submodule: the
1205submodules specified in the package's \code{__all__} variable are
1206\index{package variable!\code{__all__}}
1207\withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a
1208new reference to the imported module, or
1209\NULL{} with an exception set on failure (the module may still be
1210created in this case --- examine \code{sys.modules} to find out).
1211\withsubitem{(in module sys)}{\ttindex{modules}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001212\end{cfuncdesc}
1213
Fred Drakec6fa34e1998-04-02 06:47:24 +00001214\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001215Import a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001216Python function \function{__import__()}\bifuncindex{__import__}, as
1217the standard \function{__import__()} function calls this function
1218directly.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001219
Guido van Rossum42cefd01997-10-05 15:27:29 +00001220The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001221top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001222(the module may still be created in this case). Like for
Fred Drakee058b4f1998-02-16 06:15:35 +00001223\function{__import__()}, the return value when a submodule of a
1224package was requested is normally the top-level package, unless a
1225non-empty \var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001226\end{cfuncdesc}
1227
Fred Drakec6fa34e1998-04-02 06:47:24 +00001228\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001229This is a higher-level interface that calls the current ``import hook
Fred Drakee058b4f1998-02-16 06:15:35 +00001230function''. It invokes the \function{__import__()} function from the
Guido van Rossum42cefd01997-10-05 15:27:29 +00001231\code{__builtins__} of the current globals. This means that the
1232import is done using whatever import hooks are installed in the
Fred Drake4de05a91998-02-16 14:25:26 +00001233current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
1234\module{ihooks}\refstmodindex{ihooks}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001235\end{cfuncdesc}
1236
Fred Drakec6fa34e1998-04-02 06:47:24 +00001237\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001238Reload a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001239Python function \function{reload()}\bifuncindex{reload}, as the standard
Fred Drakee058b4f1998-02-16 06:15:35 +00001240\function{reload()} function calls this function directly. Return a
1241new reference to the reloaded module, or \NULL{} with an exception set
1242on failure (the module still exists in this case).
Guido van Rossum42cefd01997-10-05 15:27:29 +00001243\end{cfuncdesc}
1244
Fred Drakec6fa34e1998-04-02 06:47:24 +00001245\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001246Return the module object corresponding to a module name. The
1247\var{name} argument may be of the form \code{package.module}). First
1248check the modules dictionary if there's one there, and if not, create
Fred Drake659ebfa2000-04-03 15:42:13 +00001249a new one and insert in in the modules dictionary.
Guido van Rossuma096a2e1998-11-02 17:02:42 +00001250Warning: this function does not load or import the module; if the
1251module wasn't already loaded, you will get an empty module object.
1252Use \cfunction{PyImport_ImportModule()} or one of its variants to
1253import a module.
Fred Drake659ebfa2000-04-03 15:42:13 +00001254Return \NULL{} with an exception set on failure.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001255\end{cfuncdesc}
1256
Fred Drakec6fa34e1998-04-02 06:47:24 +00001257\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001258Given a module name (possibly of the form \code{package.module}) and a
1259code object read from a Python bytecode file or obtained from the
Fred Drake53fb7721998-02-16 06:23:20 +00001260built-in function \function{compile()}\bifuncindex{compile}, load the
1261module. Return a new reference to the module object, or \NULL{} with
1262an exception set if an error occurred (the module may still be created
1263in this case). (This function would reload the module if it was
1264already imported.)
Guido van Rossum42cefd01997-10-05 15:27:29 +00001265\end{cfuncdesc}
1266
1267\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001268Return the magic number for Python bytecode files (a.k.a.
1269\file{.pyc} and \file{.pyo} files). The magic number should be
1270present in the first four bytes of the bytecode file, in little-endian
1271byte order.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001272\end{cfuncdesc}
1273
Fred Drakec6fa34e1998-04-02 06:47:24 +00001274\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001275Return the dictionary used for the module administration
1276(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1277variable.
1278\end{cfuncdesc}
1279
1280\begin{cfuncdesc}{void}{_PyImport_Init}{}
1281Initialize the import mechanism. For internal use only.
1282\end{cfuncdesc}
1283
1284\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1285Empty the module table. For internal use only.
1286\end{cfuncdesc}
1287
1288\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1289Finalize the import mechanism. For internal use only.
1290\end{cfuncdesc}
1291
Fred Drakec6fa34e1998-04-02 06:47:24 +00001292\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001293For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001294\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001295
Fred Drakec6fa34e1998-04-02 06:47:24 +00001296\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001297For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001298\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001299
Fred Drake1d158692000-06-18 05:21:21 +00001300\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
1301Load a frozen module named \var{name}. Return \code{1} for success,
1302\code{0} if the module is not found, and \code{-1} with an exception
1303set if the initialization failed. To access the imported module on a
1304successful load, use \cfunction{PyImport_ImportModule()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00001305(Note the misnomer --- this function would reload the module if it was
Guido van Rossum42cefd01997-10-05 15:27:29 +00001306already imported.)
1307\end{cfuncdesc}
1308
Fred Drake659ebfa2000-04-03 15:42:13 +00001309\begin{ctypedesc}[_frozen]{struct _frozen}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001310This is the structure type definition for frozen module descriptors,
Fred Drakec6fa34e1998-04-02 06:47:24 +00001311as generated by the \program{freeze}\index{freeze utility} utility
1312(see \file{Tools/freeze/} in the Python source distribution). Its
Fred Drakee0d9a832000-09-01 05:30:00 +00001313definition, found in \file{Include/import.h}, is:
Fred Drakec6fa34e1998-04-02 06:47:24 +00001314
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001315\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001316struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001317 char *name;
1318 unsigned char *code;
1319 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001320};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001321\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001322\end{ctypedesc}
1323
Fred Drakec6fa34e1998-04-02 06:47:24 +00001324\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
Fred Drakef8830d11998-04-23 14:06:01 +00001325This pointer is initialized to point to an array of \ctype{struct
Fred Drake659ebfa2000-04-03 15:42:13 +00001326_frozen} records, terminated by one whose members are all
1327\NULL{} or zero. When a frozen module is imported, it is searched in
1328this table. Third-party code could play tricks with this to provide a
Guido van Rossum42cefd01997-10-05 15:27:29 +00001329dynamically created collection of frozen modules.
1330\end{cvardesc}
1331
Fred Drakee0d9a832000-09-01 05:30:00 +00001332\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
1333 void (*initfunc)(void)}
1334Add a single module to the existing table of built-in modules. This
1335is a convenience wrapper around \cfunction{PyImport_ExtendInittab()},
1336returning \code{-1} if the table could not be extended. The new
1337module can be imported by the name \var{name}, and uses the function
1338\var{initfunc} as the initialization function called on the first
1339attempted import. This should be called before
1340\cfunction{Py_Initialize()}.
1341\end{cfuncdesc}
1342
1343\begin{ctypedesc}[_inittab]{struct _inittab}
1344Structure describing a single entry in the list of built-in modules.
1345Each of these structures gives the name and initialization function
1346for a module built into the interpreter. Programs which embed Python
1347may use an array of these structures in conjunction with
1348\cfunction{PyImport_ExtendInittab()} to provide additional built-in
1349modules. The structure is defined in \file{Include/import.h} as:
1350
1351\begin{verbatim}
1352struct _inittab {
1353 char *name;
1354 void (*initfunc)(void);
1355};
1356\end{verbatim}
1357\end{ctypedesc}
1358
1359\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
1360Add a collection of modules to the table of built-in modules. The
1361\var{newtab} array must end with a sentinel entry which contains
1362\NULL{} for the \member{name} field; failure to provide the sentinel
1363value can result in a memory fault. Returns \code{0} on success or
1364\code{-1} if insufficient memory could be allocated to extend the
1365internal table. In the event of failure, no modules are added to the
1366internal table. This should be called before
1367\cfunction{Py_Initialize()}.
1368\end{cfuncdesc}
1369
Guido van Rossum42cefd01997-10-05 15:27:29 +00001370
Fred Drakeefd146c1999-02-15 15:30:45 +00001371\chapter{Abstract Objects Layer \label{abstract}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001372
1373The functions in this chapter interact with Python objects regardless
1374of their type, or with wide classes of object types (e.g. all
1375numerical types, or all sequence types). When used on object types
Fred Drake659ebfa2000-04-03 15:42:13 +00001376for which they do not apply, they will raise a Python exception.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001377
Fred Drakeefd146c1999-02-15 15:30:45 +00001378\section{Object Protocol \label{object}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001379
1380\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00001381Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error.
1382The flags argument is used to enable certain printing options. The
1383only option currently supported is \constant{Py_PRINT_RAW}; if given,
1384the \function{str()} of the object is written instead of the
1385\function{repr()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001386\end{cfuncdesc}
1387
1388\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001389Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1390\code{0} otherwise. This is equivalent to the Python expression
1391\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001392This function always succeeds.
1393\end{cfuncdesc}
1394
Fred Drake659ebfa2000-04-03 15:42:13 +00001395\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
1396 char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001397Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001398Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001399This is the equivalent of the Python expression
1400\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001401\end{cfuncdesc}
1402
1403
1404\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001405Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1406\code{0} otherwise. This is equivalent to the Python expression
1407\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001408This function always succeeds.
1409\end{cfuncdesc}
1410
1411
Fred Drake659ebfa2000-04-03 15:42:13 +00001412\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
1413 PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001414Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001415Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001416This is the equivalent of the Python expression
1417\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001418\end{cfuncdesc}
1419
1420
1421\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001422Set the value of the attribute named \var{attr_name}, for object
1423\var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1424the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1425\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001426\end{cfuncdesc}
1427
1428
1429\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001430Set the value of the attribute named \var{attr_name}, for
1431object \var{o},
1432to the value \var{v}. Returns \code{-1} on failure. This is
1433the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1434\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001435\end{cfuncdesc}
1436
1437
1438\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001439Delete attribute named \var{attr_name}, for object \var{o}. Returns
1440\code{-1} on failure. This is the equivalent of the Python
1441statement: \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001442\end{cfuncdesc}
1443
1444
1445\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001446Delete attribute named \var{attr_name}, for object \var{o}. Returns
1447\code{-1} on failure. This is the equivalent of the Python
1448statement \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001449\end{cfuncdesc}
1450
1451
1452\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
Fred Drakee058b4f1998-02-16 06:15:35 +00001453Compare the values of \var{o1} and \var{o2} using a routine provided
1454by \var{o1}, if one exists, otherwise with a routine provided by
1455\var{o2}. The result of the comparison is returned in \var{result}.
1456Returns \code{-1} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001457statement\bifuncindex{cmp} \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001458\end{cfuncdesc}
1459
1460
1461\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001462Compare the values of \var{o1} and \var{o2} using a routine provided
1463by \var{o1}, if one exists, otherwise with a routine provided by
1464\var{o2}. Returns the result of the comparison on success. On error,
1465the value returned is undefined; use \cfunction{PyErr_Occurred()} to
Fred Drake659ebfa2000-04-03 15:42:13 +00001466detect an error. This is equivalent to the Python
1467expression\bifuncindex{cmp} \samp{cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001468\end{cfuncdesc}
1469
1470
1471\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001472Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001473string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001474the equivalent of the Python expression \samp{repr(\var{o})}.
1475Called by the \function{repr()}\bifuncindex{repr} built-in function
1476and by reverse quotes.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001477\end{cfuncdesc}
1478
1479
1480\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001481Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001482string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001483the equivalent of the Python expression \samp{str(\var{o})}.
1484Called by the \function{str()}\bifuncindex{str} built-in function and
1485by the \keyword{print} statement.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001486\end{cfuncdesc}
1487
1488
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001489\begin{cfuncdesc}{PyObject*}{PyObject_Unicode}{PyObject *o}
1490Compute a Unicode string representation of object \var{o}. Returns the
1491Unicode string representation on success, \NULL{} on failure. This is
1492the equivalent of the Python expression \samp{unistr(\var{o})}.
1493Called by the \function{unistr()}\bifuncindex{unistr} built-in function.
1494\end{cfuncdesc}
1495
Fred Drake58c8f9f2001-03-28 21:14:32 +00001496\begin{cfuncdesc}{int}{PyObject_IsInstance}{PyObject *inst, PyObject *cls}
1497Return \code{1} if \var{inst} is an instance of the class \var{cls} or
1498a subclass of \var{cls}. If \var{cls} is a type object rather than a
1499class object, \cfunction{PyObject_IsInstance()} returns \code{1} if
1500\var{inst} is of type \var{cls}. If \var{inst} is not a class
1501instance and \var{cls} is neither a type object or class object,
1502\var{inst} must have a \member{__class__} attribute --- the class
1503relationship of the value of that attribute with \var{cls} will be
1504used to determine the result of this function.
1505\versionadded{2.1}
1506\end{cfuncdesc}
1507
1508Subclass determination is done in a fairly straightforward way, but
1509includes a wrinkle that implementors of extensions to the class system
1510may want to be aware of. If \class{A} and \class{B} are class
1511objects, \class{B} is a subclass of \class{A} if it inherits from
1512\class{A} either directly or indirectly. If either is not a class
1513object, a more general mechanism is used to determine the class
1514relationship of the two objects. When testing if \var{B} is a
1515subclass of \var{A}, if \var{A} is \var{B},
1516\cfunction{PyObject_IsSubclass()} returns true. If \var{A} and
1517\var{B} are different objects, \var{B}'s \member{__bases__} attribute
1518is searched in a depth-first fashion for \var{A} --- the presence of
1519the \member{__bases__} attribute is considered sufficient for this
1520determination.
1521
1522\begin{cfuncdesc}{int}{PyObject_IsSubclass}{PyObject *derived,
1523 PyObject *cls}
1524Returns \code{1} if the class \var{derived} is identical to or derived
1525from the class \var{cls}, otherwise returns \code{0}. In case of an
1526error, returns \code{-1}. If either \var{derived} or \var{cls} is not
1527an actual class object, this function uses the generic algorithm
1528described above.
1529\versionadded{2.1}
1530\end{cfuncdesc}
1531
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001532
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001533\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001534Determine if the object \var{o} is callable. Return \code{1} if the
Fred Drakee058b4f1998-02-16 06:15:35 +00001535object is callable and \code{0} otherwise.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001536This function always succeeds.
1537\end{cfuncdesc}
1538
1539
Fred Drake659ebfa2000-04-03 15:42:13 +00001540\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
1541 PyObject *args}
Fred Drakee058b4f1998-02-16 06:15:35 +00001542Call a callable Python object \var{callable_object}, with
1543arguments given by the tuple \var{args}. If no arguments are
Fred Drake659ebfa2000-04-03 15:42:13 +00001544needed, then \var{args} may be \NULL{}. Returns the result of the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001545call on success, or \NULL{} on failure. This is the equivalent
Fred Drake5566c1c2001-01-19 22:48:33 +00001546of the Python expression \samp{apply(\var{callable_object}, \var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001547\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001548\end{cfuncdesc}
1549
Fred Drake5566c1c2001-01-19 22:48:33 +00001550\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object,
1551 char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001552Call a callable Python object \var{callable_object}, with a
Fred Drake659ebfa2000-04-03 15:42:13 +00001553variable number of C arguments. The C arguments are described
Fred Drakee058b4f1998-02-16 06:15:35 +00001554using a \cfunction{Py_BuildValue()} style format string. The format may
1555be \NULL{}, indicating that no arguments are provided. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001556result of the call on success, or \NULL{} on failure. This is
Fred Drake5566c1c2001-01-19 22:48:33 +00001557the equivalent of the Python expression \samp{apply(\var{callable_object},
Fred Drake659ebfa2000-04-03 15:42:13 +00001558\var{args})}.\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001559\end{cfuncdesc}
1560
1561
Fred Drake5566c1c2001-01-19 22:48:33 +00001562\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o,
1563 char *method, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001564Call the method named \var{m} of object \var{o} with a variable number
Fred Drake659ebfa2000-04-03 15:42:13 +00001565of C arguments. The C arguments are described by a
Fred Drakee058b4f1998-02-16 06:15:35 +00001566\cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1567indicating that no arguments are provided. Returns the result of the
1568call on success, or \NULL{} on failure. This is the equivalent of the
1569Python expression \samp{\var{o}.\var{method}(\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001570Note that special method names, such as \method{__add__()},
1571\method{__getitem__()}, and so on are not supported. The specific
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001572abstract-object routines for these must be used.
1573\end{cfuncdesc}
1574
1575
1576\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001577Compute and return the hash value of an object \var{o}. On
1578failure, return \code{-1}. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001579expression \samp{hash(\var{o})}.\bifuncindex{hash}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001580\end{cfuncdesc}
1581
1582
1583\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001584Returns \code{1} if the object \var{o} is considered to be true, and
1585\code{0} otherwise. This is equivalent to the Python expression
1586\samp{not not \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001587This function always succeeds.
1588\end{cfuncdesc}
1589
1590
1591\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1592On success, returns a type object corresponding to the object
Fred Drakee058b4f1998-02-16 06:15:35 +00001593type of object \var{o}. On failure, returns \NULL{}. This is
1594equivalent to the Python expression \samp{type(\var{o})}.
Fred Drake53fb7721998-02-16 06:23:20 +00001595\bifuncindex{type}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001596\end{cfuncdesc}
1597
1598\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001599Return the length of object \var{o}. If the object \var{o} provides
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001600both sequence and mapping protocols, the sequence length is
Fred Drake659ebfa2000-04-03 15:42:13 +00001601returned. On error, \code{-1} is returned. This is the equivalent
1602to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001603\end{cfuncdesc}
1604
1605
1606\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001607Return element of \var{o} corresponding to the object \var{key} or
1608\NULL{} on failure. This is the equivalent of the Python expression
1609\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001610\end{cfuncdesc}
1611
1612
1613\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001614Map the object \var{key} to the value \var{v}.
1615Returns \code{-1} on failure. This is the equivalent
1616of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001617\end{cfuncdesc}
1618
1619
Guido van Rossumd1dbf631999-01-22 20:10:49 +00001620\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001621Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1622failure. This is the equivalent of the Python statement \samp{del
1623\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001624\end{cfuncdesc}
1625
Andrew M. Kuchling8c46b302000-07-13 23:58:16 +00001626\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
1627Derives a file-descriptor from a Python object. If the object
1628is an integer or long integer, its value is returned. If not, the
1629object's \method{fileno()} method is called if it exists; the method
1630must return an integer or long integer, which is returned as the file
1631descriptor value. Returns \code{-1} on failure.
1632\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001633
Fred Drakeefd146c1999-02-15 15:30:45 +00001634\section{Number Protocol \label{number}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001635
1636\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001637Returns \code{1} if the object \var{o} provides numeric protocols, and
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001638false otherwise.
1639This function always succeeds.
1640\end{cfuncdesc}
1641
1642
1643\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001644Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1645failure. This is the equivalent of the Python expression
1646\samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001647\end{cfuncdesc}
1648
1649
1650\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
Fred Drake659ebfa2000-04-03 15:42:13 +00001651Returns the result of subtracting \var{o2} from \var{o1}, or
1652\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001653\samp{\var{o1} - \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001654\end{cfuncdesc}
1655
1656
1657\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001658Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1659failure. This is the equivalent of the Python expression
1660\samp{\var{o1} * \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001661\end{cfuncdesc}
1662
1663
1664\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001665Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1666failure.
1667This is the equivalent of the Python expression \samp{\var{o1} /
1668\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001669\end{cfuncdesc}
1670
1671
1672\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001673Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1674failure. This is the equivalent of the Python expression
Fred Drake659ebfa2000-04-03 15:42:13 +00001675\samp{\var{o1} \%\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001676\end{cfuncdesc}
1677
1678
1679\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
Fred Drake53fb7721998-02-16 06:23:20 +00001680See the built-in function \function{divmod()}\bifuncindex{divmod}.
1681Returns \NULL{} on failure. This is the equivalent of the Python
1682expression \samp{divmod(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001683\end{cfuncdesc}
1684
1685
1686\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
Fred Drake53fb7721998-02-16 06:23:20 +00001687See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1688\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001689\samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
Fred Drake659ebfa2000-04-03 15:42:13 +00001690If \var{o3} is to be ignored, pass \cdata{Py_None} in its place
1691(passing \NULL{} for \var{o3} would cause an illegal memory access).
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001692\end{cfuncdesc}
1693
1694
1695\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001696Returns the negation of \var{o} on success, or \NULL{} on failure.
1697This is the equivalent of the Python expression \samp{-\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001698\end{cfuncdesc}
1699
1700
1701\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001702Returns \var{o} on success, or \NULL{} on failure.
1703This is the equivalent of the Python expression \samp{+\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001704\end{cfuncdesc}
1705
1706
1707\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001708Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1709the equivalent of the Python expression \samp{abs(\var{o})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001710\bifuncindex{abs}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001711\end{cfuncdesc}
1712
1713
1714\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001715Returns the bitwise negation of \var{o} on success, or \NULL{} on
1716failure. This is the equivalent of the Python expression
1717\samp{\~\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001718\end{cfuncdesc}
1719
1720
1721\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001722Returns the result of left shifting \var{o1} by \var{o2} on success,
1723or \NULL{} on failure. This is the equivalent of the Python
Fred Draked20d8b32001-04-13 14:52:39 +00001724expression \samp{\var{o1} <\code{<} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001725\end{cfuncdesc}
1726
1727
1728\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001729Returns the result of right shifting \var{o1} by \var{o2} on success,
1730or \NULL{} on failure. This is the equivalent of the Python
Fred Draked20d8b32001-04-13 14:52:39 +00001731expression \samp{\var{o1} >\code{>} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001732\end{cfuncdesc}
1733
1734
1735\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001736Returns the ``bitwise and'' of \var{o2} and \var{o2} on success and
1737\NULL{} on failure. This is the equivalent of the Python expression
Fred Drake5566c1c2001-01-19 22:48:33 +00001738\samp{\var{o1} \&\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001739\end{cfuncdesc}
1740
1741
1742\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001743Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success,
Fred Drakee058b4f1998-02-16 06:15:35 +00001744or \NULL{} on failure. This is the equivalent of the Python
1745expression \samp{\var{o1} \^{ }\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001746\end{cfuncdesc}
1747
1748\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001749Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
1750\NULL{} on failure. This is the equivalent of the Python expression
1751\samp{\var{o1} | \var{o2}}.
1752\end{cfuncdesc}
1753
1754
1755\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAdd}{PyObject *o1, PyObject *o2}
1756Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on failure.
1757The operation is done \emph{in-place} when \var{o1} supports it. This is the
1758equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1759\end{cfuncdesc}
1760
1761
1762\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceSubtract}{PyObject *o1, PyObject *o2}
1763Returns the result of subtracting \var{o2} from \var{o1}, or
1764\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1765supports it. This is the equivalent of the Python expression \samp{\var{o1}
1766-= \var{o2}}.
1767\end{cfuncdesc}
1768
1769
1770\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceMultiply}{PyObject *o1, PyObject *o2}
1771Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1772failure. The operation is done \emph{in-place} when \var{o1} supports it.
1773This is the equivalent of the Python expression \samp{\var{o1} *= \var{o2}}.
1774\end{cfuncdesc}
1775
1776
1777\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceDivide}{PyObject *o1, PyObject *o2}
1778Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on failure.
1779The operation is done \emph{in-place} when \var{o1} supports it. This is the
1780equivalent of the Python expression \samp{\var{o1} /= \var{o2}}.
1781\end{cfuncdesc}
1782
1783
1784\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRemainder}{PyObject *o1, PyObject *o2}
1785Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1786failure. The operation is done \emph{in-place} when \var{o1} supports it.
1787This is the equivalent of the Python expression \samp{\var{o1} \%= \var{o2}}.
1788\end{cfuncdesc}
1789
1790
1791\begin{cfuncdesc}{PyObject*}{PyNumber_InPlacePower}{PyObject *o1, PyObject *o2, PyObject *o3}
1792See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1793\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1794supports it. This is the equivalent of the Python expression \samp{\var{o1}
1795**= \var{o2}} when o3 is \cdata{Py_None}, or an in-place variant of
Fred Drake5566c1c2001-01-19 22:48:33 +00001796\samp{pow(\var{o1}, \var{o2}, \var{o3})} otherwise. If \var{o3} is to be
Fred Drake7740a012000-09-12 20:27:05 +00001797ignored, pass \cdata{Py_None} in its place (passing \NULL{} for \var{o3}
1798would cause an illegal memory access).
1799\end{cfuncdesc}
1800
1801\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceLshift}{PyObject *o1, PyObject *o2}
1802Returns the result of left shifting \var{o1} by \var{o2} on success, or
1803\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1804supports it. This is the equivalent of the Python expression \samp{\var{o1}
Fred Draked20d8b32001-04-13 14:52:39 +00001805<\code{<=} \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001806\end{cfuncdesc}
1807
1808
1809\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRshift}{PyObject *o1, PyObject *o2}
1810Returns the result of right shifting \var{o1} by \var{o2} on success, or
1811\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1812supports it. This is the equivalent of the Python expression \samp{\var{o1}
Fred Draked20d8b32001-04-13 14:52:39 +00001813>\code{>=} \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001814\end{cfuncdesc}
1815
1816
1817\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAnd}{PyObject *o1, PyObject *o2}
Fred Drake5566c1c2001-01-19 22:48:33 +00001818Returns the ``bitwise and'' of \var{o1} and \var{o2} on success
1819and \NULL{} on failure. The operation is done \emph{in-place} when
1820\var{o1} supports it. This is the equivalent of the Python expression
1821\samp{\var{o1} \&= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001822\end{cfuncdesc}
1823
1824
1825\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceXor}{PyObject *o1, PyObject *o2}
1826Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success, or
1827\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1828supports it. This is the equivalent of the Python expression \samp{\var{o1}
1829\^= \var{o2}}.
1830\end{cfuncdesc}
1831
1832\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2}
1833Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or \NULL{}
1834on failure. The operation is done \emph{in-place} when \var{o1} supports
1835it. This is the equivalent of the Python expression \samp{\var{o1} |=
1836\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001837\end{cfuncdesc}
1838
Fred Drakec0e6c5b2000-09-22 18:17:49 +00001839\begin{cfuncdesc}{int}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001840This function takes the addresses of two variables of type
Fred Drake659ebfa2000-04-03 15:42:13 +00001841\ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} and
1842\code{*\var{p2}} have the same type, increment their reference count
1843and return \code{0} (success). If the objects can be converted to a
1844common numeric type, replace \code{*p1} and \code{*p2} by their
1845converted value (with 'new' reference counts), and return \code{0}.
1846If no conversion is possible, or if some other error occurs, return
1847\code{-1} (failure) and don't increment the reference counts. The
1848call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1849statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
1850\bifuncindex{coerce}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001851\end{cfuncdesc}
1852
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001853\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001854Returns the \var{o} converted to an integer object on success, or
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001855\NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001856expression \samp{int(\var{o})}.\bifuncindex{int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001857\end{cfuncdesc}
1858
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001859\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001860Returns the \var{o} converted to a long integer object on success,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001861or \NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001862expression \samp{long(\var{o})}.\bifuncindex{long}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001863\end{cfuncdesc}
1864
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001865\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001866Returns the \var{o} converted to a float object on success, or
1867\NULL{} on failure. This is the equivalent of the Python expression
1868\samp{float(\var{o})}.\bifuncindex{float}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001869\end{cfuncdesc}
1870
1871
Fred Drakeefd146c1999-02-15 15:30:45 +00001872\section{Sequence Protocol \label{sequence}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001873
1874\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001875Return \code{1} if the object provides sequence protocol, and
1876\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001877\end{cfuncdesc}
1878
Fred Drakec6a3cb42001-04-04 01:25:17 +00001879\begin{cfuncdesc}{int}{PySequence_Size}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001880Returns the number of objects in sequence \var{o} on success, and
1881\code{-1} on failure. For objects that do not provide sequence
1882protocol, this is equivalent to the Python expression
1883\samp{len(\var{o})}.\bifuncindex{len}
1884\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001885
Fred Drakec6a3cb42001-04-04 01:25:17 +00001886\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
1887Alternate name for \cfunction{PySequence_Size()}.
1888\end{cfuncdesc}
1889
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001890\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001891Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001892failure. This is the equivalent of the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001893expression \samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001894\end{cfuncdesc}
1895
1896
1897\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Fred Drake659ebfa2000-04-03 15:42:13 +00001898Return the result of repeating sequence object
1899\var{o} \var{count} times, or \NULL{} on failure. This is the
1900equivalent of the Python expression \samp{\var{o} * \var{count}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001901\end{cfuncdesc}
1902
Fred Drake7740a012000-09-12 20:27:05 +00001903\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceConcat}{PyObject *o1, PyObject *o2}
1904Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
1905failure. The operation is done \emph{in-place} when \var{o1} supports it.
1906This is the equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1907\end{cfuncdesc}
1908
1909
1910\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceRepeat}{PyObject *o, int count}
1911Return the result of repeating sequence object \var{o} \var{count} times, or
1912\NULL{} on failure. The operation is done \emph{in-place} when \var{o}
1913supports it. This is the equivalent of the Python expression \samp{\var{o}
1914*= \var{count}}.
1915\end{cfuncdesc}
1916
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001917
1918\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001919Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
1920is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001921\end{cfuncdesc}
1922
1923
1924\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001925Return the slice of sequence object \var{o} between \var{i1} and
1926\var{i2}, or \NULL{} on failure. This is the equivalent of the Python
1927expression \samp{\var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001928\end{cfuncdesc}
1929
1930
1931\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001932Assign object \var{v} to the \var{i}th element of \var{o}.
1933Returns \code{-1} on failure. This is the equivalent of the Python
1934statement \samp{\var{o}[\var{i}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001935\end{cfuncdesc}
1936
1937\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
Fred Drake5566c1c2001-01-19 22:48:33 +00001938Delete the \var{i}th element of object \var{o}. Returns
Fred Drakee058b4f1998-02-16 06:15:35 +00001939\code{-1} on failure. This is the equivalent of the Python
1940statement \samp{del \var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001941\end{cfuncdesc}
1942
Fred Drake659ebfa2000-04-03 15:42:13 +00001943\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
1944 int i2, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001945Assign the sequence object \var{v} to the slice in sequence
1946object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
1947the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001948\end{cfuncdesc}
1949
1950\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001951Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
1952Returns \code{-1} on failure. This is the equivalent of the Python
1953statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001954\end{cfuncdesc}
1955
1956\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001957Returns the \var{o} as a tuple on success, and \NULL{} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00001958This is equivalent to the Python expression \samp{tuple(\var{o})}.
1959\bifuncindex{tuple}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001960\end{cfuncdesc}
1961
1962\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001963Return the number of occurrences of \var{value} in \var{o}, that is,
1964return the number of keys for which \code{\var{o}[\var{key}] ==
1965\var{value}}. On failure, return \code{-1}. This is equivalent to
1966the Python expression \samp{\var{o}.count(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001967\end{cfuncdesc}
1968
Fred Drake659ebfa2000-04-03 15:42:13 +00001969\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001970Determine if \var{o} contains \var{value}. If an item in \var{o} is
1971equal to \var{value}, return \code{1}, otherwise return \code{0}. On
1972error, return \code{-1}. This is equivalent to the Python expression
1973\samp{\var{value} in \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001974\end{cfuncdesc}
1975
1976\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001977Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
1978\var{value}}. On error, return \code{-1}. This is equivalent to
1979the Python expression \samp{\var{o}.index(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001980\end{cfuncdesc}
1981
Fred Drakea8455ab2000-06-16 19:58:42 +00001982\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
1983Return a list object with the same contents as the arbitrary sequence
1984\var{o}. The returned list is guaranteed to be new.
1985\end{cfuncdesc}
1986
1987\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1988Return a tuple object with the same contents as the arbitrary sequence
1989\var{o}. If \var{o} is a tuple, a new reference will be returned,
1990otherwise a tuple will be constructed with the appropriate contents.
1991\end{cfuncdesc}
1992
Fred Drakef39ed671998-02-26 22:01:23 +00001993
Fred Drake81cccb72000-09-12 15:22:05 +00001994\begin{cfuncdesc}{PyObject*}{PySequence_Fast}{PyObject *o, const char *m}
1995Returns the sequence \var{o} as a tuple, unless it is already a
1996tuple or list, in which case \var{o} is returned. Use
1997\cfunction{PySequence_Fast_GET_ITEM()} to access the members of the
1998result. Returns \NULL{} on failure. If the object is not a sequence,
1999raises \exception{TypeError} with \var{m} as the message text.
2000\end{cfuncdesc}
2001
2002\begin{cfuncdesc}{PyObject*}{PySequence_Fast_GET_ITEM}{PyObject *o, int i}
2003Return the \var{i}th element of \var{o}, assuming that \var{o} was
2004returned by \cfunction{PySequence_Fast()}, and that \var{i} is within
2005bounds. The caller is expected to get the length of the sequence by
2006calling \cfunction{PyObject_Size()} on \var{o}, since lists and tuples
2007are guaranteed to always return their true length.
2008\end{cfuncdesc}
2009
2010
Fred Drakeefd146c1999-02-15 15:30:45 +00002011\section{Mapping Protocol \label{mapping}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002012
2013\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002014Return \code{1} if the object provides mapping protocol, and
2015\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002016\end{cfuncdesc}
2017
2018
2019\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002020Returns the number of keys in object \var{o} on success, and
2021\code{-1} on failure. For objects that do not provide mapping
2022protocol, this is equivalent to the Python expression
2023\samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002024\end{cfuncdesc}
2025
2026
2027\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002028Remove the mapping for object \var{key} from the object \var{o}.
2029Return \code{-1} on failure. This is equivalent to
2030the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002031\end{cfuncdesc}
2032
2033
2034\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002035Remove the mapping for object \var{key} from the object \var{o}.
2036Return \code{-1} on failure. This is equivalent to
2037the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002038\end{cfuncdesc}
2039
2040
2041\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
Fred Drake659ebfa2000-04-03 15:42:13 +00002042On success, return \code{1} if the mapping object has the key
2043\var{key} and \code{0} otherwise. This is equivalent to the Python
2044expression \samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002045This function always succeeds.
2046\end{cfuncdesc}
2047
2048
2049\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002050Return \code{1} if the mapping object has the key \var{key} and
2051\code{0} otherwise. This is equivalent to the Python expression
2052\samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002053This function always succeeds.
2054\end{cfuncdesc}
2055
2056
2057\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002058On success, return a list of the keys in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002059failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002060expression \samp{\var{o}.keys()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002061\end{cfuncdesc}
2062
2063
2064\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002065On success, return a list of the values in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002066failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002067expression \samp{\var{o}.values()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002068\end{cfuncdesc}
2069
2070
2071\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002072On success, return a list of the items in object \var{o}, where
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002073each item is a tuple containing a key-value pair. On
2074failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002075expression \samp{\var{o}.items()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002076\end{cfuncdesc}
2077
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002078
2079\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002080Return element of \var{o} corresponding to the object \var{key} or
2081\NULL{} on failure. This is the equivalent of the Python expression
2082\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002083\end{cfuncdesc}
2084
Guido van Rossum0a0f11b1998-10-16 17:43:53 +00002085\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00002086Map the object \var{key} to the value \var{v} in object \var{o}.
2087Returns \code{-1} on failure. This is the equivalent of the Python
2088statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002089\end{cfuncdesc}
2090
2091
Fred Drakeefd146c1999-02-15 15:30:45 +00002092\chapter{Concrete Objects Layer \label{concrete}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002093
2094The functions in this chapter are specific to certain Python object
2095types. Passing them an object of the wrong type is not a good idea;
2096if you receive an object from a Python program and you are not sure
2097that it has the right type, you must perform a type check first;
Fred Drake5566c1c2001-01-19 22:48:33 +00002098for example, to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00002099\cfunction{PyDict_Check()}. The chapter is structured like the
2100``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002101
Fred Drake89024422000-10-23 16:00:54 +00002102\strong{Warning:}
2103While the functions described in this chapter carefully check the type
2104of the objects which are passed in, many of them do not check for
2105\NULL{} being passed instead of a valid object. Allowing \NULL{} to
2106be passed in can cause memory access violations and immediate
2107termination of the interpreter.
2108
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002109
Fred Drakeefd146c1999-02-15 15:30:45 +00002110\section{Fundamental Objects \label{fundamental}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002111
Fred Drakee5bf8b21998-02-12 21:22:28 +00002112This section describes Python type objects and the singleton object
2113\code{None}.
2114
2115
Fred Drakeefd146c1999-02-15 15:30:45 +00002116\subsection{Type Objects \label{typeObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002117
Fred Drake659ebfa2000-04-03 15:42:13 +00002118\obindex{type}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002119\begin{ctypedesc}{PyTypeObject}
Fred Drake659ebfa2000-04-03 15:42:13 +00002120The C structure of the objects used to describe built-in types.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002121\end{ctypedesc}
2122
Fred Drake659ebfa2000-04-03 15:42:13 +00002123\begin{cvardesc}{PyObject*}{PyType_Type}
Fred Drakeefd146c1999-02-15 15:30:45 +00002124This is the type object for type objects; it is the same object as
2125\code{types.TypeType} in the Python layer.
Fred Drake659ebfa2000-04-03 15:42:13 +00002126\withsubitem{(in module types)}{\ttindex{TypeType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002127\end{cvardesc}
2128
Fred Drake659ebfa2000-04-03 15:42:13 +00002129\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
2130Returns true is the object \var{o} is a type object.
2131\end{cfuncdesc}
2132
2133\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
2134Returns true if the type object \var{o} sets the feature
Fred Drakef0e08ef2001-02-03 01:11:26 +00002135\var{feature}. Type features are denoted by single bit flags.
Fred Drake659ebfa2000-04-03 15:42:13 +00002136\end{cfuncdesc}
2137
Fred Drakee5bf8b21998-02-12 21:22:28 +00002138
Fred Drakeefd146c1999-02-15 15:30:45 +00002139\subsection{The None Object \label{noneObject}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002140
Fred Drake659ebfa2000-04-03 15:42:13 +00002141\obindex{None@\texttt{None}}
2142Note that the \ctype{PyTypeObject} for \code{None} is not directly
2143exposed in the Python/C API. Since \code{None} is a singleton,
2144testing for object identity (using \samp{==} in C) is sufficient.
2145There is no \cfunction{PyNone_Check()} function for the same reason.
2146
2147\begin{cvardesc}{PyObject*}{Py_None}
Guido van Rossum44475131998-04-21 15:30:01 +00002148The Python \code{None} object, denoting lack of value. This object has
2149no methods.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002150\end{cvardesc}
2151
2152
Fred Drakeefd146c1999-02-15 15:30:45 +00002153\section{Sequence Objects \label{sequenceObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002154
Fred Drake659ebfa2000-04-03 15:42:13 +00002155\obindex{sequence}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002156Generic operations on sequence objects were discussed in the previous
2157chapter; this section deals with the specific kinds of sequence
2158objects that are intrinsic to the Python language.
2159
2160
Fred Drakeefd146c1999-02-15 15:30:45 +00002161\subsection{String Objects \label{stringObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002162
Fred Drake89024422000-10-23 16:00:54 +00002163These functions raise \exception{TypeError} when expecting a string
2164parameter and are called with a non-string parameter.
2165
Fred Drake659ebfa2000-04-03 15:42:13 +00002166\obindex{string}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002167\begin{ctypedesc}{PyStringObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002168This subtype of \ctype{PyObject} represents a Python string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002169\end{ctypedesc}
2170
2171\begin{cvardesc}{PyTypeObject}{PyString_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002172This instance of \ctype{PyTypeObject} represents the Python string
2173type; it is the same object as \code{types.TypeType} in the Python
2174layer.\withsubitem{(in module types)}{\ttindex{StringType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002175\end{cvardesc}
2176
2177\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002178Returns true if the object \var{o} is a string object.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002179\end{cfuncdesc}
2180
Fred Drakec6fa34e1998-04-02 06:47:24 +00002181\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002182Returns a new string object with the value \var{v} on success, and
2183\NULL{} on failure.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002184\end{cfuncdesc}
2185
Fred Drake659ebfa2000-04-03 15:42:13 +00002186\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
2187 int len}
2188Returns a new string object with the value \var{v} and length
2189\var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
2190the contents of the string are uninitialized.
2191\end{cfuncdesc}
2192
Fred Drakec6fa34e1998-04-02 06:47:24 +00002193\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002194Returns the length of the string in string object \var{string}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002195\end{cfuncdesc}
2196
Fred Drake659ebfa2000-04-03 15:42:13 +00002197\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
Fred Drake5d644212000-10-07 12:31:50 +00002198Macro form of \cfunction{PyString_Size()} but without error
Fred Drake659ebfa2000-04-03 15:42:13 +00002199checking.
2200\end{cfuncdesc}
2201
Fred Drakec6fa34e1998-04-02 06:47:24 +00002202\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
Fred Drake659ebfa2000-04-03 15:42:13 +00002203Returns a null-terminated representation of the contents of
2204\var{string}. The pointer refers to the internal buffer of
Fred Drake89024422000-10-23 16:00:54 +00002205\var{string}, not a copy. The data must not be modified in any way,
2206unless the string was just created using
2207\code{PyString_FromStringAndSize(NULL, \var{size})}.
2208It must not be deallocated.
Fred Drake659ebfa2000-04-03 15:42:13 +00002209\end{cfuncdesc}
2210
2211\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
2212Macro form of \cfunction{PyString_AsString()} but without error
2213checking.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002214\end{cfuncdesc}
2215
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002216\begin{cfuncdesc}{int}{PyString_AsStringAndSize}{PyObject *obj,
2217 char **buffer,
2218 int *length}
2219Returns a null-terminated representation of the contents of the object
2220\var{obj} through the output variables \var{buffer} and \var{length}.
2221
2222The function accepts both string and Unicode objects as input. For
2223Unicode objects it returns the default encoded version of the object.
2224If \var{length} is set to \NULL{}, the resulting buffer may not contain
2225null characters; if it does, the function returns -1 and a
2226TypeError is raised.
2227
2228The buffer refers to an internal string buffer of \var{obj}, not a
Fred Drake89024422000-10-23 16:00:54 +00002229copy. The data must not be modified in any way, unless the string was
2230just created using \code{PyString_FromStringAndSize(NULL,
2231\var{size})}. It must not be deallocated.
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002232\end{cfuncdesc}
2233
Fred Drakec6fa34e1998-04-02 06:47:24 +00002234\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
2235 PyObject *newpart}
Fred Drake66b989c1999-02-15 20:15:39 +00002236Creates a new string object in \var{*string} containing the
Fred Drakeddc6c272000-03-31 18:22:38 +00002237contents of \var{newpart} appended to \var{string}; the caller will
2238own the new reference. The reference to the old value of \var{string}
2239will be stolen. If the new string
Fred Drake66b989c1999-02-15 20:15:39 +00002240cannot be created, the old reference to \var{string} will still be
2241discarded and the value of \var{*string} will be set to
2242\NULL{}; the appropriate exception will be set.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002243\end{cfuncdesc}
2244
2245\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
2246 PyObject *newpart}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002247Creates a new string object in \var{*string} containing the contents
Guido van Rossum44475131998-04-21 15:30:01 +00002248of \var{newpart} appended to \var{string}. This version decrements
2249the reference count of \var{newpart}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002250\end{cfuncdesc}
2251
2252\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
Guido van Rossum44475131998-04-21 15:30:01 +00002253A way to resize a string object even though it is ``immutable''.
2254Only use this to build up a brand new string object; don't use this if
2255the string may already be known in other parts of the code.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002256\end{cfuncdesc}
2257
2258\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
2259 PyObject *args}
Guido van Rossum44475131998-04-21 15:30:01 +00002260Returns a new string object from \var{format} and \var{args}. Analogous
Fred Drake659ebfa2000-04-03 15:42:13 +00002261to \code{\var{format} \%\ \var{args}}. The \var{args} argument must be
Guido van Rossum44475131998-04-21 15:30:01 +00002262a tuple.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002263\end{cfuncdesc}
2264
2265\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
Guido van Rossum44475131998-04-21 15:30:01 +00002266Intern the argument \var{*string} in place. The argument must be the
2267address of a pointer variable pointing to a Python string object.
2268If there is an existing interned string that is the same as
2269\var{*string}, it sets \var{*string} to it (decrementing the reference
2270count of the old string object and incrementing the reference count of
2271the interned string object), otherwise it leaves \var{*string} alone
2272and interns it (incrementing its reference count). (Clarification:
2273even though there is a lot of talk about reference counts, think of
Fred Drakef8830d11998-04-23 14:06:01 +00002274this function as reference-count-neutral; you own the object after
2275the call if and only if you owned it before the call.)
Fred Drakec6fa34e1998-04-02 06:47:24 +00002276\end{cfuncdesc}
2277
2278\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
Fred Drakef8830d11998-04-23 14:06:01 +00002279A combination of \cfunction{PyString_FromString()} and
2280\cfunction{PyString_InternInPlace()}, returning either a new string object
Guido van Rossum44475131998-04-21 15:30:01 +00002281that has been interned, or a new (``owned'') reference to an earlier
2282interned string object with the same value.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002283\end{cfuncdesc}
2284
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002285\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
2286 int size,
2287 const char *encoding,
2288 const char *errors}
2289Create a string object by decoding \var{size} bytes of the encoded
2290buffer \var{s}. \var{encoding} and \var{errors} have the same meaning
2291as the parameters of the same name in the unicode() builtin
2292function. The codec to be used is looked up using the Python codec
2293registry. Returns \NULL{} in case an exception was raised by the
2294codec.
2295\end{cfuncdesc}
2296
2297\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const Py_UNICODE *s,
2298 int size,
2299 const char *encoding,
2300 const char *errors}
2301Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2302Python string object. \var{encoding} and \var{errors} have the same
2303meaning as the parameters of the same name in the string .encode()
2304method. The codec to be used is looked up using the Python codec
2305registry. Returns \NULL{} in case an exception was raised by the
2306codec.
2307\end{cfuncdesc}
2308
2309\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedString}{PyObject *unicode,
2310 const char *encoding,
2311 const char *errors}
2312Encodes a string object and returns the result as Python string
2313object. \var{encoding} and \var{errors} have the same meaning as the
2314parameters of the same name in the string .encode() method. The codec
2315to be used is looked up using the Python codec registry. Returns
2316\NULL{} in case an exception was raised by the codec.
2317\end{cfuncdesc}
2318
Fred Drakee5bf8b21998-02-12 21:22:28 +00002319
Fred Drakea4cd2612000-04-06 14:10:29 +00002320\subsection{Unicode Objects \label{unicodeObjects}}
2321\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
2322
2323%--- Unicode Type -------------------------------------------------------
2324
2325These are the basic Unicode object types used for the Unicode
2326implementation in Python:
2327
2328\begin{ctypedesc}{Py_UNICODE}
2329This type represents a 16-bit unsigned storage type which is used by
2330Python internally as basis for holding Unicode ordinals. On platforms
2331where \ctype{wchar_t} is available and also has 16-bits,
2332\ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
2333native platform compatibility. On all other platforms,
2334\ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
2335\end{ctypedesc}
2336
2337\begin{ctypedesc}{PyUnicodeObject}
2338This subtype of \ctype{PyObject} represents a Python Unicode object.
2339\end{ctypedesc}
2340
2341\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
2342This instance of \ctype{PyTypeObject} represents the Python Unicode type.
2343\end{cvardesc}
2344
2345%--- These are really C macros... is there a macrodesc TeX macro ?
2346
2347The following APIs are really C macros and can be used to do fast
2348checks and to access internal read-only data of Unicode objects:
2349
2350\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
2351Returns true if the object \var{o} is a Unicode object.
2352\end{cfuncdesc}
2353
2354\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
2355Returns the size of the object. o has to be a
2356PyUnicodeObject (not checked).
2357\end{cfuncdesc}
2358
2359\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
2360Returns the size of the object's internal buffer in bytes. o has to be
2361a PyUnicodeObject (not checked).
2362\end{cfuncdesc}
2363
Fred Drake992fe5a2000-06-16 21:04:15 +00002364\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002365Returns a pointer to the internal Py_UNICODE buffer of the object. o
2366has to be a PyUnicodeObject (not checked).
2367\end{cfuncdesc}
2368
Fred Drake992fe5a2000-06-16 21:04:15 +00002369\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002370Returns a (const char *) pointer to the internal buffer of the object.
2371o has to be a PyUnicodeObject (not checked).
2372\end{cfuncdesc}
2373
2374% --- Unicode character properties ---------------------------------------
2375
2376Unicode provides many different character properties. The most often
2377needed ones are available through these macros which are mapped to C
2378functions depending on the Python configuration.
2379
2380\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
2381Returns 1/0 depending on whether \var{ch} is a whitespace character.
2382\end{cfuncdesc}
2383
2384\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
2385Returns 1/0 depending on whether \var{ch} is a lowercase character.
2386\end{cfuncdesc}
2387
2388\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
Fred Drakeae96aab2000-07-03 13:38:10 +00002389Returns 1/0 depending on whether \var{ch} is an uppercase character.
Fred Drakea4cd2612000-04-06 14:10:29 +00002390\end{cfuncdesc}
2391
2392\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
2393Returns 1/0 depending on whether \var{ch} is a titlecase character.
2394\end{cfuncdesc}
2395
2396\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
2397Returns 1/0 depending on whether \var{ch} is a linebreak character.
2398\end{cfuncdesc}
2399
2400\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
2401Returns 1/0 depending on whether \var{ch} is a decimal character.
2402\end{cfuncdesc}
2403
2404\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
2405Returns 1/0 depending on whether \var{ch} is a digit character.
2406\end{cfuncdesc}
2407
2408\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
2409Returns 1/0 depending on whether \var{ch} is a numeric character.
2410\end{cfuncdesc}
2411
Fred Drakeae96aab2000-07-03 13:38:10 +00002412\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
2413Returns 1/0 depending on whether \var{ch} is an alphabetic character.
2414\end{cfuncdesc}
2415
2416\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
2417Returns 1/0 depending on whether \var{ch} is an alphanumeric character.
2418\end{cfuncdesc}
2419
Fred Drakea4cd2612000-04-06 14:10:29 +00002420These APIs can be used for fast direct character conversions:
2421
2422\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
2423Returns the character \var{ch} converted to lower case.
2424\end{cfuncdesc}
2425
2426\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
2427Returns the character \var{ch} converted to upper case.
2428\end{cfuncdesc}
2429
2430\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
2431Returns the character \var{ch} converted to title case.
2432\end{cfuncdesc}
2433
2434\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
2435Returns the character \var{ch} converted to a decimal positive integer.
2436Returns -1 in case this is not possible. Does not raise exceptions.
2437\end{cfuncdesc}
2438
2439\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
2440Returns the character \var{ch} converted to a single digit integer.
2441Returns -1 in case this is not possible. Does not raise exceptions.
2442\end{cfuncdesc}
2443
2444\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
2445Returns the character \var{ch} converted to a (positive) double.
2446Returns -1.0 in case this is not possible. Does not raise exceptions.
2447\end{cfuncdesc}
2448
2449% --- Plain Py_UNICODE ---------------------------------------------------
2450
2451To create Unicode objects and access their basic sequence properties,
2452use these APIs:
2453
2454\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
2455 int size}
2456
2457Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
2458given size. \var{u} may be \NULL{} which causes the contents to be
2459undefined. It is the user's responsibility to fill in the needed data.
2460The buffer is copied into the new object.
2461\end{cfuncdesc}
2462
Fred Drake1d158692000-06-18 05:21:21 +00002463\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002464Return a read-only pointer to the Unicode object's internal
2465\ctype{Py_UNICODE} buffer.
2466\end{cfuncdesc}
2467
2468\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
2469Return the length of the Unicode object.
2470\end{cfuncdesc}
2471
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002472\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
2473 const char *encoding,
2474 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002475
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002476Coerce an encoded object obj to an Unicode object and return a
2477reference with incremented refcount.
Fred Drakea4cd2612000-04-06 14:10:29 +00002478
2479Coercion is done in the following way:
2480\begin{enumerate}
2481\item Unicode objects are passed back as-is with incremented
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002482 refcount. Note: these cannot be decoded; passing a non-NULL
2483 value for encoding will result in a TypeError.
Fred Drakea4cd2612000-04-06 14:10:29 +00002484
2485\item String and other char buffer compatible objects are decoded
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002486 according to the given encoding and using the error handling
2487 defined by errors. Both can be NULL to have the interface use
2488 the default values (see the next section for details).
Fred Drakea4cd2612000-04-06 14:10:29 +00002489
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002490\item All other objects cause an exception.
Fred Drakea4cd2612000-04-06 14:10:29 +00002491\end{enumerate}
2492The API returns NULL in case of an error. The caller is responsible
2493for decref'ing the returned objects.
2494\end{cfuncdesc}
2495
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002496\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
2497
2498Shortcut for PyUnicode_FromEncodedObject(obj, NULL, ``strict'')
2499which is used throughout the interpreter whenever coercion to
2500Unicode is needed.
2501\end{cfuncdesc}
2502
Fred Drakea4cd2612000-04-06 14:10:29 +00002503% --- wchar_t support for platforms which support it ---------------------
2504
2505If the platform supports \ctype{wchar_t} and provides a header file
2506wchar.h, Python can interface directly to this type using the
2507following functions. Support is optimized if Python's own
2508\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
2509
2510\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
2511 int size}
2512Create a Unicode Object from the \ctype{whcar_t} buffer \var{w} of the
2513given size. Returns \NULL{} on failure.
2514\end{cfuncdesc}
2515
2516\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
2517 wchar_t *w,
2518 int size}
Fred Drakea4cd2612000-04-06 14:10:29 +00002519Copies the Unicode Object contents into the \ctype{whcar_t} buffer
2520\var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
2521Returns the number of \ctype{whcar_t} characters copied or -1 in case
2522of an error.
2523\end{cfuncdesc}
2524
2525
2526\subsubsection{Builtin Codecs \label{builtinCodecs}}
2527
2528Python provides a set of builtin codecs which are written in C
2529for speed. All of these codecs are directly usable via the
2530following functions.
2531
2532Many of the following APIs take two arguments encoding and
2533errors. These parameters encoding and errors have the same semantics
2534as the ones of the builtin unicode() Unicode object constructor.
2535
2536Setting encoding to NULL causes the default encoding to be used which
2537is UTF-8.
2538
2539Error handling is set by errors which may also be set to NULL meaning
2540to use the default handling defined for the codec. Default error
2541handling for all builtin codecs is ``strict'' (ValueErrors are raised).
2542
2543The codecs all use a similar interface. Only deviation from the
2544following generic ones are documented for simplicity.
2545
2546% --- Generic Codecs -----------------------------------------------------
2547
2548These are the generic codec APIs:
2549
2550\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
2551 int size,
2552 const char *encoding,
2553 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002554Create a Unicode object by decoding \var{size} bytes of the encoded
2555string \var{s}. \var{encoding} and \var{errors} have the same meaning
2556as the parameters of the same name in the unicode() builtin
2557function. The codec to be used is looked up using the Python codec
2558registry. Returns \NULL{} in case an exception was raised by the
2559codec.
2560\end{cfuncdesc}
2561
2562\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
2563 int size,
2564 const char *encoding,
2565 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002566Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2567Python string object. \var{encoding} and \var{errors} have the same
2568meaning as the parameters of the same name in the Unicode .encode()
2569method. The codec to be used is looked up using the Python codec
2570registry. Returns \NULL{} in case an exception was raised by the
2571codec.
2572\end{cfuncdesc}
2573
2574\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
2575 const char *encoding,
2576 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002577Encodes a Unicode object and returns the result as Python string
2578object. \var{encoding} and \var{errors} have the same meaning as the
2579parameters of the same name in the Unicode .encode() method. The codec
2580to be used is looked up using the Python codec registry. Returns
2581\NULL{} in case an exception was raised by the codec.
2582\end{cfuncdesc}
2583
2584% --- UTF-8 Codecs -------------------------------------------------------
2585
2586These are the UTF-8 codec APIs:
2587
2588\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
2589 int size,
2590 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002591Creates a Unicode object by decoding \var{size} bytes of the UTF-8
2592encoded string \var{s}. Returns \NULL{} in case an exception was
2593raised by the codec.
2594\end{cfuncdesc}
2595
2596\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
2597 int size,
2598 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002599Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
2600and returns a Python string object. Returns \NULL{} in case an
2601exception was raised by the codec.
2602\end{cfuncdesc}
2603
2604\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002605Encodes a Unicode objects using UTF-8 and returns the result as Python
2606string object. Error handling is ``strict''. Returns
2607\NULL{} in case an exception was raised by the codec.
2608\end{cfuncdesc}
2609
2610% --- UTF-16 Codecs ------------------------------------------------------ */
2611
2612These are the UTF-16 codec APIs:
2613
2614\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
2615 int size,
2616 const char *errors,
2617 int *byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002618Decodes \var{length} bytes from a UTF-16 encoded buffer string and
2619returns the corresponding Unicode object.
2620
2621\var{errors} (if non-NULL) defines the error handling. It defaults
2622to ``strict''.
2623
2624If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
2625the given byte order:
2626
2627\begin{verbatim}
2628 *byteorder == -1: little endian
2629 *byteorder == 0: native order
2630 *byteorder == 1: big endian
2631\end{verbatim}
2632
2633and then switches according to all byte order marks (BOM) it finds in
2634the input data. BOM marks are not copied into the resulting Unicode
2635string. After completion, \var{*byteorder} is set to the current byte
2636order at the end of input data.
2637
2638If \var{byteorder} is \NULL{}, the codec starts in native order mode.
2639
2640Returns \NULL{} in case an exception was raised by the codec.
2641\end{cfuncdesc}
2642
2643\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
2644 int size,
2645 const char *errors,
2646 int byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002647Returns a Python string object holding the UTF-16 encoded value of the
2648Unicode data in \var{s}.
2649
Fred Drakea8455ab2000-06-16 19:58:42 +00002650If \var{byteorder} is not \code{0}, output is written according to the
Fred Drakea4cd2612000-04-06 14:10:29 +00002651following byte order:
2652
2653\begin{verbatim}
2654 byteorder == -1: little endian
2655 byteorder == 0: native byte order (writes a BOM mark)
2656 byteorder == 1: big endian
2657\end{verbatim}
2658
Fred Drakea8455ab2000-06-16 19:58:42 +00002659If byteorder is \code{0}, the output string will always start with the
Fred Drakea4cd2612000-04-06 14:10:29 +00002660Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
2661prepended.
2662
2663Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
2664reduced to UCS-2. This trick makes it possible to add full UTF-16
2665capabilities at a later point without comprimising the APIs.
2666
2667Returns \NULL{} in case an exception was raised by the codec.
2668\end{cfuncdesc}
2669
2670\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002671Returns a Python string using the UTF-16 encoding in native byte
2672order. The string always starts with a BOM mark. Error handling is
2673``strict''. Returns \NULL{} in case an exception was raised by the
2674codec.
2675\end{cfuncdesc}
2676
2677% --- Unicode-Escape Codecs ----------------------------------------------
2678
2679These are the ``Unicode Esacpe'' codec APIs:
2680
2681\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
2682 int size,
2683 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002684Creates a Unicode object by decoding \var{size} bytes of the Unicode-Esacpe
2685encoded string \var{s}. Returns \NULL{} in case an exception was
2686raised by the codec.
2687\end{cfuncdesc}
2688
2689\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
2690 int size,
2691 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002692Encodes the \ctype{Py_UNICODE} buffer of the given size using Unicode-Escape
2693and returns a Python string object. Returns \NULL{} in case an
2694exception was raised by the codec.
2695\end{cfuncdesc}
2696
2697\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002698Encodes a Unicode objects using Unicode-Escape and returns the result
2699as Python string object. Error handling is ``strict''. Returns
2700\NULL{} in case an exception was raised by the codec.
2701\end{cfuncdesc}
2702
2703% --- Raw-Unicode-Escape Codecs ------------------------------------------
2704
2705These are the ``Raw Unicode Esacpe'' codec APIs:
2706
2707\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
2708 int size,
2709 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002710Creates a Unicode object by decoding \var{size} bytes of the Raw-Unicode-Esacpe
2711encoded string \var{s}. Returns \NULL{} in case an exception was
2712raised by the codec.
2713\end{cfuncdesc}
2714
2715\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
2716 int size,
2717 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002718Encodes the \ctype{Py_UNICODE} buffer of the given size using Raw-Unicode-Escape
2719and returns a Python string object. Returns \NULL{} in case an
2720exception was raised by the codec.
2721\end{cfuncdesc}
2722
2723\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002724Encodes a Unicode objects using Raw-Unicode-Escape and returns the result
2725as Python string object. Error handling is ``strict''. Returns
2726\NULL{} in case an exception was raised by the codec.
2727\end{cfuncdesc}
2728
2729% --- Latin-1 Codecs -----------------------------------------------------
2730
2731These are the Latin-1 codec APIs:
2732
2733Latin-1 corresponds to the first 256 Unicode ordinals and only these
2734are accepted by the codecs during encoding.
2735
2736\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002737 int size,
2738 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002739Creates a Unicode object by decoding \var{size} bytes of the Latin-1
2740encoded string \var{s}. Returns \NULL{} in case an exception was
2741raised by the codec.
2742\end{cfuncdesc}
2743
2744\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002745 int size,
2746 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002747Encodes the \ctype{Py_UNICODE} buffer of the given size using Latin-1
2748and returns a Python string object. Returns \NULL{} in case an
2749exception was raised by the codec.
2750\end{cfuncdesc}
2751
2752\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002753Encodes a Unicode objects using Latin-1 and returns the result as
2754Python string object. Error handling is ``strict''. Returns
2755\NULL{} in case an exception was raised by the codec.
2756\end{cfuncdesc}
2757
2758% --- ASCII Codecs -------------------------------------------------------
2759
Fred Drake1d158692000-06-18 05:21:21 +00002760These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
2761accepted. All other codes generate errors.
Fred Drakea4cd2612000-04-06 14:10:29 +00002762
2763\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002764 int size,
2765 const char *errors}
2766Creates a Unicode object by decoding \var{size} bytes of the
2767\ASCII{} encoded string \var{s}. Returns \NULL{} in case an exception
2768was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002769\end{cfuncdesc}
2770
2771\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002772 int size,
2773 const char *errors}
2774Encodes the \ctype{Py_UNICODE} buffer of the given size using
2775\ASCII{} and returns a Python string object. Returns \NULL{} in case
2776an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002777\end{cfuncdesc}
2778
2779\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
Fred Drake1d158692000-06-18 05:21:21 +00002780Encodes a Unicode objects using \ASCII{} and returns the result as Python
Fred Drakea4cd2612000-04-06 14:10:29 +00002781string object. Error handling is ``strict''. Returns
2782\NULL{} in case an exception was raised by the codec.
2783\end{cfuncdesc}
2784
2785% --- Character Map Codecs -----------------------------------------------
2786
2787These are the mapping codec APIs:
2788
2789This codec is special in that it can be used to implement many
2790different codecs (and this is in fact what was done to obtain most of
2791the standard codecs included in the \module{encodings} package). The
2792codec uses mapping to encode and decode characters.
2793
2794Decoding mappings must map single string characters to single Unicode
2795characters, integers (which are then interpreted as Unicode ordinals)
2796or None (meaning "undefined mapping" and causing an error).
2797
2798Encoding mappings must map single Unicode characters to single string
2799characters, integers (which are then interpreted as Latin-1 ordinals)
2800or None (meaning "undefined mapping" and causing an error).
2801
2802The mapping objects provided must only support the __getitem__ mapping
2803interface.
2804
2805If a character lookup fails with a LookupError, the character is
2806copied as-is meaning that its ordinal value will be interpreted as
2807Unicode or Latin-1 ordinal resp. Because of this, mappings only need
2808to contain those mappings which map characters to different code
2809points.
2810
2811\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
2812 int size,
2813 PyObject *mapping,
2814 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002815Creates a Unicode object by decoding \var{size} bytes of the encoded
2816string \var{s} using the given \var{mapping} object. Returns \NULL{}
2817in case an exception was raised by the codec.
2818\end{cfuncdesc}
2819
2820\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
2821 int size,
2822 PyObject *mapping,
2823 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002824Encodes the \ctype{Py_UNICODE} buffer of the given size using the
2825given \var{mapping} object and returns a Python string object.
2826Returns \NULL{} in case an exception was raised by the codec.
2827\end{cfuncdesc}
2828
2829\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
2830 PyObject *mapping}
Fred Drakea4cd2612000-04-06 14:10:29 +00002831Encodes a Unicode objects using the given \var{mapping} object and
2832returns the result as Python string object. Error handling is
2833``strict''. Returns \NULL{} in case an exception was raised by the
2834codec.
2835\end{cfuncdesc}
2836
2837The following codec API is special in that maps Unicode to Unicode.
2838
2839\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
2840 int size,
2841 PyObject *table,
2842 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002843Translates a \ctype{Py_UNICODE} buffer of the given length by applying
2844a character mapping \var{table} to it and returns the resulting
Fred Drake1d158692000-06-18 05:21:21 +00002845Unicode object. Returns \NULL{} when an exception was raised by the
2846codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002847
2848The \var{mapping} table must map Unicode ordinal integers to Unicode
2849ordinal integers or None (causing deletion of the character).
2850
2851Mapping tables must only provide the __getitem__ interface,
2852e.g. dictionaries or sequences. Unmapped character ordinals (ones
2853which cause a LookupError) are left untouched and are copied as-is.
Fred Drakea4cd2612000-04-06 14:10:29 +00002854\end{cfuncdesc}
2855
2856% --- MBCS codecs for Windows --------------------------------------------
2857
Fred Drake1d158692000-06-18 05:21:21 +00002858These are the MBCS codec APIs. They are currently only available on
Fred Drakea4cd2612000-04-06 14:10:29 +00002859Windows and use the Win32 MBCS converters to implement the
Fred Drake1d158692000-06-18 05:21:21 +00002860conversions. Note that MBCS (or DBCS) is a class of encodings, not
2861just one. The target encoding is defined by the user settings on the
2862machine running the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002863
2864\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
2865 int size,
2866 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002867Creates a Unicode object by decoding \var{size} bytes of the MBCS
Fred Drake1d158692000-06-18 05:21:21 +00002868encoded string \var{s}. Returns \NULL{} in case an exception was
Fred Drakea4cd2612000-04-06 14:10:29 +00002869raised by the codec.
2870\end{cfuncdesc}
2871
2872\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
2873 int size,
2874 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002875Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
2876and returns a Python string object. Returns \NULL{} in case an
2877exception was raised by the codec.
2878\end{cfuncdesc}
2879
2880\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002881Encodes a Unicode objects using MBCS and returns the result as Python
Fred Drake1d158692000-06-18 05:21:21 +00002882string object. Error handling is ``strict''. Returns \NULL{} in case
2883an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002884\end{cfuncdesc}
2885
2886% --- Methods & Slots ----------------------------------------------------
2887
2888\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
2889
2890The following APIs are capable of handling Unicode objects and strings
2891on input (we refer to them as strings in the descriptions) and return
2892Unicode objects or integers as apporpriate.
2893
2894They all return \NULL{} or -1 in case an exception occurrs.
2895
2896\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
2897 PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002898Concat two strings giving a new Unicode string.
2899\end{cfuncdesc}
2900
2901\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
2902 PyObject *sep,
2903 int maxsplit}
Fred Drakea4cd2612000-04-06 14:10:29 +00002904Split a string giving a list of Unicode strings.
2905
2906If sep is NULL, splitting will be done at all whitespace
2907substrings. Otherwise, splits occur at the given separator.
2908
2909At most maxsplit splits will be done. If negative, no limit is set.
2910
2911Separators are not included in the resulting list.
2912\end{cfuncdesc}
2913
2914\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
2915 int maxsplit}
Fred Drake1d158692000-06-18 05:21:21 +00002916Split a Unicode string at line breaks, returning a list of Unicode
2917strings. CRLF is considered to be one line break. The Line break
2918characters are not included in the resulting strings.
Fred Drakea4cd2612000-04-06 14:10:29 +00002919\end{cfuncdesc}
2920
2921\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
2922 PyObject *table,
2923 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002924Translate a string by applying a character mapping table to it and
2925return the resulting Unicode object.
2926
2927The mapping table must map Unicode ordinal integers to Unicode ordinal
2928integers or None (causing deletion of the character).
2929
2930Mapping tables must only provide the __getitem__ interface,
2931e.g. dictionaries or sequences. Unmapped character ordinals (ones
2932which cause a LookupError) are left untouched and are copied as-is.
2933
2934\var{errors} has the usual meaning for codecs. It may be \NULL{}
2935which indicates to use the default error handling.
Fred Drakea4cd2612000-04-06 14:10:29 +00002936\end{cfuncdesc}
2937
2938\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
2939 PyObject *seq}
Fred Drakea4cd2612000-04-06 14:10:29 +00002940Join a sequence of strings using the given separator and return
2941the resulting Unicode string.
2942\end{cfuncdesc}
2943
2944\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
2945 PyObject *substr,
2946 int start,
2947 int end,
2948 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002949Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
2950the given tail end (\var{direction} == -1 means to do a prefix match,
2951\var{direction} == 1 a suffix match), 0 otherwise.
2952\end{cfuncdesc}
2953
2954\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
2955 PyObject *substr,
2956 int start,
2957 int end,
2958 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002959Return the first position of \var{substr} in
2960\var{str}[\var{start}:\var{end}] using the given \var{direction}
2961(\var{direction} == 1 means to do a forward search,
2962\var{direction} == -1 a backward search), 0 otherwise.
2963\end{cfuncdesc}
2964
2965\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
2966 PyObject *substr,
2967 int start,
2968 int end}
Fred Drakea4cd2612000-04-06 14:10:29 +00002969Count the number of occurrences of \var{substr} in
2970\var{str}[\var{start}:\var{end}]
2971\end{cfuncdesc}
2972
2973\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
2974 PyObject *substr,
2975 PyObject *replstr,
2976 int maxcount}
Fred Drakea4cd2612000-04-06 14:10:29 +00002977Replace at most \var{maxcount} occurrences of \var{substr} in
2978\var{str} with \var{replstr} and return the resulting Unicode object.
2979\var{maxcount} == -1 means: replace all occurrences.
2980\end{cfuncdesc}
2981
Fred Drake1d158692000-06-18 05:21:21 +00002982\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002983Compare two strings and return -1, 0, 1 for less than, equal,
2984greater than resp.
2985\end{cfuncdesc}
2986
2987\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
2988 PyObject *args}
Fred Drake1d158692000-06-18 05:21:21 +00002989Returns a new string object from \var{format} and \var{args}; this is
2990analogous to \code{\var{format} \%\ \var{args}}. The
2991\var{args} argument must be a tuple.
Fred Drakea4cd2612000-04-06 14:10:29 +00002992\end{cfuncdesc}
2993
2994\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
2995 PyObject *element}
Fred Drakea4cd2612000-04-06 14:10:29 +00002996Checks whether \var{element} is contained in \var{container} and
Fred Drake1d158692000-06-18 05:21:21 +00002997returns true or false accordingly.
Fred Drakea4cd2612000-04-06 14:10:29 +00002998
Fred Drake1d158692000-06-18 05:21:21 +00002999\var{element} has to coerce to a one element Unicode string. \code{-1} is
Fred Drakea4cd2612000-04-06 14:10:29 +00003000returned in case of an error.
3001\end{cfuncdesc}
3002
3003
Fred Drake58c5a2a1999-08-04 13:13:24 +00003004\subsection{Buffer Objects \label{bufferObjects}}
Fred Drake659ebfa2000-04-03 15:42:13 +00003005\sectionauthor{Greg Stein}{gstein@lyra.org}
Fred Drake58c5a2a1999-08-04 13:13:24 +00003006
Fred Drake659ebfa2000-04-03 15:42:13 +00003007\obindex{buffer}
3008Python objects implemented in C can export a group of functions called
3009the ``buffer\index{buffer interface} interface.'' These functions can
3010be used by an object to expose its data in a raw, byte-oriented
3011format. Clients of the object can use the buffer interface to access
3012the object data directly, without needing to copy it first.
3013
3014Two examples of objects that support
3015the buffer interface are strings and arrays. The string object exposes
3016the character contents in the buffer interface's byte-oriented
3017form. An array can also expose its contents, but it should be noted
3018that array elements may be multi-byte values.
3019
3020An example user of the buffer interface is the file object's
3021\method{write()} method. Any object that can export a series of bytes
3022through the buffer interface can be written to a file. There are a
3023number of format codes to \cfunction{PyArgs_ParseTuple()} that operate
3024against an object's buffer interface, returning data from the target
3025object.
3026
3027More information on the buffer interface is provided in the section
3028``Buffer Object Structures'' (section \ref{buffer-structs}), under
3029the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
3030
3031A ``buffer object'' is defined in the \file{bufferobject.h} header
3032(included by \file{Python.h}). These objects look very similar to
3033string objects at the Python programming level: they support slicing,
3034indexing, concatenation, and some other standard string
3035operations. However, their data can come from one of two sources: from
3036a block of memory, or from another object which exports the buffer
3037interface.
3038
3039Buffer objects are useful as a way to expose the data from another
3040object's buffer interface to the Python programmer. They can also be
3041used as a zero-copy slicing mechanism. Using their ability to
3042reference a block of memory, it is possible to expose any data to the
3043Python programmer quite easily. The memory could be a large, constant
3044array in a C extension, it could be a raw block of memory for
3045manipulation before passing to an operating system library, or it
3046could be used to pass around structured data in its native, in-memory
3047format.
3048
3049\begin{ctypedesc}{PyBufferObject}
3050This subtype of \ctype{PyObject} represents a buffer object.
3051\end{ctypedesc}
Fred Drake58c5a2a1999-08-04 13:13:24 +00003052
3053\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
3054The instance of \ctype{PyTypeObject} which represents the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00003055buffer type; it is the same object as \code{types.BufferType} in the
3056Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003057\end{cvardesc}
3058
3059\begin{cvardesc}{int}{Py_END_OF_BUFFER}
Fred Drake659ebfa2000-04-03 15:42:13 +00003060This constant may be passed as the \var{size} parameter to
3061\cfunction{PyBuffer_FromObject()} or
3062\cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the new
3063\ctype{PyBufferObject} should refer to \var{base} object from the
3064specified \var{offset} to the end of its exported buffer. Using this
3065enables the caller to avoid querying the \var{base} object for its
3066length.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003067\end{cvardesc}
3068
3069\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
3070Return true if the argument has type \cdata{PyBuffer_Type}.
3071\end{cfuncdesc}
3072
3073\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
3074 int offset, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003075Return a new read-only buffer object. This raises
3076\exception{TypeError} if \var{base} doesn't support the read-only
3077buffer protocol or doesn't provide exactly one buffer segment, or it
3078raises \exception{ValueError} if \var{offset} is less than zero. The
3079buffer will hold a reference to the \var{base} object, and the
3080buffer's contents will refer to the \var{base} object's buffer
3081interface, starting as position \var{offset} and extending for
3082\var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
3083the new buffer's contents extend to the length of the
3084\var{base} object's exported buffer data.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003085\end{cfuncdesc}
3086
3087\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
3088 int offset,
3089 int size}
3090Return a new writable buffer object. Parameters and exceptions are
3091similar to those for \cfunction{PyBuffer_FromObject()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003092If the \var{base} object does not export the writeable buffer
3093protocol, then \exception{TypeError} is raised.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003094\end{cfuncdesc}
3095
3096\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003097Return a new read-only buffer object that reads from a specified
3098location in memory, with a specified size.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003099The caller is responsible for ensuring that the memory buffer, passed
3100in as \var{ptr}, is not deallocated while the returned buffer object
3101exists. Raises \exception{ValueError} if \var{size} is less than
Fred Drake659ebfa2000-04-03 15:42:13 +00003102zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be passed
3103for the \var{size} parameter; \exception{ValueError} will be raised in
3104that case.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003105\end{cfuncdesc}
3106
3107\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003108Similar to \cfunction{PyBuffer_FromMemory()}, but the returned buffer
3109is writable.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003110\end{cfuncdesc}
3111
3112\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
3113Returns a new writable buffer object that maintains its own memory
Fred Drake659ebfa2000-04-03 15:42:13 +00003114buffer of \var{size} bytes. \exception{ValueError} is returned if
3115\var{size} is not zero or positive.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003116\end{cfuncdesc}
3117
Guido van Rossum44475131998-04-21 15:30:01 +00003118
Fred Drakeefd146c1999-02-15 15:30:45 +00003119\subsection{Tuple Objects \label{tupleObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003120
Fred Drake659ebfa2000-04-03 15:42:13 +00003121\obindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003122\begin{ctypedesc}{PyTupleObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003123This subtype of \ctype{PyObject} represents a Python tuple object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003124\end{ctypedesc}
3125
3126\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003127This instance of \ctype{PyTypeObject} represents the Python tuple
3128type; it is the same object as \code{types.TupleType} in the Python
3129layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003130\end{cvardesc}
3131
3132\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
3133Return true if the argument is a tuple object.
3134\end{cfuncdesc}
3135
Fred Drake659ebfa2000-04-03 15:42:13 +00003136\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
3137Return a new tuple object of size \var{len}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003138\end{cfuncdesc}
3139
Fred Drakea05460c2001-02-12 17:38:18 +00003140\begin{cfuncdesc}{int}{PyTuple_Size}{PyObject *p}
Fred Drakee058b4f1998-02-16 06:15:35 +00003141Takes a pointer to a tuple object, and returns the size
Fred Drakee5bf8b21998-02-12 21:22:28 +00003142of that tuple.
3143\end{cfuncdesc}
3144
Fred Drakea05460c2001-02-12 17:38:18 +00003145\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003146Returns the object at position \var{pos} in the tuple pointed
3147to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003148sets an \exception{IndexError} exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003149\end{cfuncdesc}
3150
Fred Drakea05460c2001-02-12 17:38:18 +00003151\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003152Does the same, but does no checking of its arguments.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003153\end{cfuncdesc}
3154
Fred Drakea05460c2001-02-12 17:38:18 +00003155\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyObject *p,
3156 int low, int high}
Fred Drakee058b4f1998-02-16 06:15:35 +00003157Takes a slice of the tuple pointed to by \var{p} from
3158\var{low} to \var{high} and returns it as a new tuple.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003159\end{cfuncdesc}
3160
Fred Drake659ebfa2000-04-03 15:42:13 +00003161\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
3162 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003163Inserts a reference to object \var{o} at position \var{pos} of
3164the tuple pointed to by \var{p}. It returns \code{0} on success.
Fred Drake659ebfa2000-04-03 15:42:13 +00003165\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003166\end{cfuncdesc}
3167
Fred Drake659ebfa2000-04-03 15:42:13 +00003168\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
3169 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003170Does the same, but does no error checking, and
Fred Drakee5bf8b21998-02-12 21:22:28 +00003171should \emph{only} be used to fill in brand new tuples.
Fred Drake659ebfa2000-04-03 15:42:13 +00003172\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003173\end{cfuncdesc}
3174
Fred Drakea05460c2001-02-12 17:38:18 +00003175\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyObject **p,
Fred Drake659ebfa2000-04-03 15:42:13 +00003176 int newsize, int last_is_sticky}
3177Can be used to resize a tuple. \var{newsize} will be the new length
3178of the tuple. Because tuples are \emph{supposed} to be immutable,
3179this should only be used if there is only one reference to the object.
3180Do \emph{not} use this if the tuple may already be known to some other
Neil Schemenauer410cb6b2000-10-05 19:38:24 +00003181part of the code. The tuple will always grow or shrink at the end. The
3182\var{last_is_sticky} flag is not used and should always be false. Think
3183of this as destroying the old tuple and creating a new one, only more
3184efficiently. Returns \code{0} on success and \code{-1} on failure (in
3185which case a \exception{MemoryError} or \exception{SystemError} will be
3186raised).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003187\end{cfuncdesc}
3188
3189
Fred Drakeefd146c1999-02-15 15:30:45 +00003190\subsection{List Objects \label{listObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003191
Fred Drake659ebfa2000-04-03 15:42:13 +00003192\obindex{list}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003193\begin{ctypedesc}{PyListObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003194This subtype of \ctype{PyObject} represents a Python list object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003195\end{ctypedesc}
3196
3197\begin{cvardesc}{PyTypeObject}{PyList_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003198This instance of \ctype{PyTypeObject} represents the Python list
3199type. This is the same object as \code{types.ListType}.
3200\withsubitem{(in module types)}{\ttindex{ListType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003201\end{cvardesc}
3202
3203\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003204Returns true if its argument is a \ctype{PyListObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003205\end{cfuncdesc}
3206
Fred Drake659ebfa2000-04-03 15:42:13 +00003207\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
3208Returns a new list of length \var{len} on success, or \NULL{} on
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003209failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003210\end{cfuncdesc}
3211
Fred Drakec6fa34e1998-04-02 06:47:24 +00003212\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003213Returns the length of the list object in \var{list}; this is
3214equivalent to \samp{len(\var{list})} on a list object.
3215\bifuncindex{len}
3216\end{cfuncdesc}
3217
3218\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
Fred Drake5d644212000-10-07 12:31:50 +00003219Macro form of \cfunction{PyList_Size()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003220\end{cfuncdesc}
3221
Fred Drakec6fa34e1998-04-02 06:47:24 +00003222\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
Guido van Rossum44475131998-04-21 15:30:01 +00003223Returns the object at position \var{pos} in the list pointed
3224to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003225sets an \exception{IndexError} exception.
3226\end{cfuncdesc}
3227
3228\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
3229Macro form of \cfunction{PyList_GetItem()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003230\end{cfuncdesc}
3231
Fred Drakec6fa34e1998-04-02 06:47:24 +00003232\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
3233 PyObject *item}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003234Sets the item at index \var{index} in list to \var{item}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003235\strong{Note:} This function ``steals'' a reference to \var{item}.
3236\end{cfuncdesc}
3237
3238\begin{cfuncdesc}{PyObject*}{PyList_SET_ITEM}{PyObject *list, int i,
3239 PyObject *o}
3240Macro form of \cfunction{PyList_SetItem()} without error checking.
3241\strong{Note:} This function ``steals'' a reference to \var{item}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003242\end{cfuncdesc}
3243
Fred Drakec6fa34e1998-04-02 06:47:24 +00003244\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
Guido van Rossum44475131998-04-21 15:30:01 +00003245 PyObject *item}
3246Inserts the item \var{item} into list \var{list} in front of index
Fred Drake659ebfa2000-04-03 15:42:13 +00003247\var{index}. Returns \code{0} if successful; returns \code{-1} and
3248raises an exception if unsuccessful. Analogous to
3249\code{\var{list}.insert(\var{index}, \var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003250\end{cfuncdesc}
3251
Fred Drakec6fa34e1998-04-02 06:47:24 +00003252\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
Guido van Rossum44475131998-04-21 15:30:01 +00003253Appends the object \var{item} at the end of list \var{list}. Returns
Fred Drake659ebfa2000-04-03 15:42:13 +00003254\code{0} if successful; returns \code{-1} and sets an exception if
3255unsuccessful. Analogous to \code{\var{list}.append(\var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003256\end{cfuncdesc}
3257
Fred Drakec6fa34e1998-04-02 06:47:24 +00003258\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
3259 int low, int high}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003260Returns a list of the objects in \var{list} containing the objects
Guido van Rossum44475131998-04-21 15:30:01 +00003261\emph{between} \var{low} and \var{high}. Returns NULL and sets an
3262exception if unsuccessful.
Fred Drake659ebfa2000-04-03 15:42:13 +00003263Analogous to \code{\var{list}[\var{low}:\var{high}]}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003264\end{cfuncdesc}
3265
Fred Drakec6fa34e1998-04-02 06:47:24 +00003266\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
3267 int low, int high,
3268 PyObject *itemlist}
Fred Drake659ebfa2000-04-03 15:42:13 +00003269Sets the slice of \var{list} between \var{low} and \var{high} to the
3270contents of \var{itemlist}. Analogous to
3271\code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
3272\code{0} on success, \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003273\end{cfuncdesc}
3274
Fred Drakec6fa34e1998-04-02 06:47:24 +00003275\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003276Sorts the items of \var{list} in place. Returns \code{0} on success,
3277\code{-1} on failure. This is equivalent to
3278\samp{\var{list}.sort()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003279\end{cfuncdesc}
3280
Fred Drakec6fa34e1998-04-02 06:47:24 +00003281\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003282Reverses the items of \var{list} in place. Returns \code{0} on
3283success, \code{-1} on failure. This is the equivalent of
3284\samp{\var{list}.reverse()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003285\end{cfuncdesc}
3286
Fred Drakec6fa34e1998-04-02 06:47:24 +00003287\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003288Returns a new tuple object containing the contents of \var{list};
3289equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003290\end{cfuncdesc}
3291
3292
Fred Drakeefd146c1999-02-15 15:30:45 +00003293\section{Mapping Objects \label{mapObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003294
Fred Drake659ebfa2000-04-03 15:42:13 +00003295\obindex{mapping}
3296
3297
Fred Drakeefd146c1999-02-15 15:30:45 +00003298\subsection{Dictionary Objects \label{dictObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003299
Fred Drake659ebfa2000-04-03 15:42:13 +00003300\obindex{dictionary}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003301\begin{ctypedesc}{PyDictObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003302This subtype of \ctype{PyObject} represents a Python dictionary object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003303\end{ctypedesc}
3304
3305\begin{cvardesc}{PyTypeObject}{PyDict_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003306This instance of \ctype{PyTypeObject} represents the Python dictionary
3307type. This is exposed to Python programs as \code{types.DictType} and
3308\code{types.DictionaryType}.
3309\withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003310\end{cvardesc}
3311
3312\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003313Returns true if its argument is a \ctype{PyDictObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003314\end{cfuncdesc}
3315
Fred Drakec6fa34e1998-04-02 06:47:24 +00003316\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003317Returns a new empty dictionary, or \NULL{} on failure.
3318\end{cfuncdesc}
3319
3320\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
3321Empties an existing dictionary of all key-value pairs.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003322\end{cfuncdesc}
3323
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003324\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003325Returns a new dictionary that contains the same key-value pairs as p.
3326Empties an existing dictionary of all key-value pairs.
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003327\end{cfuncdesc}
3328
Fred Drake659ebfa2000-04-03 15:42:13 +00003329\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
3330 PyObject *val}
3331Inserts \var{value} into the dictionary with a key of \var{key}.
3332\var{key} must be hashable; if it isn't, \exception{TypeError} will be
3333raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003334\end{cfuncdesc}
3335
Fred Drake83e01bf2001-03-16 15:41:29 +00003336\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p,
Fred Drakee5bf8b21998-02-12 21:22:28 +00003337 char *key,
3338 PyObject *val}
Fred Drakee058b4f1998-02-16 06:15:35 +00003339Inserts \var{value} into the dictionary using \var{key}
Fred Drake1d158692000-06-18 05:21:21 +00003340as a key. \var{key} should be a \ctype{char*}. The key object is
Fred Drakee058b4f1998-02-16 06:15:35 +00003341created using \code{PyString_FromString(\var{key})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003342\ttindex{PyString_FromString()}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003343\end{cfuncdesc}
3344
Fred Drake659ebfa2000-04-03 15:42:13 +00003345\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003346Removes the entry in dictionary \var{p} with key \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003347\var{key} must be hashable; if it isn't, \exception{TypeError} is
3348raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003349\end{cfuncdesc}
3350
Fred Drake659ebfa2000-04-03 15:42:13 +00003351\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003352Removes the entry in dictionary \var{p} which has a key
Fred Drake659ebfa2000-04-03 15:42:13 +00003353specified by the string \var{key}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003354\end{cfuncdesc}
3355
Fred Drake659ebfa2000-04-03 15:42:13 +00003356\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003357Returns the object from dictionary \var{p} which has a key
Guido van Rossum44475131998-04-21 15:30:01 +00003358\var{key}. Returns \NULL{} if the key \var{key} is not present, but
Fred Drake659ebfa2000-04-03 15:42:13 +00003359\emph{without} setting an exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003360\end{cfuncdesc}
3361
Fred Drake659ebfa2000-04-03 15:42:13 +00003362\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
Fred Drakef8830d11998-04-23 14:06:01 +00003363This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
Fred Drake659ebfa2000-04-03 15:42:13 +00003364specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003365\end{cfuncdesc}
3366
Fred Drake659ebfa2000-04-03 15:42:13 +00003367\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003368Returns a \ctype{PyListObject} containing all the items
Guido van Rossum44475131998-04-21 15:30:01 +00003369from the dictionary, as in the dictinoary method \method{items()} (see
Fred Drakebe486461999-11-09 17:03:03 +00003370the \citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003371\end{cfuncdesc}
3372
Fred Drake659ebfa2000-04-03 15:42:13 +00003373\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003374Returns a \ctype{PyListObject} containing all the keys
Guido van Rossum44475131998-04-21 15:30:01 +00003375from the dictionary, as in the dictionary method \method{keys()} (see the
Fred Drakebe486461999-11-09 17:03:03 +00003376\citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003377\end{cfuncdesc}
3378
Fred Drake659ebfa2000-04-03 15:42:13 +00003379\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003380Returns a \ctype{PyListObject} containing all the values
Guido van Rossum44475131998-04-21 15:30:01 +00003381from the dictionary \var{p}, as in the dictionary method
Fred Drakebe486461999-11-09 17:03:03 +00003382\method{values()} (see the \citetitle[../lib/lib.html]{Python Library
3383Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003384\end{cfuncdesc}
3385
Fred Drake659ebfa2000-04-03 15:42:13 +00003386\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
3387Returns the number of items in the dictionary. This is equivalent to
3388\samp{len(\var{p})} on a dictionary.\bifuncindex{len}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003389\end{cfuncdesc}
3390
Fred Drake83e01bf2001-03-16 15:41:29 +00003391\begin{cfuncdesc}{int}{PyDict_Next}{PyObject *p, int *ppos,
Fred Drake7d45d342000-08-11 17:07:32 +00003392 PyObject **pkey, PyObject **pvalue}
Fred Drake83e01bf2001-03-16 15:41:29 +00003393Iterate over all key-value pairs in the dictionary \var{p}. The
3394\ctype{int} referred to by \var{ppos} must be initialized to \code{0}
3395prior to the first call to this function to start the iteration; the
3396function returns true for each pair in the dictionary, and false once
3397all pairs have been reported. The parameters \var{pkey} and
3398\var{pvalue} should either point to \ctype{PyObject*} variables that
3399will be filled in with each key and value, respectively, or may be
3400\NULL. The dictionary \var{p} must not be mutated during iteration.
3401For example:
Fred Drakee5bf8b21998-02-12 21:22:28 +00003402
Fred Drake83e01bf2001-03-16 15:41:29 +00003403\begin{verbatim}
3404PyObject *key, *value;
3405int pos = 0;
3406
3407while (PyDict_Next(self->dict, &pos, &key, &value)) {
3408 /* do something interesting with the values... */
3409 ...
3410}
3411\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003412\end{cfuncdesc}
3413
3414
Fred Drakeefd146c1999-02-15 15:30:45 +00003415\section{Numeric Objects \label{numericObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003416
Fred Drake659ebfa2000-04-03 15:42:13 +00003417\obindex{numeric}
3418
3419
Fred Drakeefd146c1999-02-15 15:30:45 +00003420\subsection{Plain Integer Objects \label{intObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003421
Fred Drake659ebfa2000-04-03 15:42:13 +00003422\obindex{integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003423\begin{ctypedesc}{PyIntObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003424This subtype of \ctype{PyObject} represents a Python integer object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003425\end{ctypedesc}
3426
3427\begin{cvardesc}{PyTypeObject}{PyInt_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003428This instance of \ctype{PyTypeObject} represents the Python plain
Fred Drake659ebfa2000-04-03 15:42:13 +00003429integer type. This is the same object as \code{types.IntType}.
3430\withsubitem{(in modules types)}{\ttindex{IntType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003431\end{cvardesc}
3432
Fred Drake659ebfa2000-04-03 15:42:13 +00003433\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
3434Returns true if \var{o} is of type \cdata{PyInt_Type}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003435\end{cfuncdesc}
3436
Fred Drakec6fa34e1998-04-02 06:47:24 +00003437\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
Fred Drakee058b4f1998-02-16 06:15:35 +00003438Creates a new integer object with a value of \var{ival}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003439
3440The current implementation keeps an array of integer objects for all
Fred Drakee058b4f1998-02-16 06:15:35 +00003441integers between \code{-1} and \code{100}, when you create an int in
3442that range you actually just get back a reference to the existing
3443object. So it should be possible to change the value of \code{1}. I
Fred Drake7e9d3141998-04-03 05:02:28 +00003444suspect the behaviour of Python in this case is undefined. :-)
Fred Drakee5bf8b21998-02-12 21:22:28 +00003445\end{cfuncdesc}
3446
Fred Drakee5bf8b21998-02-12 21:22:28 +00003447\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
Fred Drakef8830d11998-04-23 14:06:01 +00003448Will first attempt to cast the object to a \ctype{PyIntObject}, if
Fred Drakee058b4f1998-02-16 06:15:35 +00003449it is not already one, and then return its value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003450\end{cfuncdesc}
3451
Fred Drake659ebfa2000-04-03 15:42:13 +00003452\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
3453Returns the value of the object \var{io}. No error checking is
3454performed.
3455\end{cfuncdesc}
3456
Fred Drakee5bf8b21998-02-12 21:22:28 +00003457\begin{cfuncdesc}{long}{PyInt_GetMax}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003458Returns the system's idea of the largest integer it can handle
3459(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
3460header files).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003461\end{cfuncdesc}
3462
3463
Fred Drakeefd146c1999-02-15 15:30:45 +00003464\subsection{Long Integer Objects \label{longObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003465
Fred Drake659ebfa2000-04-03 15:42:13 +00003466\obindex{long integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003467\begin{ctypedesc}{PyLongObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003468This subtype of \ctype{PyObject} represents a Python long integer
Fred Drakee058b4f1998-02-16 06:15:35 +00003469object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003470\end{ctypedesc}
3471
3472\begin{cvardesc}{PyTypeObject}{PyLong_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003473This instance of \ctype{PyTypeObject} represents the Python long
Fred Drake659ebfa2000-04-03 15:42:13 +00003474integer type. This is the same object as \code{types.LongType}.
3475\withsubitem{(in modules types)}{\ttindex{LongType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003476\end{cvardesc}
3477
3478\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003479Returns true if its argument is a \ctype{PyLongObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003480\end{cfuncdesc}
3481
Fred Drakec6fa34e1998-04-02 06:47:24 +00003482\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003483Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on
3484failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003485\end{cfuncdesc}
3486
Fred Drakec6fa34e1998-04-02 06:47:24 +00003487\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003488Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
3489long}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003490\end{cfuncdesc}
3491
Fred Drakec6fa34e1998-04-02 06:47:24 +00003492\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003493Returns a new \ctype{PyLongObject} object from the integer part of
3494\var{v}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003495\end{cfuncdesc}
3496
Fred Drakec6fa34e1998-04-02 06:47:24 +00003497\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003498Returns a C \ctype{long} representation of the contents of
3499\var{pylong}. If \var{pylong} is greater than
3500\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is
3501raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003502\end{cfuncdesc}
3503
Fred Drakec6fa34e1998-04-02 06:47:24 +00003504\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003505Returns a C \ctype{unsigned long} representation of the contents of
3506\var{pylong}. If \var{pylong} is greater than
3507\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError}
3508is raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003509\end{cfuncdesc}
3510
Fred Drakec6fa34e1998-04-02 06:47:24 +00003511\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003512Returns a C \ctype{double} representation of the contents of \var{pylong}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003513\end{cfuncdesc}
3514
Fred Drakec6fa34e1998-04-02 06:47:24 +00003515\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
3516 int base}
Fred Drake659ebfa2000-04-03 15:42:13 +00003517Return a new \ctype{PyLongObject} based on the string value in
3518\var{str}, which is interpreted according to the radix in \var{base}.
3519If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first
3520character in \var{str} which follows the representation of the
3521number. If \var{base} is \code{0}, the radix will be determined base
3522on the leading characters of \var{str}: if \var{str} starts with
3523\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts
3524with \code{'0'}, radix 8 will be used; otherwise radix 10 will be
3525used. If \var{base} is not \code{0}, it must be between \code{2} and
3526\code{36}, inclusive. Leading spaces are ignored. If there are no
3527digits, \exception{ValueError} will be raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003528\end{cfuncdesc}
3529
3530
Fred Drakeefd146c1999-02-15 15:30:45 +00003531\subsection{Floating Point Objects \label{floatObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003532
Fred Drake659ebfa2000-04-03 15:42:13 +00003533\obindex{floating point}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003534\begin{ctypedesc}{PyFloatObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003535This subtype of \ctype{PyObject} represents a Python floating point
Fred Drakee058b4f1998-02-16 06:15:35 +00003536object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003537\end{ctypedesc}
3538
3539\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003540This instance of \ctype{PyTypeObject} represents the Python floating
Fred Drake659ebfa2000-04-03 15:42:13 +00003541point type. This is the same object as \code{types.FloatType}.
3542\withsubitem{(in modules types)}{\ttindex{FloatType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003543\end{cvardesc}
3544
3545\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003546Returns true if its argument is a \ctype{PyFloatObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003547\end{cfuncdesc}
3548
Fred Drakec6fa34e1998-04-02 06:47:24 +00003549\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003550Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
3551failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003552\end{cfuncdesc}
3553
Fred Drakec6fa34e1998-04-02 06:47:24 +00003554\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003555Returns a C \ctype{double} representation of the contents of \var{pyfloat}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003556\end{cfuncdesc}
3557
Fred Drakec6fa34e1998-04-02 06:47:24 +00003558\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003559Returns a C \ctype{double} representation of the contents of
Fred Drakef8830d11998-04-23 14:06:01 +00003560\var{pyfloat}, but without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003561\end{cfuncdesc}
3562
3563
Fred Drakeefd146c1999-02-15 15:30:45 +00003564\subsection{Complex Number Objects \label{complexObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003565
Fred Drake659ebfa2000-04-03 15:42:13 +00003566\obindex{complex number}
3567Python's complex number objects are implemented as two distinct types
3568when viewed from the C API: one is the Python object exposed to
3569Python programs, and the other is a C structure which represents the
3570actual complex number value. The API provides functions for working
3571with both.
3572
3573\subsubsection{Complex Numbers as C Structures}
3574
3575Note that the functions which accept these structures as parameters
3576and return them as results do so \emph{by value} rather than
3577dereferencing them through pointers. This is consistent throughout
3578the API.
3579
Fred Drakee5bf8b21998-02-12 21:22:28 +00003580\begin{ctypedesc}{Py_complex}
Fred Drake659ebfa2000-04-03 15:42:13 +00003581The C structure which corresponds to the value portion of a Python
Fred Drake4de05a91998-02-16 14:25:26 +00003582complex number object. Most of the functions for dealing with complex
3583number objects use structures of this type as input or output values,
3584as appropriate. It is defined as:
3585
Fred Drakee058b4f1998-02-16 06:15:35 +00003586\begin{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003587typedef struct {
3588 double real;
3589 double imag;
Fred Drake4de05a91998-02-16 14:25:26 +00003590} Py_complex;
Fred Drakee058b4f1998-02-16 06:15:35 +00003591\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003592\end{ctypedesc}
3593
Fred Drake659ebfa2000-04-03 15:42:13 +00003594\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
3595Return the sum of two complex numbers, using the C
3596\ctype{Py_complex} representation.
3597\end{cfuncdesc}
3598
3599\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
3600Return the difference between two complex numbers, using the C
3601\ctype{Py_complex} representation.
3602\end{cfuncdesc}
3603
3604\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
3605Return the negation of the complex number \var{complex}, using the C
3606\ctype{Py_complex} representation.
3607\end{cfuncdesc}
3608
3609\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
3610Return the product of two complex numbers, using the C
3611\ctype{Py_complex} representation.
3612\end{cfuncdesc}
3613
3614\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
3615 Py_complex divisor}
3616Return the quotient of two complex numbers, using the C
3617\ctype{Py_complex} representation.
3618\end{cfuncdesc}
3619
3620\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
3621Return the exponentiation of \var{num} by \var{exp}, using the C
3622\ctype{Py_complex} representation.
3623\end{cfuncdesc}
3624
3625
3626\subsubsection{Complex Numbers as Python Objects}
3627
Fred Drakee5bf8b21998-02-12 21:22:28 +00003628\begin{ctypedesc}{PyComplexObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003629This subtype of \ctype{PyObject} represents a Python complex number object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003630\end{ctypedesc}
3631
3632\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003633This instance of \ctype{PyTypeObject} represents the Python complex
Fred Drakee5bf8b21998-02-12 21:22:28 +00003634number type.
3635\end{cvardesc}
3636
3637\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003638Returns true if its argument is a \ctype{PyComplexObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003639\end{cfuncdesc}
3640
Fred Drakec6fa34e1998-04-02 06:47:24 +00003641\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003642Create a new Python complex number object from a C
3643\ctype{Py_complex} value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003644\end{cfuncdesc}
3645
Fred Drakec6fa34e1998-04-02 06:47:24 +00003646\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
Fred Drakef8830d11998-04-23 14:06:01 +00003647Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003648\end{cfuncdesc}
3649
3650\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003651Returns the real part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003652\end{cfuncdesc}
3653
3654\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003655Returns the imaginary part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003656\end{cfuncdesc}
3657
3658\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003659Returns the \ctype{Py_complex} value of the complex number \var{op}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003660\end{cfuncdesc}
3661
3662
3663
Fred Drakeefd146c1999-02-15 15:30:45 +00003664\section{Other Objects \label{otherObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003665
Fred Drakeefd146c1999-02-15 15:30:45 +00003666\subsection{File Objects \label{fileObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003667
Fred Drake659ebfa2000-04-03 15:42:13 +00003668\obindex{file}
3669Python's built-in file objects are implemented entirely on the
3670\ctype{FILE*} support from the C standard library. This is an
3671implementation detail and may change in future releases of Python.
3672
Fred Drakee5bf8b21998-02-12 21:22:28 +00003673\begin{ctypedesc}{PyFileObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003674This subtype of \ctype{PyObject} represents a Python file object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003675\end{ctypedesc}
3676
3677\begin{cvardesc}{PyTypeObject}{PyFile_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003678This instance of \ctype{PyTypeObject} represents the Python file
3679type. This is exposed to Python programs as \code{types.FileType}.
3680\withsubitem{(in module types)}{\ttindex{FileType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003681\end{cvardesc}
3682
3683\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003684Returns true if its argument is a \ctype{PyFileObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003685\end{cfuncdesc}
3686
Fred Drake659ebfa2000-04-03 15:42:13 +00003687\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
3688On success, returns a new file object that is opened on the
3689file given by \var{filename}, with a file mode given by \var{mode},
3690where \var{mode} has the same semantics as the standard C routine
3691\cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003692\end{cfuncdesc}
3693
Fred Drakec6fa34e1998-04-02 06:47:24 +00003694\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
Fred Drake659ebfa2000-04-03 15:42:13 +00003695 char *name, char *mode,
3696 int (*close)(FILE*)}
3697Creates a new \ctype{PyFileObject} from the already-open standard C
3698file pointer, \var{fp}. The function \var{close} will be called when
3699the file should be closed. Returns \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003700\end{cfuncdesc}
3701
Fred Drake659ebfa2000-04-03 15:42:13 +00003702\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
3703Returns the file object associated with \var{p} as a \ctype{FILE*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003704\end{cfuncdesc}
3705
Fred Drakec6fa34e1998-04-02 06:47:24 +00003706\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003707Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
3708function reads one line from the object \var{p}. \var{p} may be a
3709file object or any object with a \method{readline()} method. If
3710\var{n} is \code{0}, exactly one line is read, regardless of the
3711length of the line. If \var{n} is greater than \code{0}, no more than
3712\var{n} bytes will be read from the file; a partial line can be
3713returned. In both cases, an empty string is returned if the end of
3714the file is reached immediately. If \var{n} is less than \code{0},
3715however, one line is read regardless of length, but
3716\exception{EOFError} is raised if the end of the file is reached
3717immediately.
3718\withsubitem{(built-in exception)}{\ttindex{EOFError}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003719\end{cfuncdesc}
3720
Fred Drakec6fa34e1998-04-02 06:47:24 +00003721\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003722Returns the name of the file specified by \var{p} as a string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003723\end{cfuncdesc}
3724
3725\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003726Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
3727only. This should only be called immediately after file object
3728creation.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003729\end{cfuncdesc}
3730
Fred Drake659ebfa2000-04-03 15:42:13 +00003731\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
3732This function exists for internal use by the interpreter.
3733Sets the \member{softspace} attribute of \var{p} to \var{newflag} and
3734\withsubitem{(file attribute)}{\ttindex{softspace}}returns the
3735previous value. \var{p} does not have to be a file object
3736for this function to work properly; any object is supported (thought
3737its only interesting if the \member{softspace} attribute can be set).
3738This function clears any errors, and will return \code{0} as the
3739previous value if the attribute either does not exist or if there were
3740errors in retrieving it. There is no way to detect errors from this
3741function, but doing so should not be needed.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003742\end{cfuncdesc}
3743
Fred Drakec6fa34e1998-04-02 06:47:24 +00003744\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
3745 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003746Writes object \var{obj} to file object \var{p}. The only supported
3747flag for \var{flags} is \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW};
3748if given, the \function{str()} of the object is written instead of the
3749\function{repr()}. Returns \code{0} on success or \code{-1} on
3750failure; the appropriate exception will be set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003751\end{cfuncdesc}
3752
Fred Drakec6fa34e1998-04-02 06:47:24 +00003753\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p,
3754 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003755Writes string \var{s} to file object \var{p}. Returns \code{0} on
3756success or \code{-1} on failure; the appropriate exception will be
3757set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003758\end{cfuncdesc}
3759
3760
Fred Drake5838d0f2001-01-28 06:39:35 +00003761\subsection{Instance Objects \label{instanceObjects}}
3762
3763\obindex{instance}
3764There are very few functions specific to instance objects.
3765
3766\begin{cvardesc}{PyTypeObject}{PyInstance_Type}
3767 Type object for class instances.
3768\end{cvardesc}
3769
3770\begin{cfuncdesc}{int}{PyInstance_Check}{PyObject *obj}
3771 Returns true if \var{obj} is an instance.
3772\end{cfuncdesc}
3773
3774\begin{cfuncdesc}{PyObject*}{PyInstance_New}{PyObject *class,
3775 PyObject *arg,
3776 PyObject *kw}
3777 Create a new instance of a specific class. The parameters \var{arg}
3778 and \var{kw} are used as the positional and keyword parameters to
3779 the object's constructor.
3780\end{cfuncdesc}
3781
3782\begin{cfuncdesc}{PyObject*}{PyInstance_NewRaw}{PyObject *class,
3783 PyObject *dict}
3784 Create a new instance of a specific class without calling it's
3785 constructor. \var{class} is the class of new object. The
3786 \var{dict} parameter will be used as the object's \member{__dict__};
3787 if \NULL, a new dictionary will be created for the instance.
3788\end{cfuncdesc}
3789
3790
Fred Drakeefd146c1999-02-15 15:30:45 +00003791\subsection{Module Objects \label{moduleObjects}}
3792
3793\obindex{module}
3794There are only a few functions special to module objects.
3795
Fred Drake659ebfa2000-04-03 15:42:13 +00003796\begin{cvardesc}{PyTypeObject}{PyModule_Type}
3797This instance of \ctype{PyTypeObject} represents the Python module
3798type. This is exposed to Python programs as \code{types.ModuleType}.
3799\withsubitem{(in module types)}{\ttindex{ModuleType}}
3800\end{cvardesc}
3801
3802\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
3803Returns true if its argument is a module object.
Fred Drakeefd146c1999-02-15 15:30:45 +00003804\end{cfuncdesc}
3805
Fred Drake659ebfa2000-04-03 15:42:13 +00003806\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
3807Return a new module object with the \member{__name__} attribute set to
3808\var{name}. Only the module's \member{__doc__} and
3809\member{__name__} attributes are filled in; the caller is responsible
3810for providing a \member{__file__} attribute.
3811\withsubitem{(module attribute)}{
3812 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
3813\end{cfuncdesc}
3814
3815\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003816Return the dictionary object that implements \var{module}'s namespace;
3817this object is the same as the \member{__dict__} attribute of the
3818module object. This function never fails.
Fred Drake659ebfa2000-04-03 15:42:13 +00003819\withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003820\end{cfuncdesc}
3821
Fred Drake659ebfa2000-04-03 15:42:13 +00003822\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003823Return \var{module}'s \member{__name__} value. If the module does not
Fred Drake659ebfa2000-04-03 15:42:13 +00003824provide one, or if it is not a string, \exception{SystemError} is
3825raised and \NULL{} is returned.
3826\withsubitem{(module attribute)}{\ttindex{__name__}}
3827\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003828\end{cfuncdesc}
3829
Fred Drake659ebfa2000-04-03 15:42:13 +00003830\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003831Return the name of the file from which \var{module} was loaded using
3832\var{module}'s \member{__file__} attribute. If this is not defined,
Fred Drake659ebfa2000-04-03 15:42:13 +00003833or if it is not a string, raise \exception{SystemError} and return
3834\NULL.
3835\withsubitem{(module attribute)}{\ttindex{__file__}}
3836\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003837\end{cfuncdesc}
3838
Fred Drake891150b2000-09-23 03:25:42 +00003839\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
3840 char *name, PyObject *value}
3841Add an object to \var{module} as \var{name}. This is a convenience
3842function which can be used from the module's initialization function.
3843This steals a reference to \var{value}. Returns \code{-1} on error,
3844\code{0} on success.
3845\versionadded{2.0}
3846\end{cfuncdesc}
3847
3848\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
3849 char *name, int value}
3850Add an integer constant to \var{module} as \var{name}. This convenience
3851function can be used from the module's initialization function.
3852Returns \code{-1} on error, \code{0} on success.
3853\versionadded{2.0}
3854\end{cfuncdesc}
3855
3856\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
3857 char *name, char *value}
3858Add a string constant to \var{module} as \var{name}. This convenience
3859function can be used from the module's initialization function. The
3860string \var{value} must be null-terminated. Returns \code{-1} on
3861error, \code{0} on success.
3862\versionadded{2.0}
3863\end{cfuncdesc}
3864
Fred Drakeefd146c1999-02-15 15:30:45 +00003865
3866\subsection{CObjects \label{cObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003867
Fred Drake659ebfa2000-04-03 15:42:13 +00003868\obindex{CObject}
3869Refer to \emph{Extending and Embedding the Python Interpreter},
3870section 1.12 (``Providing a C API for an Extension Module''), for more
3871information on using these objects.
3872
3873
Guido van Rossum44475131998-04-21 15:30:01 +00003874\begin{ctypedesc}{PyCObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003875This subtype of \ctype{PyObject} represents an opaque value, useful for
Fred Drake659ebfa2000-04-03 15:42:13 +00003876C extension modules who need to pass an opaque value (as a
3877\ctype{void*} pointer) through Python code to other C code. It is
Guido van Rossum44475131998-04-21 15:30:01 +00003878often used to make a C function pointer defined in one module
3879available to other modules, so the regular import mechanism can be
3880used to access C APIs defined in dynamically loaded modules.
3881\end{ctypedesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003882
Fred Drake659ebfa2000-04-03 15:42:13 +00003883\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
3884Returns true if its argument is a \ctype{PyCObject}.
3885\end{cfuncdesc}
3886
3887\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00003888 void (*destr)(void *)}
Fred Drake1d158692000-06-18 05:21:21 +00003889Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drakedab44681999-05-13 18:41:14 +00003890\var{destr} function will be called when the object is reclaimed, unless
3891it is \NULL.
Guido van Rossum44475131998-04-21 15:30:01 +00003892\end{cfuncdesc}
3893
Fred Drake659ebfa2000-04-03 15:42:13 +00003894\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00003895 void* desc, void (*destr)(void *, void *) }
Fred Drakef8830d11998-04-23 14:06:01 +00003896Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
3897\var{destr} function will be called when the object is reclaimed. The
3898\var{desc} argument can be used to pass extra callback data for the
3899destructor function.
Guido van Rossum44475131998-04-21 15:30:01 +00003900\end{cfuncdesc}
3901
Fred Drake659ebfa2000-04-03 15:42:13 +00003902\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
3903Returns the object \ctype{void *} that the
3904\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003905\end{cfuncdesc}
3906
Fred Drake659ebfa2000-04-03 15:42:13 +00003907\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
3908Returns the description \ctype{void *} that the
3909\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003910\end{cfuncdesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003911
Fred Drake659ebfa2000-04-03 15:42:13 +00003912
Fred Drakeefd146c1999-02-15 15:30:45 +00003913\chapter{Initialization, Finalization, and Threads
3914 \label{initialization}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003915
Guido van Rossum4a944d71997-08-14 20:35:38 +00003916\begin{cfuncdesc}{void}{Py_Initialize}{}
3917Initialize the Python interpreter. In an application embedding
3918Python, this should be called before using any other Python/C API
Fred Drake659ebfa2000-04-03 15:42:13 +00003919functions; with the exception of
3920\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
3921\cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
3922\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
3923and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
3924This initializes the table of loaded modules (\code{sys.modules}), and
3925\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}creates the
3926fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake4de05a91998-02-16 14:25:26 +00003927\module{__main__}\refbimodindex{__main__} and
3928\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drake659ebfa2000-04-03 15:42:13 +00003929search\indexiii{module}{search}{path} path (\code{sys.path}).
3930It does not set \code{sys.argv}; use
3931\cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
3932is a no-op when called for a second time (without calling
3933\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is no
3934return value; it is a fatal error if the initialization fails.
Guido van Rossum42cefd01997-10-05 15:27:29 +00003935\end{cfuncdesc}
3936
3937\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00003938Return true (nonzero) when the Python interpreter has been
Fred Drakee058b4f1998-02-16 06:15:35 +00003939initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
3940called, this returns false until \cfunction{Py_Initialize()} is called
Guido van Rossum42cefd01997-10-05 15:27:29 +00003941again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003942\end{cfuncdesc}
3943
3944\begin{cfuncdesc}{void}{Py_Finalize}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003945Undo all initializations made by \cfunction{Py_Initialize()} and
3946subsequent use of Python/C API functions, and destroy all
3947sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
3948created and not yet destroyed since the last call to
3949\cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
3950by the Python interpreter. This is a no-op when called for a second
3951time (without calling \cfunction{Py_Initialize()} again first). There
3952is no return value; errors during finalization are ignored.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003953
3954This function is provided for a number of reasons. An embedding
3955application might want to restart Python without having to restart the
3956application itself. An application that has loaded the Python
3957interpreter from a dynamically loadable library (or DLL) might want to
3958free all memory allocated by Python before unloading the DLL. During a
3959hunt for memory leaks in an application a developer might want to free
3960all memory allocated by Python before exiting from the application.
3961
Fred Drakee058b4f1998-02-16 06:15:35 +00003962\strong{Bugs and caveats:} The destruction of modules and objects in
Guido van Rossum4a944d71997-08-14 20:35:38 +00003963modules is done in random order; this may cause destructors
Fred Drakee058b4f1998-02-16 06:15:35 +00003964(\method{__del__()} methods) to fail when they depend on other objects
Guido van Rossum4a944d71997-08-14 20:35:38 +00003965(even functions) or modules. Dynamically loaded extension modules
3966loaded by Python are not unloaded. Small amounts of memory allocated
3967by the Python interpreter may not be freed (if you find a leak, please
3968report it). Memory tied up in circular references between objects is
3969not freed. Some memory allocated by extension modules may not be
3970freed. Some extension may not work properly if their initialization
3971routine is called more than once; this can happen if an applcation
Fred Drakee058b4f1998-02-16 06:15:35 +00003972calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
3973than once.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003974\end{cfuncdesc}
3975
Fred Drakec6fa34e1998-04-02 06:47:24 +00003976\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003977Create a new sub-interpreter. This is an (almost) totally separate
3978environment for the execution of Python code. In particular, the new
3979interpreter has separate, independent versions of all imported
3980modules, including the fundamental modules
3981\module{__builtin__}\refbimodindex{__builtin__},
3982\module{__main__}\refbimodindex{__main__} and
3983\module{sys}\refbimodindex{sys}. The table of loaded modules
3984(\code{sys.modules}) and the module search path (\code{sys.path}) are
3985also separate. The new environment has no \code{sys.argv} variable.
3986It has new standard I/O stream file objects \code{sys.stdin},
3987\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drake659ebfa2000-04-03 15:42:13 +00003988same underlying \ctype{FILE} structures in the C library).
3989\withsubitem{(in module sys)}{
3990 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003991
3992The return value points to the first thread state created in the new
3993sub-interpreter. This thread state is made the current thread state.
3994Note that no actual thread is created; see the discussion of thread
3995states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003996\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00003997is stored in the current thread state and there may not be a current
3998thread state. (Like all other Python/C API functions, the global
3999interpreter lock must be held before calling this function and is
4000still held when it returns; however, unlike most other Python/C API
4001functions, there needn't be a current thread state on entry.)
4002
4003Extension modules are shared between (sub-)interpreters as follows:
4004the first time a particular extension is imported, it is initialized
4005normally, and a (shallow) copy of its module's dictionary is
4006squirreled away. When the same extension is imported by another
4007(sub-)interpreter, a new module is initialized and filled with the
Fred Drakee058b4f1998-02-16 06:15:35 +00004008contents of this copy; the extension's \code{init} function is not
4009called. Note that this is different from what happens when an
4010extension is imported after the interpreter has been completely
Fred Drake659ebfa2000-04-03 15:42:13 +00004011re-initialized by calling
4012\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
4013\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
4014the extension's \code{init\var{module}} function \emph{is} called
4015again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004016
Fred Drakee058b4f1998-02-16 06:15:35 +00004017\strong{Bugs and caveats:} Because sub-interpreters (and the main
Guido van Rossum4a944d71997-08-14 20:35:38 +00004018interpreter) are part of the same process, the insulation between them
Fred Drakee058b4f1998-02-16 06:15:35 +00004019isn't perfect --- for example, using low-level file operations like
Fred Drake659ebfa2000-04-03 15:42:13 +00004020\withsubitem{(in module os)}{\ttindex{close()}}
Fred Drakef8830d11998-04-23 14:06:01 +00004021\function{os.close()} they can (accidentally or maliciously) affect each
Guido van Rossum4a944d71997-08-14 20:35:38 +00004022other's open files. Because of the way extensions are shared between
4023(sub-)interpreters, some extensions may not work properly; this is
4024especially likely when the extension makes use of (static) global
4025variables, or when the extension manipulates its module's dictionary
4026after its initialization. It is possible to insert objects created in
4027one sub-interpreter into a namespace of another sub-interpreter; this
4028should be done with great care to avoid sharing user-defined
4029functions, methods, instances or classes between sub-interpreters,
4030since import operations executed by such objects may affect the
4031wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
4032a hard-to-fix bug that will be addressed in a future release.)
4033\end{cfuncdesc}
4034
4035\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
4036Destroy the (sub-)interpreter represented by the given thread state.
4037The given thread state must be the current thread state. See the
4038discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004039thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00004040interpreted are destroyed. (The global interpreter lock must be held
4041before calling this function and is still held when it returns.)
Fred Drake659ebfa2000-04-03 15:42:13 +00004042\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will destroy all
4043sub-interpreters that haven't been explicitly destroyed at that point.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004044\end{cfuncdesc}
4045
4046\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00004047This function should be called before
4048\cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
Guido van Rossum4a944d71997-08-14 20:35:38 +00004049for the first time, if it is called at all. It tells the interpreter
Fred Drake659ebfa2000-04-03 15:42:13 +00004050the value of the \code{argv[0]} argument to the
4051\cfunction{main()}\ttindex{main()} function of the program. This is
4052used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some other
Guido van Rossum4a944d71997-08-14 20:35:38 +00004053functions below to find the Python run-time libraries relative to the
Fred Drakea8455ab2000-06-16 19:58:42 +00004054interpreter executable. The default value is \code{'python'}. The
Guido van Rossum4a944d71997-08-14 20:35:38 +00004055argument should point to a zero-terminated character string in static
4056storage whose contents will not change for the duration of the
4057program's execution. No code in the Python interpreter will change
4058the contents of this storage.
4059\end{cfuncdesc}
4060
Fred Drakec6fa34e1998-04-02 06:47:24 +00004061\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00004062Return the program name set with
4063\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
Guido van Rossum4a944d71997-08-14 20:35:38 +00004064default. The returned string points into static storage; the caller
4065should not modify its value.
4066\end{cfuncdesc}
4067
Fred Drakec6fa34e1998-04-02 06:47:24 +00004068\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004069Return the \emph{prefix} for installed platform-independent files. This
Guido van Rossum4a944d71997-08-14 20:35:38 +00004070is derived through a number of complicated rules from the program name
Fred Drakee058b4f1998-02-16 06:15:35 +00004071set with \cfunction{Py_SetProgramName()} and some environment variables;
Fred Drakea8455ab2000-06-16 19:58:42 +00004072for example, if the program name is \code{'/usr/local/bin/python'},
4073the prefix is \code{'/usr/local'}. The returned string points into
Guido van Rossum4a944d71997-08-14 20:35:38 +00004074static storage; the caller should not modify its value. This
Fred Drakec94d9341998-04-12 02:39:13 +00004075corresponds to the \makevar{prefix} variable in the top-level
Fred Drakea8455ab2000-06-16 19:58:42 +00004076\file{Makefile} and the \longprogramopt{prefix} argument to the
Fred Drakee058b4f1998-02-16 06:15:35 +00004077\program{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00004078Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00004079also the next function.
4080\end{cfuncdesc}
4081
Fred Drakec6fa34e1998-04-02 06:47:24 +00004082\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004083Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
Guido van Rossum4a944d71997-08-14 20:35:38 +00004084files. This is derived through a number of complicated rules from the
Fred Drakee058b4f1998-02-16 06:15:35 +00004085program name set with \cfunction{Py_SetProgramName()} and some environment
Guido van Rossum4a944d71997-08-14 20:35:38 +00004086variables; for example, if the program name is
Fred Drakea8455ab2000-06-16 19:58:42 +00004087\code{'/usr/local/bin/python'}, the exec-prefix is
4088\code{'/usr/local'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00004089the caller should not modify its value. This corresponds to the
Fred Drakec94d9341998-04-12 02:39:13 +00004090\makevar{exec_prefix} variable in the top-level \file{Makefile} and the
Fred Drakea8455ab2000-06-16 19:58:42 +00004091\longprogramopt{exec-prefix} argument to the
Fred Drake310ee611999-11-09 17:31:42 +00004092\program{configure} script at build time. The value is available to
4093Python code as \code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004094
4095Background: The exec-prefix differs from the prefix when platform
4096dependent files (such as executables and shared libraries) are
4097installed in a different directory tree. In a typical installation,
4098platform dependent files may be installed in the
Fred Drakea8455ab2000-06-16 19:58:42 +00004099\file{/usr/local/plat} subtree while platform independent may be
4100installed in \file{/usr/local}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004101
4102Generally speaking, a platform is a combination of hardware and
4103software families, e.g. Sparc machines running the Solaris 2.x
4104operating system are considered the same platform, but Intel machines
4105running Solaris 2.x are another platform, and Intel machines running
4106Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00004107operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004108operating systems are a different story; the installation strategies
4109on those systems are so different that the prefix and exec-prefix are
4110meaningless, and set to the empty string. Note that compiled Python
4111bytecode files are platform independent (but not independent from the
4112Python version by which they were compiled!).
4113
Fred Drakee058b4f1998-02-16 06:15:35 +00004114System administrators will know how to configure the \program{mount} or
Fred Drakea8455ab2000-06-16 19:58:42 +00004115\program{automount} programs to share \file{/usr/local} between platforms
4116while having \file{/usr/local/plat} be a different filesystem for each
Guido van Rossum4a944d71997-08-14 20:35:38 +00004117platform.
4118\end{cfuncdesc}
4119
Fred Drakec6fa34e1998-04-02 06:47:24 +00004120\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004121Return the full program name of the Python executable; this is
4122computed as a side-effect of deriving the default module search path
Fred Drake659ebfa2000-04-03 15:42:13 +00004123from the program name (set by
4124\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
4125The returned string points into static storage; the caller should not
Guido van Rossum4a944d71997-08-14 20:35:38 +00004126modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00004127\code{sys.executable}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004128\withsubitem{(in module sys)}{\ttindex{executable}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004129\end{cfuncdesc}
4130
Fred Drakec6fa34e1998-04-02 06:47:24 +00004131\begin{cfuncdesc}{char*}{Py_GetPath}{}
Fred Drake4de05a91998-02-16 14:25:26 +00004132\indexiii{module}{search}{path}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004133Return the default module search path; this is computed from the
Fred Drakee058b4f1998-02-16 06:15:35 +00004134program name (set by \cfunction{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00004135environment variables. The returned string consists of a series of
4136directory names separated by a platform dependent delimiter character.
Fred Drakef8830d11998-04-23 14:06:01 +00004137The delimiter character is \character{:} on \UNIX{}, \character{;} on
Fred Drake659ebfa2000-04-03 15:42:13 +00004138DOS/Windows, and \character{\e n} (the \ASCII{} newline character) on
Fred Drakee5bc4971998-02-12 23:36:49 +00004139Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00004140should not modify its value. The value is available to Python code
Fred Drake659ebfa2000-04-03 15:42:13 +00004141as the list \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}},
4142which may be modified to change the future search path for loaded
4143modules.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004144
4145% XXX should give the exact rules
4146\end{cfuncdesc}
4147
Fred Drakec6fa34e1998-04-02 06:47:24 +00004148\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004149Return the version of this Python interpreter. This is a string that
4150looks something like
4151
Guido van Rossum09270b51997-08-15 18:57:32 +00004152\begin{verbatim}
Fred Drakee058b4f1998-02-16 06:15:35 +00004153"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
Guido van Rossum09270b51997-08-15 18:57:32 +00004154\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004155
4156The first word (up to the first space character) is the current Python
4157version; the first three characters are the major and minor version
4158separated by a period. The returned string points into static storage;
4159the caller should not modify its value. The value is available to
4160Python code as the list \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004161\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004162\end{cfuncdesc}
4163
Fred Drakec6fa34e1998-04-02 06:47:24 +00004164\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00004165Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00004166this is formed from the ``official'' name of the operating system,
4167converted to lower case, followed by the major revision number; e.g.,
4168for Solaris 2.x, which is also known as SunOS 5.x, the value is
Fred Drakea8455ab2000-06-16 19:58:42 +00004169\code{'sunos5'}. On Macintosh, it is \code{'mac'}. On Windows, it
4170is \code{'win'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00004171the caller should not modify its value. The value is available to
4172Python code as \code{sys.platform}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004173\withsubitem{(in module sys)}{\ttindex{platform}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004174\end{cfuncdesc}
4175
Fred Drakec6fa34e1998-04-02 06:47:24 +00004176\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004177Return the official copyright string for the current Python version,
4178for example
4179
Fred Drakea8455ab2000-06-16 19:58:42 +00004180\code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004181
4182The returned string points into static storage; the caller should not
4183modify its value. The value is available to Python code as the list
4184\code{sys.copyright}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004185\withsubitem{(in module sys)}{\ttindex{copyright}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004186\end{cfuncdesc}
4187
Fred Drakec6fa34e1998-04-02 06:47:24 +00004188\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004189Return an indication of the compiler used to build the current Python
Fred Drakee058b4f1998-02-16 06:15:35 +00004190version, in square brackets, for example:
Guido van Rossum4a944d71997-08-14 20:35:38 +00004191
Fred Drakee058b4f1998-02-16 06:15:35 +00004192\begin{verbatim}
4193"[GCC 2.7.2.2]"
4194\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004195
4196The returned string points into static storage; the caller should not
4197modify its value. The value is available to Python code as part of
4198the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004199\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004200\end{cfuncdesc}
4201
Fred Drakec6fa34e1998-04-02 06:47:24 +00004202\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004203Return information about the sequence number and build date and time
4204of the current Python interpreter instance, for example
4205
Guido van Rossum09270b51997-08-15 18:57:32 +00004206\begin{verbatim}
4207"#67, Aug 1 1997, 22:34:28"
4208\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004209
4210The returned string points into static storage; the caller should not
4211modify its value. The value is available to Python code as part of
4212the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004213\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004214\end{cfuncdesc}
4215
4216\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
Fred Drake659ebfa2000-04-03 15:42:13 +00004217Set \code{sys.argv} based on \var{argc} and \var{argv}. These
4218parameters are similar to those passed to the program's
4219\cfunction{main()}\ttindex{main()} function with the difference that
4220the first entry should refer to the script file to be executed rather
4221than the executable hosting the Python interpreter. If there isn't a
4222script that will be run, the first entry in \var{argv} can be an empty
4223string. If this function fails to initialize \code{sys.argv}, a fatal
4224condition is signalled using
4225\cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
4226\withsubitem{(in module sys)}{\ttindex{argv}}
4227% XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
4228% check w/ Guido.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004229\end{cfuncdesc}
4230
4231% XXX Other PySys thingies (doesn't really belong in this chapter)
4232
Fred Drakeefd146c1999-02-15 15:30:45 +00004233\section{Thread State and the Global Interpreter Lock
4234 \label{threads}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004235
Fred Drake659ebfa2000-04-03 15:42:13 +00004236\index{global interpreter lock}
4237\index{interpreter lock}
4238\index{lock, interpreter}
4239
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004240The Python interpreter is not fully thread safe. In order to support
4241multi-threaded Python programs, there's a global lock that must be
4242held by the current thread before it can safely access Python objects.
4243Without the lock, even the simplest operations could cause problems in
Fred Drake7baf3d41998-02-20 00:45:52 +00004244a multi-threaded program: for example, when two threads simultaneously
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004245increment the reference count of the same object, the reference count
4246could end up being incremented only once instead of twice.
4247
4248Therefore, the rule exists that only the thread that has acquired the
4249global interpreter lock may operate on Python objects or call Python/C
4250API functions. In order to support multi-threaded Python programs,
Fred Drake659ebfa2000-04-03 15:42:13 +00004251the interpreter regularly releases and reacquires the lock --- by
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004252default, every ten bytecode instructions (this can be changed with
Fred Drake659ebfa2000-04-03 15:42:13 +00004253\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
Fred Drakee058b4f1998-02-16 06:15:35 +00004254\function{sys.setcheckinterval()}). The lock is also released and
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004255reacquired around potentially blocking I/O operations like reading or
4256writing a file, so that other threads can run while the thread that
4257requests the I/O is waiting for the I/O operation to complete.
4258
4259The Python interpreter needs to keep some bookkeeping information
Fred Drakee058b4f1998-02-16 06:15:35 +00004260separate per thread --- for this it uses a data structure called
Fred Drake659ebfa2000-04-03 15:42:13 +00004261\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
42621.5; in earlier versions, such state was stored in global variables,
4263and switching threads could cause problems. In particular, exception
4264handling is now thread safe, when the application uses
4265\withsubitem{(in module sys)}{\ttindex{exc_info()}}
4266\function{sys.exc_info()} to access the exception last raised in the
4267current thread.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004268
4269There's one global variable left, however: the pointer to the current
Fred Drake659ebfa2000-04-03 15:42:13 +00004270\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
4271thread packages have a way to store ``per-thread global data,''
4272Python's internal platform independent thread abstraction doesn't
4273support this yet. Therefore, the current thread state must be
4274manipulated explicitly.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004275
4276This is easy enough in most cases. Most code manipulating the global
4277interpreter lock has the following simple structure:
4278
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004279\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004280Save the thread state in a local variable.
4281Release the interpreter lock.
4282...Do some blocking I/O operation...
4283Reacquire the interpreter lock.
4284Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004285\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004286
4287This is so common that a pair of macros exists to simplify it:
4288
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004289\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004290Py_BEGIN_ALLOW_THREADS
4291...Do some blocking I/O operation...
4292Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004293\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004294
Fred Drake659ebfa2000-04-03 15:42:13 +00004295The \code{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS} macro
4296opens a new block and declares a hidden local variable; the
4297\code{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS} macro closes
Fred Drakee058b4f1998-02-16 06:15:35 +00004298the block. Another advantage of using these two macros is that when
4299Python is compiled without thread support, they are defined empty,
4300thus saving the thread state and lock manipulations.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004301
4302When thread support is enabled, the block above expands to the
4303following code:
4304
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004305\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004306 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004307
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004308 _save = PyEval_SaveThread();
4309 ...Do some blocking I/O operation...
4310 PyEval_RestoreThread(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004311\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004312
4313Using even lower level primitives, we can get roughly the same effect
4314as follows:
4315
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004316\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004317 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004318
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004319 _save = PyThreadState_Swap(NULL);
4320 PyEval_ReleaseLock();
4321 ...Do some blocking I/O operation...
4322 PyEval_AcquireLock();
4323 PyThreadState_Swap(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004324\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004325
4326There are some subtle differences; in particular,
Fred Drake659ebfa2000-04-03 15:42:13 +00004327\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
4328and restores the value of the global variable
4329\cdata{errno}\ttindex{errno}, since the lock manipulation does not
Fred Drakef8830d11998-04-23 14:06:01 +00004330guarantee that \cdata{errno} is left alone. Also, when thread support
Fred Drake659ebfa2000-04-03 15:42:13 +00004331is disabled,
4332\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
Fred Drakee058b4f1998-02-16 06:15:35 +00004333\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
Fred Drake659ebfa2000-04-03 15:42:13 +00004334case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
4335\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
4336available. This is done so that dynamically loaded extensions
4337compiled with thread support enabled can be loaded by an interpreter
4338that was compiled with disabled thread support.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004339
4340The global interpreter lock is used to protect the pointer to the
4341current thread state. When releasing the lock and saving the thread
4342state, the current thread state pointer must be retrieved before the
4343lock is released (since another thread could immediately acquire the
4344lock and store its own thread state in the global variable).
Fred Drakeffe58ca2000-09-29 17:31:54 +00004345Conversely, when acquiring the lock and restoring the thread state,
4346the lock must be acquired before storing the thread state pointer.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004347
4348Why am I going on with so much detail about this? Because when
Fred Drake659ebfa2000-04-03 15:42:13 +00004349threads are created from C, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004350lock, nor is there a thread state data structure for them. Such
4351threads must bootstrap themselves into existence, by first creating a
4352thread state data structure, then acquiring the lock, and finally
4353storing their thread state pointer, before they can start using the
4354Python/C API. When they are done, they should reset the thread state
4355pointer, release the lock, and finally free their thread state data
4356structure.
4357
4358When creating a thread data structure, you need to provide an
4359interpreter state data structure. The interpreter state data
4360structure hold global data that is shared by all threads in an
4361interpreter, for example the module administration
4362(\code{sys.modules}). Depending on your needs, you can either create
4363a new interpreter state data structure, or share the interpreter state
4364data structure used by the Python main thread (to access the latter,
Fred Drakef8830d11998-04-23 14:06:01 +00004365you must obtain the thread state and access its \member{interp} member;
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004366this must be done by a thread that is created by Python or by the main
4367thread after Python is initialized).
4368
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004369
4370\begin{ctypedesc}{PyInterpreterState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004371This data structure represents the state shared by a number of
4372cooperating threads. Threads belonging to the same interpreter
4373share their module administration and a few other internal items.
4374There are no public members in this structure.
4375
4376Threads belonging to different interpreters initially share nothing,
4377except process state like available memory, open file descriptors and
4378such. The global interpreter lock is also shared by all threads,
4379regardless of to which interpreter they belong.
4380\end{ctypedesc}
4381
4382\begin{ctypedesc}{PyThreadState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004383This data structure represents the state of a single thread. The only
Fred Drakef8830d11998-04-23 14:06:01 +00004384public data member is \ctype{PyInterpreterState *}\member{interp},
4385which points to this thread's interpreter state.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004386\end{ctypedesc}
4387
4388\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
4389Initialize and acquire the global interpreter lock. It should be
4390called in the main thread before creating a second thread or engaging
Fred Drakee058b4f1998-02-16 06:15:35 +00004391in any other thread operations such as
Fred Drake659ebfa2000-04-03 15:42:13 +00004392\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
4393\code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
4394It is not needed before calling
4395\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
4396\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004397
4398This is a no-op when called for a second time. It is safe to call
Fred Drake659ebfa2000-04-03 15:42:13 +00004399this function before calling
4400\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004401
4402When only the main thread exists, no lock operations are needed. This
4403is a common situation (most Python programs do not use threads), and
4404the lock operations slow the interpreter down a bit. Therefore, the
4405lock is not created initially. This situation is equivalent to having
4406acquired the lock: when there is only a single thread, all object
4407accesses are safe. Therefore, when this function initializes the
Fred Drake4de05a91998-02-16 14:25:26 +00004408lock, it also acquires it. Before the Python
4409\module{thread}\refbimodindex{thread} module creates a new thread,
4410knowing that either it has the lock or the lock hasn't been created
4411yet, it calls \cfunction{PyEval_InitThreads()}. When this call
4412returns, it is guaranteed that the lock has been created and that it
4413has acquired it.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004414
4415It is \strong{not} safe to call this function when it is unknown which
4416thread (if any) currently has the global interpreter lock.
4417
4418This function is not available when thread support is disabled at
4419compile time.
4420\end{cfuncdesc}
4421
Guido van Rossum4a944d71997-08-14 20:35:38 +00004422\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004423Acquire the global interpreter lock. The lock must have been created
4424earlier. If this thread already has the lock, a deadlock ensues.
4425This function is not available when thread support is disabled at
4426compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004427\end{cfuncdesc}
4428
4429\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004430Release the global interpreter lock. The lock must have been created
4431earlier. This function is not available when thread support is
Fred Drakee058b4f1998-02-16 06:15:35 +00004432disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004433\end{cfuncdesc}
4434
4435\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004436Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004437state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004438have been created earlier. If this thread already has the lock,
4439deadlock ensues. This function is not available when thread support
Fred Drakee058b4f1998-02-16 06:15:35 +00004440is disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004441\end{cfuncdesc}
4442
4443\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004444Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004445interpreter lock. The lock must have been created earlier and must be
4446held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004447be \NULL{}, is only used to check that it represents the current
Fred Drakee058b4f1998-02-16 06:15:35 +00004448thread state --- if it isn't, a fatal error is reported. This
4449function is not available when thread support is disabled at compile
4450time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004451\end{cfuncdesc}
4452
Fred Drakec6fa34e1998-04-02 06:47:24 +00004453\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004454Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004455support is enabled) and reset the thread state to \NULL{},
4456returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004457the lock has been created, the current thread must have acquired it.
4458(This function is available even when thread support is disabled at
4459compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004460\end{cfuncdesc}
4461
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004462\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004463Acquire the interpreter lock (if it has been created and thread
4464support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004465must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004466thread must not have acquired it, otherwise deadlock ensues. (This
4467function is available even when thread support is disabled at compile
4468time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004469\end{cfuncdesc}
4470
Fred Drake659ebfa2000-04-03 15:42:13 +00004471The following macros are normally used without a trailing semicolon;
4472look for example usage in the Python source distribution.
4473
4474\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004475This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004476\samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004477Note that it contains an opening brace; it must be matched with a
4478following \code{Py_END_ALLOW_THREADS} macro. See above for further
4479discussion of this macro. It is a no-op when thread support is
4480disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004481\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004482
Fred Drake659ebfa2000-04-03 15:42:13 +00004483\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004484This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004485\samp{PyEval_RestoreThread(_save); \}}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004486Note that it contains a closing brace; it must be matched with an
4487earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
4488discussion of this macro. It is a no-op when thread support is
4489disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004490\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004491
Fred Drake659ebfa2000-04-03 15:42:13 +00004492\begin{csimplemacrodesc}{Py_BEGIN_BLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004493This macro expands to \samp{PyEval_RestoreThread(_save);} i.e. it
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004494is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
4495brace. It is a no-op when thread support is disabled at compile
4496time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004497\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004498
Fred Drake659ebfa2000-04-03 15:42:13 +00004499\begin{csimplemacrodesc}{Py_BEGIN_UNBLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004500This macro expands to \samp{_save = PyEval_SaveThread();} i.e. it is
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004501equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
4502and variable declaration. It is a no-op when thread support is
4503disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004504\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004505
4506All of the following functions are only available when thread support
4507is enabled at compile time, and must be called only when the
Fred Drake9d20ac31998-02-16 15:27:08 +00004508interpreter lock has been created.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004509
Fred Drakec6fa34e1998-04-02 06:47:24 +00004510\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004511Create a new interpreter state object. The interpreter lock need not
4512be held, but may be held if it is necessary to serialize calls to this
4513function.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004514\end{cfuncdesc}
4515
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004516\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
4517Reset all information in an interpreter state object. The interpreter
4518lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004519\end{cfuncdesc}
4520
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004521\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
4522Destroy an interpreter state object. The interpreter lock need not be
4523held. The interpreter state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004524call to \cfunction{PyInterpreterState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004525\end{cfuncdesc}
4526
Fred Drakec6fa34e1998-04-02 06:47:24 +00004527\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004528Create a new thread state object belonging to the given interpreter
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004529object. The interpreter lock need not be held, but may be held if it
4530is necessary to serialize calls to this function.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004531\end{cfuncdesc}
4532
4533\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
4534Reset all information in a thread state object. The interpreter lock
4535must be held.
4536\end{cfuncdesc}
4537
4538\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
4539Destroy a thread state object. The interpreter lock need not be
4540held. The thread state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004541call to \cfunction{PyThreadState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004542\end{cfuncdesc}
4543
Fred Drakec6fa34e1998-04-02 06:47:24 +00004544\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004545Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004546When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004547error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004548\end{cfuncdesc}
4549
Fred Drakec6fa34e1998-04-02 06:47:24 +00004550\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004551Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004552argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004553must be held.
4554\end{cfuncdesc}
4555
4556
Fred Drake659ebfa2000-04-03 15:42:13 +00004557\chapter{Memory Management \label{memory}}
4558\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
4559
4560
4561\section{Overview \label{memoryOverview}}
4562
4563Memory management in Python involves a private heap containing all
4564Python objects and data structures. The management of this private
4565heap is ensured internally by the \emph{Python memory manager}. The
4566Python memory manager has different components which deal with various
4567dynamic storage management aspects, like sharing, segmentation,
4568preallocation or caching.
4569
4570At the lowest level, a raw memory allocator ensures that there is
4571enough room in the private heap for storing all Python-related data
4572by interacting with the memory manager of the operating system. On top
4573of the raw memory allocator, several object-specific allocators
4574operate on the same heap and implement distinct memory management
4575policies adapted to the peculiarities of every object type. For
4576example, integer objects are managed differently within the heap than
4577strings, tuples or dictionaries because integers imply different
4578storage requirements and speed/space tradeoffs. The Python memory
4579manager thus delegates some of the work to the object-specific
4580allocators, but ensures that the latter operate within the bounds of
4581the private heap.
4582
4583It is important to understand that the management of the Python heap
4584is performed by the interpreter itself and that the user has no
4585control on it, even if she regularly manipulates object pointers to
4586memory blocks inside that heap. The allocation of heap space for
4587Python objects and other internal buffers is performed on demand by
4588the Python memory manager through the Python/C API functions listed in
4589this document.
4590
4591To avoid memory corruption, extension writers should never try to
4592operate on Python objects with the functions exported by the C
4593library: \cfunction{malloc()}\ttindex{malloc()},
4594\cfunction{calloc()}\ttindex{calloc()},
4595\cfunction{realloc()}\ttindex{realloc()} and
4596\cfunction{free()}\ttindex{free()}. This will result in
4597mixed calls between the C allocator and the Python memory manager
4598with fatal consequences, because they implement different algorithms
4599and operate on different heaps. However, one may safely allocate and
4600release memory blocks with the C library allocator for individual
4601purposes, as shown in the following example:
4602
4603\begin{verbatim}
4604 PyObject *res;
4605 char *buf = (char *) malloc(BUFSIZ); /* for I/O */
4606
4607 if (buf == NULL)
4608 return PyErr_NoMemory();
4609 ...Do some I/O operation involving buf...
4610 res = PyString_FromString(buf);
4611 free(buf); /* malloc'ed */
4612 return res;
4613\end{verbatim}
4614
4615In this example, the memory request for the I/O buffer is handled by
4616the C library allocator. The Python memory manager is involved only
4617in the allocation of the string object returned as a result.
4618
4619In most situations, however, it is recommended to allocate memory from
4620the Python heap specifically because the latter is under control of
4621the Python memory manager. For example, this is required when the
4622interpreter is extended with new object types written in C. Another
4623reason for using the Python heap is the desire to \emph{inform} the
4624Python memory manager about the memory needs of the extension module.
4625Even when the requested memory is used exclusively for internal,
4626highly-specific purposes, delegating all memory requests to the Python
4627memory manager causes the interpreter to have a more accurate image of
4628its memory footprint as a whole. Consequently, under certain
4629circumstances, the Python memory manager may or may not trigger
4630appropriate actions, like garbage collection, memory compaction or
4631other preventive procedures. Note that by using the C library
4632allocator as shown in the previous example, the allocated memory for
4633the I/O buffer escapes completely the Python memory manager.
4634
4635
4636\section{Memory Interface \label{memoryInterface}}
4637
4638The following function sets, modeled after the ANSI C standard, are
4639available for allocating and releasing memory from the Python heap:
4640
4641
Fred Drake7d45d342000-08-11 17:07:32 +00004642\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
4643Allocates \var{n} bytes and returns a pointer of type \ctype{void*} to
Fred Drake659ebfa2000-04-03 15:42:13 +00004644the allocated memory, or \NULL{} if the request fails. Requesting zero
4645bytes returns a non-\NULL{} pointer.
4646\end{cfuncdesc}
4647
Fred Drake7d45d342000-08-11 17:07:32 +00004648\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004649Resizes the memory block pointed to by \var{p} to \var{n} bytes. The
4650contents will be unchanged to the minimum of the old and the new
4651sizes. If \var{p} is \NULL{}, the call is equivalent to
4652\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the memory block
4653is resized but is not freed, and the returned pointer is non-\NULL{}.
4654Unless \var{p} is \NULL{}, it must have been returned by a previous
4655call to \cfunction{PyMem_Malloc()} or \cfunction{PyMem_Realloc()}.
4656\end{cfuncdesc}
4657
Fred Drake7d45d342000-08-11 17:07:32 +00004658\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004659Frees the memory block pointed to by \var{p}, which must have been
4660returned by a previous call to \cfunction{PyMem_Malloc()} or
4661\cfunction{PyMem_Realloc()}. Otherwise, or if
4662\cfunction{PyMem_Free(p)} has been called before, undefined behaviour
4663occurs. If \var{p} is \NULL{}, no operation is performed.
4664\end{cfuncdesc}
4665
Fred Drake659ebfa2000-04-03 15:42:13 +00004666The following type-oriented macros are provided for convenience. Note
4667that \var{TYPE} refers to any C type.
4668
Fred Drakef913e542000-09-12 20:17:17 +00004669\begin{cfuncdesc}{\var{TYPE}*}{PyMem_New}{TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004670Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
4671sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
4672\ctype{\var{TYPE}*}.
4673\end{cfuncdesc}
4674
Fred Drakef913e542000-09-12 20:17:17 +00004675\begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004676Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
4677to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
4678cast to \ctype{\var{TYPE}*}.
4679\end{cfuncdesc}
4680
Fred Drakef913e542000-09-12 20:17:17 +00004681\begin{cfuncdesc}{void}{PyMem_Del}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004682Same as \cfunction{PyMem_Free()}.
4683\end{cfuncdesc}
4684
Fred Drakef913e542000-09-12 20:17:17 +00004685In addition, the following macro sets are provided for calling the
4686Python memory allocator directly, without involving the C API functions
4687listed above. However, note that their use does not preserve binary
4688compatibility accross Python versions and is therefore deprecated in
4689extension modules.
4690
4691\cfunction{PyMem_MALLOC()}, \cfunction{PyMem_REALLOC()}, \cfunction{PyMem_FREE()}.
4692
4693\cfunction{PyMem_NEW()}, \cfunction{PyMem_RESIZE()}, \cfunction{PyMem_DEL()}.
4694
Fred Drake659ebfa2000-04-03 15:42:13 +00004695
4696\section{Examples \label{memoryExamples}}
4697
4698Here is the example from section \ref{memoryOverview}, rewritten so
4699that the I/O buffer is allocated from the Python heap by using the
4700first function set:
4701
4702\begin{verbatim}
4703 PyObject *res;
4704 char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
4705
4706 if (buf == NULL)
4707 return PyErr_NoMemory();
4708 /* ...Do some I/O operation involving buf... */
4709 res = PyString_FromString(buf);
4710 PyMem_Free(buf); /* allocated with PyMem_Malloc */
4711 return res;
4712\end{verbatim}
4713
Fred Drakef913e542000-09-12 20:17:17 +00004714The same code using the type-oriented function set:
Fred Drake659ebfa2000-04-03 15:42:13 +00004715
4716\begin{verbatim}
4717 PyObject *res;
Fred Drakef913e542000-09-12 20:17:17 +00004718 char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
Fred Drake659ebfa2000-04-03 15:42:13 +00004719
4720 if (buf == NULL)
4721 return PyErr_NoMemory();
4722 /* ...Do some I/O operation involving buf... */
4723 res = PyString_FromString(buf);
Fred Drakef913e542000-09-12 20:17:17 +00004724 PyMem_Del(buf); /* allocated with PyMem_New */
Fred Drake659ebfa2000-04-03 15:42:13 +00004725 return res;
4726\end{verbatim}
4727
Fred Drakef913e542000-09-12 20:17:17 +00004728Note that in the two examples above, the buffer is always
4729manipulated via functions belonging to the same set. Indeed, it
Fred Drake659ebfa2000-04-03 15:42:13 +00004730is required to use the same memory API family for a given
4731memory block, so that the risk of mixing different allocators is
4732reduced to a minimum. The following code sequence contains two errors,
4733one of which is labeled as \emph{fatal} because it mixes two different
4734allocators operating on different heaps.
4735
4736\begin{verbatim}
Fred Drakef913e542000-09-12 20:17:17 +00004737char *buf1 = PyMem_New(char, BUFSIZ);
Fred Drake659ebfa2000-04-03 15:42:13 +00004738char *buf2 = (char *) malloc(BUFSIZ);
4739char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
4740...
Fred Drakef913e542000-09-12 20:17:17 +00004741PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004742free(buf2); /* Right -- allocated via malloc() */
Fred Drakef913e542000-09-12 20:17:17 +00004743free(buf1); /* Fatal -- should be PyMem_Del() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004744\end{verbatim}
4745
4746In addition to the functions aimed at handling raw memory blocks from
4747the Python heap, objects in Python are allocated and released with
Fred Drakef913e542000-09-12 20:17:17 +00004748\cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()} and
4749\cfunction{PyObject_Del()}, or with their corresponding macros
4750\cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()} and
Fred Drakee06f0f92000-06-30 15:52:39 +00004751\cfunction{PyObject_DEL()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004752
Fred Drakee06f0f92000-06-30 15:52:39 +00004753These will be explained in the next chapter on defining and
4754implementing new object types in C.
Fred Drake659ebfa2000-04-03 15:42:13 +00004755
4756
Fred Drakeefd146c1999-02-15 15:30:45 +00004757\chapter{Defining New Object Types \label{newTypes}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004758
Fred Drakec6fa34e1998-04-02 06:47:24 +00004759\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00004760\end{cfuncdesc}
4761
Fred Drakef913e542000-09-12 20:17:17 +00004762\begin{cfuncdesc}{PyVarObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00004763\end{cfuncdesc}
4764
Fred Drakef913e542000-09-12 20:17:17 +00004765\begin{cfuncdesc}{void}{_PyObject_Del}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004766\end{cfuncdesc}
4767
Fred Drakef913e542000-09-12 20:17:17 +00004768\begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00004769 PyTypeObject *type}
Fred Drakef913e542000-09-12 20:17:17 +00004770\end{cfuncdesc}
4771
4772\begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00004773 PyTypeObject *type, int size}
Fred Drakef913e542000-09-12 20:17:17 +00004774\end{cfuncdesc}
4775
4776\begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type}
4777\end{cfuncdesc}
4778
4779\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type,
4780 int size}
4781\end{cfuncdesc}
4782
4783\begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op}
4784\end{cfuncdesc}
4785
4786\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW}{TYPE, PyTypeObject *type}
4787\end{cfuncdesc}
4788
4789\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
4790 int size}
4791\end{cfuncdesc}
4792
4793\begin{cfuncdesc}{void}{PyObject_DEL}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004794\end{cfuncdesc}
4795
Fred Drakeee814bf2000-11-28 22:34:32 +00004796\begin{cfuncdesc}{PyObject*}{Py_InitModule}{char *name,
4797 PyMethodDef *methods}
4798 Create a new module object based on a name and table of functions,
4799 returning the new module object.
4800\end{cfuncdesc}
4801
4802\begin{cfuncdesc}{PyObject*}{Py_InitModule3}{char *name,
4803 PyMethodDef *methods,
4804 char *doc}
4805 Create a new module object based on a name and table of functions,
4806 returning the new module object. If \var{doc} is non-\NULL, it will
4807 be used to define the docstring for the module.
4808\end{cfuncdesc}
4809
4810\begin{cfuncdesc}{PyObject*}{Py_InitModule4}{char *name,
4811 PyMethodDef *methods,
4812 char *doc, PyObject *self,
4813 int apiver}
4814 Create a new module object based on a name and table of functions,
4815 returning the new module object. If \var{doc} is non-\NULL, it will
4816 be used to define the docstring for the module. If \var{self} is
4817 non-\NULL, it will passed to the functions of the module as their
4818 (otherwise \NULL) first parameter. (This was added as an
4819 experimental feature, and there are no known uses in the current
4820 version of Python.) For \var{apiver}, the only value which should
4821 be passed is defined by the constant \constant{PYTHON_API_VERSION}.
4822
4823 \strong{Note:} Most uses of this function should probably be using
4824 the \cfunction{Py_InitModule3()} instead; only use this if you are
4825 sure you need it.
4826\end{cfuncdesc}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00004827
4828PyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse
4829
4830Py_BuildValue
Guido van Rossumae110af1997-05-22 20:11:52 +00004831
Fred Drake659ebfa2000-04-03 15:42:13 +00004832DL_IMPORT
4833
Fred Drake659ebfa2000-04-03 15:42:13 +00004834_Py_NoneStruct
4835
4836
4837\section{Common Object Structures \label{common-structs}}
4838
Guido van Rossumae110af1997-05-22 20:11:52 +00004839PyObject, PyVarObject
4840
4841PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
4842
4843Typedefs:
4844unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
4845intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
Guido van Rossumae110af1997-05-22 20:11:52 +00004846destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
4847setattrofunc, cmpfunc, reprfunc, hashfunc
4848
Fred Drakea8455ab2000-06-16 19:58:42 +00004849\begin{ctypedesc}{PyCFunction}
4850Type of the functions used to implement most Python callables in C.
4851\end{ctypedesc}
4852
4853\begin{ctypedesc}{PyMethodDef}
4854Structure used to describe a method of an extension type. This
4855structure has four fields:
4856
4857\begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
4858 \lineiii{ml_name}{char *}{name of the method}
4859 \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
4860 \lineiii{ml_flags}{int}{flag bits indicating how the call should be
4861 constructed}
4862 \lineiii{ml_doc}{char *}{points to the contents of the docstring}
4863\end{tableiii}
4864\end{ctypedesc}
4865
4866\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef[] table,
4867 PyObject *ob, char *name}
4868Return a bound method object for an extension type implemented in C.
4869This function also handles the special attribute \member{__methods__},
4870returning a list of all the method names defined in \var{table}.
4871\end{cfuncdesc}
4872
Fred Drake659ebfa2000-04-03 15:42:13 +00004873
4874\section{Mapping Object Structures \label{mapping-structs}}
4875
4876\begin{ctypedesc}{PyMappingMethods}
4877Structure used to hold pointers to the functions used to implement the
4878mapping protocol for an extension type.
4879\end{ctypedesc}
4880
4881
4882\section{Number Object Structures \label{number-structs}}
4883
4884\begin{ctypedesc}{PyNumberMethods}
4885Structure used to hold pointers to the functions an extension type
4886uses to implement the number protocol.
4887\end{ctypedesc}
4888
4889
4890\section{Sequence Object Structures \label{sequence-structs}}
4891
4892\begin{ctypedesc}{PySequenceMethods}
4893Structure used to hold pointers to the functions which an object uses
4894to implement the sequence protocol.
4895\end{ctypedesc}
4896
4897
4898\section{Buffer Object Structures \label{buffer-structs}}
4899\sectionauthor{Greg J. Stein}{greg@lyra.org}
4900
4901The buffer interface exports a model where an object can expose its
4902internal data as a set of chunks of data, where each chunk is
4903specified as a pointer/length pair. These chunks are called
4904\dfn{segments} and are presumed to be non-contiguous in memory.
4905
4906If an object does not export the buffer interface, then its
4907\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
4908should be \NULL{}. Otherwise, the \member{tp_as_buffer} will point to
4909a \ctype{PyBufferProcs} structure.
4910
4911\strong{Note:} It is very important that your
Fred Drakec392b572001-03-21 22:15:01 +00004912\ctype{PyTypeObject} structure uses \constant{Py_TPFLAGS_DEFAULT} for
4913the value of the \member{tp_flags} member rather than \code{0}. This
Fred Drake659ebfa2000-04-03 15:42:13 +00004914tells the Python runtime that your \ctype{PyBufferProcs} structure
4915contains the \member{bf_getcharbuffer} slot. Older versions of Python
4916did not have this member, so a new Python interpreter using an old
4917extension needs to be able to test for its presence before using it.
4918
4919\begin{ctypedesc}{PyBufferProcs}
4920Structure used to hold the function pointers which define an
4921implementation of the buffer protocol.
4922
4923The first slot is \member{bf_getreadbuffer}, of type
4924\ctype{getreadbufferproc}. If this slot is \NULL{}, then the object
4925does not support reading from the internal data. This is
4926non-sensical, so implementors should fill this in, but callers should
4927test that the slot contains a non-\NULL{} value.
4928
4929The next slot is \member{bf_getwritebuffer} having type
4930\ctype{getwritebufferproc}. This slot may be \NULL{} if the object
4931does not allow writing into its returned buffers.
4932
4933The third slot is \member{bf_getsegcount}, with type
4934\ctype{getsegcountproc}. This slot must not be \NULL{} and is used to
4935inform the caller how many segments the object contains. Simple
4936objects such as \ctype{PyString_Type} and
4937\ctype{PyBuffer_Type} objects contain a single segment.
4938
4939The last slot is \member{bf_getcharbuffer}, of type
4940\ctype{getcharbufferproc}. This slot will only be present if the
Fred Drakec392b572001-03-21 22:15:01 +00004941\constant{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
Fred Drake659ebfa2000-04-03 15:42:13 +00004942\member{tp_flags} field of the object's \ctype{PyTypeObject}. Before using
4943this slot, the caller should test whether it is present by using the
4944\cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()} function.
4945If present, it may be \NULL, indicating that the object's contents
4946cannot be used as \emph{8-bit characters}.
4947The slot function may also raise an error if the object's contents
4948cannot be interpreted as 8-bit characters. For example, if the object
4949is an array which is configured to hold floating point values, an
4950exception may be raised if a caller attempts to use
4951\member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
4952This notion of exporting the internal buffers as ``text'' is used to
4953distinguish between objects that are binary in nature, and those which
4954have character-based content.
4955
4956\strong{Note:} The current policy seems to state that these characters
4957may be multi-byte characters. This implies that a buffer size of
4958\var{N} does not mean there are \var{N} characters present.
4959\end{ctypedesc}
4960
4961\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
4962Flag bit set in the type structure to indicate that the
4963\member{bf_getcharbuffer} slot is known. This being set does not
4964indicate that the object supports the buffer interface or that the
4965\member{bf_getcharbuffer} slot is non-\NULL.
4966\end{datadesc}
4967
4968\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
4969 (PyObject *self, int segment, void **ptrptr)}
4970Return a pointer to a readable segment of the buffer. This function
4971is allowed to raise an exception, in which case it must return
4972\code{-1}. The \var{segment} which is passed must be zero or
4973positive, and strictly less than the number of segments returned by
Greg Stein4d4d0032001-04-07 16:14:49 +00004974the \member{bf_getsegcount} slot function. On success, it returns the
4975length of the buffer memory, and sets \code{*\var{ptrptr}} to a
4976pointer to that memory.
Fred Drake659ebfa2000-04-03 15:42:13 +00004977\end{ctypedesc}
4978
4979\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
4980 (PyObject *self, int segment, void **ptrptr)}
Greg Stein4d4d0032001-04-07 16:14:49 +00004981Return a pointer to a writable memory buffer in \code{*\var{ptrptr}},
4982and the length of that segment as the function return value.
4983The memory buffer must correspond to buffer segment \var{segment}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00004984Must return \code{-1} and set an exception on error.
4985\exception{TypeError} should be raised if the object only supports
4986read-only buffers, and \exception{SystemError} should be raised when
4987\var{segment} specifies a segment that doesn't exist.
4988% Why doesn't it raise ValueError for this one?
Fred Drake659ebfa2000-04-03 15:42:13 +00004989% GJS: because you shouldn't be calling it with an invalid
4990% segment. That indicates a blatant programming error in the C
4991% code.
Fred Drake58c5a2a1999-08-04 13:13:24 +00004992\end{ctypedesc}
4993
Fred Drake659ebfa2000-04-03 15:42:13 +00004994\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
4995 (PyObject *self, int *lenp)}
4996Return the number of memory segments which comprise the buffer. If
4997\var{lenp} is not \NULL, the implementation must report the sum of the
4998sizes (in bytes) of all segments in \code{*\var{lenp}}.
4999The function cannot fail.
5000\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00005001
Fred Drake659ebfa2000-04-03 15:42:13 +00005002\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
5003 (PyObject *self, int segment, const char **ptrptr)}
5004\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00005005
Guido van Rossumae110af1997-05-22 20:11:52 +00005006
Fred Drakec392b572001-03-21 22:15:01 +00005007\section{Supporting Cyclic Garbarge Collection
5008 \label{supporting-cycle-detection}}
5009
5010Python's support for detecting and collecting garbage which involves
5011circular references requires support from object types which are
5012``containers'' for other objects which may also be containers. Types
5013which do not store references to other objects, or which only store
5014references to atomic types (such as numbers or strings), do not need
5015to provide any explicit support for garbage collection.
5016
5017To create a container type, the \member{tp_flags} field of the type
5018object must include the \constant{Py_TPFLAGS_GC} and provide an
Fred Drakee28d8ae2001-03-22 16:30:17 +00005019implementation of the \member{tp_traverse} handler. The computed
5020value of the \member{tp_basicsize} field must include
5021\constant{PyGC_HEAD_SIZE} as well. If instances of the type are
5022mutable, a \member{tp_clear} implementation must also be provided.
Fred Drakec392b572001-03-21 22:15:01 +00005023
5024\begin{datadesc}{Py_TPFLAGS_GC}
5025 Objects with a type with this flag set must conform with the rules
5026 documented here. For convenience these objects will be referred to
5027 as container objects.
5028\end{datadesc}
5029
5030\begin{datadesc}{PyGC_HEAD_SIZE}
5031 Extra memory needed for the garbage collector. Container objects
5032 must include this in the calculation of their tp_basicsize. If the
5033 collector is disabled at compile time then this is \code{0}.
5034\end{datadesc}
5035
Fred Drakee28d8ae2001-03-22 16:30:17 +00005036Constructors for container types must conform to two rules:
5037
5038\begin{enumerate}
5039\item The memory for the object must be allocated using
5040 \cfunction{PyObject_New()} or \cfunction{PyObject_VarNew()}.
5041
5042\item Once all the fields which may contain references to other
5043 containers are initialized, it must call
5044 \cfunction{PyObject_GC_Init()}.
5045\end{enumerate}
5046
Fred Drakec392b572001-03-21 22:15:01 +00005047\begin{cfuncdesc}{void}{PyObject_GC_Init}{PyObject *op}
5048 Adds the object \var{op} to the set of container objects tracked by
5049 the collector. The collector can run at unexpected times so objects
5050 must be valid while being tracked. This should be called once all
5051 the fields followed by the \member{tp_traverse} handler become valid,
5052 usually near the end of the constructor.
5053\end{cfuncdesc}
5054
Fred Drakee28d8ae2001-03-22 16:30:17 +00005055Similarly, the deallocator for the object must conform to a similar
5056pair of rules:
5057
5058\begin{enumerate}
5059\item Before fields which refer to other containers are invalidated,
5060 \cfunction{PyObject_GC_Fini()} must be called.
5061
5062\item The object's memory must be deallocated using
5063 \cfunction{PyObject_Del()}.
5064\end{enumerate}
5065
Fred Drakec392b572001-03-21 22:15:01 +00005066\begin{cfuncdesc}{void}{PyObject_GC_Fini}{PyObject *op}
5067 Remove the object \var{op} from the set of container objects tracked
5068 by the collector. Note that \cfunction{PyObject_GC_Init()} can be
5069 called again on this object to add it back to the set of tracked
5070 objects. The deallocator (\member{tp_dealloc} handler) should call
5071 this for the object before any of the fields used by the
5072 \member{tp_traverse} handler become invalid.
Fred Drake8f6df462001-03-23 17:42:09 +00005073
5074 \strong{Note:} Any container which may be referenced from another
5075 object reachable by the collector must itself be tracked by the
5076 collector, so it is generally not safe to call this function
5077 anywhere but in the object's deallocator.
Fred Drakec392b572001-03-21 22:15:01 +00005078\end{cfuncdesc}
5079
5080The \member{tp_traverse} handler accepts a function parameter of this
5081type:
5082
5083\begin{ctypedesc}[visitproc]{int (*visitproc)(PyObject *object, void *arg)}
5084 Type of the visitor function passed to the \member{tp_traverse}
5085 handler. The function should be called with an object to traverse
5086 as \var{object} and the third parameter to the \member{tp_traverse}
5087 handler as \var{arg}.
5088\end{ctypedesc}
5089
5090The \member{tp_traverse} handler must have the following type:
5091
5092\begin{ctypedesc}[traverseproc]{int (*traverseproc)(PyObject *self,
5093 visitproc visit, void *arg)}
5094 Traversal function for a container object. Implementations must
5095 call the \var{visit} function for each object directly contained by
5096 \var{self}, with the parameters to \var{visit} being the contained
5097 object and the \var{arg} value passed to the handler. If
5098 \var{visit} returns a non-zero value then an error has occurred and
5099 that value should be returned immediately.
5100\end{ctypedesc}
5101
5102The \member{tp_clear} handler must be of the \ctype{inquiry} type, or
5103\NULL{} if the object is immutable.
5104
5105\begin{ctypedesc}[inquiry]{int (*inquiry)(PyObject *self)}
5106 Drop references that may have created reference cycles. Immutable
5107 objects do not have to define this method since they can never
5108 directly create reference cycles. Note that the object must still
5109 be valid after calling this method (i.e., don't just call
5110 \cfunction{Py_DECREF()} on a reference). The collector will call
5111 this method if it detects that this object is involved in a
5112 reference cycle.
5113\end{ctypedesc}
5114
5115
Fred Drakee28d8ae2001-03-22 16:30:17 +00005116\subsection{Example Cycle Collector Support
5117 \label{example-cycle-support}}
5118
5119This example shows only enough of the implementation of an extension
5120type to show how the garbage collector support needs to be added. It
5121shows the definition of the object structure, the
5122\member{tp_traverse}, \member{tp_clear} and \member{tp_dealloc}
5123implementations, the type structure, and a constructor --- the module
5124initialization needed to export the constructor to Python is not shown
5125as there are no special considerations there for the collector. To
5126make this interesting, assume that the module exposes ways for the
5127\member{container} field of the object to be modified. Note that
5128since no checks are made on the type of the object used to initialize
5129\member{container}, we have to assume that it may be a container.
5130
5131\begin{verbatim}
5132#include "Python.h"
5133
5134typedef struct {
5135 PyObject_HEAD
5136 PyObject *container;
5137} MyObject;
5138
5139static int
5140my_traverse(MyObject *self, visitproc visit, void *arg)
5141{
5142 if (self->container != NULL)
5143 return visit(self->container, arg);
5144 else
5145 return 0;
5146}
5147
5148static int
5149my_clear(MyObject *self)
5150{
5151 Py_XDECREF(self->container);
5152 self->container = NULL;
5153
5154 return 0;
5155}
5156
5157static void
5158my_dealloc(MyObject *self)
5159{
5160 PyObject_GC_Fini((PyObject *) self);
5161 Py_XDECREF(self->container);
5162 PyObject_Del(self);
5163}
5164\end{verbatim}
5165
5166\begin{verbatim}
5167statichere PyTypeObject
5168MyObject_Type = {
5169 PyObject_HEAD_INIT(NULL)
5170 0,
5171 "MyObject",
5172 sizeof(MyObject) + PyGC_HEAD_SIZE,
5173 0,
5174 (destructor)my_dealloc, /* tp_dealloc */
5175 0, /* tp_print */
5176 0, /* tp_getattr */
5177 0, /* tp_setattr */
5178 0, /* tp_compare */
5179 0, /* tp_repr */
5180 0, /* tp_as_number */
5181 0, /* tp_as_sequence */
5182 0, /* tp_as_mapping */
5183 0, /* tp_hash */
5184 0, /* tp_call */
5185 0, /* tp_str */
5186 0, /* tp_getattro */
5187 0, /* tp_setattro */
5188 0, /* tp_as_buffer */
5189 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC,
5190 0, /* tp_doc */
5191 (traverseproc)my_traverse, /* tp_traverse */
5192 (inquiry)my_clear, /* tp_clear */
5193 0, /* tp_richcompare */
5194 0, /* tp_weaklistoffset */
5195};
5196
5197/* This constructor should be made accessible from Python. */
5198static PyObject *
5199new_object(PyObject *unused, PyObject *args)
5200{
5201 PyObject *container = NULL;
5202 MyObject *result = NULL;
5203
5204 if (PyArg_ParseTuple(args, "|O:new_object", &container)) {
5205 result = PyObject_New(MyObject, &MyObject_Type);
5206 if (result != NULL) {
5207 result->container = container;
5208 PyObject_GC_Init();
5209 }
5210 }
5211 return (PyObject *) result;
5212}
5213\end{verbatim}
5214
5215
Fred Drake659ebfa2000-04-03 15:42:13 +00005216% \chapter{Debugging \label{debugging}}
5217%
5218% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00005219
5220
Fred Drakeed773ef2000-09-21 21:35:22 +00005221\appendix
5222\chapter{Reporting Bugs}
5223\input{reportingbugs}
5224
Marc-André Lemburga544ea22001-01-17 18:04:31 +00005225\input{api.ind} % Index -- must be last
Guido van Rossum9231c8f1997-05-15 21:43:21 +00005226
5227\end{document}