blob: a4886a7ec4c48f37b8944dbf329ba0814d64e9f9 [file] [log] [blame]
Fred Drake6659c301998-03-03 22:02:19 +00001\documentclass{manual}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003\title{Python/C API Reference Manual}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00004
5\input{boilerplate}
6
Marc-André Lemburga544ea22001-01-17 18:04:31 +00007\makeindex % tell \index to actually write the .idx file
Guido van Rossum9231c8f1997-05-15 21:43:21 +00008
9
10\begin{document}
11
Guido van Rossum9231c8f1997-05-15 21:43:21 +000012\maketitle
13
Fred Drake9f86b661998-07-28 21:55:19 +000014\ifhtml
15\chapter*{Front Matter\label{front}}
16\fi
17
Guido van Rossum9231c8f1997-05-15 21:43:21 +000018\input{copyright}
19
20\begin{abstract}
21
22\noindent
Fred Drake659ebfa2000-04-03 15:42:13 +000023This manual documents the API used by C and \Cpp{} programmers who
Fred Drakee058b4f1998-02-16 06:15:35 +000024want to write extension modules or embed Python. It is a companion to
Fred Drakebe486461999-11-09 17:03:03 +000025\citetitle[../ext/ext.html]{Extending and Embedding the Python
26Interpreter}, which describes the general principles of extension
27writing but does not document the API functions in detail.
Guido van Rossum9231c8f1997-05-15 21:43:21 +000028
Guido van Rossum5b8a5231997-12-30 04:38:44 +000029\strong{Warning:} The current version of this document is incomplete.
30I hope that it is nevertheless useful. I will continue to work on it,
31and release new versions from time to time, independent from Python
32source code releases.
33
Guido van Rossum9231c8f1997-05-15 21:43:21 +000034\end{abstract}
35
Fred Drake4d4f9e71998-01-13 22:25:02 +000036\tableofcontents
Guido van Rossum9231c8f1997-05-15 21:43:21 +000037
Guido van Rossum5060b3b1997-08-17 18:02:23 +000038% XXX Consider moving all this back to ext.tex and giving api.tex
39% XXX a *really* short intro only.
Guido van Rossum9231c8f1997-05-15 21:43:21 +000040
Fred Drakeefd146c1999-02-15 15:30:45 +000041\chapter{Introduction \label{intro}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +000042
Fred Drake659ebfa2000-04-03 15:42:13 +000043The Application Programmer's Interface to Python gives C and
44\Cpp{} programmers access to the Python interpreter at a variety of
45levels. The API is equally usable from \Cpp{}, but for brevity it is
46generally referred to as the Python/C API. There are two
47fundamentally different reasons for using the Python/C API. The first
48reason is to write \emph{extension modules} for specific purposes;
49these are C modules that extend the Python interpreter. This is
50probably the most common use. The second reason is to use Python as a
51component in a larger application; this technique is generally
52referred to as \dfn{embedding} Python in an application.
Guido van Rossum59a61351997-08-14 20:34:33 +000053
Guido van Rossum4a944d71997-08-14 20:35:38 +000054Writing an extension module is a relatively well-understood process,
55where a ``cookbook'' approach works well. There are several tools
56that automate the process to some extent. While people have embedded
57Python in other applications since its early existence, the process of
Fred Drakefc43d002001-05-21 15:03:35 +000058embedding Python is less straightforward than writing an extension.
Guido van Rossum59a61351997-08-14 20:34:33 +000059
Guido van Rossum4a944d71997-08-14 20:35:38 +000060Many API functions are useful independent of whether you're embedding
61or extending Python; moreover, most applications that embed Python
62will need to provide a custom extension as well, so it's probably a
63good idea to become familiar with writing an extension before
Guido van Rossum59a61351997-08-14 20:34:33 +000064attempting to embed Python in a real application.
65
Fred Drakeefd146c1999-02-15 15:30:45 +000066
67\section{Include Files \label{includes}}
Guido van Rossum580aa8d1997-11-25 15:34:51 +000068
69All function, type and macro definitions needed to use the Python/C
70API are included in your code by the following line:
71
Fred Drakee058b4f1998-02-16 06:15:35 +000072\begin{verbatim}
73#include "Python.h"
74\end{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +000075
Fred Drakee058b4f1998-02-16 06:15:35 +000076This implies inclusion of the following standard headers:
Fred Drake0b71cea2000-09-26 05:51:50 +000077\code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>},
78\code{<limits.h>}, and \code{<stdlib.h>} (if available).
Guido van Rossum580aa8d1997-11-25 15:34:51 +000079
80All user visible names defined by Python.h (except those defined by
Fred Drakee058b4f1998-02-16 06:15:35 +000081the included standard headers) have one of the prefixes \samp{Py} or
Fred Drake659ebfa2000-04-03 15:42:13 +000082\samp{_Py}. Names beginning with \samp{_Py} are for internal use by
83the Python implementation and should not be used by extension writers.
84Structure member names do not have a reserved prefix.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000085
Fred Drakee058b4f1998-02-16 06:15:35 +000086\strong{Important:} user code should never define names that begin
87with \samp{Py} or \samp{_Py}. This confuses the reader, and
88jeopardizes the portability of the user code to future Python
89versions, which may define additional names beginning with one of
90these prefixes.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000091
Fred Drake659ebfa2000-04-03 15:42:13 +000092The header files are typically installed with Python. On \UNIX, these
93are located in the directories
94\file{\envvar{prefix}/include/python\var{version}/} and
95\file{\envvar{exec_prefix}/include/python\var{version}/}, where
96\envvar{prefix} and \envvar{exec_prefix} are defined by the
97corresponding parameters to Python's \program{configure} script and
98\var{version} is \code{sys.version[:3]}. On Windows, the headers are
99installed in \file{\envvar{prefix}/include}, where \envvar{prefix} is
100the installation directory specified to the installer.
101
102To include the headers, place both directories (if different) on your
103compiler's search path for includes. Do \emph{not} place the parent
104directories on the search path and then use
Fred Draked5d04352000-09-14 20:24:17 +0000105\samp{\#include <python\shortversion/Python.h>}; this will break on
Fred Drake659ebfa2000-04-03 15:42:13 +0000106multi-platform builds since the platform independent headers under
107\envvar{prefix} include the platform specific headers from
108\envvar{exec_prefix}.
109
Fred 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 Drake24e62192001-05-21 15:56:55 +0000612\begin{cfuncdesc}{int}{Py_Main}{int argc, char **argv}
613 The main program for the standard interpreter. This is made
614 available for programs which embed Python. The \var{argc} and
615 \var{argv} parameters should be prepared exactly as those which are
616 passed to a C program's \cfunction{main()} function. It is
617 important to note that the argument list may be modified (but the
618 contents of the strings pointed to by the argument list are not).
619 The return value will be the integer passed to the
620 \function{sys.exit()} function, \code{1} if the interpreter exits
621 due to an exception, or \code{2} if the parameter list does not
622 represent a valid Python command line.
623\end{cfuncdesc}
624
Fred Drakec6fa34e1998-04-02 06:47:24 +0000625\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000626 If \var{fp} refers to a file associated with an interactive device
627 (console or terminal input or \UNIX{} pseudo-terminal), return the
628 value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
629 result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
Fred Drakea8d73412000-08-11 20:39:29 +0000630 \NULL{}, this function uses \code{"???"} as the filename.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000631\end{cfuncdesc}
632
Fred Drakec6fa34e1998-04-02 06:47:24 +0000633\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
Fred Drake0041a941999-04-29 04:20:46 +0000634 Executes the Python source code from \var{command} in the
635 \module{__main__} module. If \module{__main__} does not already
636 exist, it is created. Returns \code{0} on success or \code{-1} if
637 an exception was raised. If there was an error, there is no way to
638 get the exception information.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000639\end{cfuncdesc}
640
Fred Drakec6fa34e1998-04-02 06:47:24 +0000641\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000642 Similar to \cfunction{PyRun_SimpleString()}, but the Python source
643 code is read from \var{fp} instead of an in-memory string.
644 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000645\end{cfuncdesc}
646
Fred Drakec6fa34e1998-04-02 06:47:24 +0000647\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000648 Read and execute a single statement from a file associated with an
649 interactive device. If \var{filename} is \NULL, \code{"???"} is
650 used instead. The user will be prompted using \code{sys.ps1} and
651 \code{sys.ps2}. Returns \code{0} when the input was executed
652 successfully, \code{-1} if there was an exception, or an error code
653 from the \file{errcode.h} include file distributed as part of Python
654 in case of a parse error. (Note that \file{errcode.h} is not
655 included by \file{Python.h}, so must be included specifically if
656 needed.)
Fred Drakee5bf8b21998-02-12 21:22:28 +0000657\end{cfuncdesc}
658
Fred Drakec6fa34e1998-04-02 06:47:24 +0000659\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000660 Read and execute statements from a file associated with an
661 interactive device until \EOF{} is reached. If \var{filename} is
662 \NULL, \code{"???"} is used instead. The user will be prompted
663 using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000664\end{cfuncdesc}
665
Fred Drakec6fa34e1998-04-02 06:47:24 +0000666\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
667 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000668 Parse Python source code from \var{str} using the start token
669 \var{start}. The result can be used to create a code object which
670 can be evaluated efficiently. This is useful if a code fragment
671 must be evaluated many times.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000672\end{cfuncdesc}
673
Fred Drakec6fa34e1998-04-02 06:47:24 +0000674\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
675 char *filename, int start}
Fred Drake0041a941999-04-29 04:20:46 +0000676 Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
677 source code is read from \var{fp} instead of an in-memory string.
678 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000679\end{cfuncdesc}
680
Fred Drakec6fa34e1998-04-02 06:47:24 +0000681\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
682 PyObject *globals,
683 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000684 Execute Python source code from \var{str} in the context specified
685 by the dictionaries \var{globals} and \var{locals}. The parameter
686 \var{start} specifies the start token that should be used to parse
687 the source code.
688
689 Returns the result of executing the code as a Python object, or
690 \NULL{} if an exception was raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000691\end{cfuncdesc}
692
Fred Drakec6fa34e1998-04-02 06:47:24 +0000693\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
694 int start, PyObject *globals,
695 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000696 Similar to \cfunction{PyRun_String()}, but the Python source code is
Fred Drake659ebfa2000-04-03 15:42:13 +0000697 read from \var{fp} instead of an in-memory string.
698 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000699\end{cfuncdesc}
700
Fred Drakec6fa34e1998-04-02 06:47:24 +0000701\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
702 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000703 Parse and compile the Python source code in \var{str}, returning the
704 resulting code object. The start token is given by \var{start};
Fred Drakec924b8d1999-08-23 18:57:25 +0000705 this can be used to constrain the code which can be compiled and should
706 be \constant{Py_eval_input}, \constant{Py_file_input}, or
707 \constant{Py_single_input}. The filename specified by
708 \var{filename} is used to construct the code object and may appear
709 in tracebacks or \exception{SyntaxError} exception messages. This
710 returns \NULL{} if the code cannot be parsed or compiled.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000711\end{cfuncdesc}
712
Fred Drakec924b8d1999-08-23 18:57:25 +0000713\begin{cvardesc}{int}{Py_eval_input}
714 The start symbol from the Python grammar for isolated expressions;
Fred Drake659ebfa2000-04-03 15:42:13 +0000715 for use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
Fred Drakec924b8d1999-08-23 18:57:25 +0000716\end{cvardesc}
717
718\begin{cvardesc}{int}{Py_file_input}
719 The start symbol from the Python grammar for sequences of statements
720 as read from a file or other source; for use with
Fred Drake659ebfa2000-04-03 15:42:13 +0000721 \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
722 the symbol to use when compiling arbitrarily long Python source code.
Fred Drakec924b8d1999-08-23 18:57:25 +0000723\end{cvardesc}
724
725\begin{cvardesc}{int}{Py_single_input}
726 The start symbol from the Python grammar for a single statement; for
Fred Drake659ebfa2000-04-03 15:42:13 +0000727 use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
728 This is the symbol used for the interactive interpreter loop.
Fred Drakec924b8d1999-08-23 18:57:25 +0000729\end{cvardesc}
730
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000731
Fred Drakeefd146c1999-02-15 15:30:45 +0000732\chapter{Reference Counting \label{countingRefs}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000733
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000734The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000735of Python objects.
736
737\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
Fred Drakec6fa34e1998-04-02 06:47:24 +0000738Increment the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000739not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000740\cfunction{Py_XINCREF()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000741\end{cfuncdesc}
742
743\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000744Increment the reference count for object \var{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000745\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000746\end{cfuncdesc}
747
748\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000749Decrement the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000750not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000751\cfunction{Py_XDECREF()}. If the reference count reaches zero, the
752object's type's deallocation function (which must not be \NULL{}) is
753invoked.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000754
755\strong{Warning:} The deallocation function can cause arbitrary Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000756code to be invoked (e.g. when a class instance with a
757\method{__del__()} method is deallocated). While exceptions in such
758code are not propagated, the executed code has free access to all
759Python global variables. This means that any object that is reachable
760from a global variable should be in a consistent state before
761\cfunction{Py_DECREF()} is invoked. For example, code to delete an
762object from a list should copy a reference to the deleted object in a
763temporary variable, update the list data structure, and then call
764\cfunction{Py_DECREF()} for the temporary variable.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000765\end{cfuncdesc}
766
767\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000768Decrement the reference count for object \var{o}. The object may be
769\NULL{}, in which case the macro has no effect; otherwise the effect
770is the same as for \cfunction{Py_DECREF()}, and the same warning
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000771applies.
772\end{cfuncdesc}
773
Fred Drake659ebfa2000-04-03 15:42:13 +0000774The following functions or macros are only for use within the
775interpreter core: \cfunction{_Py_Dealloc()},
776\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
777well as the global variable \cdata{_Py_RefTotal}.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000778
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000779
Fred Drakeefd146c1999-02-15 15:30:45 +0000780\chapter{Exception Handling \label{exceptionHandling}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000781
Fred Drake659ebfa2000-04-03 15:42:13 +0000782The functions described in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000783exceptions. It is important to understand some of the basics of
Fred Drake659ebfa2000-04-03 15:42:13 +0000784Python exception handling. It works somewhat like the
785\UNIX{} \cdata{errno} variable: there is a global indicator (per
786thread) of the last error that occurred. Most functions don't clear
787this on success, but will set it to indicate the cause of the error on
788failure. Most functions also return an error indicator, usually
789\NULL{} if they are supposed to return a pointer, or \code{-1} if they
790return an integer (exception: the \cfunction{PyArg_Parse*()} functions
791return \code{1} for success and \code{0} for failure). When a
792function must fail because some function it called failed, it
793generally doesn't set the error indicator; the function it called
794already set it.
Guido van Rossumae110af1997-05-22 20:11:52 +0000795
796The error indicator consists of three Python objects corresponding to
Fred Drake659ebfa2000-04-03 15:42:13 +0000797\withsubitem{(in module sys)}{
798 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000799the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
800\code{sys.exc_traceback}. API functions exist to interact with the
801error indicator in various ways. There is a separate error indicator
802for each thread.
803
804% XXX Order of these should be more thoughtful.
805% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000806
807\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000808Print a standard traceback to \code{sys.stderr} and clear the error
809indicator. Call this function only when the error indicator is set.
810(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000811\end{cfuncdesc}
812
Fred Drakec6fa34e1998-04-02 06:47:24 +0000813\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000814Test whether the error indicator is set. If set, return the exception
Fred Drakee058b4f1998-02-16 06:15:35 +0000815\emph{type} (the first argument to the last call to one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000816\cfunction{PyErr_Set*()} functions or to \cfunction{PyErr_Restore()}). If
Fred Drakee058b4f1998-02-16 06:15:35 +0000817not set, return \NULL{}. You do not own a reference to the return
818value, so you do not need to \cfunction{Py_DECREF()} it.
Fred Drake659ebfa2000-04-03 15:42:13 +0000819\strong{Note:} Do not compare the return value to a specific
Fred Drakee058b4f1998-02-16 06:15:35 +0000820exception; use \cfunction{PyErr_ExceptionMatches()} instead, shown
Fred Drake659ebfa2000-04-03 15:42:13 +0000821below. (The comparison could easily fail since the exception may be
822an instance instead of a class, in the case of a class exception, or
823it may the a subclass of the expected exception.)
Guido van Rossum42cefd01997-10-05 15:27:29 +0000824\end{cfuncdesc}
825
826\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000827Equivalent to
Fred Drakee058b4f1998-02-16 06:15:35 +0000828\samp{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
Fred Drake659ebfa2000-04-03 15:42:13 +0000829This should only be called when an exception is actually set; a memory
830access violation will occur if no exception has been raised.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000831\end{cfuncdesc}
832
833\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000834Return true if the \var{given} exception matches the exception in
835\var{exc}. If \var{exc} is a class object, this also returns true
Fred Drake659ebfa2000-04-03 15:42:13 +0000836when \var{given} is an instance of a subclass. If \var{exc} is a tuple, all
Guido van Rossum42cefd01997-10-05 15:27:29 +0000837exceptions in the tuple (and recursively in subtuples) are searched
Fred Drake659ebfa2000-04-03 15:42:13 +0000838for a match. If \var{given} is \NULL, a memory access violation will
839occur.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000840\end{cfuncdesc}
841
842\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000843Under certain circumstances, the values returned by
Fred Drakee058b4f1998-02-16 06:15:35 +0000844\cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning that
845\code{*\var{exc}} is a class object but \code{*\var{val}} is not an
846instance of the same class. This function can be used to instantiate
847the class in that case. If the values are already normalized, nothing
Fred Drake659ebfa2000-04-03 15:42:13 +0000848happens. The delayed normalization is implemented to improve
849performance.
Guido van Rossumae110af1997-05-22 20:11:52 +0000850\end{cfuncdesc}
851
852\begin{cfuncdesc}{void}{PyErr_Clear}{}
853Clear the error indicator. If the error indicator is not set, there
854is no effect.
855\end{cfuncdesc}
856
Fred Drake659ebfa2000-04-03 15:42:13 +0000857\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
858 PyObject **ptraceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000859Retrieve the error indicator into three variables whose addresses are
860passed. If the error indicator is not set, set all three variables to
861\NULL{}. If it is set, it will be cleared and you own a reference to
Fred Drake659ebfa2000-04-03 15:42:13 +0000862each object retrieved. The value and traceback object may be
863\NULL{} even when the type object is not. \strong{Note:} This
864function is normally only used by code that needs to handle exceptions
865or by code that needs to save and restore the error indicator
866temporarily.
Guido van Rossumae110af1997-05-22 20:11:52 +0000867\end{cfuncdesc}
868
Fred Drake17e63432000-08-31 05:50:40 +0000869\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
870 PyObject *traceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000871Set the error indicator from the three objects. If the error
872indicator is already set, it is cleared first. If the objects are
873\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
874and non-\NULL{} value or traceback. The exception type should be a
875string or class; if it is a class, the value should be an instance of
876that class. Do not pass an invalid exception type or value.
877(Violating these rules will cause subtle problems later.) This call
Fred Drake17e63432000-08-31 05:50:40 +0000878takes away a reference to each object, i.e.\ you must own a reference
Guido van Rossumae110af1997-05-22 20:11:52 +0000879to each object before the call and after the call you no longer own
880these references. (If you don't understand this, don't use this
Fred Drake659ebfa2000-04-03 15:42:13 +0000881function. I warned you.) \strong{Note:} This function is normally
Guido van Rossumae110af1997-05-22 20:11:52 +0000882only used by code that needs to save and restore the error indicator
883temporarily.
884\end{cfuncdesc}
885
886\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
887This is the most common way to set the error indicator. The first
888argument specifies the exception type; it is normally one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000889standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
Guido van Rossumae110af1997-05-22 20:11:52 +0000890increment its reference count. The second argument is an error
891message; it is converted to a string object.
892\end{cfuncdesc}
893
894\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +0000895This function is similar to \cfunction{PyErr_SetString()} but lets you
Guido van Rossumae110af1997-05-22 20:11:52 +0000896specify an arbitrary Python object for the ``value'' of the exception.
897You need not increment its reference count.
898\end{cfuncdesc}
899
Fred Drake73577702000-04-10 18:50:14 +0000900\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
Moshe Zadka57a59322000-09-01 09:47:20 +0000901 const char *format, \moreargs}
Fred Drake89fb0352000-10-14 05:49:30 +0000902This function sets the error indicator. \var{exception} should be a
903Python exception (string or class, not an instance).
Fred Drake5566c1c2001-01-19 22:48:33 +0000904\var{format} should be a string, containing format codes, similar to
Moshe Zadka57a59322000-09-01 09:47:20 +0000905\cfunction{printf}. The \code{width.precision} before a format code
906is parsed, but the width part is ignored.
907
908\begin{tableii}{c|l}{character}{Character}{Meaning}
909 \lineii{c}{Character, as an \ctype{int} parameter}
910 \lineii{d}{Number in decimal, as an \ctype{int} parameter}
911 \lineii{x}{Number in hexadecimal, as an \ctype{int} parameter}
912 \lineii{x}{A string, as a \ctype{char *} parameter}
913\end{tableii}
914
915An unrecognized format character causes all the rest of
916the format string to be copied as-is to the result string,
917and any extra arguments discarded.
918
919A new reference is returned, which is owned by the caller.
Jeremy Hylton98605b52000-04-10 18:40:57 +0000920\end{cfuncdesc}
921
Guido van Rossumae110af1997-05-22 20:11:52 +0000922\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +0000923This is a shorthand for \samp{PyErr_SetObject(\var{type}, Py_None)}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000924\end{cfuncdesc}
925
926\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000927This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000928\var{message})}, where \var{message} indicates that a built-in operation
929was invoked with an illegal argument. It is mostly for internal use.
930\end{cfuncdesc}
931
Fred Drakec6fa34e1998-04-02 06:47:24 +0000932\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000933This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
Guido van Rossumae110af1997-05-22 20:11:52 +0000934returns \NULL{} so an object allocation function can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000935\samp{return PyErr_NoMemory();} when it runs out of memory.
Guido van Rossumae110af1997-05-22 20:11:52 +0000936\end{cfuncdesc}
937
Fred Drakec6fa34e1998-04-02 06:47:24 +0000938\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
Fred Drake659ebfa2000-04-03 15:42:13 +0000939This is a convenience function to raise an exception when a C library
940function has returned an error and set the C variable \cdata{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000941It constructs a tuple object whose first item is the integer
Fred Drakef8830d11998-04-23 14:06:01 +0000942\cdata{errno} value and whose second item is the corresponding error
Fred Drake659ebfa2000-04-03 15:42:13 +0000943message (gotten from \cfunction{strerror()}\ttindex{strerror()}), and
944then calls
Fred Drakee058b4f1998-02-16 06:15:35 +0000945\samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
Fred Drakef8830d11998-04-23 14:06:01 +0000946the \cdata{errno} value is \constant{EINTR}, indicating an interrupted
Fred Drakee058b4f1998-02-16 06:15:35 +0000947system call, this calls \cfunction{PyErr_CheckSignals()}, and if that set
Guido van Rossumae110af1997-05-22 20:11:52 +0000948the error indicator, leaves it set to that. The function always
949returns \NULL{}, so a wrapper function around a system call can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000950\samp{return PyErr_SetFromErrno();} when the system call returns an
951error.
Guido van Rossumae110af1997-05-22 20:11:52 +0000952\end{cfuncdesc}
953
954\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000955This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000956\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000957operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000958argument. It is mostly for internal use.
959\end{cfuncdesc}
960
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000961\begin{cfuncdesc}{int}{PyErr_Warn}{PyObject *category, char *message}
962Issue a warning message. The \var{category} argument is a warning
Fred Drake5566c1c2001-01-19 22:48:33 +0000963category (see below) or \NULL; the \var{message} argument is a message
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000964string.
965
966This function normally prints a warning message to \var{sys.stderr};
967however, it is also possible that the user has specified that warnings
968are to be turned into errors, and in that case this will raise an
969exception. It is also possible that the function raises an exception
970because of a problem with the warning machinery (the implementation
971imports the \module{warnings} module to do the heavy lifting). The
972return value is \code{0} if no exception is raised, or \code{-1} if
973an exception is raised. (It is not possible to determine whether a
974warning message is actually printed, nor what the reason is for the
975exception; this is intentional.) If an exception is raised, the
Fred Drake5566c1c2001-01-19 22:48:33 +0000976caller should do its normal exception handling
977(e.g. \cfunction{Py_DECREF()} owned references and return an error
978value).
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000979
980Warning categories must be subclasses of \cdata{Warning}; the default
981warning category is \cdata{RuntimeWarning}. The standard Python
982warning categories are available as global variables whose names are
983\samp{PyExc_} followed by the Python exception name. These have the
984type \ctype{PyObject*}; they are all class objects. Their names are
985\cdata{PyExc_Warning}, \cdata{PyExc_UserWarning},
986\cdata{PyExc_DeprecationWarning}, \cdata{PyExc_SyntaxWarning}, and
987\cdata{PyExc_RuntimeWarning}. \cdata{PyExc_Warning} is a subclass of
988\cdata{PyExc_Exception}; the other warning categories are subclasses
989of \cdata{PyExc_Warning}.
990
991For information about warning control, see the documentation for the
Fred Drake316ef7c2001-01-04 05:56:34 +0000992\module{warnings} module and the \programopt{-W} option in the command
993line documentation. There is no C API for warning control.
Guido van Rossum3dbb4062000-12-19 03:53:01 +0000994\end{cfuncdesc}
995
Guido van Rossum1874c8f2001-02-28 23:46:44 +0000996\begin{cfuncdesc}{int}{PyErr_WarnExplicit}{PyObject *category, char *message,
997char *filename, int lineno, char *module, PyObject *registry}
998Issue a warning message with explicit control over all warning
999attributes. This is a straightforward wrapper around the Python
1000function \function{warnings.warn_explicit()}, see there for more
1001information. The \var{module} and \var{registry} arguments may be
1002set to \code{NULL} to get the default effect described there.
1003\end{cfuncdesc}
1004
Guido van Rossumae110af1997-05-22 20:11:52 +00001005\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
1006This function interacts with Python's signal handling. It checks
1007whether a signal has been sent to the processes and if so, invokes the
Fred Drake4de05a91998-02-16 14:25:26 +00001008corresponding signal handler. If the
1009\module{signal}\refbimodindex{signal} module is supported, this can
1010invoke a signal handler written in Python. In all cases, the default
Fred Drake659ebfa2000-04-03 15:42:13 +00001011effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
1012\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
1013\exception{KeyboardInterrupt} exception. If an exception is raised the
Fred Drakee058b4f1998-02-16 06:15:35 +00001014error indicator is set and the function returns \code{1}; otherwise
1015the function returns \code{0}. The error indicator may or may not be
1016cleared if it was previously set.
Guido van Rossumae110af1997-05-22 20:11:52 +00001017\end{cfuncdesc}
1018
1019\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001020This function is obsolete. It simulates the effect of a
1021\constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
Fred Drakee058b4f1998-02-16 06:15:35 +00001022\cfunction{PyErr_CheckSignals()} is called,
Fred Drake659ebfa2000-04-03 15:42:13 +00001023\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
1024\exception{KeyboardInterrupt} will be raised.
1025It may be called without holding the interpreter lock.
Guido van Rossumae110af1997-05-22 20:11:52 +00001026\end{cfuncdesc}
1027
Fred Drakec6fa34e1998-04-02 06:47:24 +00001028\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
1029 PyObject *base,
1030 PyObject *dict}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001031This utility function creates and returns a new exception object. The
Fred Drake659ebfa2000-04-03 15:42:13 +00001032\var{name} argument must be the name of the new exception, a C string
1033of the form \code{module.class}. The \var{base} and
Fred Draked04038d2000-06-29 20:15:14 +00001034\var{dict} arguments are normally \NULL{}. This creates a
Fred Drake659ebfa2000-04-03 15:42:13 +00001035class object derived from the root for all exceptions, the built-in
1036name \exception{Exception} (accessible in C as
Fred Draked04038d2000-06-29 20:15:14 +00001037\cdata{PyExc_Exception}). The \member{__module__} attribute of the
1038new class is set to the first part (up to the last dot) of the
1039\var{name} argument, and the class name is set to the last part (after
1040the last dot). The \var{base} argument can be used to specify an
1041alternate base class. The \var{dict} argument can be used to specify
1042a dictionary of class variables and methods.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001043\end{cfuncdesc}
1044
Jeremy Hyltonb709df32000-09-01 02:47:25 +00001045\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
1046This utility function prints a warning message to \var{sys.stderr}
1047when an exception has been set but it is impossible for the
1048interpreter to actually raise the exception. It is used, for example,
1049when an exception occurs in an \member{__del__} method.
1050
1051The function is called with a single argument \var{obj} that
1052identifies where the context in which the unraisable exception
1053occurred. The repr of \var{obj} will be printed in the warning
1054message.
1055\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001056
Fred Drakeefd146c1999-02-15 15:30:45 +00001057\section{Standard Exceptions \label{standardExceptions}}
Guido van Rossumae110af1997-05-22 20:11:52 +00001058
1059All standard Python exceptions are available as global variables whose
Fred Drake659ebfa2000-04-03 15:42:13 +00001060names are \samp{PyExc_} followed by the Python exception name. These
1061have the type \ctype{PyObject*}; they are all class objects. For
1062completeness, here are all the variables:
1063
1064\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
1065 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
1066 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
1067 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
1068 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
1069 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
1070 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
1071 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
1072 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
1073 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
1074 \lineiii{PyExc_IOError}{\exception{IOError}}{}
1075 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
1076 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
1077 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
1078 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
1079 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
1080 \lineiii{PyExc_NameError}{\exception{NameError}}{}
1081 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
1082 \lineiii{PyExc_OSError}{\exception{OSError}}{}
1083 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
1084 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
1085 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
1086 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
1087 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
1088 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
1089 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
Fred Drakea8d73412000-08-11 20:39:29 +00001090 \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(2)}
Fred Drake659ebfa2000-04-03 15:42:13 +00001091 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
1092\end{tableiii}
1093
1094\noindent
Fred Drakea8d73412000-08-11 20:39:29 +00001095Notes:
Fred Drake659ebfa2000-04-03 15:42:13 +00001096\begin{description}
1097\item[(1)]
Fred Draked04038d2000-06-29 20:15:14 +00001098 This is a base class for other standard exceptions.
Fred Drakea8d73412000-08-11 20:39:29 +00001099
1100\item[(2)]
1101 Only defined on Windows; protect code that uses this by testing that
1102 the preprocessor macro \code{MS_WINDOWS} is defined.
Fred Drake659ebfa2000-04-03 15:42:13 +00001103\end{description}
1104
1105
1106\section{Deprecation of String Exceptions}
1107
Fred Draked04038d2000-06-29 20:15:14 +00001108All exceptions built into Python or provided in the standard library
1109are derived from \exception{Exception}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001110\withsubitem{(built-in exception)}{\ttindex{Exception}}
Fred Drake659ebfa2000-04-03 15:42:13 +00001111
Fred Draked04038d2000-06-29 20:15:14 +00001112String exceptions are still supported in the interpreter to allow
Fred Drake659ebfa2000-04-03 15:42:13 +00001113existing code to run unmodified, but this will also change in a future
1114release.
Guido van Rossumae110af1997-05-22 20:11:52 +00001115
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001116
Fred Drakeefd146c1999-02-15 15:30:45 +00001117\chapter{Utilities \label{utilities}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001118
1119The functions in this chapter perform various utility tasks, such as
Fred Drake659ebfa2000-04-03 15:42:13 +00001120parsing function arguments and constructing Python values from C
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001121values.
1122
Fred Drakeefd146c1999-02-15 15:30:45 +00001123\section{OS Utilities \label{os}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001124
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001125\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001126Return true (nonzero) if the standard I/O file \var{fp} with name
1127\var{filename} is deemed interactive. This is the case for files for
1128which \samp{isatty(fileno(\var{fp}))} is true. If the global flag
Fred Drakef8830d11998-04-23 14:06:01 +00001129\cdata{Py_InteractiveFlag} is true, this function also returns true if
Fred Drake5566c1c2001-01-19 22:48:33 +00001130the \var{filename} pointer is \NULL{} or if the name is equal to one of
Fred Drakea8455ab2000-06-16 19:58:42 +00001131the strings \code{'<stdin>'} or \code{'???'}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001132\end{cfuncdesc}
1133
1134\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001135Return the time of last modification of the file \var{filename}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001136The result is encoded in the same way as the timestamp returned by
Fred Drake659ebfa2000-04-03 15:42:13 +00001137the standard C library function \cfunction{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001138\end{cfuncdesc}
1139
Fred Drakecabbc3b2000-06-28 15:53:13 +00001140\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
1141Function to update some internal state after a process fork; this
1142should be called in the new process if the Python interpreter will
1143continue to be used. If a new executable is loaded into the new
1144process, this function does not need to be called.
1145\end{cfuncdesc}
1146
Fred Drake17e63432000-08-31 05:50:40 +00001147\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
1148Return true when the interpreter runs out of stack space. This is a
1149reliable check, but is only available when \code{USE_STACKCHECK} is
1150defined (currently on Windows using the Microsoft Visual C++ compiler
1151and on the Macintosh). \code{USE_CHECKSTACK} will be defined
1152automatically; you should never change the definition in your own
1153code.
1154\end{cfuncdesc}
1155
Guido van Rossumc96ec6e2000-09-16 16:30:48 +00001156\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i}
1157Return the current signal handler for signal \var{i}.
1158This is a thin wrapper around either \cfunction{sigaction} or
1159\cfunction{signal}. Do not call those functions directly!
1160\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1161\end{cfuncdesc}
1162
1163\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h}
1164Set the signal handler for signal \var{i} to be \var{h};
1165return the old signal handler.
1166This is a thin wrapper around either \cfunction{sigaction} or
1167\cfunction{signal}. Do not call those functions directly!
1168\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1169\end{cfuncdesc}
1170
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001171
Fred Drakeefd146c1999-02-15 15:30:45 +00001172\section{Process Control \label{processControl}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001173
1174\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
1175Print a fatal error message and kill the process. No cleanup is
1176performed. This function should only be invoked when a condition is
1177detected that would make it dangerous to continue using the Python
1178interpreter; e.g., when the object administration appears to be
Fred Drake659ebfa2000-04-03 15:42:13 +00001179corrupted. On \UNIX{}, the standard C library function
1180\cfunction{abort()}\ttindex{abort()} is called which will attempt to
1181produce a \file{core} file.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001182\end{cfuncdesc}
1183
1184\begin{cfuncdesc}{void}{Py_Exit}{int status}
Fred Drake659ebfa2000-04-03 15:42:13 +00001185Exit the current process. This calls
1186\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
1187then calls the standard C library function
1188\code{exit(\var{status})}\ttindex{exit()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001189\end{cfuncdesc}
1190
1191\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drake659ebfa2000-04-03 15:42:13 +00001192Register a cleanup function to be called by
1193\cfunction{Py_Finalize()}\ttindex{Py_Finalize()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001194The cleanup function will be called with no arguments and should
Fred Drake659ebfa2000-04-03 15:42:13 +00001195return no value. At most 32 \index{cleanup functions}cleanup
1196functions can be registered.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001197When the registration is successful, \cfunction{Py_AtExit()} returns
1198\code{0}; on failure, it returns \code{-1}. The cleanup function
1199registered last is called first. Each cleanup function will be called
1200at most once. Since Python's internal finallization will have
1201completed before the cleanup function, no Python APIs should be called
1202by \var{func}.
1203\end{cfuncdesc}
1204
1205
Fred Drakeefd146c1999-02-15 15:30:45 +00001206\section{Importing Modules \label{importing}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001207
Fred Drakec6fa34e1998-04-02 06:47:24 +00001208\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00001209This is a simplified interface to
1210\cfunction{PyImport_ImportModuleEx()} below, leaving the
1211\var{globals} and \var{locals} arguments set to \NULL{}. When the
1212\var{name} argument contains a dot (i.e., when it specifies a
1213submodule of a package), the \var{fromlist} argument is set to the
1214list \code{['*']} so that the return value is the named module rather
1215than the top-level package containing it as would otherwise be the
1216case. (Unfortunately, this has an additional side effect when
1217\var{name} in fact specifies a subpackage instead of a submodule: the
1218submodules specified in the package's \code{__all__} variable are
1219\index{package variable!\code{__all__}}
1220\withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a
1221new reference to the imported module, or
1222\NULL{} with an exception set on failure (the module may still be
1223created in this case --- examine \code{sys.modules} to find out).
1224\withsubitem{(in module sys)}{\ttindex{modules}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001225\end{cfuncdesc}
1226
Fred Drakec6fa34e1998-04-02 06:47:24 +00001227\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001228Import a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001229Python function \function{__import__()}\bifuncindex{__import__}, as
1230the standard \function{__import__()} function calls this function
1231directly.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001232
Guido van Rossum42cefd01997-10-05 15:27:29 +00001233The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001234top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001235(the module may still be created in this case). Like for
Fred Drakee058b4f1998-02-16 06:15:35 +00001236\function{__import__()}, the return value when a submodule of a
1237package was requested is normally the top-level package, unless a
1238non-empty \var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001239\end{cfuncdesc}
1240
Fred Drakec6fa34e1998-04-02 06:47:24 +00001241\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001242This is a higher-level interface that calls the current ``import hook
Fred Drakee058b4f1998-02-16 06:15:35 +00001243function''. It invokes the \function{__import__()} function from the
Guido van Rossum42cefd01997-10-05 15:27:29 +00001244\code{__builtins__} of the current globals. This means that the
1245import is done using whatever import hooks are installed in the
Fred Drake4de05a91998-02-16 14:25:26 +00001246current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
1247\module{ihooks}\refstmodindex{ihooks}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001248\end{cfuncdesc}
1249
Fred Drakec6fa34e1998-04-02 06:47:24 +00001250\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001251Reload a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001252Python function \function{reload()}\bifuncindex{reload}, as the standard
Fred Drakee058b4f1998-02-16 06:15:35 +00001253\function{reload()} function calls this function directly. Return a
1254new reference to the reloaded module, or \NULL{} with an exception set
1255on failure (the module still exists in this case).
Guido van Rossum42cefd01997-10-05 15:27:29 +00001256\end{cfuncdesc}
1257
Fred Drakec6fa34e1998-04-02 06:47:24 +00001258\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001259Return the module object corresponding to a module name. The
1260\var{name} argument may be of the form \code{package.module}). First
1261check the modules dictionary if there's one there, and if not, create
Fred Drake659ebfa2000-04-03 15:42:13 +00001262a new one and insert in in the modules dictionary.
Guido van Rossuma096a2e1998-11-02 17:02:42 +00001263Warning: this function does not load or import the module; if the
1264module wasn't already loaded, you will get an empty module object.
1265Use \cfunction{PyImport_ImportModule()} or one of its variants to
1266import a module.
Fred Drake659ebfa2000-04-03 15:42:13 +00001267Return \NULL{} with an exception set on failure.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001268\end{cfuncdesc}
1269
Fred Drakec6fa34e1998-04-02 06:47:24 +00001270\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001271Given a module name (possibly of the form \code{package.module}) and a
1272code object read from a Python bytecode file or obtained from the
Fred Drake53fb7721998-02-16 06:23:20 +00001273built-in function \function{compile()}\bifuncindex{compile}, load the
1274module. Return a new reference to the module object, or \NULL{} with
1275an exception set if an error occurred (the module may still be created
1276in this case). (This function would reload the module if it was
1277already imported.)
Guido van Rossum42cefd01997-10-05 15:27:29 +00001278\end{cfuncdesc}
1279
1280\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001281Return the magic number for Python bytecode files (a.k.a.
1282\file{.pyc} and \file{.pyo} files). The magic number should be
1283present in the first four bytes of the bytecode file, in little-endian
1284byte order.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001285\end{cfuncdesc}
1286
Fred Drakec6fa34e1998-04-02 06:47:24 +00001287\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001288Return the dictionary used for the module administration
1289(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1290variable.
1291\end{cfuncdesc}
1292
1293\begin{cfuncdesc}{void}{_PyImport_Init}{}
1294Initialize the import mechanism. For internal use only.
1295\end{cfuncdesc}
1296
1297\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1298Empty the module table. For internal use only.
1299\end{cfuncdesc}
1300
1301\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1302Finalize the import mechanism. For internal use only.
1303\end{cfuncdesc}
1304
Fred Drakec6fa34e1998-04-02 06:47:24 +00001305\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001306For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001307\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001308
Fred Drakec6fa34e1998-04-02 06:47:24 +00001309\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001310For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001311\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001312
Fred Drake1d158692000-06-18 05:21:21 +00001313\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
1314Load a frozen module named \var{name}. Return \code{1} for success,
1315\code{0} if the module is not found, and \code{-1} with an exception
1316set if the initialization failed. To access the imported module on a
1317successful load, use \cfunction{PyImport_ImportModule()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00001318(Note the misnomer --- this function would reload the module if it was
Guido van Rossum42cefd01997-10-05 15:27:29 +00001319already imported.)
1320\end{cfuncdesc}
1321
Fred Drake659ebfa2000-04-03 15:42:13 +00001322\begin{ctypedesc}[_frozen]{struct _frozen}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001323This is the structure type definition for frozen module descriptors,
Fred Drakec6fa34e1998-04-02 06:47:24 +00001324as generated by the \program{freeze}\index{freeze utility} utility
1325(see \file{Tools/freeze/} in the Python source distribution). Its
Fred Drakee0d9a832000-09-01 05:30:00 +00001326definition, found in \file{Include/import.h}, is:
Fred Drakec6fa34e1998-04-02 06:47:24 +00001327
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001328\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001329struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001330 char *name;
1331 unsigned char *code;
1332 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001333};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001334\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001335\end{ctypedesc}
1336
Fred Drakec6fa34e1998-04-02 06:47:24 +00001337\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
Fred Drakef8830d11998-04-23 14:06:01 +00001338This pointer is initialized to point to an array of \ctype{struct
Fred Drake659ebfa2000-04-03 15:42:13 +00001339_frozen} records, terminated by one whose members are all
1340\NULL{} or zero. When a frozen module is imported, it is searched in
1341this table. Third-party code could play tricks with this to provide a
Guido van Rossum42cefd01997-10-05 15:27:29 +00001342dynamically created collection of frozen modules.
1343\end{cvardesc}
1344
Fred Drakee0d9a832000-09-01 05:30:00 +00001345\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
1346 void (*initfunc)(void)}
1347Add a single module to the existing table of built-in modules. This
1348is a convenience wrapper around \cfunction{PyImport_ExtendInittab()},
1349returning \code{-1} if the table could not be extended. The new
1350module can be imported by the name \var{name}, and uses the function
1351\var{initfunc} as the initialization function called on the first
1352attempted import. This should be called before
1353\cfunction{Py_Initialize()}.
1354\end{cfuncdesc}
1355
1356\begin{ctypedesc}[_inittab]{struct _inittab}
1357Structure describing a single entry in the list of built-in modules.
1358Each of these structures gives the name and initialization function
1359for a module built into the interpreter. Programs which embed Python
1360may use an array of these structures in conjunction with
1361\cfunction{PyImport_ExtendInittab()} to provide additional built-in
1362modules. The structure is defined in \file{Include/import.h} as:
1363
1364\begin{verbatim}
1365struct _inittab {
1366 char *name;
1367 void (*initfunc)(void);
1368};
1369\end{verbatim}
1370\end{ctypedesc}
1371
1372\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
1373Add a collection of modules to the table of built-in modules. The
1374\var{newtab} array must end with a sentinel entry which contains
1375\NULL{} for the \member{name} field; failure to provide the sentinel
1376value can result in a memory fault. Returns \code{0} on success or
1377\code{-1} if insufficient memory could be allocated to extend the
1378internal table. In the event of failure, no modules are added to the
1379internal table. This should be called before
1380\cfunction{Py_Initialize()}.
1381\end{cfuncdesc}
1382
Guido van Rossum42cefd01997-10-05 15:27:29 +00001383
Fred Drakeefd146c1999-02-15 15:30:45 +00001384\chapter{Abstract Objects Layer \label{abstract}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001385
1386The functions in this chapter interact with Python objects regardless
1387of their type, or with wide classes of object types (e.g. all
1388numerical types, or all sequence types). When used on object types
Fred Drake659ebfa2000-04-03 15:42:13 +00001389for which they do not apply, they will raise a Python exception.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001390
Fred Drakeefd146c1999-02-15 15:30:45 +00001391\section{Object Protocol \label{object}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001392
1393\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00001394Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error.
1395The flags argument is used to enable certain printing options. The
1396only option currently supported is \constant{Py_PRINT_RAW}; if given,
1397the \function{str()} of the object is written instead of the
1398\function{repr()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001399\end{cfuncdesc}
1400
1401\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001402Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1403\code{0} otherwise. This is equivalent to the Python expression
1404\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001405This function always succeeds.
1406\end{cfuncdesc}
1407
Fred Drake659ebfa2000-04-03 15:42:13 +00001408\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
1409 char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001410Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001411Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001412This is the equivalent of the Python expression
1413\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001414\end{cfuncdesc}
1415
1416
1417\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001418Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1419\code{0} otherwise. This is equivalent to the Python expression
1420\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001421This function always succeeds.
1422\end{cfuncdesc}
1423
1424
Fred Drake659ebfa2000-04-03 15:42:13 +00001425\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
1426 PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001427Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001428Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001429This is the equivalent of the Python expression
1430\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001431\end{cfuncdesc}
1432
1433
1434\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001435Set the value of the attribute named \var{attr_name}, for object
1436\var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1437the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1438\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001439\end{cfuncdesc}
1440
1441
1442\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001443Set the value of the attribute named \var{attr_name}, for
1444object \var{o},
1445to the value \var{v}. Returns \code{-1} on failure. This is
1446the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1447\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001448\end{cfuncdesc}
1449
1450
1451\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001452Delete attribute named \var{attr_name}, for object \var{o}. Returns
1453\code{-1} on failure. This is the equivalent of the Python
1454statement: \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001455\end{cfuncdesc}
1456
1457
1458\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001459Delete attribute named \var{attr_name}, for object \var{o}. Returns
1460\code{-1} on failure. This is the equivalent of the Python
1461statement \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001462\end{cfuncdesc}
1463
1464
1465\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
Fred Drakee058b4f1998-02-16 06:15:35 +00001466Compare the values of \var{o1} and \var{o2} using a routine provided
1467by \var{o1}, if one exists, otherwise with a routine provided by
1468\var{o2}. The result of the comparison is returned in \var{result}.
1469Returns \code{-1} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001470statement\bifuncindex{cmp} \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001471\end{cfuncdesc}
1472
1473
1474\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001475Compare the values of \var{o1} and \var{o2} using a routine provided
1476by \var{o1}, if one exists, otherwise with a routine provided by
1477\var{o2}. Returns the result of the comparison on success. On error,
1478the value returned is undefined; use \cfunction{PyErr_Occurred()} to
Fred Drake659ebfa2000-04-03 15:42:13 +00001479detect an error. This is equivalent to the Python
1480expression\bifuncindex{cmp} \samp{cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001481\end{cfuncdesc}
1482
1483
1484\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001485Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001486string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001487the equivalent of the Python expression \samp{repr(\var{o})}.
1488Called by the \function{repr()}\bifuncindex{repr} built-in function
1489and by reverse quotes.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001490\end{cfuncdesc}
1491
1492
1493\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001494Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001495string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001496the equivalent of the Python expression \samp{str(\var{o})}.
1497Called by the \function{str()}\bifuncindex{str} built-in function and
1498by the \keyword{print} statement.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001499\end{cfuncdesc}
1500
1501
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001502\begin{cfuncdesc}{PyObject*}{PyObject_Unicode}{PyObject *o}
1503Compute a Unicode string representation of object \var{o}. Returns the
1504Unicode string representation on success, \NULL{} on failure. This is
1505the equivalent of the Python expression \samp{unistr(\var{o})}.
1506Called by the \function{unistr()}\bifuncindex{unistr} built-in function.
1507\end{cfuncdesc}
1508
Fred Drake58c8f9f2001-03-28 21:14:32 +00001509\begin{cfuncdesc}{int}{PyObject_IsInstance}{PyObject *inst, PyObject *cls}
1510Return \code{1} if \var{inst} is an instance of the class \var{cls} or
1511a subclass of \var{cls}. If \var{cls} is a type object rather than a
1512class object, \cfunction{PyObject_IsInstance()} returns \code{1} if
1513\var{inst} is of type \var{cls}. If \var{inst} is not a class
1514instance and \var{cls} is neither a type object or class object,
1515\var{inst} must have a \member{__class__} attribute --- the class
1516relationship of the value of that attribute with \var{cls} will be
1517used to determine the result of this function.
1518\versionadded{2.1}
1519\end{cfuncdesc}
1520
1521Subclass determination is done in a fairly straightforward way, but
1522includes a wrinkle that implementors of extensions to the class system
1523may want to be aware of. If \class{A} and \class{B} are class
1524objects, \class{B} is a subclass of \class{A} if it inherits from
1525\class{A} either directly or indirectly. If either is not a class
1526object, a more general mechanism is used to determine the class
1527relationship of the two objects. When testing if \var{B} is a
1528subclass of \var{A}, if \var{A} is \var{B},
1529\cfunction{PyObject_IsSubclass()} returns true. If \var{A} and
1530\var{B} are different objects, \var{B}'s \member{__bases__} attribute
1531is searched in a depth-first fashion for \var{A} --- the presence of
1532the \member{__bases__} attribute is considered sufficient for this
1533determination.
1534
1535\begin{cfuncdesc}{int}{PyObject_IsSubclass}{PyObject *derived,
1536 PyObject *cls}
1537Returns \code{1} if the class \var{derived} is identical to or derived
1538from the class \var{cls}, otherwise returns \code{0}. In case of an
1539error, returns \code{-1}. If either \var{derived} or \var{cls} is not
1540an actual class object, this function uses the generic algorithm
1541described above.
1542\versionadded{2.1}
1543\end{cfuncdesc}
1544
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00001545
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001546\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001547Determine if the object \var{o} is callable. Return \code{1} if the
Fred Drakee058b4f1998-02-16 06:15:35 +00001548object is callable and \code{0} otherwise.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001549This function always succeeds.
1550\end{cfuncdesc}
1551
1552
Fred Drake659ebfa2000-04-03 15:42:13 +00001553\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
1554 PyObject *args}
Fred Drakee058b4f1998-02-16 06:15:35 +00001555Call a callable Python object \var{callable_object}, with
1556arguments given by the tuple \var{args}. If no arguments are
Fred Drake659ebfa2000-04-03 15:42:13 +00001557needed, then \var{args} may be \NULL{}. Returns the result of the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001558call on success, or \NULL{} on failure. This is the equivalent
Fred Drake5566c1c2001-01-19 22:48:33 +00001559of the Python expression \samp{apply(\var{callable_object}, \var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001560\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001561\end{cfuncdesc}
1562
Fred Drake5566c1c2001-01-19 22:48:33 +00001563\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object,
1564 char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001565Call a callable Python object \var{callable_object}, with a
Fred Drake659ebfa2000-04-03 15:42:13 +00001566variable number of C arguments. The C arguments are described
Fred Drakee058b4f1998-02-16 06:15:35 +00001567using a \cfunction{Py_BuildValue()} style format string. The format may
1568be \NULL{}, indicating that no arguments are provided. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001569result of the call on success, or \NULL{} on failure. This is
Fred Drake5566c1c2001-01-19 22:48:33 +00001570the equivalent of the Python expression \samp{apply(\var{callable_object},
Fred Drake659ebfa2000-04-03 15:42:13 +00001571\var{args})}.\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001572\end{cfuncdesc}
1573
1574
Fred Drake5566c1c2001-01-19 22:48:33 +00001575\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o,
1576 char *method, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001577Call the method named \var{m} of object \var{o} with a variable number
Fred Drake659ebfa2000-04-03 15:42:13 +00001578of C arguments. The C arguments are described by a
Fred Drakee058b4f1998-02-16 06:15:35 +00001579\cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1580indicating that no arguments are provided. Returns the result of the
1581call on success, or \NULL{} on failure. This is the equivalent of the
1582Python expression \samp{\var{o}.\var{method}(\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001583Note that special method names, such as \method{__add__()},
1584\method{__getitem__()}, and so on are not supported. The specific
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001585abstract-object routines for these must be used.
1586\end{cfuncdesc}
1587
1588
1589\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001590Compute and return the hash value of an object \var{o}. On
1591failure, return \code{-1}. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001592expression \samp{hash(\var{o})}.\bifuncindex{hash}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001593\end{cfuncdesc}
1594
1595
1596\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001597Returns \code{1} if the object \var{o} is considered to be true, and
1598\code{0} otherwise. This is equivalent to the Python expression
1599\samp{not not \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001600This function always succeeds.
1601\end{cfuncdesc}
1602
1603
1604\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1605On success, returns a type object corresponding to the object
Fred Drakee058b4f1998-02-16 06:15:35 +00001606type of object \var{o}. On failure, returns \NULL{}. This is
1607equivalent to the Python expression \samp{type(\var{o})}.
Fred Drake53fb7721998-02-16 06:23:20 +00001608\bifuncindex{type}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001609\end{cfuncdesc}
1610
1611\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001612Return the length of object \var{o}. If the object \var{o} provides
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001613both sequence and mapping protocols, the sequence length is
Fred Drake659ebfa2000-04-03 15:42:13 +00001614returned. On error, \code{-1} is returned. This is the equivalent
1615to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001616\end{cfuncdesc}
1617
1618
1619\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001620Return element of \var{o} corresponding to the object \var{key} or
1621\NULL{} on failure. This is the equivalent of the Python expression
1622\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001623\end{cfuncdesc}
1624
1625
1626\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001627Map the object \var{key} to the value \var{v}.
1628Returns \code{-1} on failure. This is the equivalent
1629of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001630\end{cfuncdesc}
1631
1632
Guido van Rossumd1dbf631999-01-22 20:10:49 +00001633\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001634Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1635failure. This is the equivalent of the Python statement \samp{del
1636\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001637\end{cfuncdesc}
1638
Andrew M. Kuchling8c46b302000-07-13 23:58:16 +00001639\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
1640Derives a file-descriptor from a Python object. If the object
1641is an integer or long integer, its value is returned. If not, the
1642object's \method{fileno()} method is called if it exists; the method
1643must return an integer or long integer, which is returned as the file
1644descriptor value. Returns \code{-1} on failure.
1645\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001646
Fred Drakeefd146c1999-02-15 15:30:45 +00001647\section{Number Protocol \label{number}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001648
1649\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001650Returns \code{1} if the object \var{o} provides numeric protocols, and
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001651false otherwise.
1652This function always succeeds.
1653\end{cfuncdesc}
1654
1655
1656\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001657Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1658failure. This is the equivalent of the Python expression
1659\samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001660\end{cfuncdesc}
1661
1662
1663\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
Fred Drake659ebfa2000-04-03 15:42:13 +00001664Returns the result of subtracting \var{o2} from \var{o1}, or
1665\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001666\samp{\var{o1} - \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001667\end{cfuncdesc}
1668
1669
1670\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001671Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1672failure. This is the equivalent of the Python expression
1673\samp{\var{o1} * \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001674\end{cfuncdesc}
1675
1676
1677\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001678Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1679failure.
1680This is the equivalent of the Python expression \samp{\var{o1} /
1681\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001682\end{cfuncdesc}
1683
1684
1685\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001686Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1687failure. This is the equivalent of the Python expression
Fred Drake659ebfa2000-04-03 15:42:13 +00001688\samp{\var{o1} \%\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001689\end{cfuncdesc}
1690
1691
1692\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
Fred Drake53fb7721998-02-16 06:23:20 +00001693See the built-in function \function{divmod()}\bifuncindex{divmod}.
1694Returns \NULL{} on failure. This is the equivalent of the Python
1695expression \samp{divmod(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001696\end{cfuncdesc}
1697
1698
1699\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
Fred Drake53fb7721998-02-16 06:23:20 +00001700See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1701\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001702\samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
Fred Drake659ebfa2000-04-03 15:42:13 +00001703If \var{o3} is to be ignored, pass \cdata{Py_None} in its place
1704(passing \NULL{} for \var{o3} would cause an illegal memory access).
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001705\end{cfuncdesc}
1706
1707
1708\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001709Returns the negation of \var{o} on success, or \NULL{} on failure.
1710This is the equivalent of the Python expression \samp{-\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001711\end{cfuncdesc}
1712
1713
1714\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001715Returns \var{o} on success, or \NULL{} on failure.
1716This is the equivalent of the Python expression \samp{+\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001717\end{cfuncdesc}
1718
1719
1720\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001721Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1722the equivalent of the Python expression \samp{abs(\var{o})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001723\bifuncindex{abs}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001724\end{cfuncdesc}
1725
1726
1727\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001728Returns the bitwise negation of \var{o} on success, or \NULL{} on
1729failure. This is the equivalent of the Python expression
1730\samp{\~\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001731\end{cfuncdesc}
1732
1733
1734\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001735Returns the result of left shifting \var{o1} by \var{o2} on success,
1736or \NULL{} on failure. This is the equivalent of the Python
Fred Draked20d8b32001-04-13 14:52:39 +00001737expression \samp{\var{o1} <\code{<} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001738\end{cfuncdesc}
1739
1740
1741\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001742Returns the result of right shifting \var{o1} by \var{o2} on success,
1743or \NULL{} on failure. This is the equivalent of the Python
Fred Draked20d8b32001-04-13 14:52:39 +00001744expression \samp{\var{o1} >\code{>} \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001745\end{cfuncdesc}
1746
1747
1748\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001749Returns the ``bitwise and'' of \var{o2} and \var{o2} on success and
1750\NULL{} on failure. This is the equivalent of the Python expression
Fred Drake5566c1c2001-01-19 22:48:33 +00001751\samp{\var{o1} \&\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001752\end{cfuncdesc}
1753
1754
1755\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001756Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success,
Fred Drakee058b4f1998-02-16 06:15:35 +00001757or \NULL{} on failure. This is the equivalent of the Python
1758expression \samp{\var{o1} \^{ }\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001759\end{cfuncdesc}
1760
1761\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001762Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
1763\NULL{} on failure. This is the equivalent of the Python expression
1764\samp{\var{o1} | \var{o2}}.
1765\end{cfuncdesc}
1766
1767
1768\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAdd}{PyObject *o1, PyObject *o2}
1769Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on failure.
1770The operation is done \emph{in-place} when \var{o1} supports it. This is the
1771equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1772\end{cfuncdesc}
1773
1774
1775\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceSubtract}{PyObject *o1, PyObject *o2}
1776Returns the result of subtracting \var{o2} from \var{o1}, or
1777\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1778supports it. This is the equivalent of the Python expression \samp{\var{o1}
1779-= \var{o2}}.
1780\end{cfuncdesc}
1781
1782
1783\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceMultiply}{PyObject *o1, PyObject *o2}
1784Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1785failure. The operation is done \emph{in-place} when \var{o1} supports it.
1786This is the equivalent of the Python expression \samp{\var{o1} *= \var{o2}}.
1787\end{cfuncdesc}
1788
1789
1790\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceDivide}{PyObject *o1, PyObject *o2}
1791Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on failure.
1792The operation is done \emph{in-place} when \var{o1} supports it. This is the
1793equivalent of the Python expression \samp{\var{o1} /= \var{o2}}.
1794\end{cfuncdesc}
1795
1796
1797\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRemainder}{PyObject *o1, PyObject *o2}
1798Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1799failure. The operation is done \emph{in-place} when \var{o1} supports it.
1800This is the equivalent of the Python expression \samp{\var{o1} \%= \var{o2}}.
1801\end{cfuncdesc}
1802
1803
1804\begin{cfuncdesc}{PyObject*}{PyNumber_InPlacePower}{PyObject *o1, PyObject *o2, PyObject *o3}
1805See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1806\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1807supports it. This is the equivalent of the Python expression \samp{\var{o1}
1808**= \var{o2}} when o3 is \cdata{Py_None}, or an in-place variant of
Fred Drake5566c1c2001-01-19 22:48:33 +00001809\samp{pow(\var{o1}, \var{o2}, \var{o3})} otherwise. If \var{o3} is to be
Fred Drake7740a012000-09-12 20:27:05 +00001810ignored, pass \cdata{Py_None} in its place (passing \NULL{} for \var{o3}
1811would cause an illegal memory access).
1812\end{cfuncdesc}
1813
1814\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceLshift}{PyObject *o1, PyObject *o2}
1815Returns the result of left shifting \var{o1} by \var{o2} on success, or
1816\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1817supports it. This is the equivalent of the Python expression \samp{\var{o1}
Fred Draked20d8b32001-04-13 14:52:39 +00001818<\code{<=} \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001819\end{cfuncdesc}
1820
1821
1822\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRshift}{PyObject *o1, PyObject *o2}
1823Returns the result of right shifting \var{o1} by \var{o2} on success, or
1824\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1825supports it. This is the equivalent of the Python expression \samp{\var{o1}
Fred Draked20d8b32001-04-13 14:52:39 +00001826>\code{>=} \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001827\end{cfuncdesc}
1828
1829
1830\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAnd}{PyObject *o1, PyObject *o2}
Fred Drake5566c1c2001-01-19 22:48:33 +00001831Returns the ``bitwise and'' of \var{o1} and \var{o2} on success
1832and \NULL{} on failure. The operation is done \emph{in-place} when
1833\var{o1} supports it. This is the equivalent of the Python expression
1834\samp{\var{o1} \&= \var{o2}}.
Fred Drake7740a012000-09-12 20:27:05 +00001835\end{cfuncdesc}
1836
1837
1838\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceXor}{PyObject *o1, PyObject *o2}
1839Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success, or
1840\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1841supports it. This is the equivalent of the Python expression \samp{\var{o1}
1842\^= \var{o2}}.
1843\end{cfuncdesc}
1844
1845\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2}
1846Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or \NULL{}
1847on failure. The operation is done \emph{in-place} when \var{o1} supports
1848it. This is the equivalent of the Python expression \samp{\var{o1} |=
1849\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001850\end{cfuncdesc}
1851
Fred Drakec0e6c5b2000-09-22 18:17:49 +00001852\begin{cfuncdesc}{int}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001853This function takes the addresses of two variables of type
Fred Drake659ebfa2000-04-03 15:42:13 +00001854\ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} and
1855\code{*\var{p2}} have the same type, increment their reference count
1856and return \code{0} (success). If the objects can be converted to a
1857common numeric type, replace \code{*p1} and \code{*p2} by their
1858converted value (with 'new' reference counts), and return \code{0}.
1859If no conversion is possible, or if some other error occurs, return
1860\code{-1} (failure) and don't increment the reference counts. The
1861call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1862statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
1863\bifuncindex{coerce}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001864\end{cfuncdesc}
1865
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001866\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001867Returns the \var{o} converted to an integer object on success, or
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001868\NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001869expression \samp{int(\var{o})}.\bifuncindex{int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001870\end{cfuncdesc}
1871
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001872\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001873Returns the \var{o} converted to a long integer object on success,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001874or \NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001875expression \samp{long(\var{o})}.\bifuncindex{long}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001876\end{cfuncdesc}
1877
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001878\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001879Returns the \var{o} converted to a float object on success, or
1880\NULL{} on failure. This is the equivalent of the Python expression
1881\samp{float(\var{o})}.\bifuncindex{float}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001882\end{cfuncdesc}
1883
1884
Fred Drakeefd146c1999-02-15 15:30:45 +00001885\section{Sequence Protocol \label{sequence}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001886
1887\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001888Return \code{1} if the object provides sequence protocol, and
1889\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001890\end{cfuncdesc}
1891
Fred Drakec6a3cb42001-04-04 01:25:17 +00001892\begin{cfuncdesc}{int}{PySequence_Size}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001893Returns the number of objects in sequence \var{o} on success, and
1894\code{-1} on failure. For objects that do not provide sequence
1895protocol, this is equivalent to the Python expression
1896\samp{len(\var{o})}.\bifuncindex{len}
1897\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001898
Fred Drakec6a3cb42001-04-04 01:25:17 +00001899\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
1900Alternate name for \cfunction{PySequence_Size()}.
1901\end{cfuncdesc}
1902
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001903\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001904Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001905failure. This is the equivalent of the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001906expression \samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001907\end{cfuncdesc}
1908
1909
1910\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Fred Drake659ebfa2000-04-03 15:42:13 +00001911Return the result of repeating sequence object
1912\var{o} \var{count} times, or \NULL{} on failure. This is the
1913equivalent of the Python expression \samp{\var{o} * \var{count}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001914\end{cfuncdesc}
1915
Fred Drake7740a012000-09-12 20:27:05 +00001916\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceConcat}{PyObject *o1, PyObject *o2}
1917Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
1918failure. The operation is done \emph{in-place} when \var{o1} supports it.
1919This is the equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1920\end{cfuncdesc}
1921
1922
1923\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceRepeat}{PyObject *o, int count}
1924Return the result of repeating sequence object \var{o} \var{count} times, or
1925\NULL{} on failure. The operation is done \emph{in-place} when \var{o}
1926supports it. This is the equivalent of the Python expression \samp{\var{o}
1927*= \var{count}}.
1928\end{cfuncdesc}
1929
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001930
1931\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001932Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
1933is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001934\end{cfuncdesc}
1935
1936
1937\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001938Return the slice of sequence object \var{o} between \var{i1} and
1939\var{i2}, or \NULL{} on failure. This is the equivalent of the Python
1940expression \samp{\var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001941\end{cfuncdesc}
1942
1943
1944\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001945Assign object \var{v} to the \var{i}th element of \var{o}.
1946Returns \code{-1} on failure. This is the equivalent of the Python
1947statement \samp{\var{o}[\var{i}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001948\end{cfuncdesc}
1949
1950\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
Fred Drake5566c1c2001-01-19 22:48:33 +00001951Delete the \var{i}th element of object \var{o}. Returns
Fred Drakee058b4f1998-02-16 06:15:35 +00001952\code{-1} on failure. This is the equivalent of the Python
1953statement \samp{del \var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001954\end{cfuncdesc}
1955
Fred Drake659ebfa2000-04-03 15:42:13 +00001956\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
1957 int i2, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001958Assign the sequence object \var{v} to the slice in sequence
1959object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
1960the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001961\end{cfuncdesc}
1962
1963\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001964Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
1965Returns \code{-1} on failure. This is the equivalent of the Python
1966statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001967\end{cfuncdesc}
1968
1969\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001970Returns the \var{o} as a tuple on success, and \NULL{} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00001971This is equivalent to the Python expression \samp{tuple(\var{o})}.
1972\bifuncindex{tuple}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001973\end{cfuncdesc}
1974
1975\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001976Return the number of occurrences of \var{value} in \var{o}, that is,
1977return the number of keys for which \code{\var{o}[\var{key}] ==
1978\var{value}}. On failure, return \code{-1}. This is equivalent to
1979the Python expression \samp{\var{o}.count(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001980\end{cfuncdesc}
1981
Fred Drake659ebfa2000-04-03 15:42:13 +00001982\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001983Determine if \var{o} contains \var{value}. If an item in \var{o} is
1984equal to \var{value}, return \code{1}, otherwise return \code{0}. On
1985error, return \code{-1}. This is equivalent to the Python expression
1986\samp{\var{value} in \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001987\end{cfuncdesc}
1988
1989\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001990Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
1991\var{value}}. On error, return \code{-1}. This is equivalent to
1992the Python expression \samp{\var{o}.index(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001993\end{cfuncdesc}
1994
Fred Drakea8455ab2000-06-16 19:58:42 +00001995\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
1996Return a list object with the same contents as the arbitrary sequence
1997\var{o}. The returned list is guaranteed to be new.
1998\end{cfuncdesc}
1999
2000\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
2001Return a tuple object with the same contents as the arbitrary sequence
2002\var{o}. If \var{o} is a tuple, a new reference will be returned,
2003otherwise a tuple will be constructed with the appropriate contents.
2004\end{cfuncdesc}
2005
Fred Drakef39ed671998-02-26 22:01:23 +00002006
Fred Drake81cccb72000-09-12 15:22:05 +00002007\begin{cfuncdesc}{PyObject*}{PySequence_Fast}{PyObject *o, const char *m}
2008Returns the sequence \var{o} as a tuple, unless it is already a
2009tuple or list, in which case \var{o} is returned. Use
2010\cfunction{PySequence_Fast_GET_ITEM()} to access the members of the
2011result. Returns \NULL{} on failure. If the object is not a sequence,
2012raises \exception{TypeError} with \var{m} as the message text.
2013\end{cfuncdesc}
2014
2015\begin{cfuncdesc}{PyObject*}{PySequence_Fast_GET_ITEM}{PyObject *o, int i}
2016Return the \var{i}th element of \var{o}, assuming that \var{o} was
2017returned by \cfunction{PySequence_Fast()}, and that \var{i} is within
2018bounds. The caller is expected to get the length of the sequence by
Fred Drake96a2a802001-05-29 18:51:41 +00002019calling \cfunction{PySequence_Size()} on \var{o}, since lists and tuples
Fred Drake81cccb72000-09-12 15:22:05 +00002020are guaranteed to always return their true length.
2021\end{cfuncdesc}
2022
2023
Fred Drakeefd146c1999-02-15 15:30:45 +00002024\section{Mapping Protocol \label{mapping}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002025
2026\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002027Return \code{1} if the object provides mapping protocol, and
2028\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002029\end{cfuncdesc}
2030
2031
2032\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00002033Returns the number of keys in object \var{o} on success, and
2034\code{-1} on failure. For objects that do not provide mapping
2035protocol, this is equivalent to the Python expression
2036\samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002037\end{cfuncdesc}
2038
2039
2040\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002041Remove the mapping for object \var{key} from the object \var{o}.
2042Return \code{-1} on failure. This is equivalent to
2043the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002044\end{cfuncdesc}
2045
2046
2047\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002048Remove the mapping for object \var{key} from the object \var{o}.
2049Return \code{-1} on failure. This is equivalent to
2050the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002051\end{cfuncdesc}
2052
2053
2054\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
Fred Drake659ebfa2000-04-03 15:42:13 +00002055On success, return \code{1} if the mapping object has the key
2056\var{key} and \code{0} otherwise. This is equivalent to the Python
2057expression \samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002058This function always succeeds.
2059\end{cfuncdesc}
2060
2061
2062\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002063Return \code{1} if the mapping object has the key \var{key} and
2064\code{0} otherwise. This is equivalent to the Python expression
2065\samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002066This function always succeeds.
2067\end{cfuncdesc}
2068
2069
2070\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002071On success, return a list of the keys in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002072failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002073expression \samp{\var{o}.keys()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002074\end{cfuncdesc}
2075
2076
2077\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002078On success, return a list of the values in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002079failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002080expression \samp{\var{o}.values()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002081\end{cfuncdesc}
2082
2083
2084\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002085On success, return a list of the items in object \var{o}, where
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002086each item is a tuple containing a key-value pair. On
2087failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00002088expression \samp{\var{o}.items()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002089\end{cfuncdesc}
2090
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002091
2092\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002093Return element of \var{o} corresponding to the object \var{key} or
2094\NULL{} on failure. This is the equivalent of the Python expression
2095\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002096\end{cfuncdesc}
2097
Fred Drakedbcaeda2001-05-07 17:42:18 +00002098\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key,
2099 PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00002100Map the object \var{key} to the value \var{v} in object \var{o}.
2101Returns \code{-1} on failure. This is the equivalent of the Python
2102statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002103\end{cfuncdesc}
2104
2105
Fred Drakedbcaeda2001-05-07 17:42:18 +00002106\section{Iterator Protocol \label{iterator}}
2107
Fred Drakea8e08272001-05-07 17:47:07 +00002108\versionadded{2.2}
2109
Fred Drakedbcaeda2001-05-07 17:42:18 +00002110There are only a couple of functions specifically for working with
2111iterators.
2112
2113\begin{cfuncdesc}{int}{PyIter_Check}{PyObject *o}
2114 Return true if the object \var{o} supports the iterator protocol.
2115\end{cfuncdesc}
2116
2117\begin{cfuncdesc}{PyObject*}{PyIter_Next}{PyObject *o}
2118 Return the next value from the iteration \var{o}. If the object is
2119 an iterator, this retrieves the next value from the iteration, and
2120 returns \NULL{} with no exception set if there are no remaining
2121 items. If the object is not an iterator, \exception{TypeError} is
2122 raised, or if there is an error in retrieving the item, returns
2123 \NULL{} and passes along the exception.
2124\end{cfuncdesc}
2125
2126To write a loop which iterates over an iterator, the C code should
2127look something like this:
2128
2129\begin{verbatim}
2130PyObject *iterator = ...;
2131PyObject *item;
2132
2133while (item = PyIter_Next(iter)) {
2134 /* do something with item */
2135}
2136if (PyErr_Occurred()) {
2137 /* propogate error */
2138}
2139else {
2140 /* continue doing useful work */
2141}
2142\end{verbatim}
2143
2144
Fred Drakeefd146c1999-02-15 15:30:45 +00002145\chapter{Concrete Objects Layer \label{concrete}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002146
2147The functions in this chapter are specific to certain Python object
2148types. Passing them an object of the wrong type is not a good idea;
2149if you receive an object from a Python program and you are not sure
2150that it has the right type, you must perform a type check first;
Fred Drake5566c1c2001-01-19 22:48:33 +00002151for example, to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00002152\cfunction{PyDict_Check()}. The chapter is structured like the
2153``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002154
Fred Drake89024422000-10-23 16:00:54 +00002155\strong{Warning:}
2156While the functions described in this chapter carefully check the type
2157of the objects which are passed in, many of them do not check for
2158\NULL{} being passed instead of a valid object. Allowing \NULL{} to
2159be passed in can cause memory access violations and immediate
2160termination of the interpreter.
2161
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002162
Fred Drakeefd146c1999-02-15 15:30:45 +00002163\section{Fundamental Objects \label{fundamental}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002164
Fred Drakee5bf8b21998-02-12 21:22:28 +00002165This section describes Python type objects and the singleton object
2166\code{None}.
2167
2168
Fred Drakeefd146c1999-02-15 15:30:45 +00002169\subsection{Type Objects \label{typeObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002170
Fred Drake659ebfa2000-04-03 15:42:13 +00002171\obindex{type}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002172\begin{ctypedesc}{PyTypeObject}
Fred Drake659ebfa2000-04-03 15:42:13 +00002173The C structure of the objects used to describe built-in types.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002174\end{ctypedesc}
2175
Fred Drake659ebfa2000-04-03 15:42:13 +00002176\begin{cvardesc}{PyObject*}{PyType_Type}
Fred Drakeefd146c1999-02-15 15:30:45 +00002177This is the type object for type objects; it is the same object as
2178\code{types.TypeType} in the Python layer.
Fred Drake659ebfa2000-04-03 15:42:13 +00002179\withsubitem{(in module types)}{\ttindex{TypeType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002180\end{cvardesc}
2181
Fred Drake659ebfa2000-04-03 15:42:13 +00002182\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
2183Returns true is the object \var{o} is a type object.
2184\end{cfuncdesc}
2185
2186\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
2187Returns true if the type object \var{o} sets the feature
Fred Drakef0e08ef2001-02-03 01:11:26 +00002188\var{feature}. Type features are denoted by single bit flags.
Fred Drake659ebfa2000-04-03 15:42:13 +00002189\end{cfuncdesc}
2190
Fred Drakee5bf8b21998-02-12 21:22:28 +00002191
Fred Drakeefd146c1999-02-15 15:30:45 +00002192\subsection{The None Object \label{noneObject}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002193
Fred Drake659ebfa2000-04-03 15:42:13 +00002194\obindex{None@\texttt{None}}
2195Note that the \ctype{PyTypeObject} for \code{None} is not directly
2196exposed in the Python/C API. Since \code{None} is a singleton,
2197testing for object identity (using \samp{==} in C) is sufficient.
2198There is no \cfunction{PyNone_Check()} function for the same reason.
2199
2200\begin{cvardesc}{PyObject*}{Py_None}
Guido van Rossum44475131998-04-21 15:30:01 +00002201The Python \code{None} object, denoting lack of value. This object has
2202no methods.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002203\end{cvardesc}
2204
2205
Fred Drakeefd146c1999-02-15 15:30:45 +00002206\section{Sequence Objects \label{sequenceObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002207
Fred Drake659ebfa2000-04-03 15:42:13 +00002208\obindex{sequence}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002209Generic operations on sequence objects were discussed in the previous
2210chapter; this section deals with the specific kinds of sequence
2211objects that are intrinsic to the Python language.
2212
2213
Fred Drakeefd146c1999-02-15 15:30:45 +00002214\subsection{String Objects \label{stringObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002215
Fred Drake89024422000-10-23 16:00:54 +00002216These functions raise \exception{TypeError} when expecting a string
2217parameter and are called with a non-string parameter.
2218
Fred Drake659ebfa2000-04-03 15:42:13 +00002219\obindex{string}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002220\begin{ctypedesc}{PyStringObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002221This subtype of \ctype{PyObject} represents a Python string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002222\end{ctypedesc}
2223
2224\begin{cvardesc}{PyTypeObject}{PyString_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002225This instance of \ctype{PyTypeObject} represents the Python string
2226type; it is the same object as \code{types.TypeType} in the Python
2227layer.\withsubitem{(in module types)}{\ttindex{StringType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002228\end{cvardesc}
2229
2230\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002231Returns true if the object \var{o} is a string object.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002232\end{cfuncdesc}
2233
Fred Drakec6fa34e1998-04-02 06:47:24 +00002234\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002235Returns a new string object with the value \var{v} on success, and
2236\NULL{} on failure.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002237\end{cfuncdesc}
2238
Fred Drake659ebfa2000-04-03 15:42:13 +00002239\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
2240 int len}
2241Returns a new string object with the value \var{v} and length
2242\var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
2243the contents of the string are uninitialized.
2244\end{cfuncdesc}
2245
Fred Drakec6fa34e1998-04-02 06:47:24 +00002246\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002247Returns the length of the string in string object \var{string}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002248\end{cfuncdesc}
2249
Fred Drake659ebfa2000-04-03 15:42:13 +00002250\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
Fred Drake5d644212000-10-07 12:31:50 +00002251Macro form of \cfunction{PyString_Size()} but without error
Fred Drake659ebfa2000-04-03 15:42:13 +00002252checking.
2253\end{cfuncdesc}
2254
Fred Drakec6fa34e1998-04-02 06:47:24 +00002255\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
Fred Drake659ebfa2000-04-03 15:42:13 +00002256Returns a null-terminated representation of the contents of
2257\var{string}. The pointer refers to the internal buffer of
Fred Drake89024422000-10-23 16:00:54 +00002258\var{string}, not a copy. The data must not be modified in any way,
2259unless the string was just created using
2260\code{PyString_FromStringAndSize(NULL, \var{size})}.
2261It must not be deallocated.
Fred Drake659ebfa2000-04-03 15:42:13 +00002262\end{cfuncdesc}
2263
2264\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
2265Macro form of \cfunction{PyString_AsString()} but without error
2266checking.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002267\end{cfuncdesc}
2268
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002269\begin{cfuncdesc}{int}{PyString_AsStringAndSize}{PyObject *obj,
2270 char **buffer,
2271 int *length}
2272Returns a null-terminated representation of the contents of the object
2273\var{obj} through the output variables \var{buffer} and \var{length}.
2274
2275The function accepts both string and Unicode objects as input. For
2276Unicode objects it returns the default encoded version of the object.
2277If \var{length} is set to \NULL{}, the resulting buffer may not contain
2278null characters; if it does, the function returns -1 and a
2279TypeError is raised.
2280
2281The buffer refers to an internal string buffer of \var{obj}, not a
Fred Drake89024422000-10-23 16:00:54 +00002282copy. The data must not be modified in any way, unless the string was
2283just created using \code{PyString_FromStringAndSize(NULL,
2284\var{size})}. It must not be deallocated.
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002285\end{cfuncdesc}
2286
Fred Drakec6fa34e1998-04-02 06:47:24 +00002287\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
2288 PyObject *newpart}
Fred Drake66b989c1999-02-15 20:15:39 +00002289Creates a new string object in \var{*string} containing the
Fred Drakeddc6c272000-03-31 18:22:38 +00002290contents of \var{newpart} appended to \var{string}; the caller will
2291own the new reference. The reference to the old value of \var{string}
2292will be stolen. If the new string
Fred Drake66b989c1999-02-15 20:15:39 +00002293cannot be created, the old reference to \var{string} will still be
2294discarded and the value of \var{*string} will be set to
2295\NULL{}; the appropriate exception will be set.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002296\end{cfuncdesc}
2297
2298\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
2299 PyObject *newpart}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002300Creates a new string object in \var{*string} containing the contents
Guido van Rossum44475131998-04-21 15:30:01 +00002301of \var{newpart} appended to \var{string}. This version decrements
2302the reference count of \var{newpart}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002303\end{cfuncdesc}
2304
2305\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
Guido van Rossum44475131998-04-21 15:30:01 +00002306A way to resize a string object even though it is ``immutable''.
2307Only use this to build up a brand new string object; don't use this if
2308the string may already be known in other parts of the code.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002309\end{cfuncdesc}
2310
2311\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
2312 PyObject *args}
Guido van Rossum44475131998-04-21 15:30:01 +00002313Returns a new string object from \var{format} and \var{args}. Analogous
Fred Drake659ebfa2000-04-03 15:42:13 +00002314to \code{\var{format} \%\ \var{args}}. The \var{args} argument must be
Guido van Rossum44475131998-04-21 15:30:01 +00002315a tuple.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002316\end{cfuncdesc}
2317
2318\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
Guido van Rossum44475131998-04-21 15:30:01 +00002319Intern the argument \var{*string} in place. The argument must be the
2320address of a pointer variable pointing to a Python string object.
2321If there is an existing interned string that is the same as
2322\var{*string}, it sets \var{*string} to it (decrementing the reference
2323count of the old string object and incrementing the reference count of
2324the interned string object), otherwise it leaves \var{*string} alone
2325and interns it (incrementing its reference count). (Clarification:
2326even though there is a lot of talk about reference counts, think of
Fred Drakef8830d11998-04-23 14:06:01 +00002327this function as reference-count-neutral; you own the object after
2328the call if and only if you owned it before the call.)
Fred Drakec6fa34e1998-04-02 06:47:24 +00002329\end{cfuncdesc}
2330
2331\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
Fred Drakef8830d11998-04-23 14:06:01 +00002332A combination of \cfunction{PyString_FromString()} and
2333\cfunction{PyString_InternInPlace()}, returning either a new string object
Guido van Rossum44475131998-04-21 15:30:01 +00002334that has been interned, or a new (``owned'') reference to an earlier
2335interned string object with the same value.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002336\end{cfuncdesc}
2337
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002338\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
2339 int size,
2340 const char *encoding,
2341 const char *errors}
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002342Creates an object by decoding \var{size} bytes of the encoded
2343buffer \var{s} using the codec registered
2344for \var{encoding}. \var{encoding} and \var{errors} have the same meaning
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002345as the parameters of the same name in the unicode() builtin
2346function. The codec to be used is looked up using the Python codec
2347registry. Returns \NULL{} in case an exception was raised by the
2348codec.
2349\end{cfuncdesc}
2350
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002351\begin{cfuncdesc}{PyObject*}{PyString_AsDecodedObject}{PyObject *str,
2352 const char *encoding,
2353 const char *errors}
2354Decodes a string object by passing it to the codec registered
2355for \var{encoding} and returns the result as Python
2356object. \var{encoding} and \var{errors} have the same meaning as the
2357parameters of the same name in the string .encode() method. The codec
2358to be used is looked up using the Python codec registry. Returns
2359\NULL{} in case an exception was raised by the codec.
2360\end{cfuncdesc}
2361
2362\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const char *s,
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002363 int size,
2364 const char *encoding,
2365 const char *errors}
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002366Encodes the \ctype{char} buffer of the given size by passing it to
2367the codec registered for \var{encoding} and returns a Python object.
2368\var{encoding} and \var{errors} have the same
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002369meaning as the parameters of the same name in the string .encode()
2370method. The codec to be used is looked up using the Python codec
2371registry. Returns \NULL{} in case an exception was raised by the
2372codec.
2373\end{cfuncdesc}
2374
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002375\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedObject}{PyObject *str,
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002376 const char *encoding,
2377 const char *errors}
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002378Encodes a string object using the codec registered
2379for \var{encoding} and returns the result as Python
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002380object. \var{encoding} and \var{errors} have the same meaning as the
2381parameters of the same name in the string .encode() method. The codec
2382to be used is looked up using the Python codec registry. Returns
2383\NULL{} in case an exception was raised by the codec.
2384\end{cfuncdesc}
2385
Fred Drakee5bf8b21998-02-12 21:22:28 +00002386
Fred Drakea4cd2612000-04-06 14:10:29 +00002387\subsection{Unicode Objects \label{unicodeObjects}}
2388\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
2389
2390%--- Unicode Type -------------------------------------------------------
2391
2392These are the basic Unicode object types used for the Unicode
2393implementation in Python:
2394
2395\begin{ctypedesc}{Py_UNICODE}
2396This type represents a 16-bit unsigned storage type which is used by
2397Python internally as basis for holding Unicode ordinals. On platforms
2398where \ctype{wchar_t} is available and also has 16-bits,
2399\ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
2400native platform compatibility. On all other platforms,
2401\ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
2402\end{ctypedesc}
2403
2404\begin{ctypedesc}{PyUnicodeObject}
2405This subtype of \ctype{PyObject} represents a Python Unicode object.
2406\end{ctypedesc}
2407
2408\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
2409This instance of \ctype{PyTypeObject} represents the Python Unicode type.
2410\end{cvardesc}
2411
2412%--- These are really C macros... is there a macrodesc TeX macro ?
2413
2414The following APIs are really C macros and can be used to do fast
2415checks and to access internal read-only data of Unicode objects:
2416
2417\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
2418Returns true if the object \var{o} is a Unicode object.
2419\end{cfuncdesc}
2420
2421\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
2422Returns the size of the object. o has to be a
2423PyUnicodeObject (not checked).
2424\end{cfuncdesc}
2425
2426\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
2427Returns the size of the object's internal buffer in bytes. o has to be
2428a PyUnicodeObject (not checked).
2429\end{cfuncdesc}
2430
Fred Drake992fe5a2000-06-16 21:04:15 +00002431\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002432Returns a pointer to the internal Py_UNICODE buffer of the object. o
2433has to be a PyUnicodeObject (not checked).
2434\end{cfuncdesc}
2435
Fred Drake992fe5a2000-06-16 21:04:15 +00002436\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002437Returns a (const char *) pointer to the internal buffer of the object.
2438o has to be a PyUnicodeObject (not checked).
2439\end{cfuncdesc}
2440
2441% --- Unicode character properties ---------------------------------------
2442
2443Unicode provides many different character properties. The most often
2444needed ones are available through these macros which are mapped to C
2445functions depending on the Python configuration.
2446
2447\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
2448Returns 1/0 depending on whether \var{ch} is a whitespace character.
2449\end{cfuncdesc}
2450
2451\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
2452Returns 1/0 depending on whether \var{ch} is a lowercase character.
2453\end{cfuncdesc}
2454
2455\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
Fred Drakeae96aab2000-07-03 13:38:10 +00002456Returns 1/0 depending on whether \var{ch} is an uppercase character.
Fred Drakea4cd2612000-04-06 14:10:29 +00002457\end{cfuncdesc}
2458
2459\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
2460Returns 1/0 depending on whether \var{ch} is a titlecase character.
2461\end{cfuncdesc}
2462
2463\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
2464Returns 1/0 depending on whether \var{ch} is a linebreak character.
2465\end{cfuncdesc}
2466
2467\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
2468Returns 1/0 depending on whether \var{ch} is a decimal character.
2469\end{cfuncdesc}
2470
2471\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
2472Returns 1/0 depending on whether \var{ch} is a digit character.
2473\end{cfuncdesc}
2474
2475\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
2476Returns 1/0 depending on whether \var{ch} is a numeric character.
2477\end{cfuncdesc}
2478
Fred Drakeae96aab2000-07-03 13:38:10 +00002479\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
2480Returns 1/0 depending on whether \var{ch} is an alphabetic character.
2481\end{cfuncdesc}
2482
2483\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
2484Returns 1/0 depending on whether \var{ch} is an alphanumeric character.
2485\end{cfuncdesc}
2486
Fred Drakea4cd2612000-04-06 14:10:29 +00002487These APIs can be used for fast direct character conversions:
2488
2489\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
2490Returns the character \var{ch} converted to lower case.
2491\end{cfuncdesc}
2492
2493\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
2494Returns the character \var{ch} converted to upper case.
2495\end{cfuncdesc}
2496
2497\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
2498Returns the character \var{ch} converted to title case.
2499\end{cfuncdesc}
2500
2501\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
2502Returns the character \var{ch} converted to a decimal positive integer.
2503Returns -1 in case this is not possible. Does not raise exceptions.
2504\end{cfuncdesc}
2505
2506\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
2507Returns the character \var{ch} converted to a single digit integer.
2508Returns -1 in case this is not possible. Does not raise exceptions.
2509\end{cfuncdesc}
2510
2511\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
2512Returns the character \var{ch} converted to a (positive) double.
2513Returns -1.0 in case this is not possible. Does not raise exceptions.
2514\end{cfuncdesc}
2515
2516% --- Plain Py_UNICODE ---------------------------------------------------
2517
2518To create Unicode objects and access their basic sequence properties,
2519use these APIs:
2520
2521\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
2522 int size}
2523
2524Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
2525given size. \var{u} may be \NULL{} which causes the contents to be
2526undefined. It is the user's responsibility to fill in the needed data.
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002527The buffer is copied into the new object. If the buffer is not \NULL{},
2528the return value might be a shared object. Therefore, modification of
2529the resulting Unicode Object is only allowed when \var{u} is \NULL{}.
Fred Drakea4cd2612000-04-06 14:10:29 +00002530\end{cfuncdesc}
2531
Fred Drake1d158692000-06-18 05:21:21 +00002532\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002533Return a read-only pointer to the Unicode object's internal
2534\ctype{Py_UNICODE} buffer.
2535\end{cfuncdesc}
2536
2537\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
2538Return the length of the Unicode object.
2539\end{cfuncdesc}
2540
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002541\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
2542 const char *encoding,
2543 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002544
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002545Coerce an encoded object obj to an Unicode object and return a
2546reference with incremented refcount.
Fred Drakea4cd2612000-04-06 14:10:29 +00002547
2548Coercion is done in the following way:
2549\begin{enumerate}
2550\item Unicode objects are passed back as-is with incremented
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002551 refcount. Note: these cannot be decoded; passing a non-NULL
2552 value for encoding will result in a TypeError.
Fred Drakea4cd2612000-04-06 14:10:29 +00002553
2554\item String and other char buffer compatible objects are decoded
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002555 according to the given encoding and using the error handling
2556 defined by errors. Both can be NULL to have the interface use
2557 the default values (see the next section for details).
Fred Drakea4cd2612000-04-06 14:10:29 +00002558
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002559\item All other objects cause an exception.
Fred Drakea4cd2612000-04-06 14:10:29 +00002560\end{enumerate}
2561The API returns NULL in case of an error. The caller is responsible
2562for decref'ing the returned objects.
2563\end{cfuncdesc}
2564
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002565\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
2566
2567Shortcut for PyUnicode_FromEncodedObject(obj, NULL, ``strict'')
2568which is used throughout the interpreter whenever coercion to
2569Unicode is needed.
2570\end{cfuncdesc}
2571
Fred Drakea4cd2612000-04-06 14:10:29 +00002572% --- wchar_t support for platforms which support it ---------------------
2573
2574If the platform supports \ctype{wchar_t} and provides a header file
2575wchar.h, Python can interface directly to this type using the
2576following functions. Support is optimized if Python's own
2577\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
2578
2579\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
2580 int size}
2581Create a Unicode Object from the \ctype{whcar_t} buffer \var{w} of the
2582given size. Returns \NULL{} on failure.
2583\end{cfuncdesc}
2584
2585\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
2586 wchar_t *w,
2587 int size}
Fred Drakea4cd2612000-04-06 14:10:29 +00002588Copies the Unicode Object contents into the \ctype{whcar_t} buffer
2589\var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
2590Returns the number of \ctype{whcar_t} characters copied or -1 in case
2591of an error.
2592\end{cfuncdesc}
2593
2594
2595\subsubsection{Builtin Codecs \label{builtinCodecs}}
2596
2597Python provides a set of builtin codecs which are written in C
2598for speed. All of these codecs are directly usable via the
2599following functions.
2600
2601Many of the following APIs take two arguments encoding and
2602errors. These parameters encoding and errors have the same semantics
2603as the ones of the builtin unicode() Unicode object constructor.
2604
2605Setting encoding to NULL causes the default encoding to be used which
2606is UTF-8.
2607
2608Error handling is set by errors which may also be set to NULL meaning
2609to use the default handling defined for the codec. Default error
2610handling for all builtin codecs is ``strict'' (ValueErrors are raised).
2611
2612The codecs all use a similar interface. Only deviation from the
2613following generic ones are documented for simplicity.
2614
2615% --- Generic Codecs -----------------------------------------------------
2616
2617These are the generic codec APIs:
2618
2619\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
2620 int size,
2621 const char *encoding,
2622 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002623Create a Unicode object by decoding \var{size} bytes of the encoded
2624string \var{s}. \var{encoding} and \var{errors} have the same meaning
2625as the parameters of the same name in the unicode() builtin
2626function. The codec to be used is looked up using the Python codec
2627registry. Returns \NULL{} in case an exception was raised by the
2628codec.
2629\end{cfuncdesc}
2630
2631\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
2632 int size,
2633 const char *encoding,
2634 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002635Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2636Python string object. \var{encoding} and \var{errors} have the same
2637meaning as the parameters of the same name in the Unicode .encode()
2638method. The codec to be used is looked up using the Python codec
2639registry. Returns \NULL{} in case an exception was raised by the
2640codec.
2641\end{cfuncdesc}
2642
2643\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
2644 const char *encoding,
2645 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002646Encodes a Unicode object and returns the result as Python string
2647object. \var{encoding} and \var{errors} have the same meaning as the
2648parameters of the same name in the Unicode .encode() method. The codec
2649to be used is looked up using the Python codec registry. Returns
2650\NULL{} in case an exception was raised by the codec.
2651\end{cfuncdesc}
2652
2653% --- UTF-8 Codecs -------------------------------------------------------
2654
2655These are the UTF-8 codec APIs:
2656
2657\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
2658 int size,
2659 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002660Creates a Unicode object by decoding \var{size} bytes of the UTF-8
2661encoded string \var{s}. Returns \NULL{} in case an exception was
2662raised by the codec.
2663\end{cfuncdesc}
2664
2665\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
2666 int size,
2667 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002668Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
2669and returns a Python string object. Returns \NULL{} in case an
2670exception was raised by the codec.
2671\end{cfuncdesc}
2672
2673\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002674Encodes a Unicode objects using UTF-8 and returns the result as Python
2675string object. Error handling is ``strict''. Returns
2676\NULL{} in case an exception was raised by the codec.
2677\end{cfuncdesc}
2678
2679% --- UTF-16 Codecs ------------------------------------------------------ */
2680
2681These are the UTF-16 codec APIs:
2682
2683\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
2684 int size,
2685 const char *errors,
2686 int *byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002687Decodes \var{length} bytes from a UTF-16 encoded buffer string and
2688returns the corresponding Unicode object.
2689
2690\var{errors} (if non-NULL) defines the error handling. It defaults
2691to ``strict''.
2692
2693If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
2694the given byte order:
2695
2696\begin{verbatim}
2697 *byteorder == -1: little endian
2698 *byteorder == 0: native order
2699 *byteorder == 1: big endian
2700\end{verbatim}
2701
2702and then switches according to all byte order marks (BOM) it finds in
2703the input data. BOM marks are not copied into the resulting Unicode
2704string. After completion, \var{*byteorder} is set to the current byte
2705order at the end of input data.
2706
2707If \var{byteorder} is \NULL{}, the codec starts in native order mode.
2708
2709Returns \NULL{} in case an exception was raised by the codec.
2710\end{cfuncdesc}
2711
2712\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
2713 int size,
2714 const char *errors,
2715 int byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002716Returns a Python string object holding the UTF-16 encoded value of the
2717Unicode data in \var{s}.
2718
Fred Drakea8455ab2000-06-16 19:58:42 +00002719If \var{byteorder} is not \code{0}, output is written according to the
Fred Drakea4cd2612000-04-06 14:10:29 +00002720following byte order:
2721
2722\begin{verbatim}
2723 byteorder == -1: little endian
2724 byteorder == 0: native byte order (writes a BOM mark)
2725 byteorder == 1: big endian
2726\end{verbatim}
2727
Fred Drakea8455ab2000-06-16 19:58:42 +00002728If byteorder is \code{0}, the output string will always start with the
Fred Drakea4cd2612000-04-06 14:10:29 +00002729Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
2730prepended.
2731
2732Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
2733reduced to UCS-2. This trick makes it possible to add full UTF-16
2734capabilities at a later point without comprimising the APIs.
2735
2736Returns \NULL{} in case an exception was raised by the codec.
2737\end{cfuncdesc}
2738
2739\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002740Returns a Python string using the UTF-16 encoding in native byte
2741order. The string always starts with a BOM mark. Error handling is
2742``strict''. Returns \NULL{} in case an exception was raised by the
2743codec.
2744\end{cfuncdesc}
2745
2746% --- Unicode-Escape Codecs ----------------------------------------------
2747
2748These are the ``Unicode Esacpe'' codec APIs:
2749
2750\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
2751 int size,
2752 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002753Creates a Unicode object by decoding \var{size} bytes of the Unicode-Esacpe
2754encoded string \var{s}. Returns \NULL{} in case an exception was
2755raised by the codec.
2756\end{cfuncdesc}
2757
2758\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
2759 int size,
2760 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002761Encodes the \ctype{Py_UNICODE} buffer of the given size using Unicode-Escape
2762and returns a Python string object. Returns \NULL{} in case an
2763exception was raised by the codec.
2764\end{cfuncdesc}
2765
2766\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002767Encodes a Unicode objects using Unicode-Escape and returns the result
2768as Python string object. Error handling is ``strict''. Returns
2769\NULL{} in case an exception was raised by the codec.
2770\end{cfuncdesc}
2771
2772% --- Raw-Unicode-Escape Codecs ------------------------------------------
2773
2774These are the ``Raw Unicode Esacpe'' codec APIs:
2775
2776\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
2777 int size,
2778 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002779Creates a Unicode object by decoding \var{size} bytes of the Raw-Unicode-Esacpe
2780encoded string \var{s}. Returns \NULL{} in case an exception was
2781raised by the codec.
2782\end{cfuncdesc}
2783
2784\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
2785 int size,
2786 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002787Encodes the \ctype{Py_UNICODE} buffer of the given size using Raw-Unicode-Escape
2788and returns a Python string object. Returns \NULL{} in case an
2789exception was raised by the codec.
2790\end{cfuncdesc}
2791
2792\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002793Encodes a Unicode objects using Raw-Unicode-Escape and returns the result
2794as Python string object. Error handling is ``strict''. Returns
2795\NULL{} in case an exception was raised by the codec.
2796\end{cfuncdesc}
2797
2798% --- Latin-1 Codecs -----------------------------------------------------
2799
2800These are the Latin-1 codec APIs:
2801
2802Latin-1 corresponds to the first 256 Unicode ordinals and only these
2803are accepted by the codecs during encoding.
2804
2805\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002806 int size,
2807 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002808Creates a Unicode object by decoding \var{size} bytes of the Latin-1
2809encoded string \var{s}. Returns \NULL{} in case an exception was
2810raised by the codec.
2811\end{cfuncdesc}
2812
2813\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002814 int size,
2815 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002816Encodes the \ctype{Py_UNICODE} buffer of the given size using Latin-1
2817and returns a Python string object. Returns \NULL{} in case an
2818exception was raised by the codec.
2819\end{cfuncdesc}
2820
2821\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002822Encodes a Unicode objects using Latin-1 and returns the result as
2823Python string object. Error handling is ``strict''. Returns
2824\NULL{} in case an exception was raised by the codec.
2825\end{cfuncdesc}
2826
2827% --- ASCII Codecs -------------------------------------------------------
2828
Fred Drake1d158692000-06-18 05:21:21 +00002829These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
2830accepted. All other codes generate errors.
Fred Drakea4cd2612000-04-06 14:10:29 +00002831
2832\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002833 int size,
2834 const char *errors}
2835Creates a Unicode object by decoding \var{size} bytes of the
2836\ASCII{} encoded string \var{s}. Returns \NULL{} in case an exception
2837was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002838\end{cfuncdesc}
2839
2840\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002841 int size,
2842 const char *errors}
2843Encodes the \ctype{Py_UNICODE} buffer of the given size using
2844\ASCII{} and returns a Python string object. Returns \NULL{} in case
2845an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002846\end{cfuncdesc}
2847
2848\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
Fred Drake1d158692000-06-18 05:21:21 +00002849Encodes a Unicode objects using \ASCII{} and returns the result as Python
Fred Drakea4cd2612000-04-06 14:10:29 +00002850string object. Error handling is ``strict''. Returns
2851\NULL{} in case an exception was raised by the codec.
2852\end{cfuncdesc}
2853
2854% --- Character Map Codecs -----------------------------------------------
2855
2856These are the mapping codec APIs:
2857
2858This codec is special in that it can be used to implement many
2859different codecs (and this is in fact what was done to obtain most of
2860the standard codecs included in the \module{encodings} package). The
2861codec uses mapping to encode and decode characters.
2862
2863Decoding mappings must map single string characters to single Unicode
2864characters, integers (which are then interpreted as Unicode ordinals)
2865or None (meaning "undefined mapping" and causing an error).
2866
2867Encoding mappings must map single Unicode characters to single string
2868characters, integers (which are then interpreted as Latin-1 ordinals)
2869or None (meaning "undefined mapping" and causing an error).
2870
2871The mapping objects provided must only support the __getitem__ mapping
2872interface.
2873
2874If a character lookup fails with a LookupError, the character is
2875copied as-is meaning that its ordinal value will be interpreted as
2876Unicode or Latin-1 ordinal resp. Because of this, mappings only need
2877to contain those mappings which map characters to different code
2878points.
2879
2880\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
2881 int size,
2882 PyObject *mapping,
2883 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002884Creates a Unicode object by decoding \var{size} bytes of the encoded
2885string \var{s} using the given \var{mapping} object. Returns \NULL{}
2886in case an exception was raised by the codec.
2887\end{cfuncdesc}
2888
2889\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
2890 int size,
2891 PyObject *mapping,
2892 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002893Encodes the \ctype{Py_UNICODE} buffer of the given size using the
2894given \var{mapping} object and returns a Python string object.
2895Returns \NULL{} in case an exception was raised by the codec.
2896\end{cfuncdesc}
2897
2898\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
2899 PyObject *mapping}
Fred Drakea4cd2612000-04-06 14:10:29 +00002900Encodes a Unicode objects using the given \var{mapping} object and
2901returns the result as Python string object. Error handling is
2902``strict''. Returns \NULL{} in case an exception was raised by the
2903codec.
2904\end{cfuncdesc}
2905
2906The following codec API is special in that maps Unicode to Unicode.
2907
2908\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
2909 int size,
2910 PyObject *table,
2911 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002912Translates a \ctype{Py_UNICODE} buffer of the given length by applying
2913a character mapping \var{table} to it and returns the resulting
Fred Drake1d158692000-06-18 05:21:21 +00002914Unicode object. Returns \NULL{} when an exception was raised by the
2915codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002916
2917The \var{mapping} table must map Unicode ordinal integers to Unicode
2918ordinal integers or None (causing deletion of the character).
2919
2920Mapping tables must only provide the __getitem__ interface,
2921e.g. dictionaries or sequences. Unmapped character ordinals (ones
2922which cause a LookupError) are left untouched and are copied as-is.
Fred Drakea4cd2612000-04-06 14:10:29 +00002923\end{cfuncdesc}
2924
2925% --- MBCS codecs for Windows --------------------------------------------
2926
Fred Drake1d158692000-06-18 05:21:21 +00002927These are the MBCS codec APIs. They are currently only available on
Fred Drakea4cd2612000-04-06 14:10:29 +00002928Windows and use the Win32 MBCS converters to implement the
Fred Drake1d158692000-06-18 05:21:21 +00002929conversions. Note that MBCS (or DBCS) is a class of encodings, not
2930just one. The target encoding is defined by the user settings on the
2931machine running the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002932
2933\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
2934 int size,
2935 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002936Creates a Unicode object by decoding \var{size} bytes of the MBCS
Fred Drake1d158692000-06-18 05:21:21 +00002937encoded string \var{s}. Returns \NULL{} in case an exception was
Fred Drakea4cd2612000-04-06 14:10:29 +00002938raised by the codec.
2939\end{cfuncdesc}
2940
2941\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
2942 int size,
2943 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002944Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
2945and returns a Python string object. Returns \NULL{} in case an
2946exception was raised by the codec.
2947\end{cfuncdesc}
2948
2949\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002950Encodes a Unicode objects using MBCS and returns the result as Python
Fred Drake1d158692000-06-18 05:21:21 +00002951string object. Error handling is ``strict''. Returns \NULL{} in case
2952an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002953\end{cfuncdesc}
2954
2955% --- Methods & Slots ----------------------------------------------------
2956
2957\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
2958
2959The following APIs are capable of handling Unicode objects and strings
2960on input (we refer to them as strings in the descriptions) and return
2961Unicode objects or integers as apporpriate.
2962
2963They all return \NULL{} or -1 in case an exception occurrs.
2964
2965\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
2966 PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002967Concat two strings giving a new Unicode string.
2968\end{cfuncdesc}
2969
2970\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
2971 PyObject *sep,
2972 int maxsplit}
Fred Drakea4cd2612000-04-06 14:10:29 +00002973Split a string giving a list of Unicode strings.
2974
2975If sep is NULL, splitting will be done at all whitespace
2976substrings. Otherwise, splits occur at the given separator.
2977
2978At most maxsplit splits will be done. If negative, no limit is set.
2979
2980Separators are not included in the resulting list.
2981\end{cfuncdesc}
2982
2983\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
2984 int maxsplit}
Fred Drake1d158692000-06-18 05:21:21 +00002985Split a Unicode string at line breaks, returning a list of Unicode
2986strings. CRLF is considered to be one line break. The Line break
2987characters are not included in the resulting strings.
Fred Drakea4cd2612000-04-06 14:10:29 +00002988\end{cfuncdesc}
2989
2990\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
2991 PyObject *table,
2992 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002993Translate a string by applying a character mapping table to it and
2994return the resulting Unicode object.
2995
2996The mapping table must map Unicode ordinal integers to Unicode ordinal
2997integers or None (causing deletion of the character).
2998
2999Mapping tables must only provide the __getitem__ interface,
3000e.g. dictionaries or sequences. Unmapped character ordinals (ones
3001which cause a LookupError) are left untouched and are copied as-is.
3002
3003\var{errors} has the usual meaning for codecs. It may be \NULL{}
3004which indicates to use the default error handling.
Fred Drakea4cd2612000-04-06 14:10:29 +00003005\end{cfuncdesc}
3006
3007\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
3008 PyObject *seq}
Fred Drakea4cd2612000-04-06 14:10:29 +00003009Join a sequence of strings using the given separator and return
3010the resulting Unicode string.
3011\end{cfuncdesc}
3012
3013\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
3014 PyObject *substr,
3015 int start,
3016 int end,
3017 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00003018Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
3019the given tail end (\var{direction} == -1 means to do a prefix match,
3020\var{direction} == 1 a suffix match), 0 otherwise.
3021\end{cfuncdesc}
3022
3023\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
3024 PyObject *substr,
3025 int start,
3026 int end,
3027 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00003028Return the first position of \var{substr} in
3029\var{str}[\var{start}:\var{end}] using the given \var{direction}
3030(\var{direction} == 1 means to do a forward search,
3031\var{direction} == -1 a backward search), 0 otherwise.
3032\end{cfuncdesc}
3033
3034\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
3035 PyObject *substr,
3036 int start,
3037 int end}
Fred Drakea4cd2612000-04-06 14:10:29 +00003038Count the number of occurrences of \var{substr} in
3039\var{str}[\var{start}:\var{end}]
3040\end{cfuncdesc}
3041
3042\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
3043 PyObject *substr,
3044 PyObject *replstr,
3045 int maxcount}
Fred Drakea4cd2612000-04-06 14:10:29 +00003046Replace at most \var{maxcount} occurrences of \var{substr} in
3047\var{str} with \var{replstr} and return the resulting Unicode object.
3048\var{maxcount} == -1 means: replace all occurrences.
3049\end{cfuncdesc}
3050
Fred Drake1d158692000-06-18 05:21:21 +00003051\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00003052Compare two strings and return -1, 0, 1 for less than, equal,
3053greater than resp.
3054\end{cfuncdesc}
3055
3056\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
3057 PyObject *args}
Fred Drake1d158692000-06-18 05:21:21 +00003058Returns a new string object from \var{format} and \var{args}; this is
3059analogous to \code{\var{format} \%\ \var{args}}. The
3060\var{args} argument must be a tuple.
Fred Drakea4cd2612000-04-06 14:10:29 +00003061\end{cfuncdesc}
3062
3063\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
3064 PyObject *element}
Fred Drakea4cd2612000-04-06 14:10:29 +00003065Checks whether \var{element} is contained in \var{container} and
Fred Drake1d158692000-06-18 05:21:21 +00003066returns true or false accordingly.
Fred Drakea4cd2612000-04-06 14:10:29 +00003067
Fred Drake1d158692000-06-18 05:21:21 +00003068\var{element} has to coerce to a one element Unicode string. \code{-1} is
Fred Drakea4cd2612000-04-06 14:10:29 +00003069returned in case of an error.
3070\end{cfuncdesc}
3071
3072
Fred Drake58c5a2a1999-08-04 13:13:24 +00003073\subsection{Buffer Objects \label{bufferObjects}}
Fred Drake659ebfa2000-04-03 15:42:13 +00003074\sectionauthor{Greg Stein}{gstein@lyra.org}
Fred Drake58c5a2a1999-08-04 13:13:24 +00003075
Fred Drake659ebfa2000-04-03 15:42:13 +00003076\obindex{buffer}
3077Python objects implemented in C can export a group of functions called
3078the ``buffer\index{buffer interface} interface.'' These functions can
3079be used by an object to expose its data in a raw, byte-oriented
3080format. Clients of the object can use the buffer interface to access
3081the object data directly, without needing to copy it first.
3082
3083Two examples of objects that support
3084the buffer interface are strings and arrays. The string object exposes
3085the character contents in the buffer interface's byte-oriented
3086form. An array can also expose its contents, but it should be noted
3087that array elements may be multi-byte values.
3088
3089An example user of the buffer interface is the file object's
3090\method{write()} method. Any object that can export a series of bytes
3091through the buffer interface can be written to a file. There are a
3092number of format codes to \cfunction{PyArgs_ParseTuple()} that operate
3093against an object's buffer interface, returning data from the target
3094object.
3095
3096More information on the buffer interface is provided in the section
3097``Buffer Object Structures'' (section \ref{buffer-structs}), under
3098the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
3099
3100A ``buffer object'' is defined in the \file{bufferobject.h} header
3101(included by \file{Python.h}). These objects look very similar to
3102string objects at the Python programming level: they support slicing,
3103indexing, concatenation, and some other standard string
3104operations. However, their data can come from one of two sources: from
3105a block of memory, or from another object which exports the buffer
3106interface.
3107
3108Buffer objects are useful as a way to expose the data from another
3109object's buffer interface to the Python programmer. They can also be
3110used as a zero-copy slicing mechanism. Using their ability to
3111reference a block of memory, it is possible to expose any data to the
3112Python programmer quite easily. The memory could be a large, constant
3113array in a C extension, it could be a raw block of memory for
3114manipulation before passing to an operating system library, or it
3115could be used to pass around structured data in its native, in-memory
3116format.
3117
3118\begin{ctypedesc}{PyBufferObject}
3119This subtype of \ctype{PyObject} represents a buffer object.
3120\end{ctypedesc}
Fred Drake58c5a2a1999-08-04 13:13:24 +00003121
3122\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
3123The instance of \ctype{PyTypeObject} which represents the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00003124buffer type; it is the same object as \code{types.BufferType} in the
3125Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003126\end{cvardesc}
3127
3128\begin{cvardesc}{int}{Py_END_OF_BUFFER}
Fred Drake659ebfa2000-04-03 15:42:13 +00003129This constant may be passed as the \var{size} parameter to
3130\cfunction{PyBuffer_FromObject()} or
3131\cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the new
3132\ctype{PyBufferObject} should refer to \var{base} object from the
3133specified \var{offset} to the end of its exported buffer. Using this
3134enables the caller to avoid querying the \var{base} object for its
3135length.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003136\end{cvardesc}
3137
3138\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
3139Return true if the argument has type \cdata{PyBuffer_Type}.
3140\end{cfuncdesc}
3141
3142\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
3143 int offset, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003144Return a new read-only buffer object. This raises
3145\exception{TypeError} if \var{base} doesn't support the read-only
3146buffer protocol or doesn't provide exactly one buffer segment, or it
3147raises \exception{ValueError} if \var{offset} is less than zero. The
3148buffer will hold a reference to the \var{base} object, and the
3149buffer's contents will refer to the \var{base} object's buffer
3150interface, starting as position \var{offset} and extending for
3151\var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
3152the new buffer's contents extend to the length of the
3153\var{base} object's exported buffer data.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003154\end{cfuncdesc}
3155
3156\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
3157 int offset,
3158 int size}
3159Return a new writable buffer object. Parameters and exceptions are
3160similar to those for \cfunction{PyBuffer_FromObject()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003161If the \var{base} object does not export the writeable buffer
3162protocol, then \exception{TypeError} is raised.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003163\end{cfuncdesc}
3164
3165\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003166Return a new read-only buffer object that reads from a specified
3167location in memory, with a specified size.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003168The caller is responsible for ensuring that the memory buffer, passed
3169in as \var{ptr}, is not deallocated while the returned buffer object
3170exists. Raises \exception{ValueError} if \var{size} is less than
Fred Drake659ebfa2000-04-03 15:42:13 +00003171zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be passed
3172for the \var{size} parameter; \exception{ValueError} will be raised in
3173that case.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003174\end{cfuncdesc}
3175
3176\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003177Similar to \cfunction{PyBuffer_FromMemory()}, but the returned buffer
3178is writable.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003179\end{cfuncdesc}
3180
3181\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
3182Returns a new writable buffer object that maintains its own memory
Fred Drake659ebfa2000-04-03 15:42:13 +00003183buffer of \var{size} bytes. \exception{ValueError} is returned if
3184\var{size} is not zero or positive.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003185\end{cfuncdesc}
3186
Guido van Rossum44475131998-04-21 15:30:01 +00003187
Fred Drakeefd146c1999-02-15 15:30:45 +00003188\subsection{Tuple Objects \label{tupleObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003189
Fred Drake659ebfa2000-04-03 15:42:13 +00003190\obindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003191\begin{ctypedesc}{PyTupleObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003192This subtype of \ctype{PyObject} represents a Python tuple object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003193\end{ctypedesc}
3194
3195\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003196This instance of \ctype{PyTypeObject} represents the Python tuple
3197type; it is the same object as \code{types.TupleType} in the Python
3198layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003199\end{cvardesc}
3200
3201\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
3202Return true if the argument is a tuple object.
3203\end{cfuncdesc}
3204
Fred Drake659ebfa2000-04-03 15:42:13 +00003205\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
3206Return a new tuple object of size \var{len}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003207\end{cfuncdesc}
3208
Fred Drakea05460c2001-02-12 17:38:18 +00003209\begin{cfuncdesc}{int}{PyTuple_Size}{PyObject *p}
Fred Drakee058b4f1998-02-16 06:15:35 +00003210Takes a pointer to a tuple object, and returns the size
Fred Drakee5bf8b21998-02-12 21:22:28 +00003211of that tuple.
3212\end{cfuncdesc}
3213
Fred Drakea05460c2001-02-12 17:38:18 +00003214\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003215Returns the object at position \var{pos} in the tuple pointed
3216to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003217sets an \exception{IndexError} exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003218\end{cfuncdesc}
3219
Fred Drakea05460c2001-02-12 17:38:18 +00003220\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyObject *p, int pos}
Fred Drakefac312f2001-05-29 15:13:00 +00003221Like \cfunction{PyTuple_GetItem()}, but does no checking of its
3222arguments.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003223\end{cfuncdesc}
3224
Fred Drakea05460c2001-02-12 17:38:18 +00003225\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyObject *p,
3226 int low, int high}
Fred Drakee058b4f1998-02-16 06:15:35 +00003227Takes a slice of the tuple pointed to by \var{p} from
3228\var{low} to \var{high} and returns it as a new tuple.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003229\end{cfuncdesc}
3230
Fred Drake659ebfa2000-04-03 15:42:13 +00003231\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
3232 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003233Inserts a reference to object \var{o} at position \var{pos} of
3234the tuple pointed to by \var{p}. It returns \code{0} on success.
Fred Drake659ebfa2000-04-03 15:42:13 +00003235\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003236\end{cfuncdesc}
3237
Fred Drake659ebfa2000-04-03 15:42:13 +00003238\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
3239 int pos, PyObject *o}
Fred Drakefac312f2001-05-29 15:13:00 +00003240Like \cfunction{PyTuple_SetItem()}, but does no error checking, and
Fred Drakee5bf8b21998-02-12 21:22:28 +00003241should \emph{only} be used to fill in brand new tuples.
Fred Drake659ebfa2000-04-03 15:42:13 +00003242\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003243\end{cfuncdesc}
3244
Fred Drakefac312f2001-05-29 15:13:00 +00003245\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyObject **p, int newsize}
Fred Drake659ebfa2000-04-03 15:42:13 +00003246Can be used to resize a tuple. \var{newsize} will be the new length
3247of the tuple. Because tuples are \emph{supposed} to be immutable,
3248this should only be used if there is only one reference to the object.
3249Do \emph{not} use this if the tuple may already be known to some other
Fred Drakefac312f2001-05-29 15:13:00 +00003250part of the code. The tuple will always grow or shrink at the end.
3251Think of this as destroying the old tuple and creating a new one, only
3252more efficiently. Returns \code{0} on success. Client code should
3253never assume that the resulting value of \code{*\var{p}} will be the
3254same as before calling this function. If the object referenced by
3255\code{*\var{p}} is replaced, the original \code{*\var{p}} is
3256destroyed. On failure, returns \code{-1} and sets \code{*\var{p}} to
3257\NULL, and raises \exception{MemoryError} or \exception{SystemError}.
3258\versionchanged[Removed unused third parameter, \var{last_is_sticky}]{2.2}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003259\end{cfuncdesc}
3260
3261
Fred Drakeefd146c1999-02-15 15:30:45 +00003262\subsection{List Objects \label{listObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003263
Fred Drake659ebfa2000-04-03 15:42:13 +00003264\obindex{list}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003265\begin{ctypedesc}{PyListObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003266This subtype of \ctype{PyObject} represents a Python list object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003267\end{ctypedesc}
3268
3269\begin{cvardesc}{PyTypeObject}{PyList_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003270This instance of \ctype{PyTypeObject} represents the Python list
3271type. This is the same object as \code{types.ListType}.
3272\withsubitem{(in module types)}{\ttindex{ListType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003273\end{cvardesc}
3274
3275\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003276Returns true if its argument is a \ctype{PyListObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003277\end{cfuncdesc}
3278
Fred Drake659ebfa2000-04-03 15:42:13 +00003279\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
3280Returns a new list of length \var{len} on success, or \NULL{} on
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003281failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003282\end{cfuncdesc}
3283
Fred Drakec6fa34e1998-04-02 06:47:24 +00003284\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003285Returns the length of the list object in \var{list}; this is
3286equivalent to \samp{len(\var{list})} on a list object.
3287\bifuncindex{len}
3288\end{cfuncdesc}
3289
3290\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
Fred Drake5d644212000-10-07 12:31:50 +00003291Macro form of \cfunction{PyList_Size()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003292\end{cfuncdesc}
3293
Fred Drakec6fa34e1998-04-02 06:47:24 +00003294\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
Guido van Rossum44475131998-04-21 15:30:01 +00003295Returns the object at position \var{pos} in the list pointed
3296to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003297sets an \exception{IndexError} exception.
3298\end{cfuncdesc}
3299
3300\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
3301Macro form of \cfunction{PyList_GetItem()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003302\end{cfuncdesc}
3303
Fred Drakec6fa34e1998-04-02 06:47:24 +00003304\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
3305 PyObject *item}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003306Sets the item at index \var{index} in list to \var{item}.
Fred Drake00d0cb62001-06-03 03:12:57 +00003307\strong{Note:} This function ``steals'' a reference to \var{item} and
3308discards a reference to an item already in the list at the affected
3309position.
Fred Drake659ebfa2000-04-03 15:42:13 +00003310\end{cfuncdesc}
3311
3312\begin{cfuncdesc}{PyObject*}{PyList_SET_ITEM}{PyObject *list, int i,
3313 PyObject *o}
3314Macro form of \cfunction{PyList_SetItem()} without error checking.
Fred Drake00d0cb62001-06-03 03:12:57 +00003315\strong{Note:} This function ``steals'' a reference to \var{item},
3316and, unlike \cfunction{PyList_SetItem()}, does \emph{not} discard a
3317reference to any item that it being replaced. This is normally only
3318used to fill in new lists where there is no previous content..
Fred Drakee5bf8b21998-02-12 21:22:28 +00003319\end{cfuncdesc}
3320
Fred Drakec6fa34e1998-04-02 06:47:24 +00003321\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
Guido van Rossum44475131998-04-21 15:30:01 +00003322 PyObject *item}
3323Inserts the item \var{item} into list \var{list} in front of index
Fred Drake659ebfa2000-04-03 15:42:13 +00003324\var{index}. Returns \code{0} if successful; returns \code{-1} and
3325raises an exception if unsuccessful. Analogous to
3326\code{\var{list}.insert(\var{index}, \var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003327\end{cfuncdesc}
3328
Fred Drakec6fa34e1998-04-02 06:47:24 +00003329\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
Guido van Rossum44475131998-04-21 15:30:01 +00003330Appends the object \var{item} at the end of list \var{list}. Returns
Fred Drake659ebfa2000-04-03 15:42:13 +00003331\code{0} if successful; returns \code{-1} and sets an exception if
3332unsuccessful. Analogous to \code{\var{list}.append(\var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003333\end{cfuncdesc}
3334
Fred Drakec6fa34e1998-04-02 06:47:24 +00003335\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
3336 int low, int high}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003337Returns a list of the objects in \var{list} containing the objects
Guido van Rossum44475131998-04-21 15:30:01 +00003338\emph{between} \var{low} and \var{high}. Returns NULL and sets an
3339exception if unsuccessful.
Fred Drake659ebfa2000-04-03 15:42:13 +00003340Analogous to \code{\var{list}[\var{low}:\var{high}]}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003341\end{cfuncdesc}
3342
Fred Drakec6fa34e1998-04-02 06:47:24 +00003343\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
3344 int low, int high,
3345 PyObject *itemlist}
Fred Drake659ebfa2000-04-03 15:42:13 +00003346Sets the slice of \var{list} between \var{low} and \var{high} to the
3347contents of \var{itemlist}. Analogous to
3348\code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
3349\code{0} on success, \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003350\end{cfuncdesc}
3351
Fred Drakec6fa34e1998-04-02 06:47:24 +00003352\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003353Sorts the items of \var{list} in place. Returns \code{0} on success,
3354\code{-1} on failure. This is equivalent to
3355\samp{\var{list}.sort()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003356\end{cfuncdesc}
3357
Fred Drakec6fa34e1998-04-02 06:47:24 +00003358\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003359Reverses the items of \var{list} in place. Returns \code{0} on
3360success, \code{-1} on failure. This is the equivalent of
3361\samp{\var{list}.reverse()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003362\end{cfuncdesc}
3363
Fred Drakec6fa34e1998-04-02 06:47:24 +00003364\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003365Returns a new tuple object containing the contents of \var{list};
3366equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003367\end{cfuncdesc}
3368
3369
Fred Drakeefd146c1999-02-15 15:30:45 +00003370\section{Mapping Objects \label{mapObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003371
Fred Drake659ebfa2000-04-03 15:42:13 +00003372\obindex{mapping}
3373
3374
Fred Drakeefd146c1999-02-15 15:30:45 +00003375\subsection{Dictionary Objects \label{dictObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003376
Fred Drake659ebfa2000-04-03 15:42:13 +00003377\obindex{dictionary}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003378\begin{ctypedesc}{PyDictObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003379This subtype of \ctype{PyObject} represents a Python dictionary object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003380\end{ctypedesc}
3381
3382\begin{cvardesc}{PyTypeObject}{PyDict_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003383This instance of \ctype{PyTypeObject} represents the Python dictionary
3384type. This is exposed to Python programs as \code{types.DictType} and
3385\code{types.DictionaryType}.
3386\withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003387\end{cvardesc}
3388
3389\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003390Returns true if its argument is a \ctype{PyDictObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003391\end{cfuncdesc}
3392
Fred Drakec6fa34e1998-04-02 06:47:24 +00003393\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003394Returns a new empty dictionary, or \NULL{} on failure.
3395\end{cfuncdesc}
3396
3397\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
3398Empties an existing dictionary of all key-value pairs.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003399\end{cfuncdesc}
3400
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003401\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003402Returns a new dictionary that contains the same key-value pairs as p.
3403Empties an existing dictionary of all key-value pairs.
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003404\end{cfuncdesc}
3405
Fred Drake659ebfa2000-04-03 15:42:13 +00003406\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
3407 PyObject *val}
3408Inserts \var{value} into the dictionary with a key of \var{key}.
3409\var{key} must be hashable; if it isn't, \exception{TypeError} will be
3410raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003411\end{cfuncdesc}
3412
Fred Drake83e01bf2001-03-16 15:41:29 +00003413\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p,
Fred Drakee5bf8b21998-02-12 21:22:28 +00003414 char *key,
3415 PyObject *val}
Fred Drakee058b4f1998-02-16 06:15:35 +00003416Inserts \var{value} into the dictionary using \var{key}
Fred Drake1d158692000-06-18 05:21:21 +00003417as a key. \var{key} should be a \ctype{char*}. The key object is
Fred Drakee058b4f1998-02-16 06:15:35 +00003418created using \code{PyString_FromString(\var{key})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003419\ttindex{PyString_FromString()}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003420\end{cfuncdesc}
3421
Fred Drake659ebfa2000-04-03 15:42:13 +00003422\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003423Removes the entry in dictionary \var{p} with key \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003424\var{key} must be hashable; if it isn't, \exception{TypeError} is
3425raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003426\end{cfuncdesc}
3427
Fred Drake659ebfa2000-04-03 15:42:13 +00003428\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003429Removes the entry in dictionary \var{p} which has a key
Fred Drake659ebfa2000-04-03 15:42:13 +00003430specified by the string \var{key}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003431\end{cfuncdesc}
3432
Fred Drake659ebfa2000-04-03 15:42:13 +00003433\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003434Returns the object from dictionary \var{p} which has a key
Guido van Rossum44475131998-04-21 15:30:01 +00003435\var{key}. Returns \NULL{} if the key \var{key} is not present, but
Fred Drake659ebfa2000-04-03 15:42:13 +00003436\emph{without} setting an exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003437\end{cfuncdesc}
3438
Fred Drake659ebfa2000-04-03 15:42:13 +00003439\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
Fred Drakef8830d11998-04-23 14:06:01 +00003440This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
Fred Drake659ebfa2000-04-03 15:42:13 +00003441specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003442\end{cfuncdesc}
3443
Fred Drake659ebfa2000-04-03 15:42:13 +00003444\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003445Returns a \ctype{PyListObject} containing all the items
Guido van Rossum44475131998-04-21 15:30:01 +00003446from the dictionary, as in the dictinoary method \method{items()} (see
Fred Drakebe486461999-11-09 17:03:03 +00003447the \citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003448\end{cfuncdesc}
3449
Fred Drake659ebfa2000-04-03 15:42:13 +00003450\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003451Returns a \ctype{PyListObject} containing all the keys
Guido van Rossum44475131998-04-21 15:30:01 +00003452from the dictionary, as in the dictionary method \method{keys()} (see the
Fred Drakebe486461999-11-09 17:03:03 +00003453\citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003454\end{cfuncdesc}
3455
Fred Drake659ebfa2000-04-03 15:42:13 +00003456\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003457Returns a \ctype{PyListObject} containing all the values
Guido van Rossum44475131998-04-21 15:30:01 +00003458from the dictionary \var{p}, as in the dictionary method
Fred Drakebe486461999-11-09 17:03:03 +00003459\method{values()} (see the \citetitle[../lib/lib.html]{Python Library
3460Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003461\end{cfuncdesc}
3462
Fred Drake659ebfa2000-04-03 15:42:13 +00003463\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
3464Returns the number of items in the dictionary. This is equivalent to
3465\samp{len(\var{p})} on a dictionary.\bifuncindex{len}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003466\end{cfuncdesc}
3467
Fred Drake83e01bf2001-03-16 15:41:29 +00003468\begin{cfuncdesc}{int}{PyDict_Next}{PyObject *p, int *ppos,
Fred Drake7d45d342000-08-11 17:07:32 +00003469 PyObject **pkey, PyObject **pvalue}
Fred Drake83e01bf2001-03-16 15:41:29 +00003470Iterate over all key-value pairs in the dictionary \var{p}. The
3471\ctype{int} referred to by \var{ppos} must be initialized to \code{0}
3472prior to the first call to this function to start the iteration; the
3473function returns true for each pair in the dictionary, and false once
3474all pairs have been reported. The parameters \var{pkey} and
3475\var{pvalue} should either point to \ctype{PyObject*} variables that
3476will be filled in with each key and value, respectively, or may be
Fred Drake8d00a0f2001-04-13 17:55:02 +00003477\NULL.
3478
Fred Drake83e01bf2001-03-16 15:41:29 +00003479For example:
Fred Drakee5bf8b21998-02-12 21:22:28 +00003480
Fred Drake83e01bf2001-03-16 15:41:29 +00003481\begin{verbatim}
3482PyObject *key, *value;
3483int pos = 0;
3484
3485while (PyDict_Next(self->dict, &pos, &key, &value)) {
3486 /* do something interesting with the values... */
3487 ...
3488}
3489\end{verbatim}
Fred Drake8d00a0f2001-04-13 17:55:02 +00003490
3491The dictionary \var{p} should not be mutated during iteration. It is
3492safe (since Python 2.1) to modify the values of the keys as you
3493iterate over the dictionary, for example:
3494
3495\begin{verbatim}
3496PyObject *key, *value;
3497int pos = 0;
3498
3499while (PyDict_Next(self->dict, &pos, &key, &value)) {
3500 int i = PyInt_AS_LONG(value) + 1;
3501 PyObject *o = PyInt_FromLong(i);
3502 if (o == NULL)
3503 return -1;
3504 if (PyDict_SetItem(self->dict, key, o) < 0) {
3505 Py_DECREF(o);
3506 return -1;
3507 }
3508 Py_DECREF(o);
3509}
3510\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003511\end{cfuncdesc}
3512
3513
Fred Drakeefd146c1999-02-15 15:30:45 +00003514\section{Numeric Objects \label{numericObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003515
Fred Drake659ebfa2000-04-03 15:42:13 +00003516\obindex{numeric}
3517
3518
Fred Drakeefd146c1999-02-15 15:30:45 +00003519\subsection{Plain Integer Objects \label{intObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003520
Fred Drake659ebfa2000-04-03 15:42:13 +00003521\obindex{integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003522\begin{ctypedesc}{PyIntObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003523This subtype of \ctype{PyObject} represents a Python integer object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003524\end{ctypedesc}
3525
3526\begin{cvardesc}{PyTypeObject}{PyInt_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003527This instance of \ctype{PyTypeObject} represents the Python plain
Fred Drake659ebfa2000-04-03 15:42:13 +00003528integer type. This is the same object as \code{types.IntType}.
3529\withsubitem{(in modules types)}{\ttindex{IntType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003530\end{cvardesc}
3531
Fred Drake659ebfa2000-04-03 15:42:13 +00003532\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
3533Returns true if \var{o} is of type \cdata{PyInt_Type}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003534\end{cfuncdesc}
3535
Fred Drakec6fa34e1998-04-02 06:47:24 +00003536\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
Fred Drakee058b4f1998-02-16 06:15:35 +00003537Creates a new integer object with a value of \var{ival}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003538
3539The current implementation keeps an array of integer objects for all
Fred Drakee058b4f1998-02-16 06:15:35 +00003540integers between \code{-1} and \code{100}, when you create an int in
3541that range you actually just get back a reference to the existing
3542object. So it should be possible to change the value of \code{1}. I
Fred Drake7e9d3141998-04-03 05:02:28 +00003543suspect the behaviour of Python in this case is undefined. :-)
Fred Drakee5bf8b21998-02-12 21:22:28 +00003544\end{cfuncdesc}
3545
Fred Drakee5bf8b21998-02-12 21:22:28 +00003546\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
Fred Drakef8830d11998-04-23 14:06:01 +00003547Will first attempt to cast the object to a \ctype{PyIntObject}, if
Fred Drakee058b4f1998-02-16 06:15:35 +00003548it is not already one, and then return its value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003549\end{cfuncdesc}
3550
Fred Drake659ebfa2000-04-03 15:42:13 +00003551\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
3552Returns the value of the object \var{io}. No error checking is
3553performed.
3554\end{cfuncdesc}
3555
Fred Drakee5bf8b21998-02-12 21:22:28 +00003556\begin{cfuncdesc}{long}{PyInt_GetMax}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003557Returns the system's idea of the largest integer it can handle
3558(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
3559header files).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003560\end{cfuncdesc}
3561
3562
Fred Drakeefd146c1999-02-15 15:30:45 +00003563\subsection{Long Integer Objects \label{longObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003564
Fred Drake659ebfa2000-04-03 15:42:13 +00003565\obindex{long integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003566\begin{ctypedesc}{PyLongObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003567This subtype of \ctype{PyObject} represents a Python long integer
Fred Drakee058b4f1998-02-16 06:15:35 +00003568object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003569\end{ctypedesc}
3570
3571\begin{cvardesc}{PyTypeObject}{PyLong_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003572This instance of \ctype{PyTypeObject} represents the Python long
Fred Drake659ebfa2000-04-03 15:42:13 +00003573integer type. This is the same object as \code{types.LongType}.
3574\withsubitem{(in modules types)}{\ttindex{LongType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003575\end{cvardesc}
3576
3577\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003578Returns true if its argument is a \ctype{PyLongObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003579\end{cfuncdesc}
3580
Fred Drakec6fa34e1998-04-02 06:47:24 +00003581\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003582Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on
3583failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003584\end{cfuncdesc}
3585
Fred Drakec6fa34e1998-04-02 06:47:24 +00003586\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003587Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
3588long}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003589\end{cfuncdesc}
3590
Fred Drakec6fa34e1998-04-02 06:47:24 +00003591\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003592Returns a new \ctype{PyLongObject} object from the integer part of
3593\var{v}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003594\end{cfuncdesc}
3595
Fred Drakec6fa34e1998-04-02 06:47:24 +00003596\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003597Returns a C \ctype{long} representation of the contents of
3598\var{pylong}. If \var{pylong} is greater than
3599\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is
3600raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003601\end{cfuncdesc}
3602
Fred Drakec6fa34e1998-04-02 06:47:24 +00003603\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003604Returns a C \ctype{unsigned long} representation of the contents of
3605\var{pylong}. If \var{pylong} is greater than
3606\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError}
3607is raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003608\end{cfuncdesc}
3609
Fred Drakec6fa34e1998-04-02 06:47:24 +00003610\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003611Returns a C \ctype{double} representation of the contents of \var{pylong}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003612\end{cfuncdesc}
3613
Fred Drakec6fa34e1998-04-02 06:47:24 +00003614\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
3615 int base}
Fred Drake659ebfa2000-04-03 15:42:13 +00003616Return a new \ctype{PyLongObject} based on the string value in
3617\var{str}, which is interpreted according to the radix in \var{base}.
3618If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first
3619character in \var{str} which follows the representation of the
3620number. If \var{base} is \code{0}, the radix will be determined base
3621on the leading characters of \var{str}: if \var{str} starts with
3622\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts
3623with \code{'0'}, radix 8 will be used; otherwise radix 10 will be
3624used. If \var{base} is not \code{0}, it must be between \code{2} and
3625\code{36}, inclusive. Leading spaces are ignored. If there are no
3626digits, \exception{ValueError} will be raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003627\end{cfuncdesc}
3628
3629
Fred Drakeefd146c1999-02-15 15:30:45 +00003630\subsection{Floating Point Objects \label{floatObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003631
Fred Drake659ebfa2000-04-03 15:42:13 +00003632\obindex{floating point}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003633\begin{ctypedesc}{PyFloatObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003634This subtype of \ctype{PyObject} represents a Python floating point
Fred Drakee058b4f1998-02-16 06:15:35 +00003635object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003636\end{ctypedesc}
3637
3638\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003639This instance of \ctype{PyTypeObject} represents the Python floating
Fred Drake659ebfa2000-04-03 15:42:13 +00003640point type. This is the same object as \code{types.FloatType}.
3641\withsubitem{(in modules types)}{\ttindex{FloatType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003642\end{cvardesc}
3643
3644\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003645Returns true if its argument is a \ctype{PyFloatObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003646\end{cfuncdesc}
3647
Fred Drakec6fa34e1998-04-02 06:47:24 +00003648\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003649Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
3650failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003651\end{cfuncdesc}
3652
Fred Drakec6fa34e1998-04-02 06:47:24 +00003653\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003654Returns a C \ctype{double} representation of the contents of \var{pyfloat}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003655\end{cfuncdesc}
3656
Fred Drakec6fa34e1998-04-02 06:47:24 +00003657\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003658Returns a C \ctype{double} representation of the contents of
Fred Drakef8830d11998-04-23 14:06:01 +00003659\var{pyfloat}, but without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003660\end{cfuncdesc}
3661
3662
Fred Drakeefd146c1999-02-15 15:30:45 +00003663\subsection{Complex Number Objects \label{complexObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003664
Fred Drake659ebfa2000-04-03 15:42:13 +00003665\obindex{complex number}
3666Python's complex number objects are implemented as two distinct types
3667when viewed from the C API: one is the Python object exposed to
3668Python programs, and the other is a C structure which represents the
3669actual complex number value. The API provides functions for working
3670with both.
3671
3672\subsubsection{Complex Numbers as C Structures}
3673
3674Note that the functions which accept these structures as parameters
3675and return them as results do so \emph{by value} rather than
3676dereferencing them through pointers. This is consistent throughout
3677the API.
3678
Fred Drakee5bf8b21998-02-12 21:22:28 +00003679\begin{ctypedesc}{Py_complex}
Fred Drake659ebfa2000-04-03 15:42:13 +00003680The C structure which corresponds to the value portion of a Python
Fred Drake4de05a91998-02-16 14:25:26 +00003681complex number object. Most of the functions for dealing with complex
3682number objects use structures of this type as input or output values,
3683as appropriate. It is defined as:
3684
Fred Drakee058b4f1998-02-16 06:15:35 +00003685\begin{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003686typedef struct {
3687 double real;
3688 double imag;
Fred Drake4de05a91998-02-16 14:25:26 +00003689} Py_complex;
Fred Drakee058b4f1998-02-16 06:15:35 +00003690\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003691\end{ctypedesc}
3692
Fred Drake659ebfa2000-04-03 15:42:13 +00003693\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
3694Return the sum of two complex numbers, using the C
3695\ctype{Py_complex} representation.
3696\end{cfuncdesc}
3697
3698\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
3699Return the difference between two complex numbers, using the C
3700\ctype{Py_complex} representation.
3701\end{cfuncdesc}
3702
3703\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
3704Return the negation of the complex number \var{complex}, using the C
3705\ctype{Py_complex} representation.
3706\end{cfuncdesc}
3707
3708\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
3709Return the product of two complex numbers, using the C
3710\ctype{Py_complex} representation.
3711\end{cfuncdesc}
3712
3713\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
3714 Py_complex divisor}
3715Return the quotient of two complex numbers, using the C
3716\ctype{Py_complex} representation.
3717\end{cfuncdesc}
3718
3719\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
3720Return the exponentiation of \var{num} by \var{exp}, using the C
3721\ctype{Py_complex} representation.
3722\end{cfuncdesc}
3723
3724
3725\subsubsection{Complex Numbers as Python Objects}
3726
Fred Drakee5bf8b21998-02-12 21:22:28 +00003727\begin{ctypedesc}{PyComplexObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003728This subtype of \ctype{PyObject} represents a Python complex number object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003729\end{ctypedesc}
3730
3731\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003732This instance of \ctype{PyTypeObject} represents the Python complex
Fred Drakee5bf8b21998-02-12 21:22:28 +00003733number type.
3734\end{cvardesc}
3735
3736\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003737Returns true if its argument is a \ctype{PyComplexObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003738\end{cfuncdesc}
3739
Fred Drakec6fa34e1998-04-02 06:47:24 +00003740\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003741Create a new Python complex number object from a C
3742\ctype{Py_complex} value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003743\end{cfuncdesc}
3744
Fred Drakec6fa34e1998-04-02 06:47:24 +00003745\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
Fred Drakef8830d11998-04-23 14:06:01 +00003746Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003747\end{cfuncdesc}
3748
3749\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003750Returns the real part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003751\end{cfuncdesc}
3752
3753\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003754Returns the imaginary part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003755\end{cfuncdesc}
3756
3757\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003758Returns the \ctype{Py_complex} value of the complex number \var{op}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003759\end{cfuncdesc}
3760
3761
3762
Fred Drakeefd146c1999-02-15 15:30:45 +00003763\section{Other Objects \label{otherObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003764
Fred Drakeefd146c1999-02-15 15:30:45 +00003765\subsection{File Objects \label{fileObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003766
Fred Drake659ebfa2000-04-03 15:42:13 +00003767\obindex{file}
3768Python's built-in file objects are implemented entirely on the
3769\ctype{FILE*} support from the C standard library. This is an
3770implementation detail and may change in future releases of Python.
3771
Fred Drakee5bf8b21998-02-12 21:22:28 +00003772\begin{ctypedesc}{PyFileObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003773This subtype of \ctype{PyObject} represents a Python file object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003774\end{ctypedesc}
3775
3776\begin{cvardesc}{PyTypeObject}{PyFile_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003777This instance of \ctype{PyTypeObject} represents the Python file
3778type. This is exposed to Python programs as \code{types.FileType}.
3779\withsubitem{(in module types)}{\ttindex{FileType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003780\end{cvardesc}
3781
3782\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003783Returns true if its argument is a \ctype{PyFileObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003784\end{cfuncdesc}
3785
Fred Drake659ebfa2000-04-03 15:42:13 +00003786\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
3787On success, returns a new file object that is opened on the
3788file given by \var{filename}, with a file mode given by \var{mode},
3789where \var{mode} has the same semantics as the standard C routine
3790\cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003791\end{cfuncdesc}
3792
Fred Drakec6fa34e1998-04-02 06:47:24 +00003793\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
Fred Drake659ebfa2000-04-03 15:42:13 +00003794 char *name, char *mode,
3795 int (*close)(FILE*)}
3796Creates a new \ctype{PyFileObject} from the already-open standard C
3797file pointer, \var{fp}. The function \var{close} will be called when
3798the file should be closed. Returns \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003799\end{cfuncdesc}
3800
Fred Drake659ebfa2000-04-03 15:42:13 +00003801\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
3802Returns the file object associated with \var{p} as a \ctype{FILE*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003803\end{cfuncdesc}
3804
Fred Drakec6fa34e1998-04-02 06:47:24 +00003805\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003806Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
3807function reads one line from the object \var{p}. \var{p} may be a
3808file object or any object with a \method{readline()} method. If
3809\var{n} is \code{0}, exactly one line is read, regardless of the
3810length of the line. If \var{n} is greater than \code{0}, no more than
3811\var{n} bytes will be read from the file; a partial line can be
3812returned. In both cases, an empty string is returned if the end of
3813the file is reached immediately. If \var{n} is less than \code{0},
3814however, one line is read regardless of length, but
3815\exception{EOFError} is raised if the end of the file is reached
3816immediately.
3817\withsubitem{(built-in exception)}{\ttindex{EOFError}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003818\end{cfuncdesc}
3819
Fred Drakec6fa34e1998-04-02 06:47:24 +00003820\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003821Returns the name of the file specified by \var{p} as a string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003822\end{cfuncdesc}
3823
3824\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003825Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
3826only. This should only be called immediately after file object
3827creation.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003828\end{cfuncdesc}
3829
Fred Drake659ebfa2000-04-03 15:42:13 +00003830\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
3831This function exists for internal use by the interpreter.
3832Sets the \member{softspace} attribute of \var{p} to \var{newflag} and
3833\withsubitem{(file attribute)}{\ttindex{softspace}}returns the
3834previous value. \var{p} does not have to be a file object
3835for this function to work properly; any object is supported (thought
3836its only interesting if the \member{softspace} attribute can be set).
3837This function clears any errors, and will return \code{0} as the
3838previous value if the attribute either does not exist or if there were
3839errors in retrieving it. There is no way to detect errors from this
3840function, but doing so should not be needed.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003841\end{cfuncdesc}
3842
Fred Drakec6fa34e1998-04-02 06:47:24 +00003843\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
3844 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003845Writes object \var{obj} to file object \var{p}. The only supported
3846flag for \var{flags} is \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW};
3847if given, the \function{str()} of the object is written instead of the
3848\function{repr()}. Returns \code{0} on success or \code{-1} on
3849failure; the appropriate exception will be set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003850\end{cfuncdesc}
3851
Fred Drakec6fa34e1998-04-02 06:47:24 +00003852\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p,
3853 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003854Writes string \var{s} to file object \var{p}. Returns \code{0} on
3855success or \code{-1} on failure; the appropriate exception will be
3856set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003857\end{cfuncdesc}
3858
3859
Fred Drake5838d0f2001-01-28 06:39:35 +00003860\subsection{Instance Objects \label{instanceObjects}}
3861
3862\obindex{instance}
3863There are very few functions specific to instance objects.
3864
3865\begin{cvardesc}{PyTypeObject}{PyInstance_Type}
3866 Type object for class instances.
3867\end{cvardesc}
3868
3869\begin{cfuncdesc}{int}{PyInstance_Check}{PyObject *obj}
3870 Returns true if \var{obj} is an instance.
3871\end{cfuncdesc}
3872
3873\begin{cfuncdesc}{PyObject*}{PyInstance_New}{PyObject *class,
3874 PyObject *arg,
3875 PyObject *kw}
3876 Create a new instance of a specific class. The parameters \var{arg}
3877 and \var{kw} are used as the positional and keyword parameters to
3878 the object's constructor.
3879\end{cfuncdesc}
3880
3881\begin{cfuncdesc}{PyObject*}{PyInstance_NewRaw}{PyObject *class,
3882 PyObject *dict}
3883 Create a new instance of a specific class without calling it's
3884 constructor. \var{class} is the class of new object. The
3885 \var{dict} parameter will be used as the object's \member{__dict__};
3886 if \NULL, a new dictionary will be created for the instance.
3887\end{cfuncdesc}
3888
3889
Fred Drakeefd146c1999-02-15 15:30:45 +00003890\subsection{Module Objects \label{moduleObjects}}
3891
3892\obindex{module}
3893There are only a few functions special to module objects.
3894
Fred Drake659ebfa2000-04-03 15:42:13 +00003895\begin{cvardesc}{PyTypeObject}{PyModule_Type}
3896This instance of \ctype{PyTypeObject} represents the Python module
3897type. This is exposed to Python programs as \code{types.ModuleType}.
3898\withsubitem{(in module types)}{\ttindex{ModuleType}}
3899\end{cvardesc}
3900
3901\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
3902Returns true if its argument is a module object.
Fred Drakeefd146c1999-02-15 15:30:45 +00003903\end{cfuncdesc}
3904
Fred Drake659ebfa2000-04-03 15:42:13 +00003905\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
3906Return a new module object with the \member{__name__} attribute set to
3907\var{name}. Only the module's \member{__doc__} and
3908\member{__name__} attributes are filled in; the caller is responsible
3909for providing a \member{__file__} attribute.
3910\withsubitem{(module attribute)}{
3911 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
3912\end{cfuncdesc}
3913
3914\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003915Return the dictionary object that implements \var{module}'s namespace;
3916this object is the same as the \member{__dict__} attribute of the
3917module object. This function never fails.
Fred Drake659ebfa2000-04-03 15:42:13 +00003918\withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003919\end{cfuncdesc}
3920
Fred Drake659ebfa2000-04-03 15:42:13 +00003921\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003922Return \var{module}'s \member{__name__} value. If the module does not
Fred Drake659ebfa2000-04-03 15:42:13 +00003923provide one, or if it is not a string, \exception{SystemError} is
3924raised and \NULL{} is returned.
3925\withsubitem{(module attribute)}{\ttindex{__name__}}
3926\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003927\end{cfuncdesc}
3928
Fred Drake659ebfa2000-04-03 15:42:13 +00003929\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003930Return the name of the file from which \var{module} was loaded using
3931\var{module}'s \member{__file__} attribute. If this is not defined,
Fred Drake659ebfa2000-04-03 15:42:13 +00003932or if it is not a string, raise \exception{SystemError} and return
3933\NULL.
3934\withsubitem{(module attribute)}{\ttindex{__file__}}
3935\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003936\end{cfuncdesc}
3937
Fred Drake891150b2000-09-23 03:25:42 +00003938\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
3939 char *name, PyObject *value}
3940Add an object to \var{module} as \var{name}. This is a convenience
3941function which can be used from the module's initialization function.
3942This steals a reference to \var{value}. Returns \code{-1} on error,
3943\code{0} on success.
3944\versionadded{2.0}
3945\end{cfuncdesc}
3946
3947\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
3948 char *name, int value}
3949Add an integer constant to \var{module} as \var{name}. This convenience
3950function can be used from the module's initialization function.
3951Returns \code{-1} on error, \code{0} on success.
3952\versionadded{2.0}
3953\end{cfuncdesc}
3954
3955\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
3956 char *name, char *value}
3957Add a string constant to \var{module} as \var{name}. This convenience
3958function can be used from the module's initialization function. The
3959string \var{value} must be null-terminated. Returns \code{-1} on
3960error, \code{0} on success.
3961\versionadded{2.0}
3962\end{cfuncdesc}
3963
Fred Drakeefd146c1999-02-15 15:30:45 +00003964
3965\subsection{CObjects \label{cObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003966
Fred Drake659ebfa2000-04-03 15:42:13 +00003967\obindex{CObject}
3968Refer to \emph{Extending and Embedding the Python Interpreter},
3969section 1.12 (``Providing a C API for an Extension Module''), for more
3970information on using these objects.
3971
3972
Guido van Rossum44475131998-04-21 15:30:01 +00003973\begin{ctypedesc}{PyCObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003974This subtype of \ctype{PyObject} represents an opaque value, useful for
Fred Drake659ebfa2000-04-03 15:42:13 +00003975C extension modules who need to pass an opaque value (as a
3976\ctype{void*} pointer) through Python code to other C code. It is
Guido van Rossum44475131998-04-21 15:30:01 +00003977often used to make a C function pointer defined in one module
3978available to other modules, so the regular import mechanism can be
3979used to access C APIs defined in dynamically loaded modules.
3980\end{ctypedesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003981
Fred Drake659ebfa2000-04-03 15:42:13 +00003982\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
3983Returns true if its argument is a \ctype{PyCObject}.
3984\end{cfuncdesc}
3985
3986\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00003987 void (*destr)(void *)}
Fred Drake1d158692000-06-18 05:21:21 +00003988Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drakedab44681999-05-13 18:41:14 +00003989\var{destr} function will be called when the object is reclaimed, unless
3990it is \NULL.
Guido van Rossum44475131998-04-21 15:30:01 +00003991\end{cfuncdesc}
3992
Fred Drake659ebfa2000-04-03 15:42:13 +00003993\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00003994 void* desc, void (*destr)(void *, void *) }
Fred Drakef8830d11998-04-23 14:06:01 +00003995Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
3996\var{destr} function will be called when the object is reclaimed. The
3997\var{desc} argument can be used to pass extra callback data for the
3998destructor function.
Guido van Rossum44475131998-04-21 15:30:01 +00003999\end{cfuncdesc}
4000
Fred Drake659ebfa2000-04-03 15:42:13 +00004001\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
4002Returns the object \ctype{void *} that the
4003\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00004004\end{cfuncdesc}
4005
Fred Drake659ebfa2000-04-03 15:42:13 +00004006\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
4007Returns the description \ctype{void *} that the
4008\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00004009\end{cfuncdesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00004010
Fred Drake659ebfa2000-04-03 15:42:13 +00004011
Fred Drakeefd146c1999-02-15 15:30:45 +00004012\chapter{Initialization, Finalization, and Threads
4013 \label{initialization}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004014
Guido van Rossum4a944d71997-08-14 20:35:38 +00004015\begin{cfuncdesc}{void}{Py_Initialize}{}
4016Initialize the Python interpreter. In an application embedding
4017Python, this should be called before using any other Python/C API
Fred Drake659ebfa2000-04-03 15:42:13 +00004018functions; with the exception of
4019\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
4020\cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
4021\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
4022and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
4023This initializes the table of loaded modules (\code{sys.modules}), and
4024\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}creates the
4025fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake4de05a91998-02-16 14:25:26 +00004026\module{__main__}\refbimodindex{__main__} and
4027\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drake659ebfa2000-04-03 15:42:13 +00004028search\indexiii{module}{search}{path} path (\code{sys.path}).
4029It does not set \code{sys.argv}; use
4030\cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
4031is a no-op when called for a second time (without calling
4032\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is no
4033return value; it is a fatal error if the initialization fails.
Guido van Rossum42cefd01997-10-05 15:27:29 +00004034\end{cfuncdesc}
4035
4036\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00004037Return true (nonzero) when the Python interpreter has been
Fred Drakee058b4f1998-02-16 06:15:35 +00004038initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
4039called, this returns false until \cfunction{Py_Initialize()} is called
Guido van Rossum42cefd01997-10-05 15:27:29 +00004040again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004041\end{cfuncdesc}
4042
4043\begin{cfuncdesc}{void}{Py_Finalize}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004044Undo all initializations made by \cfunction{Py_Initialize()} and
4045subsequent use of Python/C API functions, and destroy all
4046sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
4047created and not yet destroyed since the last call to
4048\cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
4049by the Python interpreter. This is a no-op when called for a second
4050time (without calling \cfunction{Py_Initialize()} again first). There
4051is no return value; errors during finalization are ignored.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004052
4053This function is provided for a number of reasons. An embedding
4054application might want to restart Python without having to restart the
4055application itself. An application that has loaded the Python
4056interpreter from a dynamically loadable library (or DLL) might want to
4057free all memory allocated by Python before unloading the DLL. During a
4058hunt for memory leaks in an application a developer might want to free
4059all memory allocated by Python before exiting from the application.
4060
Fred Drakee058b4f1998-02-16 06:15:35 +00004061\strong{Bugs and caveats:} The destruction of modules and objects in
Guido van Rossum4a944d71997-08-14 20:35:38 +00004062modules is done in random order; this may cause destructors
Fred Drakee058b4f1998-02-16 06:15:35 +00004063(\method{__del__()} methods) to fail when they depend on other objects
Guido van Rossum4a944d71997-08-14 20:35:38 +00004064(even functions) or modules. Dynamically loaded extension modules
4065loaded by Python are not unloaded. Small amounts of memory allocated
4066by the Python interpreter may not be freed (if you find a leak, please
4067report it). Memory tied up in circular references between objects is
4068not freed. Some memory allocated by extension modules may not be
4069freed. Some extension may not work properly if their initialization
4070routine is called more than once; this can happen if an applcation
Fred Drakee058b4f1998-02-16 06:15:35 +00004071calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
4072than once.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004073\end{cfuncdesc}
4074
Fred Drakec6fa34e1998-04-02 06:47:24 +00004075\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
Fred Drake4de05a91998-02-16 14:25:26 +00004076Create a new sub-interpreter. This is an (almost) totally separate
4077environment for the execution of Python code. In particular, the new
4078interpreter has separate, independent versions of all imported
4079modules, including the fundamental modules
4080\module{__builtin__}\refbimodindex{__builtin__},
4081\module{__main__}\refbimodindex{__main__} and
4082\module{sys}\refbimodindex{sys}. The table of loaded modules
4083(\code{sys.modules}) and the module search path (\code{sys.path}) are
4084also separate. The new environment has no \code{sys.argv} variable.
4085It has new standard I/O stream file objects \code{sys.stdin},
4086\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drake659ebfa2000-04-03 15:42:13 +00004087same underlying \ctype{FILE} structures in the C library).
4088\withsubitem{(in module sys)}{
4089 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004090
4091The return value points to the first thread state created in the new
4092sub-interpreter. This thread state is made the current thread state.
4093Note that no actual thread is created; see the discussion of thread
4094states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004095\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00004096is stored in the current thread state and there may not be a current
4097thread state. (Like all other Python/C API functions, the global
4098interpreter lock must be held before calling this function and is
4099still held when it returns; however, unlike most other Python/C API
4100functions, there needn't be a current thread state on entry.)
4101
4102Extension modules are shared between (sub-)interpreters as follows:
4103the first time a particular extension is imported, it is initialized
4104normally, and a (shallow) copy of its module's dictionary is
4105squirreled away. When the same extension is imported by another
4106(sub-)interpreter, a new module is initialized and filled with the
Fred Drakee058b4f1998-02-16 06:15:35 +00004107contents of this copy; the extension's \code{init} function is not
4108called. Note that this is different from what happens when an
4109extension is imported after the interpreter has been completely
Fred Drake659ebfa2000-04-03 15:42:13 +00004110re-initialized by calling
4111\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
4112\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
4113the extension's \code{init\var{module}} function \emph{is} called
4114again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004115
Fred Drakee058b4f1998-02-16 06:15:35 +00004116\strong{Bugs and caveats:} Because sub-interpreters (and the main
Guido van Rossum4a944d71997-08-14 20:35:38 +00004117interpreter) are part of the same process, the insulation between them
Fred Drakee058b4f1998-02-16 06:15:35 +00004118isn't perfect --- for example, using low-level file operations like
Fred Drake659ebfa2000-04-03 15:42:13 +00004119\withsubitem{(in module os)}{\ttindex{close()}}
Fred Drakef8830d11998-04-23 14:06:01 +00004120\function{os.close()} they can (accidentally or maliciously) affect each
Guido van Rossum4a944d71997-08-14 20:35:38 +00004121other's open files. Because of the way extensions are shared between
4122(sub-)interpreters, some extensions may not work properly; this is
4123especially likely when the extension makes use of (static) global
4124variables, or when the extension manipulates its module's dictionary
4125after its initialization. It is possible to insert objects created in
4126one sub-interpreter into a namespace of another sub-interpreter; this
4127should be done with great care to avoid sharing user-defined
4128functions, methods, instances or classes between sub-interpreters,
4129since import operations executed by such objects may affect the
4130wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
4131a hard-to-fix bug that will be addressed in a future release.)
4132\end{cfuncdesc}
4133
4134\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
4135Destroy the (sub-)interpreter represented by the given thread state.
4136The given thread state must be the current thread state. See the
4137discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004138thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00004139interpreted are destroyed. (The global interpreter lock must be held
4140before calling this function and is still held when it returns.)
Fred Drake659ebfa2000-04-03 15:42:13 +00004141\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will destroy all
4142sub-interpreters that haven't been explicitly destroyed at that point.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004143\end{cfuncdesc}
4144
4145\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00004146This function should be called before
4147\cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
Guido van Rossum4a944d71997-08-14 20:35:38 +00004148for the first time, if it is called at all. It tells the interpreter
Fred Drake659ebfa2000-04-03 15:42:13 +00004149the value of the \code{argv[0]} argument to the
4150\cfunction{main()}\ttindex{main()} function of the program. This is
4151used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some other
Guido van Rossum4a944d71997-08-14 20:35:38 +00004152functions below to find the Python run-time libraries relative to the
Fred Drakea8455ab2000-06-16 19:58:42 +00004153interpreter executable. The default value is \code{'python'}. The
Guido van Rossum4a944d71997-08-14 20:35:38 +00004154argument should point to a zero-terminated character string in static
4155storage whose contents will not change for the duration of the
4156program's execution. No code in the Python interpreter will change
4157the contents of this storage.
4158\end{cfuncdesc}
4159
Fred Drakec6fa34e1998-04-02 06:47:24 +00004160\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00004161Return the program name set with
4162\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
Guido van Rossum4a944d71997-08-14 20:35:38 +00004163default. The returned string points into static storage; the caller
4164should not modify its value.
4165\end{cfuncdesc}
4166
Fred Drakec6fa34e1998-04-02 06:47:24 +00004167\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004168Return the \emph{prefix} for installed platform-independent files. This
Guido van Rossum4a944d71997-08-14 20:35:38 +00004169is derived through a number of complicated rules from the program name
Fred Drakee058b4f1998-02-16 06:15:35 +00004170set with \cfunction{Py_SetProgramName()} and some environment variables;
Fred Drakea8455ab2000-06-16 19:58:42 +00004171for example, if the program name is \code{'/usr/local/bin/python'},
4172the prefix is \code{'/usr/local'}. The returned string points into
Guido van Rossum4a944d71997-08-14 20:35:38 +00004173static storage; the caller should not modify its value. This
Fred Drakec94d9341998-04-12 02:39:13 +00004174corresponds to the \makevar{prefix} variable in the top-level
Fred Drakea8455ab2000-06-16 19:58:42 +00004175\file{Makefile} and the \longprogramopt{prefix} argument to the
Fred Drakee058b4f1998-02-16 06:15:35 +00004176\program{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00004177Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00004178also the next function.
4179\end{cfuncdesc}
4180
Fred Drakec6fa34e1998-04-02 06:47:24 +00004181\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00004182Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
Guido van Rossum4a944d71997-08-14 20:35:38 +00004183files. This is derived through a number of complicated rules from the
Fred Drakee058b4f1998-02-16 06:15:35 +00004184program name set with \cfunction{Py_SetProgramName()} and some environment
Guido van Rossum4a944d71997-08-14 20:35:38 +00004185variables; for example, if the program name is
Fred Drakea8455ab2000-06-16 19:58:42 +00004186\code{'/usr/local/bin/python'}, the exec-prefix is
4187\code{'/usr/local'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00004188the caller should not modify its value. This corresponds to the
Fred Drakec94d9341998-04-12 02:39:13 +00004189\makevar{exec_prefix} variable in the top-level \file{Makefile} and the
Fred Drakea8455ab2000-06-16 19:58:42 +00004190\longprogramopt{exec-prefix} argument to the
Fred Drake310ee611999-11-09 17:31:42 +00004191\program{configure} script at build time. The value is available to
4192Python code as \code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004193
4194Background: The exec-prefix differs from the prefix when platform
4195dependent files (such as executables and shared libraries) are
4196installed in a different directory tree. In a typical installation,
4197platform dependent files may be installed in the
Fred Drakea8455ab2000-06-16 19:58:42 +00004198\file{/usr/local/plat} subtree while platform independent may be
4199installed in \file{/usr/local}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004200
4201Generally speaking, a platform is a combination of hardware and
4202software families, e.g. Sparc machines running the Solaris 2.x
4203operating system are considered the same platform, but Intel machines
4204running Solaris 2.x are another platform, and Intel machines running
4205Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00004206operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004207operating systems are a different story; the installation strategies
4208on those systems are so different that the prefix and exec-prefix are
4209meaningless, and set to the empty string. Note that compiled Python
4210bytecode files are platform independent (but not independent from the
4211Python version by which they were compiled!).
4212
Fred Drakee058b4f1998-02-16 06:15:35 +00004213System administrators will know how to configure the \program{mount} or
Fred Drakea8455ab2000-06-16 19:58:42 +00004214\program{automount} programs to share \file{/usr/local} between platforms
4215while having \file{/usr/local/plat} be a different filesystem for each
Guido van Rossum4a944d71997-08-14 20:35:38 +00004216platform.
4217\end{cfuncdesc}
4218
Fred Drakec6fa34e1998-04-02 06:47:24 +00004219\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004220Return the full program name of the Python executable; this is
4221computed as a side-effect of deriving the default module search path
Fred Drake659ebfa2000-04-03 15:42:13 +00004222from the program name (set by
4223\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
4224The returned string points into static storage; the caller should not
Guido van Rossum4a944d71997-08-14 20:35:38 +00004225modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00004226\code{sys.executable}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004227\withsubitem{(in module sys)}{\ttindex{executable}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004228\end{cfuncdesc}
4229
Fred Drakec6fa34e1998-04-02 06:47:24 +00004230\begin{cfuncdesc}{char*}{Py_GetPath}{}
Fred Drake4de05a91998-02-16 14:25:26 +00004231\indexiii{module}{search}{path}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004232Return the default module search path; this is computed from the
Fred Drakee058b4f1998-02-16 06:15:35 +00004233program name (set by \cfunction{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00004234environment variables. The returned string consists of a series of
4235directory names separated by a platform dependent delimiter character.
Fred Drakef8830d11998-04-23 14:06:01 +00004236The delimiter character is \character{:} on \UNIX{}, \character{;} on
Fred Drake659ebfa2000-04-03 15:42:13 +00004237DOS/Windows, and \character{\e n} (the \ASCII{} newline character) on
Fred Drakee5bc4971998-02-12 23:36:49 +00004238Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00004239should not modify its value. The value is available to Python code
Fred Drake659ebfa2000-04-03 15:42:13 +00004240as the list \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}},
4241which may be modified to change the future search path for loaded
4242modules.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004243
4244% XXX should give the exact rules
4245\end{cfuncdesc}
4246
Fred Drakec6fa34e1998-04-02 06:47:24 +00004247\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004248Return the version of this Python interpreter. This is a string that
4249looks something like
4250
Guido van Rossum09270b51997-08-15 18:57:32 +00004251\begin{verbatim}
Fred Drakee058b4f1998-02-16 06:15:35 +00004252"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
Guido van Rossum09270b51997-08-15 18:57:32 +00004253\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004254
4255The first word (up to the first space character) is the current Python
4256version; the first three characters are the major and minor version
4257separated by a period. The returned string points into static storage;
4258the caller should not modify its value. The value is available to
4259Python code as the list \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004260\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004261\end{cfuncdesc}
4262
Fred Drakec6fa34e1998-04-02 06:47:24 +00004263\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00004264Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00004265this is formed from the ``official'' name of the operating system,
4266converted to lower case, followed by the major revision number; e.g.,
4267for Solaris 2.x, which is also known as SunOS 5.x, the value is
Fred Drakea8455ab2000-06-16 19:58:42 +00004268\code{'sunos5'}. On Macintosh, it is \code{'mac'}. On Windows, it
4269is \code{'win'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00004270the caller should not modify its value. The value is available to
4271Python code as \code{sys.platform}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004272\withsubitem{(in module sys)}{\ttindex{platform}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004273\end{cfuncdesc}
4274
Fred Drakec6fa34e1998-04-02 06:47:24 +00004275\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004276Return the official copyright string for the current Python version,
4277for example
4278
Fred Drakea8455ab2000-06-16 19:58:42 +00004279\code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004280
4281The returned string points into static storage; the caller should not
4282modify its value. The value is available to Python code as the list
4283\code{sys.copyright}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004284\withsubitem{(in module sys)}{\ttindex{copyright}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004285\end{cfuncdesc}
4286
Fred Drakec6fa34e1998-04-02 06:47:24 +00004287\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004288Return an indication of the compiler used to build the current Python
Fred Drakee058b4f1998-02-16 06:15:35 +00004289version, in square brackets, for example:
Guido van Rossum4a944d71997-08-14 20:35:38 +00004290
Fred Drakee058b4f1998-02-16 06:15:35 +00004291\begin{verbatim}
4292"[GCC 2.7.2.2]"
4293\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004294
4295The returned string points into static storage; the caller should not
4296modify its value. The value is available to Python code as part of
4297the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004298\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004299\end{cfuncdesc}
4300
Fred Drakec6fa34e1998-04-02 06:47:24 +00004301\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004302Return information about the sequence number and build date and time
4303of the current Python interpreter instance, for example
4304
Guido van Rossum09270b51997-08-15 18:57:32 +00004305\begin{verbatim}
4306"#67, Aug 1 1997, 22:34:28"
4307\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004308
4309The returned string points into static storage; the caller should not
4310modify its value. The value is available to Python code as part of
4311the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004312\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004313\end{cfuncdesc}
4314
4315\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
Fred Drake659ebfa2000-04-03 15:42:13 +00004316Set \code{sys.argv} based on \var{argc} and \var{argv}. These
4317parameters are similar to those passed to the program's
4318\cfunction{main()}\ttindex{main()} function with the difference that
4319the first entry should refer to the script file to be executed rather
4320than the executable hosting the Python interpreter. If there isn't a
4321script that will be run, the first entry in \var{argv} can be an empty
4322string. If this function fails to initialize \code{sys.argv}, a fatal
4323condition is signalled using
4324\cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
4325\withsubitem{(in module sys)}{\ttindex{argv}}
4326% XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
4327% check w/ Guido.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004328\end{cfuncdesc}
4329
4330% XXX Other PySys thingies (doesn't really belong in this chapter)
4331
Fred Drakeefd146c1999-02-15 15:30:45 +00004332\section{Thread State and the Global Interpreter Lock
4333 \label{threads}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004334
Fred Drake659ebfa2000-04-03 15:42:13 +00004335\index{global interpreter lock}
4336\index{interpreter lock}
4337\index{lock, interpreter}
4338
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004339The Python interpreter is not fully thread safe. In order to support
4340multi-threaded Python programs, there's a global lock that must be
4341held by the current thread before it can safely access Python objects.
4342Without the lock, even the simplest operations could cause problems in
Fred Drake7baf3d41998-02-20 00:45:52 +00004343a multi-threaded program: for example, when two threads simultaneously
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004344increment the reference count of the same object, the reference count
4345could end up being incremented only once instead of twice.
4346
4347Therefore, the rule exists that only the thread that has acquired the
4348global interpreter lock may operate on Python objects or call Python/C
4349API functions. In order to support multi-threaded Python programs,
Fred Drake659ebfa2000-04-03 15:42:13 +00004350the interpreter regularly releases and reacquires the lock --- by
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004351default, every ten bytecode instructions (this can be changed with
Fred Drake659ebfa2000-04-03 15:42:13 +00004352\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
Fred Drakee058b4f1998-02-16 06:15:35 +00004353\function{sys.setcheckinterval()}). The lock is also released and
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004354reacquired around potentially blocking I/O operations like reading or
4355writing a file, so that other threads can run while the thread that
4356requests the I/O is waiting for the I/O operation to complete.
4357
4358The Python interpreter needs to keep some bookkeeping information
Fred Drakee058b4f1998-02-16 06:15:35 +00004359separate per thread --- for this it uses a data structure called
Fred Drake659ebfa2000-04-03 15:42:13 +00004360\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
43611.5; in earlier versions, such state was stored in global variables,
4362and switching threads could cause problems. In particular, exception
4363handling is now thread safe, when the application uses
4364\withsubitem{(in module sys)}{\ttindex{exc_info()}}
4365\function{sys.exc_info()} to access the exception last raised in the
4366current thread.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004367
4368There's one global variable left, however: the pointer to the current
Fred Drake659ebfa2000-04-03 15:42:13 +00004369\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
4370thread packages have a way to store ``per-thread global data,''
4371Python's internal platform independent thread abstraction doesn't
4372support this yet. Therefore, the current thread state must be
4373manipulated explicitly.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004374
4375This is easy enough in most cases. Most code manipulating the global
4376interpreter lock has the following simple structure:
4377
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004378\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004379Save the thread state in a local variable.
4380Release the interpreter lock.
4381...Do some blocking I/O operation...
4382Reacquire the interpreter lock.
4383Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004384\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004385
4386This is so common that a pair of macros exists to simplify it:
4387
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004388\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004389Py_BEGIN_ALLOW_THREADS
4390...Do some blocking I/O operation...
4391Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004392\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004393
Fred Drake659ebfa2000-04-03 15:42:13 +00004394The \code{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS} macro
4395opens a new block and declares a hidden local variable; the
4396\code{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS} macro closes
Fred Drakee058b4f1998-02-16 06:15:35 +00004397the block. Another advantage of using these two macros is that when
4398Python is compiled without thread support, they are defined empty,
4399thus saving the thread state and lock manipulations.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004400
4401When thread support is enabled, the block above expands to the
4402following code:
4403
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004404\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004405 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004406
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004407 _save = PyEval_SaveThread();
4408 ...Do some blocking I/O operation...
4409 PyEval_RestoreThread(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004410\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004411
4412Using even lower level primitives, we can get roughly the same effect
4413as follows:
4414
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004415\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004416 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004417
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004418 _save = PyThreadState_Swap(NULL);
4419 PyEval_ReleaseLock();
4420 ...Do some blocking I/O operation...
4421 PyEval_AcquireLock();
4422 PyThreadState_Swap(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004423\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004424
4425There are some subtle differences; in particular,
Fred Drake659ebfa2000-04-03 15:42:13 +00004426\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
4427and restores the value of the global variable
4428\cdata{errno}\ttindex{errno}, since the lock manipulation does not
Fred Drakef8830d11998-04-23 14:06:01 +00004429guarantee that \cdata{errno} is left alone. Also, when thread support
Fred Drake659ebfa2000-04-03 15:42:13 +00004430is disabled,
4431\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
Fred Drakee058b4f1998-02-16 06:15:35 +00004432\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
Fred Drake659ebfa2000-04-03 15:42:13 +00004433case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
4434\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
4435available. This is done so that dynamically loaded extensions
4436compiled with thread support enabled can be loaded by an interpreter
4437that was compiled with disabled thread support.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004438
4439The global interpreter lock is used to protect the pointer to the
4440current thread state. When releasing the lock and saving the thread
4441state, the current thread state pointer must be retrieved before the
4442lock is released (since another thread could immediately acquire the
4443lock and store its own thread state in the global variable).
Fred Drakeffe58ca2000-09-29 17:31:54 +00004444Conversely, when acquiring the lock and restoring the thread state,
4445the lock must be acquired before storing the thread state pointer.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004446
4447Why am I going on with so much detail about this? Because when
Fred Drake659ebfa2000-04-03 15:42:13 +00004448threads are created from C, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004449lock, nor is there a thread state data structure for them. Such
4450threads must bootstrap themselves into existence, by first creating a
4451thread state data structure, then acquiring the lock, and finally
4452storing their thread state pointer, before they can start using the
4453Python/C API. When they are done, they should reset the thread state
4454pointer, release the lock, and finally free their thread state data
4455structure.
4456
4457When creating a thread data structure, you need to provide an
4458interpreter state data structure. The interpreter state data
4459structure hold global data that is shared by all threads in an
4460interpreter, for example the module administration
4461(\code{sys.modules}). Depending on your needs, you can either create
4462a new interpreter state data structure, or share the interpreter state
4463data structure used by the Python main thread (to access the latter,
Fred Drakef8830d11998-04-23 14:06:01 +00004464you must obtain the thread state and access its \member{interp} member;
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004465this must be done by a thread that is created by Python or by the main
4466thread after Python is initialized).
4467
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004468
4469\begin{ctypedesc}{PyInterpreterState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004470This data structure represents the state shared by a number of
4471cooperating threads. Threads belonging to the same interpreter
4472share their module administration and a few other internal items.
4473There are no public members in this structure.
4474
4475Threads belonging to different interpreters initially share nothing,
4476except process state like available memory, open file descriptors and
4477such. The global interpreter lock is also shared by all threads,
4478regardless of to which interpreter they belong.
4479\end{ctypedesc}
4480
4481\begin{ctypedesc}{PyThreadState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004482This data structure represents the state of a single thread. The only
Fred Drakef8830d11998-04-23 14:06:01 +00004483public data member is \ctype{PyInterpreterState *}\member{interp},
4484which points to this thread's interpreter state.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004485\end{ctypedesc}
4486
4487\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
4488Initialize and acquire the global interpreter lock. It should be
4489called in the main thread before creating a second thread or engaging
Fred Drakee058b4f1998-02-16 06:15:35 +00004490in any other thread operations such as
Fred Drake659ebfa2000-04-03 15:42:13 +00004491\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
4492\code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
4493It is not needed before calling
4494\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
4495\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004496
4497This is a no-op when called for a second time. It is safe to call
Fred Drake659ebfa2000-04-03 15:42:13 +00004498this function before calling
4499\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004500
4501When only the main thread exists, no lock operations are needed. This
4502is a common situation (most Python programs do not use threads), and
4503the lock operations slow the interpreter down a bit. Therefore, the
4504lock is not created initially. This situation is equivalent to having
4505acquired the lock: when there is only a single thread, all object
4506accesses are safe. Therefore, when this function initializes the
Fred Drake4de05a91998-02-16 14:25:26 +00004507lock, it also acquires it. Before the Python
4508\module{thread}\refbimodindex{thread} module creates a new thread,
4509knowing that either it has the lock or the lock hasn't been created
4510yet, it calls \cfunction{PyEval_InitThreads()}. When this call
4511returns, it is guaranteed that the lock has been created and that it
4512has acquired it.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004513
4514It is \strong{not} safe to call this function when it is unknown which
4515thread (if any) currently has the global interpreter lock.
4516
4517This function is not available when thread support is disabled at
4518compile time.
4519\end{cfuncdesc}
4520
Guido van Rossum4a944d71997-08-14 20:35:38 +00004521\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004522Acquire the global interpreter lock. The lock must have been created
4523earlier. If this thread already has the lock, a deadlock ensues.
4524This function is not available when thread support is disabled at
4525compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004526\end{cfuncdesc}
4527
4528\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004529Release the global interpreter lock. The lock must have been created
4530earlier. This function is not available when thread support is
Fred Drakee058b4f1998-02-16 06:15:35 +00004531disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004532\end{cfuncdesc}
4533
4534\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004535Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004536state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004537have been created earlier. If this thread already has the lock,
4538deadlock ensues. This function is not available when thread support
Fred Drakee058b4f1998-02-16 06:15:35 +00004539is disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004540\end{cfuncdesc}
4541
4542\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004543Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004544interpreter lock. The lock must have been created earlier and must be
4545held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004546be \NULL{}, is only used to check that it represents the current
Fred Drakee058b4f1998-02-16 06:15:35 +00004547thread state --- if it isn't, a fatal error is reported. This
4548function is not available when thread support is disabled at compile
4549time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004550\end{cfuncdesc}
4551
Fred Drakec6fa34e1998-04-02 06:47:24 +00004552\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004553Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004554support is enabled) and reset the thread state to \NULL{},
4555returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004556the lock has been created, the current thread must have acquired it.
4557(This function is available even when thread support is disabled at
4558compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004559\end{cfuncdesc}
4560
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004561\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004562Acquire the interpreter lock (if it has been created and thread
4563support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004564must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004565thread must not have acquired it, otherwise deadlock ensues. (This
4566function is available even when thread support is disabled at compile
4567time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004568\end{cfuncdesc}
4569
Fred Drake659ebfa2000-04-03 15:42:13 +00004570The following macros are normally used without a trailing semicolon;
4571look for example usage in the Python source distribution.
4572
4573\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004574This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004575\samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004576Note that it contains an opening brace; it must be matched with a
4577following \code{Py_END_ALLOW_THREADS} macro. See above for further
4578discussion of this macro. It is a no-op when thread support is
4579disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004580\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004581
Fred Drake659ebfa2000-04-03 15:42:13 +00004582\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004583This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004584\samp{PyEval_RestoreThread(_save); \}}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004585Note that it contains a closing brace; it must be matched with an
4586earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
4587discussion of this macro. It is a no-op when thread support is
4588disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004589\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004590
Fred Drake659ebfa2000-04-03 15:42:13 +00004591\begin{csimplemacrodesc}{Py_BEGIN_BLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004592This macro expands to \samp{PyEval_RestoreThread(_save);} i.e. it
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004593is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
4594brace. It is a no-op when thread support is disabled at compile
4595time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004596\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004597
Fred Drake659ebfa2000-04-03 15:42:13 +00004598\begin{csimplemacrodesc}{Py_BEGIN_UNBLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004599This macro expands to \samp{_save = PyEval_SaveThread();} i.e. it is
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004600equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
4601and variable declaration. It is a no-op when thread support is
4602disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004603\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004604
4605All of the following functions are only available when thread support
4606is enabled at compile time, and must be called only when the
Fred Drake9d20ac31998-02-16 15:27:08 +00004607interpreter lock has been created.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004608
Fred Drakec6fa34e1998-04-02 06:47:24 +00004609\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004610Create a new interpreter state object. The interpreter lock need not
4611be held, but may be held if it is necessary to serialize calls to this
4612function.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004613\end{cfuncdesc}
4614
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004615\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
4616Reset all information in an interpreter state object. The interpreter
4617lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004618\end{cfuncdesc}
4619
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004620\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
4621Destroy an interpreter state object. The interpreter lock need not be
4622held. The interpreter state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004623call to \cfunction{PyInterpreterState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004624\end{cfuncdesc}
4625
Fred Drakec6fa34e1998-04-02 06:47:24 +00004626\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004627Create a new thread state object belonging to the given interpreter
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004628object. The interpreter lock need not be held, but may be held if it
4629is necessary to serialize calls to this function.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004630\end{cfuncdesc}
4631
4632\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
4633Reset all information in a thread state object. The interpreter lock
4634must be held.
4635\end{cfuncdesc}
4636
4637\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
4638Destroy a thread state object. The interpreter lock need not be
4639held. The thread state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004640call to \cfunction{PyThreadState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004641\end{cfuncdesc}
4642
Fred Drakec6fa34e1998-04-02 06:47:24 +00004643\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004644Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004645When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004646error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004647\end{cfuncdesc}
4648
Fred Drakec6fa34e1998-04-02 06:47:24 +00004649\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004650Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004651argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004652must be held.
4653\end{cfuncdesc}
4654
Fred Drake24e62192001-05-21 15:56:55 +00004655\begin{cfuncdesc}{PyObject*}{PyThreadState_GetDict}{}
4656Return a dictionary in which extensions can store thread-specific
4657state information. Each extension should use a unique key to use to
4658store state in the dictionary. If this function returns \NULL, an
4659exception has been raised and the caller should allow it to
4660propogate.
4661\end{cfuncdesc}
4662
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004663
Fred Drake659ebfa2000-04-03 15:42:13 +00004664\chapter{Memory Management \label{memory}}
4665\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
4666
4667
4668\section{Overview \label{memoryOverview}}
4669
4670Memory management in Python involves a private heap containing all
4671Python objects and data structures. The management of this private
4672heap is ensured internally by the \emph{Python memory manager}. The
4673Python memory manager has different components which deal with various
4674dynamic storage management aspects, like sharing, segmentation,
4675preallocation or caching.
4676
4677At the lowest level, a raw memory allocator ensures that there is
4678enough room in the private heap for storing all Python-related data
4679by interacting with the memory manager of the operating system. On top
4680of the raw memory allocator, several object-specific allocators
4681operate on the same heap and implement distinct memory management
4682policies adapted to the peculiarities of every object type. For
4683example, integer objects are managed differently within the heap than
4684strings, tuples or dictionaries because integers imply different
4685storage requirements and speed/space tradeoffs. The Python memory
4686manager thus delegates some of the work to the object-specific
4687allocators, but ensures that the latter operate within the bounds of
4688the private heap.
4689
4690It is important to understand that the management of the Python heap
4691is performed by the interpreter itself and that the user has no
4692control on it, even if she regularly manipulates object pointers to
4693memory blocks inside that heap. The allocation of heap space for
4694Python objects and other internal buffers is performed on demand by
4695the Python memory manager through the Python/C API functions listed in
4696this document.
4697
4698To avoid memory corruption, extension writers should never try to
4699operate on Python objects with the functions exported by the C
4700library: \cfunction{malloc()}\ttindex{malloc()},
4701\cfunction{calloc()}\ttindex{calloc()},
4702\cfunction{realloc()}\ttindex{realloc()} and
4703\cfunction{free()}\ttindex{free()}. This will result in
4704mixed calls between the C allocator and the Python memory manager
4705with fatal consequences, because they implement different algorithms
4706and operate on different heaps. However, one may safely allocate and
4707release memory blocks with the C library allocator for individual
4708purposes, as shown in the following example:
4709
4710\begin{verbatim}
4711 PyObject *res;
4712 char *buf = (char *) malloc(BUFSIZ); /* for I/O */
4713
4714 if (buf == NULL)
4715 return PyErr_NoMemory();
4716 ...Do some I/O operation involving buf...
4717 res = PyString_FromString(buf);
4718 free(buf); /* malloc'ed */
4719 return res;
4720\end{verbatim}
4721
4722In this example, the memory request for the I/O buffer is handled by
4723the C library allocator. The Python memory manager is involved only
4724in the allocation of the string object returned as a result.
4725
4726In most situations, however, it is recommended to allocate memory from
4727the Python heap specifically because the latter is under control of
4728the Python memory manager. For example, this is required when the
4729interpreter is extended with new object types written in C. Another
4730reason for using the Python heap is the desire to \emph{inform} the
4731Python memory manager about the memory needs of the extension module.
4732Even when the requested memory is used exclusively for internal,
4733highly-specific purposes, delegating all memory requests to the Python
4734memory manager causes the interpreter to have a more accurate image of
4735its memory footprint as a whole. Consequently, under certain
4736circumstances, the Python memory manager may or may not trigger
4737appropriate actions, like garbage collection, memory compaction or
4738other preventive procedures. Note that by using the C library
4739allocator as shown in the previous example, the allocated memory for
4740the I/O buffer escapes completely the Python memory manager.
4741
4742
4743\section{Memory Interface \label{memoryInterface}}
4744
4745The following function sets, modeled after the ANSI C standard, are
4746available for allocating and releasing memory from the Python heap:
4747
4748
Fred Drake7d45d342000-08-11 17:07:32 +00004749\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
4750Allocates \var{n} bytes and returns a pointer of type \ctype{void*} to
Fred Drake659ebfa2000-04-03 15:42:13 +00004751the allocated memory, or \NULL{} if the request fails. Requesting zero
4752bytes returns a non-\NULL{} pointer.
4753\end{cfuncdesc}
4754
Fred Drake7d45d342000-08-11 17:07:32 +00004755\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004756Resizes the memory block pointed to by \var{p} to \var{n} bytes. The
4757contents will be unchanged to the minimum of the old and the new
4758sizes. If \var{p} is \NULL{}, the call is equivalent to
4759\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the memory block
4760is resized but is not freed, and the returned pointer is non-\NULL{}.
4761Unless \var{p} is \NULL{}, it must have been returned by a previous
4762call to \cfunction{PyMem_Malloc()} or \cfunction{PyMem_Realloc()}.
4763\end{cfuncdesc}
4764
Fred Drake7d45d342000-08-11 17:07:32 +00004765\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004766Frees the memory block pointed to by \var{p}, which must have been
4767returned by a previous call to \cfunction{PyMem_Malloc()} or
4768\cfunction{PyMem_Realloc()}. Otherwise, or if
4769\cfunction{PyMem_Free(p)} has been called before, undefined behaviour
4770occurs. If \var{p} is \NULL{}, no operation is performed.
4771\end{cfuncdesc}
4772
Fred Drake659ebfa2000-04-03 15:42:13 +00004773The following type-oriented macros are provided for convenience. Note
4774that \var{TYPE} refers to any C type.
4775
Fred Drakef913e542000-09-12 20:17:17 +00004776\begin{cfuncdesc}{\var{TYPE}*}{PyMem_New}{TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004777Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
4778sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
4779\ctype{\var{TYPE}*}.
4780\end{cfuncdesc}
4781
Fred Drakef913e542000-09-12 20:17:17 +00004782\begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004783Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
4784to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
4785cast to \ctype{\var{TYPE}*}.
4786\end{cfuncdesc}
4787
Fred Drakef913e542000-09-12 20:17:17 +00004788\begin{cfuncdesc}{void}{PyMem_Del}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004789Same as \cfunction{PyMem_Free()}.
4790\end{cfuncdesc}
4791
Fred Drakef913e542000-09-12 20:17:17 +00004792In addition, the following macro sets are provided for calling the
4793Python memory allocator directly, without involving the C API functions
4794listed above. However, note that their use does not preserve binary
4795compatibility accross Python versions and is therefore deprecated in
4796extension modules.
4797
4798\cfunction{PyMem_MALLOC()}, \cfunction{PyMem_REALLOC()}, \cfunction{PyMem_FREE()}.
4799
4800\cfunction{PyMem_NEW()}, \cfunction{PyMem_RESIZE()}, \cfunction{PyMem_DEL()}.
4801
Fred Drake659ebfa2000-04-03 15:42:13 +00004802
4803\section{Examples \label{memoryExamples}}
4804
4805Here is the example from section \ref{memoryOverview}, rewritten so
4806that the I/O buffer is allocated from the Python heap by using the
4807first function set:
4808
4809\begin{verbatim}
4810 PyObject *res;
4811 char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
4812
4813 if (buf == NULL)
4814 return PyErr_NoMemory();
4815 /* ...Do some I/O operation involving buf... */
4816 res = PyString_FromString(buf);
4817 PyMem_Free(buf); /* allocated with PyMem_Malloc */
4818 return res;
4819\end{verbatim}
4820
Fred Drakef913e542000-09-12 20:17:17 +00004821The same code using the type-oriented function set:
Fred Drake659ebfa2000-04-03 15:42:13 +00004822
4823\begin{verbatim}
4824 PyObject *res;
Fred Drakef913e542000-09-12 20:17:17 +00004825 char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
Fred Drake659ebfa2000-04-03 15:42:13 +00004826
4827 if (buf == NULL)
4828 return PyErr_NoMemory();
4829 /* ...Do some I/O operation involving buf... */
4830 res = PyString_FromString(buf);
Fred Drakef913e542000-09-12 20:17:17 +00004831 PyMem_Del(buf); /* allocated with PyMem_New */
Fred Drake659ebfa2000-04-03 15:42:13 +00004832 return res;
4833\end{verbatim}
4834
Fred Drakef913e542000-09-12 20:17:17 +00004835Note that in the two examples above, the buffer is always
4836manipulated via functions belonging to the same set. Indeed, it
Fred Drake659ebfa2000-04-03 15:42:13 +00004837is required to use the same memory API family for a given
4838memory block, so that the risk of mixing different allocators is
4839reduced to a minimum. The following code sequence contains two errors,
4840one of which is labeled as \emph{fatal} because it mixes two different
4841allocators operating on different heaps.
4842
4843\begin{verbatim}
Fred Drakef913e542000-09-12 20:17:17 +00004844char *buf1 = PyMem_New(char, BUFSIZ);
Fred Drake659ebfa2000-04-03 15:42:13 +00004845char *buf2 = (char *) malloc(BUFSIZ);
4846char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
4847...
Fred Drakef913e542000-09-12 20:17:17 +00004848PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004849free(buf2); /* Right -- allocated via malloc() */
Fred Drakef913e542000-09-12 20:17:17 +00004850free(buf1); /* Fatal -- should be PyMem_Del() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004851\end{verbatim}
4852
4853In addition to the functions aimed at handling raw memory blocks from
4854the Python heap, objects in Python are allocated and released with
Fred Drakef913e542000-09-12 20:17:17 +00004855\cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()} and
4856\cfunction{PyObject_Del()}, or with their corresponding macros
4857\cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()} and
Fred Drakee06f0f92000-06-30 15:52:39 +00004858\cfunction{PyObject_DEL()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004859
Fred Drakee06f0f92000-06-30 15:52:39 +00004860These will be explained in the next chapter on defining and
4861implementing new object types in C.
Fred Drake659ebfa2000-04-03 15:42:13 +00004862
4863
Fred Drakeefd146c1999-02-15 15:30:45 +00004864\chapter{Defining New Object Types \label{newTypes}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004865
Fred Drakec6fa34e1998-04-02 06:47:24 +00004866\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00004867\end{cfuncdesc}
4868
Fred Drakef913e542000-09-12 20:17:17 +00004869\begin{cfuncdesc}{PyVarObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00004870\end{cfuncdesc}
4871
Fred Drakef913e542000-09-12 20:17:17 +00004872\begin{cfuncdesc}{void}{_PyObject_Del}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004873\end{cfuncdesc}
4874
Fred Drakef913e542000-09-12 20:17:17 +00004875\begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00004876 PyTypeObject *type}
Fred Drakef913e542000-09-12 20:17:17 +00004877\end{cfuncdesc}
4878
4879\begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op,
Marc-André Lemburga544ea22001-01-17 18:04:31 +00004880 PyTypeObject *type, int size}
Fred Drakef913e542000-09-12 20:17:17 +00004881\end{cfuncdesc}
4882
4883\begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type}
4884\end{cfuncdesc}
4885
4886\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type,
4887 int size}
4888\end{cfuncdesc}
4889
4890\begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op}
4891\end{cfuncdesc}
4892
4893\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW}{TYPE, PyTypeObject *type}
4894\end{cfuncdesc}
4895
4896\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
4897 int size}
4898\end{cfuncdesc}
4899
4900\begin{cfuncdesc}{void}{PyObject_DEL}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004901\end{cfuncdesc}
4902
Fred Drakeee814bf2000-11-28 22:34:32 +00004903\begin{cfuncdesc}{PyObject*}{Py_InitModule}{char *name,
4904 PyMethodDef *methods}
4905 Create a new module object based on a name and table of functions,
4906 returning the new module object.
4907\end{cfuncdesc}
4908
4909\begin{cfuncdesc}{PyObject*}{Py_InitModule3}{char *name,
4910 PyMethodDef *methods,
4911 char *doc}
4912 Create a new module object based on a name and table of functions,
4913 returning the new module object. If \var{doc} is non-\NULL, it will
4914 be used to define the docstring for the module.
4915\end{cfuncdesc}
4916
4917\begin{cfuncdesc}{PyObject*}{Py_InitModule4}{char *name,
4918 PyMethodDef *methods,
4919 char *doc, PyObject *self,
4920 int apiver}
4921 Create a new module object based on a name and table of functions,
4922 returning the new module object. If \var{doc} is non-\NULL, it will
4923 be used to define the docstring for the module. If \var{self} is
4924 non-\NULL, it will passed to the functions of the module as their
4925 (otherwise \NULL) first parameter. (This was added as an
4926 experimental feature, and there are no known uses in the current
4927 version of Python.) For \var{apiver}, the only value which should
4928 be passed is defined by the constant \constant{PYTHON_API_VERSION}.
4929
4930 \strong{Note:} Most uses of this function should probably be using
4931 the \cfunction{Py_InitModule3()} instead; only use this if you are
4932 sure you need it.
4933\end{cfuncdesc}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00004934
4935PyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse
4936
4937Py_BuildValue
Guido van Rossumae110af1997-05-22 20:11:52 +00004938
Fred Drake659ebfa2000-04-03 15:42:13 +00004939DL_IMPORT
4940
Fred Drake659ebfa2000-04-03 15:42:13 +00004941_Py_NoneStruct
4942
4943
4944\section{Common Object Structures \label{common-structs}}
4945
Guido van Rossumae110af1997-05-22 20:11:52 +00004946PyObject, PyVarObject
4947
4948PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
4949
4950Typedefs:
4951unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
4952intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
Guido van Rossumae110af1997-05-22 20:11:52 +00004953destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
4954setattrofunc, cmpfunc, reprfunc, hashfunc
4955
Fred Drakea8455ab2000-06-16 19:58:42 +00004956\begin{ctypedesc}{PyCFunction}
4957Type of the functions used to implement most Python callables in C.
4958\end{ctypedesc}
4959
4960\begin{ctypedesc}{PyMethodDef}
4961Structure used to describe a method of an extension type. This
4962structure has four fields:
4963
4964\begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
4965 \lineiii{ml_name}{char *}{name of the method}
4966 \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
4967 \lineiii{ml_flags}{int}{flag bits indicating how the call should be
4968 constructed}
4969 \lineiii{ml_doc}{char *}{points to the contents of the docstring}
4970\end{tableiii}
4971\end{ctypedesc}
4972
4973\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef[] table,
4974 PyObject *ob, char *name}
4975Return a bound method object for an extension type implemented in C.
4976This function also handles the special attribute \member{__methods__},
4977returning a list of all the method names defined in \var{table}.
4978\end{cfuncdesc}
4979
Fred Drake659ebfa2000-04-03 15:42:13 +00004980
4981\section{Mapping Object Structures \label{mapping-structs}}
4982
4983\begin{ctypedesc}{PyMappingMethods}
4984Structure used to hold pointers to the functions used to implement the
4985mapping protocol for an extension type.
4986\end{ctypedesc}
4987
4988
4989\section{Number Object Structures \label{number-structs}}
4990
4991\begin{ctypedesc}{PyNumberMethods}
4992Structure used to hold pointers to the functions an extension type
4993uses to implement the number protocol.
4994\end{ctypedesc}
4995
4996
4997\section{Sequence Object Structures \label{sequence-structs}}
4998
4999\begin{ctypedesc}{PySequenceMethods}
5000Structure used to hold pointers to the functions which an object uses
5001to implement the sequence protocol.
5002\end{ctypedesc}
5003
5004
5005\section{Buffer Object Structures \label{buffer-structs}}
5006\sectionauthor{Greg J. Stein}{greg@lyra.org}
5007
5008The buffer interface exports a model where an object can expose its
5009internal data as a set of chunks of data, where each chunk is
5010specified as a pointer/length pair. These chunks are called
5011\dfn{segments} and are presumed to be non-contiguous in memory.
5012
5013If an object does not export the buffer interface, then its
5014\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
5015should be \NULL{}. Otherwise, the \member{tp_as_buffer} will point to
5016a \ctype{PyBufferProcs} structure.
5017
5018\strong{Note:} It is very important that your
Fred Drakec392b572001-03-21 22:15:01 +00005019\ctype{PyTypeObject} structure uses \constant{Py_TPFLAGS_DEFAULT} for
5020the value of the \member{tp_flags} member rather than \code{0}. This
Fred Drake659ebfa2000-04-03 15:42:13 +00005021tells the Python runtime that your \ctype{PyBufferProcs} structure
5022contains the \member{bf_getcharbuffer} slot. Older versions of Python
5023did not have this member, so a new Python interpreter using an old
5024extension needs to be able to test for its presence before using it.
5025
5026\begin{ctypedesc}{PyBufferProcs}
5027Structure used to hold the function pointers which define an
5028implementation of the buffer protocol.
5029
5030The first slot is \member{bf_getreadbuffer}, of type
5031\ctype{getreadbufferproc}. If this slot is \NULL{}, then the object
5032does not support reading from the internal data. This is
5033non-sensical, so implementors should fill this in, but callers should
5034test that the slot contains a non-\NULL{} value.
5035
5036The next slot is \member{bf_getwritebuffer} having type
5037\ctype{getwritebufferproc}. This slot may be \NULL{} if the object
5038does not allow writing into its returned buffers.
5039
5040The third slot is \member{bf_getsegcount}, with type
5041\ctype{getsegcountproc}. This slot must not be \NULL{} and is used to
5042inform the caller how many segments the object contains. Simple
5043objects such as \ctype{PyString_Type} and
5044\ctype{PyBuffer_Type} objects contain a single segment.
5045
5046The last slot is \member{bf_getcharbuffer}, of type
5047\ctype{getcharbufferproc}. This slot will only be present if the
Fred Drakec392b572001-03-21 22:15:01 +00005048\constant{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
Fred Drake659ebfa2000-04-03 15:42:13 +00005049\member{tp_flags} field of the object's \ctype{PyTypeObject}. Before using
5050this slot, the caller should test whether it is present by using the
5051\cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()} function.
5052If present, it may be \NULL, indicating that the object's contents
5053cannot be used as \emph{8-bit characters}.
5054The slot function may also raise an error if the object's contents
5055cannot be interpreted as 8-bit characters. For example, if the object
5056is an array which is configured to hold floating point values, an
5057exception may be raised if a caller attempts to use
5058\member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
5059This notion of exporting the internal buffers as ``text'' is used to
5060distinguish between objects that are binary in nature, and those which
5061have character-based content.
5062
5063\strong{Note:} The current policy seems to state that these characters
5064may be multi-byte characters. This implies that a buffer size of
5065\var{N} does not mean there are \var{N} characters present.
5066\end{ctypedesc}
5067
5068\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
5069Flag bit set in the type structure to indicate that the
5070\member{bf_getcharbuffer} slot is known. This being set does not
5071indicate that the object supports the buffer interface or that the
5072\member{bf_getcharbuffer} slot is non-\NULL.
5073\end{datadesc}
5074
5075\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
5076 (PyObject *self, int segment, void **ptrptr)}
5077Return a pointer to a readable segment of the buffer. This function
5078is allowed to raise an exception, in which case it must return
5079\code{-1}. The \var{segment} which is passed must be zero or
5080positive, and strictly less than the number of segments returned by
Greg Stein4d4d0032001-04-07 16:14:49 +00005081the \member{bf_getsegcount} slot function. On success, it returns the
5082length of the buffer memory, and sets \code{*\var{ptrptr}} to a
5083pointer to that memory.
Fred Drake659ebfa2000-04-03 15:42:13 +00005084\end{ctypedesc}
5085
5086\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
5087 (PyObject *self, int segment, void **ptrptr)}
Greg Stein4d4d0032001-04-07 16:14:49 +00005088Return a pointer to a writable memory buffer in \code{*\var{ptrptr}},
5089and the length of that segment as the function return value.
5090The memory buffer must correspond to buffer segment \var{segment}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00005091Must return \code{-1} and set an exception on error.
5092\exception{TypeError} should be raised if the object only supports
5093read-only buffers, and \exception{SystemError} should be raised when
5094\var{segment} specifies a segment that doesn't exist.
5095% Why doesn't it raise ValueError for this one?
Fred Drake659ebfa2000-04-03 15:42:13 +00005096% GJS: because you shouldn't be calling it with an invalid
5097% segment. That indicates a blatant programming error in the C
5098% code.
Fred Drake58c5a2a1999-08-04 13:13:24 +00005099\end{ctypedesc}
5100
Fred Drake659ebfa2000-04-03 15:42:13 +00005101\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
5102 (PyObject *self, int *lenp)}
5103Return the number of memory segments which comprise the buffer. If
5104\var{lenp} is not \NULL, the implementation must report the sum of the
5105sizes (in bytes) of all segments in \code{*\var{lenp}}.
5106The function cannot fail.
5107\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00005108
Fred Drake659ebfa2000-04-03 15:42:13 +00005109\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
5110 (PyObject *self, int segment, const char **ptrptr)}
5111\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00005112
Guido van Rossumae110af1997-05-22 20:11:52 +00005113
Fred Drakec392b572001-03-21 22:15:01 +00005114\section{Supporting Cyclic Garbarge Collection
5115 \label{supporting-cycle-detection}}
5116
5117Python's support for detecting and collecting garbage which involves
5118circular references requires support from object types which are
5119``containers'' for other objects which may also be containers. Types
5120which do not store references to other objects, or which only store
5121references to atomic types (such as numbers or strings), do not need
5122to provide any explicit support for garbage collection.
5123
5124To create a container type, the \member{tp_flags} field of the type
5125object must include the \constant{Py_TPFLAGS_GC} and provide an
Fred Drakee28d8ae2001-03-22 16:30:17 +00005126implementation of the \member{tp_traverse} handler. The computed
5127value of the \member{tp_basicsize} field must include
5128\constant{PyGC_HEAD_SIZE} as well. If instances of the type are
5129mutable, a \member{tp_clear} implementation must also be provided.
Fred Drakec392b572001-03-21 22:15:01 +00005130
5131\begin{datadesc}{Py_TPFLAGS_GC}
5132 Objects with a type with this flag set must conform with the rules
5133 documented here. For convenience these objects will be referred to
5134 as container objects.
5135\end{datadesc}
5136
5137\begin{datadesc}{PyGC_HEAD_SIZE}
5138 Extra memory needed for the garbage collector. Container objects
5139 must include this in the calculation of their tp_basicsize. If the
5140 collector is disabled at compile time then this is \code{0}.
5141\end{datadesc}
5142
Fred Drakee28d8ae2001-03-22 16:30:17 +00005143Constructors for container types must conform to two rules:
5144
5145\begin{enumerate}
5146\item The memory for the object must be allocated using
5147 \cfunction{PyObject_New()} or \cfunction{PyObject_VarNew()}.
5148
5149\item Once all the fields which may contain references to other
5150 containers are initialized, it must call
5151 \cfunction{PyObject_GC_Init()}.
5152\end{enumerate}
5153
Fred Drakec392b572001-03-21 22:15:01 +00005154\begin{cfuncdesc}{void}{PyObject_GC_Init}{PyObject *op}
5155 Adds the object \var{op} to the set of container objects tracked by
5156 the collector. The collector can run at unexpected times so objects
5157 must be valid while being tracked. This should be called once all
5158 the fields followed by the \member{tp_traverse} handler become valid,
5159 usually near the end of the constructor.
5160\end{cfuncdesc}
5161
Fred Drakee28d8ae2001-03-22 16:30:17 +00005162Similarly, the deallocator for the object must conform to a similar
5163pair of rules:
5164
5165\begin{enumerate}
5166\item Before fields which refer to other containers are invalidated,
5167 \cfunction{PyObject_GC_Fini()} must be called.
5168
5169\item The object's memory must be deallocated using
5170 \cfunction{PyObject_Del()}.
5171\end{enumerate}
5172
Fred Drakec392b572001-03-21 22:15:01 +00005173\begin{cfuncdesc}{void}{PyObject_GC_Fini}{PyObject *op}
5174 Remove the object \var{op} from the set of container objects tracked
5175 by the collector. Note that \cfunction{PyObject_GC_Init()} can be
5176 called again on this object to add it back to the set of tracked
5177 objects. The deallocator (\member{tp_dealloc} handler) should call
5178 this for the object before any of the fields used by the
5179 \member{tp_traverse} handler become invalid.
Fred Drake8f6df462001-03-23 17:42:09 +00005180
5181 \strong{Note:} Any container which may be referenced from another
5182 object reachable by the collector must itself be tracked by the
5183 collector, so it is generally not safe to call this function
5184 anywhere but in the object's deallocator.
Fred Drakec392b572001-03-21 22:15:01 +00005185\end{cfuncdesc}
5186
5187The \member{tp_traverse} handler accepts a function parameter of this
5188type:
5189
5190\begin{ctypedesc}[visitproc]{int (*visitproc)(PyObject *object, void *arg)}
5191 Type of the visitor function passed to the \member{tp_traverse}
5192 handler. The function should be called with an object to traverse
5193 as \var{object} and the third parameter to the \member{tp_traverse}
5194 handler as \var{arg}.
5195\end{ctypedesc}
5196
5197The \member{tp_traverse} handler must have the following type:
5198
5199\begin{ctypedesc}[traverseproc]{int (*traverseproc)(PyObject *self,
5200 visitproc visit, void *arg)}
5201 Traversal function for a container object. Implementations must
5202 call the \var{visit} function for each object directly contained by
5203 \var{self}, with the parameters to \var{visit} being the contained
5204 object and the \var{arg} value passed to the handler. If
5205 \var{visit} returns a non-zero value then an error has occurred and
5206 that value should be returned immediately.
5207\end{ctypedesc}
5208
5209The \member{tp_clear} handler must be of the \ctype{inquiry} type, or
5210\NULL{} if the object is immutable.
5211
5212\begin{ctypedesc}[inquiry]{int (*inquiry)(PyObject *self)}
5213 Drop references that may have created reference cycles. Immutable
5214 objects do not have to define this method since they can never
5215 directly create reference cycles. Note that the object must still
5216 be valid after calling this method (i.e., don't just call
5217 \cfunction{Py_DECREF()} on a reference). The collector will call
5218 this method if it detects that this object is involved in a
5219 reference cycle.
5220\end{ctypedesc}
5221
5222
Fred Drakee28d8ae2001-03-22 16:30:17 +00005223\subsection{Example Cycle Collector Support
5224 \label{example-cycle-support}}
5225
5226This example shows only enough of the implementation of an extension
5227type to show how the garbage collector support needs to be added. It
5228shows the definition of the object structure, the
5229\member{tp_traverse}, \member{tp_clear} and \member{tp_dealloc}
5230implementations, the type structure, and a constructor --- the module
5231initialization needed to export the constructor to Python is not shown
5232as there are no special considerations there for the collector. To
5233make this interesting, assume that the module exposes ways for the
5234\member{container} field of the object to be modified. Note that
5235since no checks are made on the type of the object used to initialize
5236\member{container}, we have to assume that it may be a container.
5237
5238\begin{verbatim}
5239#include "Python.h"
5240
5241typedef struct {
5242 PyObject_HEAD
5243 PyObject *container;
5244} MyObject;
5245
5246static int
5247my_traverse(MyObject *self, visitproc visit, void *arg)
5248{
5249 if (self->container != NULL)
5250 return visit(self->container, arg);
5251 else
5252 return 0;
5253}
5254
5255static int
5256my_clear(MyObject *self)
5257{
5258 Py_XDECREF(self->container);
5259 self->container = NULL;
5260
5261 return 0;
5262}
5263
5264static void
5265my_dealloc(MyObject *self)
5266{
5267 PyObject_GC_Fini((PyObject *) self);
5268 Py_XDECREF(self->container);
5269 PyObject_Del(self);
5270}
5271\end{verbatim}
5272
5273\begin{verbatim}
5274statichere PyTypeObject
5275MyObject_Type = {
5276 PyObject_HEAD_INIT(NULL)
5277 0,
5278 "MyObject",
5279 sizeof(MyObject) + PyGC_HEAD_SIZE,
5280 0,
5281 (destructor)my_dealloc, /* tp_dealloc */
5282 0, /* tp_print */
5283 0, /* tp_getattr */
5284 0, /* tp_setattr */
5285 0, /* tp_compare */
5286 0, /* tp_repr */
5287 0, /* tp_as_number */
5288 0, /* tp_as_sequence */
5289 0, /* tp_as_mapping */
5290 0, /* tp_hash */
5291 0, /* tp_call */
5292 0, /* tp_str */
5293 0, /* tp_getattro */
5294 0, /* tp_setattro */
5295 0, /* tp_as_buffer */
5296 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC,
5297 0, /* tp_doc */
5298 (traverseproc)my_traverse, /* tp_traverse */
5299 (inquiry)my_clear, /* tp_clear */
5300 0, /* tp_richcompare */
5301 0, /* tp_weaklistoffset */
5302};
5303
5304/* This constructor should be made accessible from Python. */
5305static PyObject *
5306new_object(PyObject *unused, PyObject *args)
5307{
5308 PyObject *container = NULL;
5309 MyObject *result = NULL;
5310
5311 if (PyArg_ParseTuple(args, "|O:new_object", &container)) {
5312 result = PyObject_New(MyObject, &MyObject_Type);
5313 if (result != NULL) {
5314 result->container = container;
5315 PyObject_GC_Init();
5316 }
5317 }
5318 return (PyObject *) result;
5319}
5320\end{verbatim}
5321
5322
Fred Drake659ebfa2000-04-03 15:42:13 +00005323% \chapter{Debugging \label{debugging}}
5324%
5325% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00005326
5327
Fred Drakeed773ef2000-09-21 21:35:22 +00005328\appendix
5329\chapter{Reporting Bugs}
5330\input{reportingbugs}
5331
Marc-André Lemburga544ea22001-01-17 18:04:31 +00005332\input{api.ind} % Index -- must be last
Guido van Rossum9231c8f1997-05-15 21:43:21 +00005333
5334\end{document}