blob: 9396960a894c5ccf4bc04765edea27126d305692 [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
7\makeindex % tell \index to actually write the .idx file
8
9
10\begin{document}
11
Guido van Rossum9231c8f1997-05-15 21:43:21 +000012\maketitle
13
Fred Drake9f86b661998-07-28 21:55:19 +000014\ifhtml
15\chapter*{Front Matter\label{front}}
16\fi
17
Guido van Rossum9231c8f1997-05-15 21:43:21 +000018\input{copyright}
19
20\begin{abstract}
21
22\noindent
Fred Drake659ebfa2000-04-03 15:42:13 +000023This manual documents the API used by C and \Cpp{} programmers who
Fred Drakee058b4f1998-02-16 06:15:35 +000024want to write extension modules or embed Python. It is a companion to
Fred Drakebe486461999-11-09 17:03:03 +000025\citetitle[../ext/ext.html]{Extending and Embedding the Python
26Interpreter}, which describes the general principles of extension
27writing but does not document the API functions in detail.
Guido van Rossum9231c8f1997-05-15 21:43:21 +000028
Guido van Rossum5b8a5231997-12-30 04:38:44 +000029\strong{Warning:} The current version of this document is incomplete.
30I hope that it is nevertheless useful. I will continue to work on it,
31and release new versions from time to time, independent from Python
32source code releases.
33
Guido van Rossum9231c8f1997-05-15 21:43:21 +000034\end{abstract}
35
Fred Drake4d4f9e71998-01-13 22:25:02 +000036\tableofcontents
Guido van Rossum9231c8f1997-05-15 21:43:21 +000037
Guido van Rossum5060b3b1997-08-17 18:02:23 +000038% XXX Consider moving all this back to ext.tex and giving api.tex
39% XXX a *really* short intro only.
Guido van Rossum9231c8f1997-05-15 21:43:21 +000040
Fred Drakeefd146c1999-02-15 15:30:45 +000041\chapter{Introduction \label{intro}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +000042
Fred Drake659ebfa2000-04-03 15:42:13 +000043The Application Programmer's Interface to Python gives C and
44\Cpp{} programmers access to the Python interpreter at a variety of
45levels. The API is equally usable from \Cpp{}, but for brevity it is
46generally referred to as the Python/C API. There are two
47fundamentally different reasons for using the Python/C API. The first
48reason is to write \emph{extension modules} for specific purposes;
49these are C modules that extend the Python interpreter. This is
50probably the most common use. The second reason is to use Python as a
51component in a larger application; this technique is generally
52referred to as \dfn{embedding} Python in an application.
Guido van Rossum59a61351997-08-14 20:34:33 +000053
Guido van Rossum4a944d71997-08-14 20:35:38 +000054Writing an extension module is a relatively well-understood process,
55where a ``cookbook'' approach works well. There are several tools
56that automate the process to some extent. While people have embedded
57Python in other applications since its early existence, the process of
58embedding Python is less straightforward that writing an extension.
Guido van Rossum59a61351997-08-14 20:34:33 +000059
Guido van Rossum4a944d71997-08-14 20:35:38 +000060Many API functions are useful independent of whether you're embedding
61or extending Python; moreover, most applications that embed Python
62will need to provide a custom extension as well, so it's probably a
63good idea to become familiar with writing an extension before
Guido van Rossum59a61351997-08-14 20:34:33 +000064attempting to embed Python in a real application.
65
Fred Drakeefd146c1999-02-15 15:30:45 +000066
67\section{Include Files \label{includes}}
Guido van Rossum580aa8d1997-11-25 15:34:51 +000068
69All function, type and macro definitions needed to use the Python/C
70API are included in your code by the following line:
71
Fred Drakee058b4f1998-02-16 06:15:35 +000072\begin{verbatim}
73#include "Python.h"
74\end{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +000075
Fred Drakee058b4f1998-02-16 06:15:35 +000076This implies inclusion of the following standard headers:
77\code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>}, and
78\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 Drake933f0c32000-09-14 18:12:48 +0000105\samp{\#include <python\var{version}/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
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000459 return 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: */
475 if (!PyErr_ExceptionMatches(PyExc_KeyError)) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000476
477 /* Clear the error and use zero: */
478 PyErr_Clear();
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000479 item = PyInt_FromLong(0L);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000480 if (item == NULL) goto error;
481 }
482
483 const_one = PyInt_FromLong(1L);
484 if (const_one == NULL) goto error;
485
486 incremented_item = PyNumber_Add(item, const_one);
487 if (incremented_item == NULL) goto error;
488
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000489 if (PyObject_SetItem(dict, key, incremented_item) < 0) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000490 rv = 0; /* Success */
491 /* Continue with cleanup code */
492
493 error:
494 /* Cleanup code, shared by success and failure path */
495
496 /* Use Py_XDECREF() to ignore NULL references */
497 Py_XDECREF(item);
498 Py_XDECREF(const_one);
499 Py_XDECREF(incremented_item);
500
501 return rv; /* -1 for error, 0 for success */
502}
503\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000504\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000505
Fred Drakef8830d11998-04-23 14:06:01 +0000506This example represents an endorsed use of the \keyword{goto} statement
Fred Drake659ebfa2000-04-03 15:42:13 +0000507in C! It illustrates the use of
508\cfunction{PyErr_ExceptionMatches()}\ttindex{PyErr_ExceptionMatches()} and
509\cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} to
510handle specific exceptions, and the use of
511\cfunction{Py_XDECREF()}\ttindex{Py_XDECREF()} to
512dispose of owned references that may be \NULL{} (note the
513\character{X} in the name; \cfunction{Py_DECREF()} would crash when
514confronted with a \NULL{} reference). It is important that the
515variables used to hold owned references are initialized to \NULL{} for
516this to work; likewise, the proposed return value is initialized to
517\code{-1} (failure) and only set to success after the final call made
518is successful.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000519
Guido van Rossum59a61351997-08-14 20:34:33 +0000520
Fred Drakeefd146c1999-02-15 15:30:45 +0000521\section{Embedding Python \label{embedding}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000522
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000523The one important task that only embedders (as opposed to extension
524writers) of the Python interpreter have to worry about is the
525initialization, and possibly the finalization, of the Python
526interpreter. Most functionality of the interpreter can only be used
527after the interpreter has been initialized.
Guido van Rossum59a61351997-08-14 20:34:33 +0000528
Fred Drake659ebfa2000-04-03 15:42:13 +0000529The basic initialization function is
530\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Fred Drakee058b4f1998-02-16 06:15:35 +0000531This initializes the table of loaded modules, and creates the
Fred Drake4de05a91998-02-16 14:25:26 +0000532fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
533\module{__main__}\refbimodindex{__main__} and
534\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drakec6fa34e1998-04-02 06:47:24 +0000535search path (\code{sys.path}).%
536\indexiii{module}{search}{path}
Fred Drake659ebfa2000-04-03 15:42:13 +0000537\withsubitem{(in module sys)}{\ttindex{path}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000538
Fred Drakee058b4f1998-02-16 06:15:35 +0000539\cfunction{Py_Initialize()} does not set the ``script argument list''
Guido van Rossum4a944d71997-08-14 20:35:38 +0000540(\code{sys.argv}). If this variable is needed by Python code that
541will be executed later, it must be set explicitly with a call to
Fred Drake659ebfa2000-04-03 15:42:13 +0000542\code{PySys_SetArgv(\var{argc},
543\var{argv})}\ttindex{PySys_SetArgv()} subsequent to the call to
544\cfunction{Py_Initialize()}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000545
Fred Drakeb0a78731998-01-13 18:51:10 +0000546On most systems (in particular, on \UNIX{} and Windows, although the
Fred Drake659ebfa2000-04-03 15:42:13 +0000547details are slightly different),
548\cfunction{Py_Initialize()} calculates the module search path based
549upon its best guess for the location of the standard Python
550interpreter executable, assuming that the Python library is found in a
551fixed location relative to the Python interpreter executable. In
552particular, it looks for a directory named
Fred Drake933f0c32000-09-14 18:12:48 +0000553\file{lib/python\var{version}} (replacing \var{version} with the current
Guido van Rossum42cefd01997-10-05 15:27:29 +0000554interpreter version) relative to the parent directory where the
Fred Drakee058b4f1998-02-16 06:15:35 +0000555executable named \file{python} is found on the shell command search
Fred Drakec6fa34e1998-04-02 06:47:24 +0000556path (the environment variable \envvar{PATH}).
Guido van Rossum42cefd01997-10-05 15:27:29 +0000557
558For instance, if the Python executable is found in
Fred Drakee058b4f1998-02-16 06:15:35 +0000559\file{/usr/local/bin/python}, it will assume that the libraries are in
Fred Drake933f0c32000-09-14 18:12:48 +0000560\file{/usr/local/lib/python\var{version}}. (In fact, this particular path
Fred Drakee058b4f1998-02-16 06:15:35 +0000561is also the ``fallback'' location, used when no executable file named
Fred Drakec6fa34e1998-04-02 06:47:24 +0000562\file{python} is found along \envvar{PATH}.) The user can override
563this behavior by setting the environment variable \envvar{PYTHONHOME},
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000564or insert additional directories in front of the standard path by
Fred Drakec6fa34e1998-04-02 06:47:24 +0000565setting \envvar{PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000566
Guido van Rossum4a944d71997-08-14 20:35:38 +0000567The embedding application can steer the search by calling
Fred Drake659ebfa2000-04-03 15:42:13 +0000568\code{Py_SetProgramName(\var{file})}\ttindex{Py_SetProgramName()} \emph{before} calling
Fred Drakec6fa34e1998-04-02 06:47:24 +0000569\cfunction{Py_Initialize()}. Note that \envvar{PYTHONHOME} still
570overrides this and \envvar{PYTHONPATH} is still inserted in front of
Fred Drakee058b4f1998-02-16 06:15:35 +0000571the standard path. An application that requires total control has to
Fred Drake659ebfa2000-04-03 15:42:13 +0000572provide its own implementation of
573\cfunction{Py_GetPath()}\ttindex{Py_GetPath()},
574\cfunction{Py_GetPrefix()}\ttindex{Py_GetPrefix()},
575\cfunction{Py_GetExecPrefix()}\ttindex{Py_GetExecPrefix()}, and
576\cfunction{Py_GetProgramFullPath()}\ttindex{Py_GetProgramFullPath()} (all
577defined in \file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000578
Guido van Rossum4a944d71997-08-14 20:35:38 +0000579Sometimes, it is desirable to ``uninitialize'' Python. For instance,
580the application may want to start over (make another call to
Fred Drakee058b4f1998-02-16 06:15:35 +0000581\cfunction{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000582use of Python and wants to free all memory allocated by Python. This
Fred Drakee058b4f1998-02-16 06:15:35 +0000583can be accomplished by calling \cfunction{Py_Finalize()}. The function
Fred Drake659ebfa2000-04-03 15:42:13 +0000584\cfunction{Py_IsInitialized()}\ttindex{Py_IsInitialized()} returns
585true if Python is currently in the initialized state. More
586information about these functions is given in a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000587
Guido van Rossum4a944d71997-08-14 20:35:38 +0000588
Fred Drakeefd146c1999-02-15 15:30:45 +0000589\chapter{The Very High Level Layer \label{veryhigh}}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000590
Fred Drakee5bf8b21998-02-12 21:22:28 +0000591The functions in this chapter will let you execute Python source code
592given in a file or a buffer, but they will not let you interact in a
593more detailed way with the interpreter.
Guido van Rossum4a944d71997-08-14 20:35:38 +0000594
Fred Drake659ebfa2000-04-03 15:42:13 +0000595Several of these functions accept a start symbol from the grammar as a
596parameter. The available start symbols are \constant{Py_eval_input},
597\constant{Py_file_input}, and \constant{Py_single_input}. These are
598described following the functions which accept them as parameters.
599
Fred Drake510d08b2000-08-14 02:50:21 +0000600Note also that several of these functions take \ctype{FILE*}
601parameters. On particular issue which needs to be handled carefully
602is that the \ctype{FILE} structure for different C libraries can be
603different and incompatible. Under Windows (at least), it is possible
604for dynamically linked extensions to actually use different libraries,
605so care should be taken that \ctype{FILE*} parameters are only passed
606to these functions if it is certain that they were created by the same
607library that the Python runtime is using.
608
Fred Drakec6fa34e1998-04-02 06:47:24 +0000609\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000610 If \var{fp} refers to a file associated with an interactive device
611 (console or terminal input or \UNIX{} pseudo-terminal), return the
612 value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
613 result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
Fred Drakea8d73412000-08-11 20:39:29 +0000614 \NULL{}, this function uses \code{"???"} as the filename.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000615\end{cfuncdesc}
616
Fred Drakec6fa34e1998-04-02 06:47:24 +0000617\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
Fred Drake0041a941999-04-29 04:20:46 +0000618 Executes the Python source code from \var{command} in the
619 \module{__main__} module. If \module{__main__} does not already
620 exist, it is created. Returns \code{0} on success or \code{-1} if
621 an exception was raised. If there was an error, there is no way to
622 get the exception information.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000623\end{cfuncdesc}
624
Fred Drakec6fa34e1998-04-02 06:47:24 +0000625\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000626 Similar to \cfunction{PyRun_SimpleString()}, but the Python source
627 code is read from \var{fp} instead of an in-memory string.
628 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000629\end{cfuncdesc}
630
Fred Drakec6fa34e1998-04-02 06:47:24 +0000631\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000632 Read and execute a single statement from a file associated with an
633 interactive device. If \var{filename} is \NULL, \code{"???"} is
634 used instead. The user will be prompted using \code{sys.ps1} and
635 \code{sys.ps2}. Returns \code{0} when the input was executed
636 successfully, \code{-1} if there was an exception, or an error code
637 from the \file{errcode.h} include file distributed as part of Python
638 in case of a parse error. (Note that \file{errcode.h} is not
639 included by \file{Python.h}, so must be included specifically if
640 needed.)
Fred Drakee5bf8b21998-02-12 21:22:28 +0000641\end{cfuncdesc}
642
Fred Drakec6fa34e1998-04-02 06:47:24 +0000643\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000644 Read and execute statements from a file associated with an
645 interactive device until \EOF{} is reached. If \var{filename} is
646 \NULL, \code{"???"} is used instead. The user will be prompted
647 using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000648\end{cfuncdesc}
649
Fred Drakec6fa34e1998-04-02 06:47:24 +0000650\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
651 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000652 Parse Python source code from \var{str} using the start token
653 \var{start}. The result can be used to create a code object which
654 can be evaluated efficiently. This is useful if a code fragment
655 must be evaluated many times.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000656\end{cfuncdesc}
657
Fred Drakec6fa34e1998-04-02 06:47:24 +0000658\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
659 char *filename, int start}
Fred Drake0041a941999-04-29 04:20:46 +0000660 Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
661 source code is read from \var{fp} instead of an in-memory string.
662 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000663\end{cfuncdesc}
664
Fred Drakec6fa34e1998-04-02 06:47:24 +0000665\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
666 PyObject *globals,
667 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000668 Execute Python source code from \var{str} in the context specified
669 by the dictionaries \var{globals} and \var{locals}. The parameter
670 \var{start} specifies the start token that should be used to parse
671 the source code.
672
673 Returns the result of executing the code as a Python object, or
674 \NULL{} if an exception was raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000675\end{cfuncdesc}
676
Fred Drakec6fa34e1998-04-02 06:47:24 +0000677\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
678 int start, PyObject *globals,
679 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000680 Similar to \cfunction{PyRun_String()}, but the Python source code is
Fred Drake659ebfa2000-04-03 15:42:13 +0000681 read from \var{fp} instead of an in-memory string.
682 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000683\end{cfuncdesc}
684
Fred Drakec6fa34e1998-04-02 06:47:24 +0000685\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
686 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000687 Parse and compile the Python source code in \var{str}, returning the
688 resulting code object. The start token is given by \var{start};
Fred Drakec924b8d1999-08-23 18:57:25 +0000689 this can be used to constrain the code which can be compiled and should
690 be \constant{Py_eval_input}, \constant{Py_file_input}, or
691 \constant{Py_single_input}. The filename specified by
692 \var{filename} is used to construct the code object and may appear
693 in tracebacks or \exception{SyntaxError} exception messages. This
694 returns \NULL{} if the code cannot be parsed or compiled.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000695\end{cfuncdesc}
696
Fred Drakec924b8d1999-08-23 18:57:25 +0000697\begin{cvardesc}{int}{Py_eval_input}
698 The start symbol from the Python grammar for isolated expressions;
Fred Drake659ebfa2000-04-03 15:42:13 +0000699 for use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
Fred Drakec924b8d1999-08-23 18:57:25 +0000700\end{cvardesc}
701
702\begin{cvardesc}{int}{Py_file_input}
703 The start symbol from the Python grammar for sequences of statements
704 as read from a file or other source; for use with
Fred Drake659ebfa2000-04-03 15:42:13 +0000705 \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
706 the symbol to use when compiling arbitrarily long Python source code.
Fred Drakec924b8d1999-08-23 18:57:25 +0000707\end{cvardesc}
708
709\begin{cvardesc}{int}{Py_single_input}
710 The start symbol from the Python grammar for a single statement; for
Fred Drake659ebfa2000-04-03 15:42:13 +0000711 use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
712 This is the symbol used for the interactive interpreter loop.
Fred Drakec924b8d1999-08-23 18:57:25 +0000713\end{cvardesc}
714
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000715
Fred Drakeefd146c1999-02-15 15:30:45 +0000716\chapter{Reference Counting \label{countingRefs}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000717
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000718The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000719of Python objects.
720
721\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
Fred Drakec6fa34e1998-04-02 06:47:24 +0000722Increment the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000723not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000724\cfunction{Py_XINCREF()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000725\end{cfuncdesc}
726
727\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000728Increment the reference count for object \var{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000729\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000730\end{cfuncdesc}
731
732\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000733Decrement the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000734not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000735\cfunction{Py_XDECREF()}. If the reference count reaches zero, the
736object's type's deallocation function (which must not be \NULL{}) is
737invoked.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000738
739\strong{Warning:} The deallocation function can cause arbitrary Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000740code to be invoked (e.g. when a class instance with a
741\method{__del__()} method is deallocated). While exceptions in such
742code are not propagated, the executed code has free access to all
743Python global variables. This means that any object that is reachable
744from a global variable should be in a consistent state before
745\cfunction{Py_DECREF()} is invoked. For example, code to delete an
746object from a list should copy a reference to the deleted object in a
747temporary variable, update the list data structure, and then call
748\cfunction{Py_DECREF()} for the temporary variable.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000749\end{cfuncdesc}
750
751\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000752Decrement the reference count for object \var{o}. The object may be
753\NULL{}, in which case the macro has no effect; otherwise the effect
754is the same as for \cfunction{Py_DECREF()}, and the same warning
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000755applies.
756\end{cfuncdesc}
757
Fred Drake659ebfa2000-04-03 15:42:13 +0000758The following functions or macros are only for use within the
759interpreter core: \cfunction{_Py_Dealloc()},
760\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
761well as the global variable \cdata{_Py_RefTotal}.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000762
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000763
Fred Drakeefd146c1999-02-15 15:30:45 +0000764\chapter{Exception Handling \label{exceptionHandling}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000765
Fred Drake659ebfa2000-04-03 15:42:13 +0000766The functions described in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000767exceptions. It is important to understand some of the basics of
Fred Drake659ebfa2000-04-03 15:42:13 +0000768Python exception handling. It works somewhat like the
769\UNIX{} \cdata{errno} variable: there is a global indicator (per
770thread) of the last error that occurred. Most functions don't clear
771this on success, but will set it to indicate the cause of the error on
772failure. Most functions also return an error indicator, usually
773\NULL{} if they are supposed to return a pointer, or \code{-1} if they
774return an integer (exception: the \cfunction{PyArg_Parse*()} functions
775return \code{1} for success and \code{0} for failure). When a
776function must fail because some function it called failed, it
777generally doesn't set the error indicator; the function it called
778already set it.
Guido van Rossumae110af1997-05-22 20:11:52 +0000779
780The error indicator consists of three Python objects corresponding to
Fred Drake659ebfa2000-04-03 15:42:13 +0000781\withsubitem{(in module sys)}{
782 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000783the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
784\code{sys.exc_traceback}. API functions exist to interact with the
785error indicator in various ways. There is a separate error indicator
786for each thread.
787
788% XXX Order of these should be more thoughtful.
789% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000790
791\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000792Print a standard traceback to \code{sys.stderr} and clear the error
793indicator. Call this function only when the error indicator is set.
794(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000795\end{cfuncdesc}
796
Fred Drakec6fa34e1998-04-02 06:47:24 +0000797\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000798Test whether the error indicator is set. If set, return the exception
Fred Drakee058b4f1998-02-16 06:15:35 +0000799\emph{type} (the first argument to the last call to one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000800\cfunction{PyErr_Set*()} functions or to \cfunction{PyErr_Restore()}). If
Fred Drakee058b4f1998-02-16 06:15:35 +0000801not set, return \NULL{}. You do not own a reference to the return
802value, so you do not need to \cfunction{Py_DECREF()} it.
Fred Drake659ebfa2000-04-03 15:42:13 +0000803\strong{Note:} Do not compare the return value to a specific
Fred Drakee058b4f1998-02-16 06:15:35 +0000804exception; use \cfunction{PyErr_ExceptionMatches()} instead, shown
Fred Drake659ebfa2000-04-03 15:42:13 +0000805below. (The comparison could easily fail since the exception may be
806an instance instead of a class, in the case of a class exception, or
807it may the a subclass of the expected exception.)
Guido van Rossum42cefd01997-10-05 15:27:29 +0000808\end{cfuncdesc}
809
810\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000811Equivalent to
Fred Drakee058b4f1998-02-16 06:15:35 +0000812\samp{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
Fred Drake659ebfa2000-04-03 15:42:13 +0000813This should only be called when an exception is actually set; a memory
814access violation will occur if no exception has been raised.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000815\end{cfuncdesc}
816
817\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000818Return true if the \var{given} exception matches the exception in
819\var{exc}. If \var{exc} is a class object, this also returns true
Fred Drake659ebfa2000-04-03 15:42:13 +0000820when \var{given} is an instance of a subclass. If \var{exc} is a tuple, all
Guido van Rossum42cefd01997-10-05 15:27:29 +0000821exceptions in the tuple (and recursively in subtuples) are searched
Fred Drake659ebfa2000-04-03 15:42:13 +0000822for a match. If \var{given} is \NULL, a memory access violation will
823occur.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000824\end{cfuncdesc}
825
826\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000827Under certain circumstances, the values returned by
Fred Drakee058b4f1998-02-16 06:15:35 +0000828\cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning that
829\code{*\var{exc}} is a class object but \code{*\var{val}} is not an
830instance of the same class. This function can be used to instantiate
831the class in that case. If the values are already normalized, nothing
Fred Drake659ebfa2000-04-03 15:42:13 +0000832happens. The delayed normalization is implemented to improve
833performance.
Guido van Rossumae110af1997-05-22 20:11:52 +0000834\end{cfuncdesc}
835
836\begin{cfuncdesc}{void}{PyErr_Clear}{}
837Clear the error indicator. If the error indicator is not set, there
838is no effect.
839\end{cfuncdesc}
840
Fred Drake659ebfa2000-04-03 15:42:13 +0000841\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
842 PyObject **ptraceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000843Retrieve the error indicator into three variables whose addresses are
844passed. If the error indicator is not set, set all three variables to
845\NULL{}. If it is set, it will be cleared and you own a reference to
Fred Drake659ebfa2000-04-03 15:42:13 +0000846each object retrieved. The value and traceback object may be
847\NULL{} even when the type object is not. \strong{Note:} This
848function is normally only used by code that needs to handle exceptions
849or by code that needs to save and restore the error indicator
850temporarily.
Guido van Rossumae110af1997-05-22 20:11:52 +0000851\end{cfuncdesc}
852
Fred Drake17e63432000-08-31 05:50:40 +0000853\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
854 PyObject *traceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000855Set the error indicator from the three objects. If the error
856indicator is already set, it is cleared first. If the objects are
857\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
858and non-\NULL{} value or traceback. The exception type should be a
859string or class; if it is a class, the value should be an instance of
860that class. Do not pass an invalid exception type or value.
861(Violating these rules will cause subtle problems later.) This call
Fred Drake17e63432000-08-31 05:50:40 +0000862takes away a reference to each object, i.e.\ you must own a reference
Guido van Rossumae110af1997-05-22 20:11:52 +0000863to each object before the call and after the call you no longer own
864these references. (If you don't understand this, don't use this
Fred Drake659ebfa2000-04-03 15:42:13 +0000865function. I warned you.) \strong{Note:} This function is normally
Guido van Rossumae110af1997-05-22 20:11:52 +0000866only used by code that needs to save and restore the error indicator
867temporarily.
868\end{cfuncdesc}
869
870\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
871This is the most common way to set the error indicator. The first
872argument specifies the exception type; it is normally one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000873standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
Guido van Rossumae110af1997-05-22 20:11:52 +0000874increment its reference count. The second argument is an error
875message; it is converted to a string object.
876\end{cfuncdesc}
877
878\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +0000879This function is similar to \cfunction{PyErr_SetString()} but lets you
Guido van Rossumae110af1997-05-22 20:11:52 +0000880specify an arbitrary Python object for the ``value'' of the exception.
881You need not increment its reference count.
882\end{cfuncdesc}
883
Fred Drake73577702000-04-10 18:50:14 +0000884\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
Moshe Zadka57a59322000-09-01 09:47:20 +0000885 const char *format, \moreargs}
886This function sets the error indicator.
887\var{exception} should be a Python object.
888\var{fmt} should be a string, containing format codes, similar to
889\cfunction{printf}. The \code{width.precision} before a format code
890is parsed, but the width part is ignored.
891
892\begin{tableii}{c|l}{character}{Character}{Meaning}
893 \lineii{c}{Character, as an \ctype{int} parameter}
894 \lineii{d}{Number in decimal, as an \ctype{int} parameter}
895 \lineii{x}{Number in hexadecimal, as an \ctype{int} parameter}
896 \lineii{x}{A string, as a \ctype{char *} parameter}
897\end{tableii}
898
899An unrecognized format character causes all the rest of
900the format string to be copied as-is to the result string,
901and any extra arguments discarded.
902
903A new reference is returned, which is owned by the caller.
Jeremy Hylton98605b52000-04-10 18:40:57 +0000904\end{cfuncdesc}
905
Guido van Rossumae110af1997-05-22 20:11:52 +0000906\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +0000907This is a shorthand for \samp{PyErr_SetObject(\var{type}, Py_None)}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000908\end{cfuncdesc}
909
910\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000911This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000912\var{message})}, where \var{message} indicates that a built-in operation
913was invoked with an illegal argument. It is mostly for internal use.
914\end{cfuncdesc}
915
Fred Drakec6fa34e1998-04-02 06:47:24 +0000916\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000917This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
Guido van Rossumae110af1997-05-22 20:11:52 +0000918returns \NULL{} so an object allocation function can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000919\samp{return PyErr_NoMemory();} when it runs out of memory.
Guido van Rossumae110af1997-05-22 20:11:52 +0000920\end{cfuncdesc}
921
Fred Drakec6fa34e1998-04-02 06:47:24 +0000922\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
Fred Drake659ebfa2000-04-03 15:42:13 +0000923This is a convenience function to raise an exception when a C library
924function has returned an error and set the C variable \cdata{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000925It constructs a tuple object whose first item is the integer
Fred Drakef8830d11998-04-23 14:06:01 +0000926\cdata{errno} value and whose second item is the corresponding error
Fred Drake659ebfa2000-04-03 15:42:13 +0000927message (gotten from \cfunction{strerror()}\ttindex{strerror()}), and
928then calls
Fred Drakee058b4f1998-02-16 06:15:35 +0000929\samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
Fred Drakef8830d11998-04-23 14:06:01 +0000930the \cdata{errno} value is \constant{EINTR}, indicating an interrupted
Fred Drakee058b4f1998-02-16 06:15:35 +0000931system call, this calls \cfunction{PyErr_CheckSignals()}, and if that set
Guido van Rossumae110af1997-05-22 20:11:52 +0000932the error indicator, leaves it set to that. The function always
933returns \NULL{}, so a wrapper function around a system call can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000934\samp{return PyErr_SetFromErrno();} when the system call returns an
935error.
Guido van Rossumae110af1997-05-22 20:11:52 +0000936\end{cfuncdesc}
937
938\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000939This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000940\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000941operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000942argument. It is mostly for internal use.
943\end{cfuncdesc}
944
945\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
946This function interacts with Python's signal handling. It checks
947whether a signal has been sent to the processes and if so, invokes the
Fred Drake4de05a91998-02-16 14:25:26 +0000948corresponding signal handler. If the
949\module{signal}\refbimodindex{signal} module is supported, this can
950invoke a signal handler written in Python. In all cases, the default
Fred Drake659ebfa2000-04-03 15:42:13 +0000951effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
952\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
953\exception{KeyboardInterrupt} exception. If an exception is raised the
Fred Drakee058b4f1998-02-16 06:15:35 +0000954error indicator is set and the function returns \code{1}; otherwise
955the function returns \code{0}. The error indicator may or may not be
956cleared if it was previously set.
Guido van Rossumae110af1997-05-22 20:11:52 +0000957\end{cfuncdesc}
958
959\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
Fred Drake659ebfa2000-04-03 15:42:13 +0000960This function is obsolete. It simulates the effect of a
961\constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
Fred Drakee058b4f1998-02-16 06:15:35 +0000962\cfunction{PyErr_CheckSignals()} is called,
Fred Drake659ebfa2000-04-03 15:42:13 +0000963\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
964\exception{KeyboardInterrupt} will be raised.
965It may be called without holding the interpreter lock.
Guido van Rossumae110af1997-05-22 20:11:52 +0000966\end{cfuncdesc}
967
Fred Drakec6fa34e1998-04-02 06:47:24 +0000968\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
969 PyObject *base,
970 PyObject *dict}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000971This utility function creates and returns a new exception object. The
Fred Drake659ebfa2000-04-03 15:42:13 +0000972\var{name} argument must be the name of the new exception, a C string
973of the form \code{module.class}. The \var{base} and
Fred Draked04038d2000-06-29 20:15:14 +0000974\var{dict} arguments are normally \NULL{}. This creates a
Fred Drake659ebfa2000-04-03 15:42:13 +0000975class object derived from the root for all exceptions, the built-in
976name \exception{Exception} (accessible in C as
Fred Draked04038d2000-06-29 20:15:14 +0000977\cdata{PyExc_Exception}). The \member{__module__} attribute of the
978new class is set to the first part (up to the last dot) of the
979\var{name} argument, and the class name is set to the last part (after
980the last dot). The \var{base} argument can be used to specify an
981alternate base class. The \var{dict} argument can be used to specify
982a dictionary of class variables and methods.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000983\end{cfuncdesc}
984
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000985\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
986This utility function prints a warning message to \var{sys.stderr}
987when an exception has been set but it is impossible for the
988interpreter to actually raise the exception. It is used, for example,
989when an exception occurs in an \member{__del__} method.
990
991The function is called with a single argument \var{obj} that
992identifies where the context in which the unraisable exception
993occurred. The repr of \var{obj} will be printed in the warning
994message.
995\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000996
Fred Drakeefd146c1999-02-15 15:30:45 +0000997\section{Standard Exceptions \label{standardExceptions}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000998
999All standard Python exceptions are available as global variables whose
Fred Drake659ebfa2000-04-03 15:42:13 +00001000names are \samp{PyExc_} followed by the Python exception name. These
1001have the type \ctype{PyObject*}; they are all class objects. For
1002completeness, here are all the variables:
1003
1004\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
1005 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
1006 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
1007 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
1008 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
1009 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
1010 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
1011 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
1012 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
1013 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
1014 \lineiii{PyExc_IOError}{\exception{IOError}}{}
1015 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
1016 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
1017 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
1018 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
1019 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
1020 \lineiii{PyExc_NameError}{\exception{NameError}}{}
1021 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
1022 \lineiii{PyExc_OSError}{\exception{OSError}}{}
1023 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
1024 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
1025 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
1026 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
1027 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
1028 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
1029 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
Fred Drakea8d73412000-08-11 20:39:29 +00001030 \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(2)}
Fred Drake659ebfa2000-04-03 15:42:13 +00001031 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
1032\end{tableiii}
1033
1034\noindent
Fred Drakea8d73412000-08-11 20:39:29 +00001035Notes:
Fred Drake659ebfa2000-04-03 15:42:13 +00001036\begin{description}
1037\item[(1)]
Fred Draked04038d2000-06-29 20:15:14 +00001038 This is a base class for other standard exceptions.
Fred Drakea8d73412000-08-11 20:39:29 +00001039
1040\item[(2)]
1041 Only defined on Windows; protect code that uses this by testing that
1042 the preprocessor macro \code{MS_WINDOWS} is defined.
Fred Drake659ebfa2000-04-03 15:42:13 +00001043\end{description}
1044
1045
1046\section{Deprecation of String Exceptions}
1047
Fred Draked04038d2000-06-29 20:15:14 +00001048All exceptions built into Python or provided in the standard library
1049are derived from \exception{Exception}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001050\withsubitem{(built-in exception)}{\ttindex{Exception}}
Fred Drake659ebfa2000-04-03 15:42:13 +00001051
Fred Draked04038d2000-06-29 20:15:14 +00001052String exceptions are still supported in the interpreter to allow
Fred Drake659ebfa2000-04-03 15:42:13 +00001053existing code to run unmodified, but this will also change in a future
1054release.
Guido van Rossumae110af1997-05-22 20:11:52 +00001055
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001056
Fred Drakeefd146c1999-02-15 15:30:45 +00001057\chapter{Utilities \label{utilities}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001058
1059The functions in this chapter perform various utility tasks, such as
Fred Drake659ebfa2000-04-03 15:42:13 +00001060parsing function arguments and constructing Python values from C
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001061values.
1062
Fred Drakeefd146c1999-02-15 15:30:45 +00001063\section{OS Utilities \label{os}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001064
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001065\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001066Return true (nonzero) if the standard I/O file \var{fp} with name
1067\var{filename} is deemed interactive. This is the case for files for
1068which \samp{isatty(fileno(\var{fp}))} is true. If the global flag
Fred Drakef8830d11998-04-23 14:06:01 +00001069\cdata{Py_InteractiveFlag} is true, this function also returns true if
Fred Drakee058b4f1998-02-16 06:15:35 +00001070the \var{name} pointer is \NULL{} or if the name is equal to one of
Fred Drakea8455ab2000-06-16 19:58:42 +00001071the strings \code{'<stdin>'} or \code{'???'}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001072\end{cfuncdesc}
1073
1074\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001075Return the time of last modification of the file \var{filename}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001076The result is encoded in the same way as the timestamp returned by
Fred Drake659ebfa2000-04-03 15:42:13 +00001077the standard C library function \cfunction{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001078\end{cfuncdesc}
1079
Fred Drakecabbc3b2000-06-28 15:53:13 +00001080\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
1081Function to update some internal state after a process fork; this
1082should be called in the new process if the Python interpreter will
1083continue to be used. If a new executable is loaded into the new
1084process, this function does not need to be called.
1085\end{cfuncdesc}
1086
Fred Drake17e63432000-08-31 05:50:40 +00001087\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
1088Return true when the interpreter runs out of stack space. This is a
1089reliable check, but is only available when \code{USE_STACKCHECK} is
1090defined (currently on Windows using the Microsoft Visual C++ compiler
1091and on the Macintosh). \code{USE_CHECKSTACK} will be defined
1092automatically; you should never change the definition in your own
1093code.
1094\end{cfuncdesc}
1095
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001096
Fred Drakeefd146c1999-02-15 15:30:45 +00001097\section{Process Control \label{processControl}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001098
1099\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
1100Print a fatal error message and kill the process. No cleanup is
1101performed. This function should only be invoked when a condition is
1102detected that would make it dangerous to continue using the Python
1103interpreter; e.g., when the object administration appears to be
Fred Drake659ebfa2000-04-03 15:42:13 +00001104corrupted. On \UNIX{}, the standard C library function
1105\cfunction{abort()}\ttindex{abort()} is called which will attempt to
1106produce a \file{core} file.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001107\end{cfuncdesc}
1108
1109\begin{cfuncdesc}{void}{Py_Exit}{int status}
Fred Drake659ebfa2000-04-03 15:42:13 +00001110Exit the current process. This calls
1111\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
1112then calls the standard C library function
1113\code{exit(\var{status})}\ttindex{exit()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001114\end{cfuncdesc}
1115
1116\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drake659ebfa2000-04-03 15:42:13 +00001117Register a cleanup function to be called by
1118\cfunction{Py_Finalize()}\ttindex{Py_Finalize()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001119The cleanup function will be called with no arguments and should
Fred Drake659ebfa2000-04-03 15:42:13 +00001120return no value. At most 32 \index{cleanup functions}cleanup
1121functions can be registered.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001122When the registration is successful, \cfunction{Py_AtExit()} returns
1123\code{0}; on failure, it returns \code{-1}. The cleanup function
1124registered last is called first. Each cleanup function will be called
1125at most once. Since Python's internal finallization will have
1126completed before the cleanup function, no Python APIs should be called
1127by \var{func}.
1128\end{cfuncdesc}
1129
1130
Fred Drakeefd146c1999-02-15 15:30:45 +00001131\section{Importing Modules \label{importing}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001132
Fred Drakec6fa34e1998-04-02 06:47:24 +00001133\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00001134This is a simplified interface to
1135\cfunction{PyImport_ImportModuleEx()} below, leaving the
1136\var{globals} and \var{locals} arguments set to \NULL{}. When the
1137\var{name} argument contains a dot (i.e., when it specifies a
1138submodule of a package), the \var{fromlist} argument is set to the
1139list \code{['*']} so that the return value is the named module rather
1140than the top-level package containing it as would otherwise be the
1141case. (Unfortunately, this has an additional side effect when
1142\var{name} in fact specifies a subpackage instead of a submodule: the
1143submodules specified in the package's \code{__all__} variable are
1144\index{package variable!\code{__all__}}
1145\withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a
1146new reference to the imported module, or
1147\NULL{} with an exception set on failure (the module may still be
1148created in this case --- examine \code{sys.modules} to find out).
1149\withsubitem{(in module sys)}{\ttindex{modules}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001150\end{cfuncdesc}
1151
Fred Drakec6fa34e1998-04-02 06:47:24 +00001152\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001153Import a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001154Python function \function{__import__()}\bifuncindex{__import__}, as
1155the standard \function{__import__()} function calls this function
1156directly.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001157
Guido van Rossum42cefd01997-10-05 15:27:29 +00001158The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001159top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001160(the module may still be created in this case). Like for
Fred Drakee058b4f1998-02-16 06:15:35 +00001161\function{__import__()}, the return value when a submodule of a
1162package was requested is normally the top-level package, unless a
1163non-empty \var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001164\end{cfuncdesc}
1165
Fred Drakec6fa34e1998-04-02 06:47:24 +00001166\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001167This is a higher-level interface that calls the current ``import hook
Fred Drakee058b4f1998-02-16 06:15:35 +00001168function''. It invokes the \function{__import__()} function from the
Guido van Rossum42cefd01997-10-05 15:27:29 +00001169\code{__builtins__} of the current globals. This means that the
1170import is done using whatever import hooks are installed in the
Fred Drake4de05a91998-02-16 14:25:26 +00001171current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
1172\module{ihooks}\refstmodindex{ihooks}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001173\end{cfuncdesc}
1174
Fred Drakec6fa34e1998-04-02 06:47:24 +00001175\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001176Reload a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001177Python function \function{reload()}\bifuncindex{reload}, as the standard
Fred Drakee058b4f1998-02-16 06:15:35 +00001178\function{reload()} function calls this function directly. Return a
1179new reference to the reloaded module, or \NULL{} with an exception set
1180on failure (the module still exists in this case).
Guido van Rossum42cefd01997-10-05 15:27:29 +00001181\end{cfuncdesc}
1182
Fred Drakec6fa34e1998-04-02 06:47:24 +00001183\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001184Return the module object corresponding to a module name. The
1185\var{name} argument may be of the form \code{package.module}). First
1186check the modules dictionary if there's one there, and if not, create
Fred Drake659ebfa2000-04-03 15:42:13 +00001187a new one and insert in in the modules dictionary.
Guido van Rossuma096a2e1998-11-02 17:02:42 +00001188Warning: this function does not load or import the module; if the
1189module wasn't already loaded, you will get an empty module object.
1190Use \cfunction{PyImport_ImportModule()} or one of its variants to
1191import a module.
Fred Drake659ebfa2000-04-03 15:42:13 +00001192Return \NULL{} with an exception set on failure.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001193\end{cfuncdesc}
1194
Fred Drakec6fa34e1998-04-02 06:47:24 +00001195\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001196Given a module name (possibly of the form \code{package.module}) and a
1197code object read from a Python bytecode file or obtained from the
Fred Drake53fb7721998-02-16 06:23:20 +00001198built-in function \function{compile()}\bifuncindex{compile}, load the
1199module. Return a new reference to the module object, or \NULL{} with
1200an exception set if an error occurred (the module may still be created
1201in this case). (This function would reload the module if it was
1202already imported.)
Guido van Rossum42cefd01997-10-05 15:27:29 +00001203\end{cfuncdesc}
1204
1205\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001206Return the magic number for Python bytecode files (a.k.a.
1207\file{.pyc} and \file{.pyo} files). The magic number should be
1208present in the first four bytes of the bytecode file, in little-endian
1209byte order.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001210\end{cfuncdesc}
1211
Fred Drakec6fa34e1998-04-02 06:47:24 +00001212\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001213Return the dictionary used for the module administration
1214(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1215variable.
1216\end{cfuncdesc}
1217
1218\begin{cfuncdesc}{void}{_PyImport_Init}{}
1219Initialize the import mechanism. For internal use only.
1220\end{cfuncdesc}
1221
1222\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1223Empty the module table. For internal use only.
1224\end{cfuncdesc}
1225
1226\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1227Finalize the import mechanism. For internal use only.
1228\end{cfuncdesc}
1229
Fred Drakec6fa34e1998-04-02 06:47:24 +00001230\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001231For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001232\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001233
Fred Drakec6fa34e1998-04-02 06:47:24 +00001234\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001235For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001236\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001237
Fred Drake1d158692000-06-18 05:21:21 +00001238\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
1239Load a frozen module named \var{name}. Return \code{1} for success,
1240\code{0} if the module is not found, and \code{-1} with an exception
1241set if the initialization failed. To access the imported module on a
1242successful load, use \cfunction{PyImport_ImportModule()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00001243(Note the misnomer --- this function would reload the module if it was
Guido van Rossum42cefd01997-10-05 15:27:29 +00001244already imported.)
1245\end{cfuncdesc}
1246
Fred Drake659ebfa2000-04-03 15:42:13 +00001247\begin{ctypedesc}[_frozen]{struct _frozen}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001248This is the structure type definition for frozen module descriptors,
Fred Drakec6fa34e1998-04-02 06:47:24 +00001249as generated by the \program{freeze}\index{freeze utility} utility
1250(see \file{Tools/freeze/} in the Python source distribution). Its
Fred Drakee0d9a832000-09-01 05:30:00 +00001251definition, found in \file{Include/import.h}, is:
Fred Drakec6fa34e1998-04-02 06:47:24 +00001252
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001253\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001254struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001255 char *name;
1256 unsigned char *code;
1257 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001258};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001259\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001260\end{ctypedesc}
1261
Fred Drakec6fa34e1998-04-02 06:47:24 +00001262\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
Fred Drakef8830d11998-04-23 14:06:01 +00001263This pointer is initialized to point to an array of \ctype{struct
Fred Drake659ebfa2000-04-03 15:42:13 +00001264_frozen} records, terminated by one whose members are all
1265\NULL{} or zero. When a frozen module is imported, it is searched in
1266this table. Third-party code could play tricks with this to provide a
Guido van Rossum42cefd01997-10-05 15:27:29 +00001267dynamically created collection of frozen modules.
1268\end{cvardesc}
1269
Fred Drakee0d9a832000-09-01 05:30:00 +00001270\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
1271 void (*initfunc)(void)}
1272Add a single module to the existing table of built-in modules. This
1273is a convenience wrapper around \cfunction{PyImport_ExtendInittab()},
1274returning \code{-1} if the table could not be extended. The new
1275module can be imported by the name \var{name}, and uses the function
1276\var{initfunc} as the initialization function called on the first
1277attempted import. This should be called before
1278\cfunction{Py_Initialize()}.
1279\end{cfuncdesc}
1280
1281\begin{ctypedesc}[_inittab]{struct _inittab}
1282Structure describing a single entry in the list of built-in modules.
1283Each of these structures gives the name and initialization function
1284for a module built into the interpreter. Programs which embed Python
1285may use an array of these structures in conjunction with
1286\cfunction{PyImport_ExtendInittab()} to provide additional built-in
1287modules. The structure is defined in \file{Include/import.h} as:
1288
1289\begin{verbatim}
1290struct _inittab {
1291 char *name;
1292 void (*initfunc)(void);
1293};
1294\end{verbatim}
1295\end{ctypedesc}
1296
1297\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
1298Add a collection of modules to the table of built-in modules. The
1299\var{newtab} array must end with a sentinel entry which contains
1300\NULL{} for the \member{name} field; failure to provide the sentinel
1301value can result in a memory fault. Returns \code{0} on success or
1302\code{-1} if insufficient memory could be allocated to extend the
1303internal table. In the event of failure, no modules are added to the
1304internal table. This should be called before
1305\cfunction{Py_Initialize()}.
1306\end{cfuncdesc}
1307
Guido van Rossum42cefd01997-10-05 15:27:29 +00001308
Fred Drakeefd146c1999-02-15 15:30:45 +00001309\chapter{Abstract Objects Layer \label{abstract}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001310
1311The functions in this chapter interact with Python objects regardless
1312of their type, or with wide classes of object types (e.g. all
1313numerical types, or all sequence types). When used on object types
Fred Drake659ebfa2000-04-03 15:42:13 +00001314for which they do not apply, they will raise a Python exception.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001315
Fred Drakeefd146c1999-02-15 15:30:45 +00001316\section{Object Protocol \label{object}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001317
1318\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00001319Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error.
1320The flags argument is used to enable certain printing options. The
1321only option currently supported is \constant{Py_PRINT_RAW}; if given,
1322the \function{str()} of the object is written instead of the
1323\function{repr()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001324\end{cfuncdesc}
1325
1326\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001327Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1328\code{0} otherwise. This is equivalent to the Python expression
1329\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001330This function always succeeds.
1331\end{cfuncdesc}
1332
Fred Drake659ebfa2000-04-03 15:42:13 +00001333\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
1334 char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001335Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001336Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001337This is the equivalent of the Python expression
1338\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001339\end{cfuncdesc}
1340
1341
1342\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001343Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1344\code{0} otherwise. This is equivalent to the Python expression
1345\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001346This function always succeeds.
1347\end{cfuncdesc}
1348
1349
Fred Drake659ebfa2000-04-03 15:42:13 +00001350\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
1351 PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001352Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001353Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001354This is the equivalent of the Python expression
1355\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001356\end{cfuncdesc}
1357
1358
1359\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001360Set the value of the attribute named \var{attr_name}, for object
1361\var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1362the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1363\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001364\end{cfuncdesc}
1365
1366
1367\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001368Set the value of the attribute named \var{attr_name}, for
1369object \var{o},
1370to the value \var{v}. Returns \code{-1} on failure. This is
1371the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1372\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001373\end{cfuncdesc}
1374
1375
1376\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001377Delete attribute named \var{attr_name}, for object \var{o}. Returns
1378\code{-1} on failure. This is the equivalent of the Python
1379statement: \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001380\end{cfuncdesc}
1381
1382
1383\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001384Delete attribute named \var{attr_name}, for object \var{o}. Returns
1385\code{-1} on failure. This is the equivalent of the Python
1386statement \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001387\end{cfuncdesc}
1388
1389
1390\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
Fred Drakee058b4f1998-02-16 06:15:35 +00001391Compare the values of \var{o1} and \var{o2} using a routine provided
1392by \var{o1}, if one exists, otherwise with a routine provided by
1393\var{o2}. The result of the comparison is returned in \var{result}.
1394Returns \code{-1} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001395statement\bifuncindex{cmp} \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001396\end{cfuncdesc}
1397
1398
1399\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001400Compare the values of \var{o1} and \var{o2} using a routine provided
1401by \var{o1}, if one exists, otherwise with a routine provided by
1402\var{o2}. Returns the result of the comparison on success. On error,
1403the value returned is undefined; use \cfunction{PyErr_Occurred()} to
Fred Drake659ebfa2000-04-03 15:42:13 +00001404detect an error. This is equivalent to the Python
1405expression\bifuncindex{cmp} \samp{cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001406\end{cfuncdesc}
1407
1408
1409\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001410Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001411string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001412the equivalent of the Python expression \samp{repr(\var{o})}.
1413Called by the \function{repr()}\bifuncindex{repr} built-in function
1414and by reverse quotes.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001415\end{cfuncdesc}
1416
1417
1418\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001419Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001420string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001421the equivalent of the Python expression \samp{str(\var{o})}.
1422Called by the \function{str()}\bifuncindex{str} built-in function and
1423by the \keyword{print} statement.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001424\end{cfuncdesc}
1425
1426
1427\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001428Determine if the object \var{o} is callable. Return \code{1} if the
Fred Drakee058b4f1998-02-16 06:15:35 +00001429object is callable and \code{0} otherwise.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001430This function always succeeds.
1431\end{cfuncdesc}
1432
1433
Fred Drake659ebfa2000-04-03 15:42:13 +00001434\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
1435 PyObject *args}
Fred Drakee058b4f1998-02-16 06:15:35 +00001436Call a callable Python object \var{callable_object}, with
1437arguments given by the tuple \var{args}. If no arguments are
Fred Drake659ebfa2000-04-03 15:42:13 +00001438needed, then \var{args} may be \NULL{}. Returns the result of the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001439call on success, or \NULL{} on failure. This is the equivalent
Fred Drakee058b4f1998-02-16 06:15:35 +00001440of the Python expression \samp{apply(\var{o}, \var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001441\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001442\end{cfuncdesc}
1443
1444\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001445Call a callable Python object \var{callable_object}, with a
Fred Drake659ebfa2000-04-03 15:42:13 +00001446variable number of C arguments. The C arguments are described
Fred Drakee058b4f1998-02-16 06:15:35 +00001447using a \cfunction{Py_BuildValue()} style format string. The format may
1448be \NULL{}, indicating that no arguments are provided. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001449result of the call on success, or \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001450the equivalent of the Python expression \samp{apply(\var{o},
Fred Drake659ebfa2000-04-03 15:42:13 +00001451\var{args})}.\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001452\end{cfuncdesc}
1453
1454
1455\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001456Call the method named \var{m} of object \var{o} with a variable number
Fred Drake659ebfa2000-04-03 15:42:13 +00001457of C arguments. The C arguments are described by a
Fred Drakee058b4f1998-02-16 06:15:35 +00001458\cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1459indicating that no arguments are provided. Returns the result of the
1460call on success, or \NULL{} on failure. This is the equivalent of the
1461Python expression \samp{\var{o}.\var{method}(\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001462Note that special method names, such as \method{__add__()},
1463\method{__getitem__()}, and so on are not supported. The specific
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001464abstract-object routines for these must be used.
1465\end{cfuncdesc}
1466
1467
1468\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001469Compute and return the hash value of an object \var{o}. On
1470failure, return \code{-1}. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001471expression \samp{hash(\var{o})}.\bifuncindex{hash}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001472\end{cfuncdesc}
1473
1474
1475\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001476Returns \code{1} if the object \var{o} is considered to be true, and
1477\code{0} otherwise. This is equivalent to the Python expression
1478\samp{not not \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001479This function always succeeds.
1480\end{cfuncdesc}
1481
1482
1483\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1484On success, returns a type object corresponding to the object
Fred Drakee058b4f1998-02-16 06:15:35 +00001485type of object \var{o}. On failure, returns \NULL{}. This is
1486equivalent to the Python expression \samp{type(\var{o})}.
Fred Drake53fb7721998-02-16 06:23:20 +00001487\bifuncindex{type}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001488\end{cfuncdesc}
1489
1490\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001491Return the length of object \var{o}. If the object \var{o} provides
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001492both sequence and mapping protocols, the sequence length is
Fred Drake659ebfa2000-04-03 15:42:13 +00001493returned. On error, \code{-1} is returned. This is the equivalent
1494to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001495\end{cfuncdesc}
1496
1497
1498\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001499Return element of \var{o} corresponding to the object \var{key} or
1500\NULL{} on failure. This is the equivalent of the Python expression
1501\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001502\end{cfuncdesc}
1503
1504
1505\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001506Map the object \var{key} to the value \var{v}.
1507Returns \code{-1} on failure. This is the equivalent
1508of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001509\end{cfuncdesc}
1510
1511
Guido van Rossumd1dbf631999-01-22 20:10:49 +00001512\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001513Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1514failure. This is the equivalent of the Python statement \samp{del
1515\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001516\end{cfuncdesc}
1517
Andrew M. Kuchling8c46b302000-07-13 23:58:16 +00001518\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
1519Derives a file-descriptor from a Python object. If the object
1520is an integer or long integer, its value is returned. If not, the
1521object's \method{fileno()} method is called if it exists; the method
1522must return an integer or long integer, which is returned as the file
1523descriptor value. Returns \code{-1} on failure.
1524\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001525
Fred Drakeefd146c1999-02-15 15:30:45 +00001526\section{Number Protocol \label{number}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001527
1528\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001529Returns \code{1} if the object \var{o} provides numeric protocols, and
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001530false otherwise.
1531This function always succeeds.
1532\end{cfuncdesc}
1533
1534
1535\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001536Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1537failure. This is the equivalent of the Python expression
1538\samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001539\end{cfuncdesc}
1540
1541
1542\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
Fred Drake659ebfa2000-04-03 15:42:13 +00001543Returns the result of subtracting \var{o2} from \var{o1}, or
1544\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001545\samp{\var{o1} - \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001546\end{cfuncdesc}
1547
1548
1549\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001550Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1551failure. This is the equivalent of the Python expression
1552\samp{\var{o1} * \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001553\end{cfuncdesc}
1554
1555
1556\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001557Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1558failure.
1559This is the equivalent of the Python expression \samp{\var{o1} /
1560\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001561\end{cfuncdesc}
1562
1563
1564\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001565Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1566failure. This is the equivalent of the Python expression
Fred Drake659ebfa2000-04-03 15:42:13 +00001567\samp{\var{o1} \%\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001568\end{cfuncdesc}
1569
1570
1571\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
Fred Drake53fb7721998-02-16 06:23:20 +00001572See the built-in function \function{divmod()}\bifuncindex{divmod}.
1573Returns \NULL{} on failure. This is the equivalent of the Python
1574expression \samp{divmod(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001575\end{cfuncdesc}
1576
1577
1578\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
Fred Drake53fb7721998-02-16 06:23:20 +00001579See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1580\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001581\samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
Fred Drake659ebfa2000-04-03 15:42:13 +00001582If \var{o3} is to be ignored, pass \cdata{Py_None} in its place
1583(passing \NULL{} for \var{o3} would cause an illegal memory access).
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001584\end{cfuncdesc}
1585
1586
1587\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001588Returns the negation of \var{o} on success, or \NULL{} on failure.
1589This is the equivalent of the Python expression \samp{-\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001590\end{cfuncdesc}
1591
1592
1593\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001594Returns \var{o} on success, or \NULL{} on failure.
1595This is the equivalent of the Python expression \samp{+\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001596\end{cfuncdesc}
1597
1598
1599\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001600Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1601the equivalent of the Python expression \samp{abs(\var{o})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001602\bifuncindex{abs}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001603\end{cfuncdesc}
1604
1605
1606\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001607Returns the bitwise negation of \var{o} on success, or \NULL{} on
1608failure. This is the equivalent of the Python expression
1609\samp{\~\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001610\end{cfuncdesc}
1611
1612
1613\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001614Returns the result of left shifting \var{o1} by \var{o2} on success,
1615or \NULL{} on failure. This is the equivalent of the Python
1616expression \samp{\var{o1} << \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001617\end{cfuncdesc}
1618
1619
1620\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001621Returns the result of right shifting \var{o1} by \var{o2} on success,
1622or \NULL{} on failure. This is the equivalent of the Python
1623expression \samp{\var{o1} >> \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001624\end{cfuncdesc}
1625
1626
1627\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001628Returns the ``bitwise and'' of \var{o2} and \var{o2} on success and
1629\NULL{} on failure. This is the equivalent of the Python expression
1630\samp{\var{o1} \& \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001631\end{cfuncdesc}
1632
1633
1634\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001635Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success,
Fred Drakee058b4f1998-02-16 06:15:35 +00001636or \NULL{} on failure. This is the equivalent of the Python
1637expression \samp{\var{o1} \^{ }\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001638\end{cfuncdesc}
1639
1640\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001641Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
1642\NULL{} on failure. This is the equivalent of the Python expression
1643\samp{\var{o1} | \var{o2}}.
1644\end{cfuncdesc}
1645
1646
1647\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAdd}{PyObject *o1, PyObject *o2}
1648Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on failure.
1649The operation is done \emph{in-place} when \var{o1} supports it. This is the
1650equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1651\end{cfuncdesc}
1652
1653
1654\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceSubtract}{PyObject *o1, PyObject *o2}
1655Returns the result of subtracting \var{o2} from \var{o1}, or
1656\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1657supports it. This is the equivalent of the Python expression \samp{\var{o1}
1658-= \var{o2}}.
1659\end{cfuncdesc}
1660
1661
1662\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceMultiply}{PyObject *o1, PyObject *o2}
1663Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1664failure. The operation is done \emph{in-place} when \var{o1} supports it.
1665This is the equivalent of the Python expression \samp{\var{o1} *= \var{o2}}.
1666\end{cfuncdesc}
1667
1668
1669\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceDivide}{PyObject *o1, PyObject *o2}
1670Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on failure.
1671The operation is done \emph{in-place} when \var{o1} supports it. This is the
1672equivalent of the Python expression \samp{\var{o1} /= \var{o2}}.
1673\end{cfuncdesc}
1674
1675
1676\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRemainder}{PyObject *o1, PyObject *o2}
1677Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1678failure. The operation is done \emph{in-place} when \var{o1} supports it.
1679This is the equivalent of the Python expression \samp{\var{o1} \%= \var{o2}}.
1680\end{cfuncdesc}
1681
1682
1683\begin{cfuncdesc}{PyObject*}{PyNumber_InPlacePower}{PyObject *o1, PyObject *o2, PyObject *o3}
1684See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1685\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1686supports it. This is the equivalent of the Python expression \samp{\var{o1}
1687**= \var{o2}} when o3 is \cdata{Py_None}, or an in-place variant of
1688\samp{pow(\var{o1}, \var{o2}, var{o3})} otherwise. If \var{o3} is to be
1689ignored, pass \cdata{Py_None} in its place (passing \NULL{} for \var{o3}
1690would cause an illegal memory access).
1691\end{cfuncdesc}
1692
1693\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceLshift}{PyObject *o1, PyObject *o2}
1694Returns the result of left shifting \var{o1} by \var{o2} on success, or
1695\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1696supports it. This is the equivalent of the Python expression \samp{\var{o1}
1697<<= \var{o2}}.
1698\end{cfuncdesc}
1699
1700
1701\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRshift}{PyObject *o1, PyObject *o2}
1702Returns the result of right shifting \var{o1} by \var{o2} on success, or
1703\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1704supports it. This is the equivalent of the Python expression \samp{\var{o1}
1705>>= \var{o2}}.
1706\end{cfuncdesc}
1707
1708
1709\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAnd}{PyObject *o1, PyObject *o2}
1710Returns the ``bitwise and'' of \var{o2} and \var{o2} on success
1711and \NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1712supports it. This is the equivalent of the Python expression \samp{\var{o1}
1713\&= \var{o2}}.
1714\end{cfuncdesc}
1715
1716
1717\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceXor}{PyObject *o1, PyObject *o2}
1718Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success, or
1719\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1720supports it. This is the equivalent of the Python expression \samp{\var{o1}
1721\^= \var{o2}}.
1722\end{cfuncdesc}
1723
1724\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2}
1725Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or \NULL{}
1726on failure. The operation is done \emph{in-place} when \var{o1} supports
1727it. This is the equivalent of the Python expression \samp{\var{o1} |=
1728\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001729\end{cfuncdesc}
1730
Fred Drakee058b4f1998-02-16 06:15:35 +00001731\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001732This function takes the addresses of two variables of type
Fred Drake659ebfa2000-04-03 15:42:13 +00001733\ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} and
1734\code{*\var{p2}} have the same type, increment their reference count
1735and return \code{0} (success). If the objects can be converted to a
1736common numeric type, replace \code{*p1} and \code{*p2} by their
1737converted value (with 'new' reference counts), and return \code{0}.
1738If no conversion is possible, or if some other error occurs, return
1739\code{-1} (failure) and don't increment the reference counts. The
1740call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1741statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
1742\bifuncindex{coerce}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001743\end{cfuncdesc}
1744
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001745\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001746Returns the \var{o} converted to an integer object on success, or
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001747\NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001748expression \samp{int(\var{o})}.\bifuncindex{int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001749\end{cfuncdesc}
1750
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001751\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001752Returns the \var{o} converted to a long integer object on success,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001753or \NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001754expression \samp{long(\var{o})}.\bifuncindex{long}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001755\end{cfuncdesc}
1756
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001757\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001758Returns the \var{o} converted to a float object on success, or
1759\NULL{} on failure. This is the equivalent of the Python expression
1760\samp{float(\var{o})}.\bifuncindex{float}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001761\end{cfuncdesc}
1762
1763
Fred Drakeefd146c1999-02-15 15:30:45 +00001764\section{Sequence Protocol \label{sequence}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001765
1766\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001767Return \code{1} if the object provides sequence protocol, and
1768\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001769\end{cfuncdesc}
1770
Fred Drake659ebfa2000-04-03 15:42:13 +00001771\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
1772Returns the number of objects in sequence \var{o} on success, and
1773\code{-1} on failure. For objects that do not provide sequence
1774protocol, this is equivalent to the Python expression
1775\samp{len(\var{o})}.\bifuncindex{len}
1776\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001777
1778\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001779Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001780failure. This is the equivalent of the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001781expression \samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001782\end{cfuncdesc}
1783
1784
1785\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Fred Drake659ebfa2000-04-03 15:42:13 +00001786Return the result of repeating sequence object
1787\var{o} \var{count} times, or \NULL{} on failure. This is the
1788equivalent of the Python expression \samp{\var{o} * \var{count}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001789\end{cfuncdesc}
1790
Fred Drake7740a012000-09-12 20:27:05 +00001791\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceConcat}{PyObject *o1, PyObject *o2}
1792Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
1793failure. The operation is done \emph{in-place} when \var{o1} supports it.
1794This is the equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1795\end{cfuncdesc}
1796
1797
1798\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceRepeat}{PyObject *o, int count}
1799Return the result of repeating sequence object \var{o} \var{count} times, or
1800\NULL{} on failure. The operation is done \emph{in-place} when \var{o}
1801supports it. This is the equivalent of the Python expression \samp{\var{o}
1802*= \var{count}}.
1803\end{cfuncdesc}
1804
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001805
1806\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001807Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
1808is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001809\end{cfuncdesc}
1810
1811
1812\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001813Return the slice of sequence object \var{o} between \var{i1} and
1814\var{i2}, or \NULL{} on failure. This is the equivalent of the Python
1815expression \samp{\var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001816\end{cfuncdesc}
1817
1818
1819\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001820Assign object \var{v} to the \var{i}th element of \var{o}.
1821Returns \code{-1} on failure. This is the equivalent of the Python
1822statement \samp{\var{o}[\var{i}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001823\end{cfuncdesc}
1824
1825\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001826Delete the \var{i}th element of object \var{v}. Returns
1827\code{-1} on failure. This is the equivalent of the Python
1828statement \samp{del \var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001829\end{cfuncdesc}
1830
Fred Drake659ebfa2000-04-03 15:42:13 +00001831\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
1832 int i2, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001833Assign the sequence object \var{v} to the slice in sequence
1834object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
1835the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001836\end{cfuncdesc}
1837
1838\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001839Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
1840Returns \code{-1} on failure. This is the equivalent of the Python
1841statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001842\end{cfuncdesc}
1843
1844\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001845Returns the \var{o} as a tuple on success, and \NULL{} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00001846This is equivalent to the Python expression \samp{tuple(\var{o})}.
1847\bifuncindex{tuple}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001848\end{cfuncdesc}
1849
1850\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001851Return the number of occurrences of \var{value} in \var{o}, that is,
1852return the number of keys for which \code{\var{o}[\var{key}] ==
1853\var{value}}. On failure, return \code{-1}. This is equivalent to
1854the Python expression \samp{\var{o}.count(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001855\end{cfuncdesc}
1856
Fred Drake659ebfa2000-04-03 15:42:13 +00001857\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001858Determine if \var{o} contains \var{value}. If an item in \var{o} is
1859equal to \var{value}, return \code{1}, otherwise return \code{0}. On
1860error, return \code{-1}. This is equivalent to the Python expression
1861\samp{\var{value} in \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001862\end{cfuncdesc}
1863
1864\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001865Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
1866\var{value}}. On error, return \code{-1}. This is equivalent to
1867the Python expression \samp{\var{o}.index(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001868\end{cfuncdesc}
1869
Fred Drakea8455ab2000-06-16 19:58:42 +00001870\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
1871Return a list object with the same contents as the arbitrary sequence
1872\var{o}. The returned list is guaranteed to be new.
1873\end{cfuncdesc}
1874
1875\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1876Return a tuple object with the same contents as the arbitrary sequence
1877\var{o}. If \var{o} is a tuple, a new reference will be returned,
1878otherwise a tuple will be constructed with the appropriate contents.
1879\end{cfuncdesc}
1880
Fred Drakef39ed671998-02-26 22:01:23 +00001881
Fred Drake81cccb72000-09-12 15:22:05 +00001882\begin{cfuncdesc}{PyObject*}{PySequence_Fast}{PyObject *o, const char *m}
1883Returns the sequence \var{o} as a tuple, unless it is already a
1884tuple or list, in which case \var{o} is returned. Use
1885\cfunction{PySequence_Fast_GET_ITEM()} to access the members of the
1886result. Returns \NULL{} on failure. If the object is not a sequence,
1887raises \exception{TypeError} with \var{m} as the message text.
1888\end{cfuncdesc}
1889
1890\begin{cfuncdesc}{PyObject*}{PySequence_Fast_GET_ITEM}{PyObject *o, int i}
1891Return the \var{i}th element of \var{o}, assuming that \var{o} was
1892returned by \cfunction{PySequence_Fast()}, and that \var{i} is within
1893bounds. The caller is expected to get the length of the sequence by
1894calling \cfunction{PyObject_Size()} on \var{o}, since lists and tuples
1895are guaranteed to always return their true length.
1896\end{cfuncdesc}
1897
1898
Fred Drakeefd146c1999-02-15 15:30:45 +00001899\section{Mapping Protocol \label{mapping}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001900
1901\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001902Return \code{1} if the object provides mapping protocol, and
1903\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001904\end{cfuncdesc}
1905
1906
1907\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001908Returns the number of keys in object \var{o} on success, and
1909\code{-1} on failure. For objects that do not provide mapping
1910protocol, this is equivalent to the Python expression
1911\samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001912\end{cfuncdesc}
1913
1914
1915\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001916Remove the mapping for object \var{key} from the object \var{o}.
1917Return \code{-1} on failure. This is equivalent to
1918the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001919\end{cfuncdesc}
1920
1921
1922\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001923Remove the mapping for object \var{key} from the object \var{o}.
1924Return \code{-1} on failure. This is equivalent to
1925the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001926\end{cfuncdesc}
1927
1928
1929\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
Fred Drake659ebfa2000-04-03 15:42:13 +00001930On success, return \code{1} if the mapping object has the key
1931\var{key} and \code{0} otherwise. This is equivalent to the Python
1932expression \samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001933This function always succeeds.
1934\end{cfuncdesc}
1935
1936
1937\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001938Return \code{1} if the mapping object has the key \var{key} and
1939\code{0} otherwise. This is equivalent to the Python expression
1940\samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001941This function always succeeds.
1942\end{cfuncdesc}
1943
1944
1945\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001946On success, return a list of the keys in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001947failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001948expression \samp{\var{o}.keys()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001949\end{cfuncdesc}
1950
1951
1952\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001953On success, return a list of the values in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001954failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001955expression \samp{\var{o}.values()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001956\end{cfuncdesc}
1957
1958
1959\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001960On success, return a list of the items in object \var{o}, where
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001961each item is a tuple containing a key-value pair. On
1962failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001963expression \samp{\var{o}.items()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001964\end{cfuncdesc}
1965
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001966
1967\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001968Return element of \var{o} corresponding to the object \var{key} or
1969\NULL{} on failure. This is the equivalent of the Python expression
1970\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001971\end{cfuncdesc}
1972
Guido van Rossum0a0f11b1998-10-16 17:43:53 +00001973\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001974Map the object \var{key} to the value \var{v} in object \var{o}.
1975Returns \code{-1} on failure. This is the equivalent of the Python
1976statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001977\end{cfuncdesc}
1978
1979
Fred Drakeefd146c1999-02-15 15:30:45 +00001980\chapter{Concrete Objects Layer \label{concrete}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001981
1982The functions in this chapter are specific to certain Python object
1983types. Passing them an object of the wrong type is not a good idea;
1984if you receive an object from a Python program and you are not sure
1985that it has the right type, you must perform a type check first;
Fred Drake659ebfa2000-04-03 15:42:13 +00001986for example. to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00001987\cfunction{PyDict_Check()}. The chapter is structured like the
1988``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001989
1990
Fred Drakeefd146c1999-02-15 15:30:45 +00001991\section{Fundamental Objects \label{fundamental}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001992
Fred Drakee5bf8b21998-02-12 21:22:28 +00001993This section describes Python type objects and the singleton object
1994\code{None}.
1995
1996
Fred Drakeefd146c1999-02-15 15:30:45 +00001997\subsection{Type Objects \label{typeObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001998
Fred Drake659ebfa2000-04-03 15:42:13 +00001999\obindex{type}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002000\begin{ctypedesc}{PyTypeObject}
Fred Drake659ebfa2000-04-03 15:42:13 +00002001The C structure of the objects used to describe built-in types.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002002\end{ctypedesc}
2003
Fred Drake659ebfa2000-04-03 15:42:13 +00002004\begin{cvardesc}{PyObject*}{PyType_Type}
Fred Drakeefd146c1999-02-15 15:30:45 +00002005This is the type object for type objects; it is the same object as
2006\code{types.TypeType} in the Python layer.
Fred Drake659ebfa2000-04-03 15:42:13 +00002007\withsubitem{(in module types)}{\ttindex{TypeType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002008\end{cvardesc}
2009
Fred Drake659ebfa2000-04-03 15:42:13 +00002010\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
2011Returns true is the object \var{o} is a type object.
2012\end{cfuncdesc}
2013
2014\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
2015Returns true if the type object \var{o} sets the feature
2016\var{feature}. Type features are denoted by single bit flags. The
2017only defined feature flag is \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER},
2018described in section \ref{buffer-structs}.
2019\end{cfuncdesc}
2020
Fred Drakee5bf8b21998-02-12 21:22:28 +00002021
Fred Drakeefd146c1999-02-15 15:30:45 +00002022\subsection{The None Object \label{noneObject}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002023
Fred Drake659ebfa2000-04-03 15:42:13 +00002024\obindex{None@\texttt{None}}
2025Note that the \ctype{PyTypeObject} for \code{None} is not directly
2026exposed in the Python/C API. Since \code{None} is a singleton,
2027testing for object identity (using \samp{==} in C) is sufficient.
2028There is no \cfunction{PyNone_Check()} function for the same reason.
2029
2030\begin{cvardesc}{PyObject*}{Py_None}
Guido van Rossum44475131998-04-21 15:30:01 +00002031The Python \code{None} object, denoting lack of value. This object has
2032no methods.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002033\end{cvardesc}
2034
2035
Fred Drakeefd146c1999-02-15 15:30:45 +00002036\section{Sequence Objects \label{sequenceObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002037
Fred Drake659ebfa2000-04-03 15:42:13 +00002038\obindex{sequence}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002039Generic operations on sequence objects were discussed in the previous
2040chapter; this section deals with the specific kinds of sequence
2041objects that are intrinsic to the Python language.
2042
2043
Fred Drakeefd146c1999-02-15 15:30:45 +00002044\subsection{String Objects \label{stringObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002045
Fred Drake659ebfa2000-04-03 15:42:13 +00002046\obindex{string}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002047\begin{ctypedesc}{PyStringObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002048This subtype of \ctype{PyObject} represents a Python string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002049\end{ctypedesc}
2050
2051\begin{cvardesc}{PyTypeObject}{PyString_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002052This instance of \ctype{PyTypeObject} represents the Python string
2053type; it is the same object as \code{types.TypeType} in the Python
2054layer.\withsubitem{(in module types)}{\ttindex{StringType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002055\end{cvardesc}
2056
2057\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002058Returns true if the object \var{o} is a string object.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002059\end{cfuncdesc}
2060
Fred Drakec6fa34e1998-04-02 06:47:24 +00002061\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002062Returns a new string object with the value \var{v} on success, and
2063\NULL{} on failure.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002064\end{cfuncdesc}
2065
Fred Drake659ebfa2000-04-03 15:42:13 +00002066\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
2067 int len}
2068Returns a new string object with the value \var{v} and length
2069\var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
2070the contents of the string are uninitialized.
2071\end{cfuncdesc}
2072
Fred Drakec6fa34e1998-04-02 06:47:24 +00002073\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002074Returns the length of the string in string object \var{string}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002075\end{cfuncdesc}
2076
Fred Drake659ebfa2000-04-03 15:42:13 +00002077\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
2078Macro form of \cfunction{PyString_GetSize()} but without error
2079checking.
2080\end{cfuncdesc}
2081
Fred Drakec6fa34e1998-04-02 06:47:24 +00002082\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
Fred Drake659ebfa2000-04-03 15:42:13 +00002083Returns a null-terminated representation of the contents of
2084\var{string}. The pointer refers to the internal buffer of
2085\var{string}, not a copy. The data must not be modified in any way.
2086It must not be de-allocated.
2087\end{cfuncdesc}
2088
2089\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
2090Macro form of \cfunction{PyString_AsString()} but without error
2091checking.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002092\end{cfuncdesc}
2093
2094\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
2095 PyObject *newpart}
Fred Drake66b989c1999-02-15 20:15:39 +00002096Creates a new string object in \var{*string} containing the
Fred Drakeddc6c272000-03-31 18:22:38 +00002097contents of \var{newpart} appended to \var{string}; the caller will
2098own the new reference. The reference to the old value of \var{string}
2099will be stolen. If the new string
Fred Drake66b989c1999-02-15 20:15:39 +00002100cannot be created, the old reference to \var{string} will still be
2101discarded and the value of \var{*string} will be set to
2102\NULL{}; the appropriate exception will be set.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002103\end{cfuncdesc}
2104
2105\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
2106 PyObject *newpart}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002107Creates a new string object in \var{*string} containing the contents
Guido van Rossum44475131998-04-21 15:30:01 +00002108of \var{newpart} appended to \var{string}. This version decrements
2109the reference count of \var{newpart}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002110\end{cfuncdesc}
2111
2112\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
Guido van Rossum44475131998-04-21 15:30:01 +00002113A way to resize a string object even though it is ``immutable''.
2114Only use this to build up a brand new string object; don't use this if
2115the string may already be known in other parts of the code.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002116\end{cfuncdesc}
2117
2118\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
2119 PyObject *args}
Guido van Rossum44475131998-04-21 15:30:01 +00002120Returns a new string object from \var{format} and \var{args}. Analogous
Fred Drake659ebfa2000-04-03 15:42:13 +00002121to \code{\var{format} \%\ \var{args}}. The \var{args} argument must be
Guido van Rossum44475131998-04-21 15:30:01 +00002122a tuple.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002123\end{cfuncdesc}
2124
2125\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
Guido van Rossum44475131998-04-21 15:30:01 +00002126Intern the argument \var{*string} in place. The argument must be the
2127address of a pointer variable pointing to a Python string object.
2128If there is an existing interned string that is the same as
2129\var{*string}, it sets \var{*string} to it (decrementing the reference
2130count of the old string object and incrementing the reference count of
2131the interned string object), otherwise it leaves \var{*string} alone
2132and interns it (incrementing its reference count). (Clarification:
2133even though there is a lot of talk about reference counts, think of
Fred Drakef8830d11998-04-23 14:06:01 +00002134this function as reference-count-neutral; you own the object after
2135the call if and only if you owned it before the call.)
Fred Drakec6fa34e1998-04-02 06:47:24 +00002136\end{cfuncdesc}
2137
2138\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
Fred Drakef8830d11998-04-23 14:06:01 +00002139A combination of \cfunction{PyString_FromString()} and
2140\cfunction{PyString_InternInPlace()}, returning either a new string object
Guido van Rossum44475131998-04-21 15:30:01 +00002141that has been interned, or a new (``owned'') reference to an earlier
2142interned string object with the same value.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002143\end{cfuncdesc}
2144
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002145\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
2146 int size,
2147 const char *encoding,
2148 const char *errors}
2149Create a string object by decoding \var{size} bytes of the encoded
2150buffer \var{s}. \var{encoding} and \var{errors} have the same meaning
2151as the parameters of the same name in the unicode() builtin
2152function. The codec to be used is looked up using the Python codec
2153registry. Returns \NULL{} in case an exception was raised by the
2154codec.
2155\end{cfuncdesc}
2156
2157\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const Py_UNICODE *s,
2158 int size,
2159 const char *encoding,
2160 const char *errors}
2161Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2162Python string object. \var{encoding} and \var{errors} have the same
2163meaning as the parameters of the same name in the string .encode()
2164method. The codec to be used is looked up using the Python codec
2165registry. Returns \NULL{} in case an exception was raised by the
2166codec.
2167\end{cfuncdesc}
2168
2169\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedString}{PyObject *unicode,
2170 const char *encoding,
2171 const char *errors}
2172Encodes a string object and returns the result as Python string
2173object. \var{encoding} and \var{errors} have the same meaning as the
2174parameters of the same name in the string .encode() method. The codec
2175to be used is looked up using the Python codec registry. Returns
2176\NULL{} in case an exception was raised by the codec.
2177\end{cfuncdesc}
2178
Fred Drakee5bf8b21998-02-12 21:22:28 +00002179
Fred Drakea4cd2612000-04-06 14:10:29 +00002180\subsection{Unicode Objects \label{unicodeObjects}}
2181\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
2182
2183%--- Unicode Type -------------------------------------------------------
2184
2185These are the basic Unicode object types used for the Unicode
2186implementation in Python:
2187
2188\begin{ctypedesc}{Py_UNICODE}
2189This type represents a 16-bit unsigned storage type which is used by
2190Python internally as basis for holding Unicode ordinals. On platforms
2191where \ctype{wchar_t} is available and also has 16-bits,
2192\ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
2193native platform compatibility. On all other platforms,
2194\ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
2195\end{ctypedesc}
2196
2197\begin{ctypedesc}{PyUnicodeObject}
2198This subtype of \ctype{PyObject} represents a Python Unicode object.
2199\end{ctypedesc}
2200
2201\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
2202This instance of \ctype{PyTypeObject} represents the Python Unicode type.
2203\end{cvardesc}
2204
2205%--- These are really C macros... is there a macrodesc TeX macro ?
2206
2207The following APIs are really C macros and can be used to do fast
2208checks and to access internal read-only data of Unicode objects:
2209
2210\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
2211Returns true if the object \var{o} is a Unicode object.
2212\end{cfuncdesc}
2213
2214\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
2215Returns the size of the object. o has to be a
2216PyUnicodeObject (not checked).
2217\end{cfuncdesc}
2218
2219\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
2220Returns the size of the object's internal buffer in bytes. o has to be
2221a PyUnicodeObject (not checked).
2222\end{cfuncdesc}
2223
Fred Drake992fe5a2000-06-16 21:04:15 +00002224\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002225Returns a pointer to the internal Py_UNICODE buffer of the object. o
2226has to be a PyUnicodeObject (not checked).
2227\end{cfuncdesc}
2228
Fred Drake992fe5a2000-06-16 21:04:15 +00002229\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002230Returns a (const char *) pointer to the internal buffer of the object.
2231o has to be a PyUnicodeObject (not checked).
2232\end{cfuncdesc}
2233
2234% --- Unicode character properties ---------------------------------------
2235
2236Unicode provides many different character properties. The most often
2237needed ones are available through these macros which are mapped to C
2238functions depending on the Python configuration.
2239
2240\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
2241Returns 1/0 depending on whether \var{ch} is a whitespace character.
2242\end{cfuncdesc}
2243
2244\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
2245Returns 1/0 depending on whether \var{ch} is a lowercase character.
2246\end{cfuncdesc}
2247
2248\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
Fred Drakeae96aab2000-07-03 13:38:10 +00002249Returns 1/0 depending on whether \var{ch} is an uppercase character.
Fred Drakea4cd2612000-04-06 14:10:29 +00002250\end{cfuncdesc}
2251
2252\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
2253Returns 1/0 depending on whether \var{ch} is a titlecase character.
2254\end{cfuncdesc}
2255
2256\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
2257Returns 1/0 depending on whether \var{ch} is a linebreak character.
2258\end{cfuncdesc}
2259
2260\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
2261Returns 1/0 depending on whether \var{ch} is a decimal character.
2262\end{cfuncdesc}
2263
2264\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
2265Returns 1/0 depending on whether \var{ch} is a digit character.
2266\end{cfuncdesc}
2267
2268\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
2269Returns 1/0 depending on whether \var{ch} is a numeric character.
2270\end{cfuncdesc}
2271
Fred Drakeae96aab2000-07-03 13:38:10 +00002272\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
2273Returns 1/0 depending on whether \var{ch} is an alphabetic character.
2274\end{cfuncdesc}
2275
2276\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
2277Returns 1/0 depending on whether \var{ch} is an alphanumeric character.
2278\end{cfuncdesc}
2279
Fred Drakea4cd2612000-04-06 14:10:29 +00002280These APIs can be used for fast direct character conversions:
2281
2282\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
2283Returns the character \var{ch} converted to lower case.
2284\end{cfuncdesc}
2285
2286\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
2287Returns the character \var{ch} converted to upper case.
2288\end{cfuncdesc}
2289
2290\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
2291Returns the character \var{ch} converted to title case.
2292\end{cfuncdesc}
2293
2294\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
2295Returns the character \var{ch} converted to a decimal positive integer.
2296Returns -1 in case this is not possible. Does not raise exceptions.
2297\end{cfuncdesc}
2298
2299\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
2300Returns the character \var{ch} converted to a single digit integer.
2301Returns -1 in case this is not possible. Does not raise exceptions.
2302\end{cfuncdesc}
2303
2304\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
2305Returns the character \var{ch} converted to a (positive) double.
2306Returns -1.0 in case this is not possible. Does not raise exceptions.
2307\end{cfuncdesc}
2308
2309% --- Plain Py_UNICODE ---------------------------------------------------
2310
2311To create Unicode objects and access their basic sequence properties,
2312use these APIs:
2313
2314\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
2315 int size}
2316
2317Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
2318given size. \var{u} may be \NULL{} which causes the contents to be
2319undefined. It is the user's responsibility to fill in the needed data.
2320The buffer is copied into the new object.
2321\end{cfuncdesc}
2322
Fred Drake1d158692000-06-18 05:21:21 +00002323\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002324Return a read-only pointer to the Unicode object's internal
2325\ctype{Py_UNICODE} buffer.
2326\end{cfuncdesc}
2327
2328\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
2329Return the length of the Unicode object.
2330\end{cfuncdesc}
2331
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002332\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
2333 const char *encoding,
2334 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002335
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002336Coerce an encoded object obj to an Unicode object and return a
2337reference with incremented refcount.
Fred Drakea4cd2612000-04-06 14:10:29 +00002338
2339Coercion is done in the following way:
2340\begin{enumerate}
2341\item Unicode objects are passed back as-is with incremented
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002342 refcount. Note: these cannot be decoded; passing a non-NULL
2343 value for encoding will result in a TypeError.
Fred Drakea4cd2612000-04-06 14:10:29 +00002344
2345\item String and other char buffer compatible objects are decoded
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002346 according to the given encoding and using the error handling
2347 defined by errors. Both can be NULL to have the interface use
2348 the default values (see the next section for details).
Fred Drakea4cd2612000-04-06 14:10:29 +00002349
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002350\item All other objects cause an exception.
Fred Drakea4cd2612000-04-06 14:10:29 +00002351\end{enumerate}
2352The API returns NULL in case of an error. The caller is responsible
2353for decref'ing the returned objects.
2354\end{cfuncdesc}
2355
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002356\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
2357
2358Shortcut for PyUnicode_FromEncodedObject(obj, NULL, ``strict'')
2359which is used throughout the interpreter whenever coercion to
2360Unicode is needed.
2361\end{cfuncdesc}
2362
Fred Drakea4cd2612000-04-06 14:10:29 +00002363% --- wchar_t support for platforms which support it ---------------------
2364
2365If the platform supports \ctype{wchar_t} and provides a header file
2366wchar.h, Python can interface directly to this type using the
2367following functions. Support is optimized if Python's own
2368\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
2369
2370\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
2371 int size}
2372Create a Unicode Object from the \ctype{whcar_t} buffer \var{w} of the
2373given size. Returns \NULL{} on failure.
2374\end{cfuncdesc}
2375
2376\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
2377 wchar_t *w,
2378 int size}
Fred Drakea4cd2612000-04-06 14:10:29 +00002379Copies the Unicode Object contents into the \ctype{whcar_t} buffer
2380\var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
2381Returns the number of \ctype{whcar_t} characters copied or -1 in case
2382of an error.
2383\end{cfuncdesc}
2384
2385
2386\subsubsection{Builtin Codecs \label{builtinCodecs}}
2387
2388Python provides a set of builtin codecs which are written in C
2389for speed. All of these codecs are directly usable via the
2390following functions.
2391
2392Many of the following APIs take two arguments encoding and
2393errors. These parameters encoding and errors have the same semantics
2394as the ones of the builtin unicode() Unicode object constructor.
2395
2396Setting encoding to NULL causes the default encoding to be used which
2397is UTF-8.
2398
2399Error handling is set by errors which may also be set to NULL meaning
2400to use the default handling defined for the codec. Default error
2401handling for all builtin codecs is ``strict'' (ValueErrors are raised).
2402
2403The codecs all use a similar interface. Only deviation from the
2404following generic ones are documented for simplicity.
2405
2406% --- Generic Codecs -----------------------------------------------------
2407
2408These are the generic codec APIs:
2409
2410\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
2411 int size,
2412 const char *encoding,
2413 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002414Create a Unicode object by decoding \var{size} bytes of the encoded
2415string \var{s}. \var{encoding} and \var{errors} have the same meaning
2416as the parameters of the same name in the unicode() builtin
2417function. The codec to be used is looked up using the Python codec
2418registry. Returns \NULL{} in case an exception was raised by the
2419codec.
2420\end{cfuncdesc}
2421
2422\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
2423 int size,
2424 const char *encoding,
2425 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002426Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2427Python string object. \var{encoding} and \var{errors} have the same
2428meaning as the parameters of the same name in the Unicode .encode()
2429method. The codec to be used is looked up using the Python codec
2430registry. Returns \NULL{} in case an exception was raised by the
2431codec.
2432\end{cfuncdesc}
2433
2434\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
2435 const char *encoding,
2436 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002437Encodes a Unicode object and returns the result as Python string
2438object. \var{encoding} and \var{errors} have the same meaning as the
2439parameters of the same name in the Unicode .encode() method. The codec
2440to be used is looked up using the Python codec registry. Returns
2441\NULL{} in case an exception was raised by the codec.
2442\end{cfuncdesc}
2443
2444% --- UTF-8 Codecs -------------------------------------------------------
2445
2446These are the UTF-8 codec APIs:
2447
2448\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
2449 int size,
2450 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002451Creates a Unicode object by decoding \var{size} bytes of the UTF-8
2452encoded string \var{s}. Returns \NULL{} in case an exception was
2453raised by the codec.
2454\end{cfuncdesc}
2455
2456\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
2457 int size,
2458 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002459Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
2460and returns a Python string object. Returns \NULL{} in case an
2461exception was raised by the codec.
2462\end{cfuncdesc}
2463
2464\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002465Encodes a Unicode objects using UTF-8 and returns the result as Python
2466string object. Error handling is ``strict''. Returns
2467\NULL{} in case an exception was raised by the codec.
2468\end{cfuncdesc}
2469
2470% --- UTF-16 Codecs ------------------------------------------------------ */
2471
2472These are the UTF-16 codec APIs:
2473
2474\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
2475 int size,
2476 const char *errors,
2477 int *byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002478Decodes \var{length} bytes from a UTF-16 encoded buffer string and
2479returns the corresponding Unicode object.
2480
2481\var{errors} (if non-NULL) defines the error handling. It defaults
2482to ``strict''.
2483
2484If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
2485the given byte order:
2486
2487\begin{verbatim}
2488 *byteorder == -1: little endian
2489 *byteorder == 0: native order
2490 *byteorder == 1: big endian
2491\end{verbatim}
2492
2493and then switches according to all byte order marks (BOM) it finds in
2494the input data. BOM marks are not copied into the resulting Unicode
2495string. After completion, \var{*byteorder} is set to the current byte
2496order at the end of input data.
2497
2498If \var{byteorder} is \NULL{}, the codec starts in native order mode.
2499
2500Returns \NULL{} in case an exception was raised by the codec.
2501\end{cfuncdesc}
2502
2503\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
2504 int size,
2505 const char *errors,
2506 int byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002507Returns a Python string object holding the UTF-16 encoded value of the
2508Unicode data in \var{s}.
2509
Fred Drakea8455ab2000-06-16 19:58:42 +00002510If \var{byteorder} is not \code{0}, output is written according to the
Fred Drakea4cd2612000-04-06 14:10:29 +00002511following byte order:
2512
2513\begin{verbatim}
2514 byteorder == -1: little endian
2515 byteorder == 0: native byte order (writes a BOM mark)
2516 byteorder == 1: big endian
2517\end{verbatim}
2518
Fred Drakea8455ab2000-06-16 19:58:42 +00002519If byteorder is \code{0}, the output string will always start with the
Fred Drakea4cd2612000-04-06 14:10:29 +00002520Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
2521prepended.
2522
2523Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
2524reduced to UCS-2. This trick makes it possible to add full UTF-16
2525capabilities at a later point without comprimising the APIs.
2526
2527Returns \NULL{} in case an exception was raised by the codec.
2528\end{cfuncdesc}
2529
2530\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002531Returns a Python string using the UTF-16 encoding in native byte
2532order. The string always starts with a BOM mark. Error handling is
2533``strict''. Returns \NULL{} in case an exception was raised by the
2534codec.
2535\end{cfuncdesc}
2536
2537% --- Unicode-Escape Codecs ----------------------------------------------
2538
2539These are the ``Unicode Esacpe'' codec APIs:
2540
2541\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
2542 int size,
2543 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002544Creates a Unicode object by decoding \var{size} bytes of the Unicode-Esacpe
2545encoded string \var{s}. Returns \NULL{} in case an exception was
2546raised by the codec.
2547\end{cfuncdesc}
2548
2549\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
2550 int size,
2551 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002552Encodes the \ctype{Py_UNICODE} buffer of the given size using Unicode-Escape
2553and returns a Python string object. Returns \NULL{} in case an
2554exception was raised by the codec.
2555\end{cfuncdesc}
2556
2557\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002558Encodes a Unicode objects using Unicode-Escape and returns the result
2559as Python string object. Error handling is ``strict''. Returns
2560\NULL{} in case an exception was raised by the codec.
2561\end{cfuncdesc}
2562
2563% --- Raw-Unicode-Escape Codecs ------------------------------------------
2564
2565These are the ``Raw Unicode Esacpe'' codec APIs:
2566
2567\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
2568 int size,
2569 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002570Creates a Unicode object by decoding \var{size} bytes of the Raw-Unicode-Esacpe
2571encoded string \var{s}. Returns \NULL{} in case an exception was
2572raised by the codec.
2573\end{cfuncdesc}
2574
2575\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
2576 int size,
2577 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002578Encodes the \ctype{Py_UNICODE} buffer of the given size using Raw-Unicode-Escape
2579and returns a Python string object. Returns \NULL{} in case an
2580exception was raised by the codec.
2581\end{cfuncdesc}
2582
2583\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002584Encodes a Unicode objects using Raw-Unicode-Escape and returns the result
2585as Python string object. Error handling is ``strict''. Returns
2586\NULL{} in case an exception was raised by the codec.
2587\end{cfuncdesc}
2588
2589% --- Latin-1 Codecs -----------------------------------------------------
2590
2591These are the Latin-1 codec APIs:
2592
2593Latin-1 corresponds to the first 256 Unicode ordinals and only these
2594are accepted by the codecs during encoding.
2595
2596\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002597 int size,
2598 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002599Creates a Unicode object by decoding \var{size} bytes of the Latin-1
2600encoded string \var{s}. Returns \NULL{} in case an exception was
2601raised by the codec.
2602\end{cfuncdesc}
2603
2604\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002605 int size,
2606 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002607Encodes the \ctype{Py_UNICODE} buffer of the given size using Latin-1
2608and returns a Python string object. Returns \NULL{} in case an
2609exception was raised by the codec.
2610\end{cfuncdesc}
2611
2612\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002613Encodes a Unicode objects using Latin-1 and returns the result as
2614Python string object. Error handling is ``strict''. Returns
2615\NULL{} in case an exception was raised by the codec.
2616\end{cfuncdesc}
2617
2618% --- ASCII Codecs -------------------------------------------------------
2619
Fred Drake1d158692000-06-18 05:21:21 +00002620These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
2621accepted. All other codes generate errors.
Fred Drakea4cd2612000-04-06 14:10:29 +00002622
2623\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002624 int size,
2625 const char *errors}
2626Creates a Unicode object by decoding \var{size} bytes of the
2627\ASCII{} encoded string \var{s}. Returns \NULL{} in case an exception
2628was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002629\end{cfuncdesc}
2630
2631\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002632 int size,
2633 const char *errors}
2634Encodes the \ctype{Py_UNICODE} buffer of the given size using
2635\ASCII{} and returns a Python string object. Returns \NULL{} in case
2636an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002637\end{cfuncdesc}
2638
2639\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
Fred Drake1d158692000-06-18 05:21:21 +00002640Encodes a Unicode objects using \ASCII{} and returns the result as Python
Fred Drakea4cd2612000-04-06 14:10:29 +00002641string object. Error handling is ``strict''. Returns
2642\NULL{} in case an exception was raised by the codec.
2643\end{cfuncdesc}
2644
2645% --- Character Map Codecs -----------------------------------------------
2646
2647These are the mapping codec APIs:
2648
2649This codec is special in that it can be used to implement many
2650different codecs (and this is in fact what was done to obtain most of
2651the standard codecs included in the \module{encodings} package). The
2652codec uses mapping to encode and decode characters.
2653
2654Decoding mappings must map single string characters to single Unicode
2655characters, integers (which are then interpreted as Unicode ordinals)
2656or None (meaning "undefined mapping" and causing an error).
2657
2658Encoding mappings must map single Unicode characters to single string
2659characters, integers (which are then interpreted as Latin-1 ordinals)
2660or None (meaning "undefined mapping" and causing an error).
2661
2662The mapping objects provided must only support the __getitem__ mapping
2663interface.
2664
2665If a character lookup fails with a LookupError, the character is
2666copied as-is meaning that its ordinal value will be interpreted as
2667Unicode or Latin-1 ordinal resp. Because of this, mappings only need
2668to contain those mappings which map characters to different code
2669points.
2670
2671\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
2672 int size,
2673 PyObject *mapping,
2674 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002675Creates a Unicode object by decoding \var{size} bytes of the encoded
2676string \var{s} using the given \var{mapping} object. Returns \NULL{}
2677in case an exception was raised by the codec.
2678\end{cfuncdesc}
2679
2680\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
2681 int size,
2682 PyObject *mapping,
2683 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002684Encodes the \ctype{Py_UNICODE} buffer of the given size using the
2685given \var{mapping} object and returns a Python string object.
2686Returns \NULL{} in case an exception was raised by the codec.
2687\end{cfuncdesc}
2688
2689\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
2690 PyObject *mapping}
Fred Drakea4cd2612000-04-06 14:10:29 +00002691Encodes a Unicode objects using the given \var{mapping} object and
2692returns the result as Python string object. Error handling is
2693``strict''. Returns \NULL{} in case an exception was raised by the
2694codec.
2695\end{cfuncdesc}
2696
2697The following codec API is special in that maps Unicode to Unicode.
2698
2699\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
2700 int size,
2701 PyObject *table,
2702 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002703Translates a \ctype{Py_UNICODE} buffer of the given length by applying
2704a character mapping \var{table} to it and returns the resulting
Fred Drake1d158692000-06-18 05:21:21 +00002705Unicode object. Returns \NULL{} when an exception was raised by the
2706codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002707
2708The \var{mapping} table must map Unicode ordinal integers to Unicode
2709ordinal integers or None (causing deletion of the character).
2710
2711Mapping tables must only provide the __getitem__ interface,
2712e.g. dictionaries or sequences. Unmapped character ordinals (ones
2713which cause a LookupError) are left untouched and are copied as-is.
Fred Drakea4cd2612000-04-06 14:10:29 +00002714\end{cfuncdesc}
2715
2716% --- MBCS codecs for Windows --------------------------------------------
2717
Fred Drake1d158692000-06-18 05:21:21 +00002718These are the MBCS codec APIs. They are currently only available on
Fred Drakea4cd2612000-04-06 14:10:29 +00002719Windows and use the Win32 MBCS converters to implement the
Fred Drake1d158692000-06-18 05:21:21 +00002720conversions. Note that MBCS (or DBCS) is a class of encodings, not
2721just one. The target encoding is defined by the user settings on the
2722machine running the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002723
2724\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
2725 int size,
2726 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002727Creates a Unicode object by decoding \var{size} bytes of the MBCS
Fred Drake1d158692000-06-18 05:21:21 +00002728encoded string \var{s}. Returns \NULL{} in case an exception was
Fred Drakea4cd2612000-04-06 14:10:29 +00002729raised by the codec.
2730\end{cfuncdesc}
2731
2732\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
2733 int size,
2734 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002735Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
2736and returns a Python string object. Returns \NULL{} in case an
2737exception was raised by the codec.
2738\end{cfuncdesc}
2739
2740\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002741Encodes a Unicode objects using MBCS and returns the result as Python
Fred Drake1d158692000-06-18 05:21:21 +00002742string object. Error handling is ``strict''. Returns \NULL{} in case
2743an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002744\end{cfuncdesc}
2745
2746% --- Methods & Slots ----------------------------------------------------
2747
2748\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
2749
2750The following APIs are capable of handling Unicode objects and strings
2751on input (we refer to them as strings in the descriptions) and return
2752Unicode objects or integers as apporpriate.
2753
2754They all return \NULL{} or -1 in case an exception occurrs.
2755
2756\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
2757 PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002758Concat two strings giving a new Unicode string.
2759\end{cfuncdesc}
2760
2761\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
2762 PyObject *sep,
2763 int maxsplit}
Fred Drakea4cd2612000-04-06 14:10:29 +00002764Split a string giving a list of Unicode strings.
2765
2766If sep is NULL, splitting will be done at all whitespace
2767substrings. Otherwise, splits occur at the given separator.
2768
2769At most maxsplit splits will be done. If negative, no limit is set.
2770
2771Separators are not included in the resulting list.
2772\end{cfuncdesc}
2773
2774\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
2775 int maxsplit}
Fred Drake1d158692000-06-18 05:21:21 +00002776Split a Unicode string at line breaks, returning a list of Unicode
2777strings. CRLF is considered to be one line break. The Line break
2778characters are not included in the resulting strings.
Fred Drakea4cd2612000-04-06 14:10:29 +00002779\end{cfuncdesc}
2780
2781\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
2782 PyObject *table,
2783 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002784Translate a string by applying a character mapping table to it and
2785return the resulting Unicode object.
2786
2787The mapping table must map Unicode ordinal integers to Unicode ordinal
2788integers or None (causing deletion of the character).
2789
2790Mapping tables must only provide the __getitem__ interface,
2791e.g. dictionaries or sequences. Unmapped character ordinals (ones
2792which cause a LookupError) are left untouched and are copied as-is.
2793
2794\var{errors} has the usual meaning for codecs. It may be \NULL{}
2795which indicates to use the default error handling.
Fred Drakea4cd2612000-04-06 14:10:29 +00002796\end{cfuncdesc}
2797
2798\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
2799 PyObject *seq}
Fred Drakea4cd2612000-04-06 14:10:29 +00002800Join a sequence of strings using the given separator and return
2801the resulting Unicode string.
2802\end{cfuncdesc}
2803
2804\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
2805 PyObject *substr,
2806 int start,
2807 int end,
2808 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002809Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
2810the given tail end (\var{direction} == -1 means to do a prefix match,
2811\var{direction} == 1 a suffix match), 0 otherwise.
2812\end{cfuncdesc}
2813
2814\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
2815 PyObject *substr,
2816 int start,
2817 int end,
2818 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002819Return the first position of \var{substr} in
2820\var{str}[\var{start}:\var{end}] using the given \var{direction}
2821(\var{direction} == 1 means to do a forward search,
2822\var{direction} == -1 a backward search), 0 otherwise.
2823\end{cfuncdesc}
2824
2825\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
2826 PyObject *substr,
2827 int start,
2828 int end}
Fred Drakea4cd2612000-04-06 14:10:29 +00002829Count the number of occurrences of \var{substr} in
2830\var{str}[\var{start}:\var{end}]
2831\end{cfuncdesc}
2832
2833\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
2834 PyObject *substr,
2835 PyObject *replstr,
2836 int maxcount}
Fred Drakea4cd2612000-04-06 14:10:29 +00002837Replace at most \var{maxcount} occurrences of \var{substr} in
2838\var{str} with \var{replstr} and return the resulting Unicode object.
2839\var{maxcount} == -1 means: replace all occurrences.
2840\end{cfuncdesc}
2841
Fred Drake1d158692000-06-18 05:21:21 +00002842\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002843Compare two strings and return -1, 0, 1 for less than, equal,
2844greater than resp.
2845\end{cfuncdesc}
2846
2847\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
2848 PyObject *args}
Fred Drake1d158692000-06-18 05:21:21 +00002849Returns a new string object from \var{format} and \var{args}; this is
2850analogous to \code{\var{format} \%\ \var{args}}. The
2851\var{args} argument must be a tuple.
Fred Drakea4cd2612000-04-06 14:10:29 +00002852\end{cfuncdesc}
2853
2854\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
2855 PyObject *element}
Fred Drakea4cd2612000-04-06 14:10:29 +00002856Checks whether \var{element} is contained in \var{container} and
Fred Drake1d158692000-06-18 05:21:21 +00002857returns true or false accordingly.
Fred Drakea4cd2612000-04-06 14:10:29 +00002858
Fred Drake1d158692000-06-18 05:21:21 +00002859\var{element} has to coerce to a one element Unicode string. \code{-1} is
Fred Drakea4cd2612000-04-06 14:10:29 +00002860returned in case of an error.
2861\end{cfuncdesc}
2862
2863
Fred Drake58c5a2a1999-08-04 13:13:24 +00002864\subsection{Buffer Objects \label{bufferObjects}}
Fred Drake659ebfa2000-04-03 15:42:13 +00002865\sectionauthor{Greg Stein}{gstein@lyra.org}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002866
Fred Drake659ebfa2000-04-03 15:42:13 +00002867\obindex{buffer}
2868Python objects implemented in C can export a group of functions called
2869the ``buffer\index{buffer interface} interface.'' These functions can
2870be used by an object to expose its data in a raw, byte-oriented
2871format. Clients of the object can use the buffer interface to access
2872the object data directly, without needing to copy it first.
2873
2874Two examples of objects that support
2875the buffer interface are strings and arrays. The string object exposes
2876the character contents in the buffer interface's byte-oriented
2877form. An array can also expose its contents, but it should be noted
2878that array elements may be multi-byte values.
2879
2880An example user of the buffer interface is the file object's
2881\method{write()} method. Any object that can export a series of bytes
2882through the buffer interface can be written to a file. There are a
2883number of format codes to \cfunction{PyArgs_ParseTuple()} that operate
2884against an object's buffer interface, returning data from the target
2885object.
2886
2887More information on the buffer interface is provided in the section
2888``Buffer Object Structures'' (section \ref{buffer-structs}), under
2889the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
2890
2891A ``buffer object'' is defined in the \file{bufferobject.h} header
2892(included by \file{Python.h}). These objects look very similar to
2893string objects at the Python programming level: they support slicing,
2894indexing, concatenation, and some other standard string
2895operations. However, their data can come from one of two sources: from
2896a block of memory, or from another object which exports the buffer
2897interface.
2898
2899Buffer objects are useful as a way to expose the data from another
2900object's buffer interface to the Python programmer. They can also be
2901used as a zero-copy slicing mechanism. Using their ability to
2902reference a block of memory, it is possible to expose any data to the
2903Python programmer quite easily. The memory could be a large, constant
2904array in a C extension, it could be a raw block of memory for
2905manipulation before passing to an operating system library, or it
2906could be used to pass around structured data in its native, in-memory
2907format.
2908
2909\begin{ctypedesc}{PyBufferObject}
2910This subtype of \ctype{PyObject} represents a buffer object.
2911\end{ctypedesc}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002912
2913\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
2914The instance of \ctype{PyTypeObject} which represents the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00002915buffer type; it is the same object as \code{types.BufferType} in the
2916Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002917\end{cvardesc}
2918
2919\begin{cvardesc}{int}{Py_END_OF_BUFFER}
Fred Drake659ebfa2000-04-03 15:42:13 +00002920This constant may be passed as the \var{size} parameter to
2921\cfunction{PyBuffer_FromObject()} or
2922\cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the new
2923\ctype{PyBufferObject} should refer to \var{base} object from the
2924specified \var{offset} to the end of its exported buffer. Using this
2925enables the caller to avoid querying the \var{base} object for its
2926length.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002927\end{cvardesc}
2928
2929\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
2930Return true if the argument has type \cdata{PyBuffer_Type}.
2931\end{cfuncdesc}
2932
2933\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
2934 int offset, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002935Return a new read-only buffer object. This raises
2936\exception{TypeError} if \var{base} doesn't support the read-only
2937buffer protocol or doesn't provide exactly one buffer segment, or it
2938raises \exception{ValueError} if \var{offset} is less than zero. The
2939buffer will hold a reference to the \var{base} object, and the
2940buffer's contents will refer to the \var{base} object's buffer
2941interface, starting as position \var{offset} and extending for
2942\var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
2943the new buffer's contents extend to the length of the
2944\var{base} object's exported buffer data.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002945\end{cfuncdesc}
2946
2947\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
2948 int offset,
2949 int size}
2950Return a new writable buffer object. Parameters and exceptions are
2951similar to those for \cfunction{PyBuffer_FromObject()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00002952If the \var{base} object does not export the writeable buffer
2953protocol, then \exception{TypeError} is raised.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002954\end{cfuncdesc}
2955
2956\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002957Return a new read-only buffer object that reads from a specified
2958location in memory, with a specified size.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002959The caller is responsible for ensuring that the memory buffer, passed
2960in as \var{ptr}, is not deallocated while the returned buffer object
2961exists. Raises \exception{ValueError} if \var{size} is less than
Fred Drake659ebfa2000-04-03 15:42:13 +00002962zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be passed
2963for the \var{size} parameter; \exception{ValueError} will be raised in
2964that case.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002965\end{cfuncdesc}
2966
2967\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002968Similar to \cfunction{PyBuffer_FromMemory()}, but the returned buffer
2969is writable.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002970\end{cfuncdesc}
2971
2972\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
2973Returns a new writable buffer object that maintains its own memory
Fred Drake659ebfa2000-04-03 15:42:13 +00002974buffer of \var{size} bytes. \exception{ValueError} is returned if
2975\var{size} is not zero or positive.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002976\end{cfuncdesc}
2977
Guido van Rossum44475131998-04-21 15:30:01 +00002978
Fred Drakeefd146c1999-02-15 15:30:45 +00002979\subsection{Tuple Objects \label{tupleObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002980
Fred Drake659ebfa2000-04-03 15:42:13 +00002981\obindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002982\begin{ctypedesc}{PyTupleObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002983This subtype of \ctype{PyObject} represents a Python tuple object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002984\end{ctypedesc}
2985
2986\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002987This instance of \ctype{PyTypeObject} represents the Python tuple
2988type; it is the same object as \code{types.TupleType} in the Python
2989layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002990\end{cvardesc}
2991
2992\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
2993Return true if the argument is a tuple object.
2994\end{cfuncdesc}
2995
Fred Drake659ebfa2000-04-03 15:42:13 +00002996\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
2997Return a new tuple object of size \var{len}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002998\end{cfuncdesc}
2999
3000\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
Fred Drakee058b4f1998-02-16 06:15:35 +00003001Takes a pointer to a tuple object, and returns the size
Fred Drakee5bf8b21998-02-12 21:22:28 +00003002of that tuple.
3003\end{cfuncdesc}
3004
Fred Drakec6fa34e1998-04-02 06:47:24 +00003005\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003006Returns the object at position \var{pos} in the tuple pointed
3007to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003008sets an \exception{IndexError} exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003009\end{cfuncdesc}
3010
Fred Drakec6fa34e1998-04-02 06:47:24 +00003011\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003012Does the same, but does no checking of its arguments.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003013\end{cfuncdesc}
3014
Fred Drakec6fa34e1998-04-02 06:47:24 +00003015\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyTupleObject *p,
Fred Drakee5bf8b21998-02-12 21:22:28 +00003016 int low,
3017 int high}
Fred Drakee058b4f1998-02-16 06:15:35 +00003018Takes a slice of the tuple pointed to by \var{p} from
3019\var{low} to \var{high} and returns it as a new tuple.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003020\end{cfuncdesc}
3021
Fred Drake659ebfa2000-04-03 15:42:13 +00003022\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
3023 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003024Inserts a reference to object \var{o} at position \var{pos} of
3025the tuple pointed to by \var{p}. It returns \code{0} on success.
Fred Drake659ebfa2000-04-03 15:42:13 +00003026\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003027\end{cfuncdesc}
3028
Fred Drake659ebfa2000-04-03 15:42:13 +00003029\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
3030 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003031Does the same, but does no error checking, and
Fred Drakee5bf8b21998-02-12 21:22:28 +00003032should \emph{only} be used to fill in brand new tuples.
Fred Drake659ebfa2000-04-03 15:42:13 +00003033\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003034\end{cfuncdesc}
3035
Fred Drakec6fa34e1998-04-02 06:47:24 +00003036\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyTupleObject *p,
Fred Drake659ebfa2000-04-03 15:42:13 +00003037 int newsize, int last_is_sticky}
3038Can be used to resize a tuple. \var{newsize} will be the new length
3039of the tuple. Because tuples are \emph{supposed} to be immutable,
3040this should only be used if there is only one reference to the object.
3041Do \emph{not} use this if the tuple may already be known to some other
3042part of the code. \var{last_is_sticky} is a flag --- if true, the
3043tuple will grow or shrink at the front, otherwise it will grow or
3044shrink at the end. Think of this as destroying the old tuple and
3045creating a new one, only more efficiently. Returns \code{0} on
3046success and \code{-1} on failure (in which case a
3047\exception{MemoryError} or \exception{SystemError} will be raised).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003048\end{cfuncdesc}
3049
3050
Fred Drakeefd146c1999-02-15 15:30:45 +00003051\subsection{List Objects \label{listObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003052
Fred Drake659ebfa2000-04-03 15:42:13 +00003053\obindex{list}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003054\begin{ctypedesc}{PyListObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003055This subtype of \ctype{PyObject} represents a Python list object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003056\end{ctypedesc}
3057
3058\begin{cvardesc}{PyTypeObject}{PyList_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003059This instance of \ctype{PyTypeObject} represents the Python list
3060type. This is the same object as \code{types.ListType}.
3061\withsubitem{(in module types)}{\ttindex{ListType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003062\end{cvardesc}
3063
3064\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003065Returns true if its argument is a \ctype{PyListObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003066\end{cfuncdesc}
3067
Fred Drake659ebfa2000-04-03 15:42:13 +00003068\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
3069Returns a new list of length \var{len} on success, or \NULL{} on
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003070failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003071\end{cfuncdesc}
3072
Fred Drakec6fa34e1998-04-02 06:47:24 +00003073\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003074Returns the length of the list object in \var{list}; this is
3075equivalent to \samp{len(\var{list})} on a list object.
3076\bifuncindex{len}
3077\end{cfuncdesc}
3078
3079\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
3080Macro form of \cfunction{PyList_GetSize()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003081\end{cfuncdesc}
3082
Fred Drakec6fa34e1998-04-02 06:47:24 +00003083\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
Guido van Rossum44475131998-04-21 15:30:01 +00003084Returns the object at position \var{pos} in the list pointed
3085to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003086sets an \exception{IndexError} exception.
3087\end{cfuncdesc}
3088
3089\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
3090Macro form of \cfunction{PyList_GetItem()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003091\end{cfuncdesc}
3092
Fred Drakec6fa34e1998-04-02 06:47:24 +00003093\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
3094 PyObject *item}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003095Sets the item at index \var{index} in list to \var{item}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003096\strong{Note:} This function ``steals'' a reference to \var{item}.
3097\end{cfuncdesc}
3098
3099\begin{cfuncdesc}{PyObject*}{PyList_SET_ITEM}{PyObject *list, int i,
3100 PyObject *o}
3101Macro form of \cfunction{PyList_SetItem()} without error checking.
3102\strong{Note:} This function ``steals'' a reference to \var{item}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003103\end{cfuncdesc}
3104
Fred Drakec6fa34e1998-04-02 06:47:24 +00003105\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
Guido van Rossum44475131998-04-21 15:30:01 +00003106 PyObject *item}
3107Inserts the item \var{item} into list \var{list} in front of index
Fred Drake659ebfa2000-04-03 15:42:13 +00003108\var{index}. Returns \code{0} if successful; returns \code{-1} and
3109raises an exception if unsuccessful. Analogous to
3110\code{\var{list}.insert(\var{index}, \var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003111\end{cfuncdesc}
3112
Fred Drakec6fa34e1998-04-02 06:47:24 +00003113\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
Guido van Rossum44475131998-04-21 15:30:01 +00003114Appends the object \var{item} at the end of list \var{list}. Returns
Fred Drake659ebfa2000-04-03 15:42:13 +00003115\code{0} if successful; returns \code{-1} and sets an exception if
3116unsuccessful. Analogous to \code{\var{list}.append(\var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003117\end{cfuncdesc}
3118
Fred Drakec6fa34e1998-04-02 06:47:24 +00003119\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
3120 int low, int high}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003121Returns a list of the objects in \var{list} containing the objects
Guido van Rossum44475131998-04-21 15:30:01 +00003122\emph{between} \var{low} and \var{high}. Returns NULL and sets an
3123exception if unsuccessful.
Fred Drake659ebfa2000-04-03 15:42:13 +00003124Analogous to \code{\var{list}[\var{low}:\var{high}]}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003125\end{cfuncdesc}
3126
Fred Drakec6fa34e1998-04-02 06:47:24 +00003127\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
3128 int low, int high,
3129 PyObject *itemlist}
Fred Drake659ebfa2000-04-03 15:42:13 +00003130Sets the slice of \var{list} between \var{low} and \var{high} to the
3131contents of \var{itemlist}. Analogous to
3132\code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
3133\code{0} on success, \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003134\end{cfuncdesc}
3135
Fred Drakec6fa34e1998-04-02 06:47:24 +00003136\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003137Sorts the items of \var{list} in place. Returns \code{0} on success,
3138\code{-1} on failure. This is equivalent to
3139\samp{\var{list}.sort()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003140\end{cfuncdesc}
3141
Fred Drakec6fa34e1998-04-02 06:47:24 +00003142\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003143Reverses the items of \var{list} in place. Returns \code{0} on
3144success, \code{-1} on failure. This is the equivalent of
3145\samp{\var{list}.reverse()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003146\end{cfuncdesc}
3147
Fred Drakec6fa34e1998-04-02 06:47:24 +00003148\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003149Returns a new tuple object containing the contents of \var{list};
3150equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003151\end{cfuncdesc}
3152
3153
Fred Drakeefd146c1999-02-15 15:30:45 +00003154\section{Mapping Objects \label{mapObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003155
Fred Drake659ebfa2000-04-03 15:42:13 +00003156\obindex{mapping}
3157
3158
Fred Drakeefd146c1999-02-15 15:30:45 +00003159\subsection{Dictionary Objects \label{dictObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003160
Fred Drake659ebfa2000-04-03 15:42:13 +00003161\obindex{dictionary}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003162\begin{ctypedesc}{PyDictObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003163This subtype of \ctype{PyObject} represents a Python dictionary object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003164\end{ctypedesc}
3165
3166\begin{cvardesc}{PyTypeObject}{PyDict_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003167This instance of \ctype{PyTypeObject} represents the Python dictionary
3168type. This is exposed to Python programs as \code{types.DictType} and
3169\code{types.DictionaryType}.
3170\withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003171\end{cvardesc}
3172
3173\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003174Returns true if its argument is a \ctype{PyDictObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003175\end{cfuncdesc}
3176
Fred Drakec6fa34e1998-04-02 06:47:24 +00003177\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003178Returns a new empty dictionary, or \NULL{} on failure.
3179\end{cfuncdesc}
3180
3181\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
3182Empties an existing dictionary of all key-value pairs.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003183\end{cfuncdesc}
3184
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003185\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003186Returns a new dictionary that contains the same key-value pairs as p.
3187Empties an existing dictionary of all key-value pairs.
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003188\end{cfuncdesc}
3189
Fred Drake659ebfa2000-04-03 15:42:13 +00003190\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
3191 PyObject *val}
3192Inserts \var{value} into the dictionary with a key of \var{key}.
3193\var{key} must be hashable; if it isn't, \exception{TypeError} will be
3194raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003195\end{cfuncdesc}
3196
3197\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
3198 char *key,
3199 PyObject *val}
Fred Drakee058b4f1998-02-16 06:15:35 +00003200Inserts \var{value} into the dictionary using \var{key}
Fred Drake1d158692000-06-18 05:21:21 +00003201as a key. \var{key} should be a \ctype{char*}. The key object is
Fred Drakee058b4f1998-02-16 06:15:35 +00003202created using \code{PyString_FromString(\var{key})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003203\ttindex{PyString_FromString()}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003204\end{cfuncdesc}
3205
Fred Drake659ebfa2000-04-03 15:42:13 +00003206\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003207Removes the entry in dictionary \var{p} with key \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003208\var{key} must be hashable; if it isn't, \exception{TypeError} is
3209raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003210\end{cfuncdesc}
3211
Fred Drake659ebfa2000-04-03 15:42:13 +00003212\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003213Removes the entry in dictionary \var{p} which has a key
Fred Drake659ebfa2000-04-03 15:42:13 +00003214specified by the string \var{key}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003215\end{cfuncdesc}
3216
Fred Drake659ebfa2000-04-03 15:42:13 +00003217\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003218Returns the object from dictionary \var{p} which has a key
Guido van Rossum44475131998-04-21 15:30:01 +00003219\var{key}. Returns \NULL{} if the key \var{key} is not present, but
Fred Drake659ebfa2000-04-03 15:42:13 +00003220\emph{without} setting an exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003221\end{cfuncdesc}
3222
Fred Drake659ebfa2000-04-03 15:42:13 +00003223\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
Fred Drakef8830d11998-04-23 14:06:01 +00003224This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
Fred Drake659ebfa2000-04-03 15:42:13 +00003225specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003226\end{cfuncdesc}
3227
Fred Drake659ebfa2000-04-03 15:42:13 +00003228\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003229Returns a \ctype{PyListObject} containing all the items
Guido van Rossum44475131998-04-21 15:30:01 +00003230from the dictionary, as in the dictinoary method \method{items()} (see
Fred Drakebe486461999-11-09 17:03:03 +00003231the \citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003232\end{cfuncdesc}
3233
Fred Drake659ebfa2000-04-03 15:42:13 +00003234\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003235Returns a \ctype{PyListObject} containing all the keys
Guido van Rossum44475131998-04-21 15:30:01 +00003236from the dictionary, as in the dictionary method \method{keys()} (see the
Fred Drakebe486461999-11-09 17:03:03 +00003237\citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003238\end{cfuncdesc}
3239
Fred Drake659ebfa2000-04-03 15:42:13 +00003240\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003241Returns a \ctype{PyListObject} containing all the values
Guido van Rossum44475131998-04-21 15:30:01 +00003242from the dictionary \var{p}, as in the dictionary method
Fred Drakebe486461999-11-09 17:03:03 +00003243\method{values()} (see the \citetitle[../lib/lib.html]{Python Library
3244Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003245\end{cfuncdesc}
3246
Fred Drake659ebfa2000-04-03 15:42:13 +00003247\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
3248Returns the number of items in the dictionary. This is equivalent to
3249\samp{len(\var{p})} on a dictionary.\bifuncindex{len}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003250\end{cfuncdesc}
3251
Fred Drake7d45d342000-08-11 17:07:32 +00003252\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p, int *ppos,
3253 PyObject **pkey, PyObject **pvalue}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003254
3255\end{cfuncdesc}
3256
3257
Fred Drakeefd146c1999-02-15 15:30:45 +00003258\section{Numeric Objects \label{numericObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003259
Fred Drake659ebfa2000-04-03 15:42:13 +00003260\obindex{numeric}
3261
3262
Fred Drakeefd146c1999-02-15 15:30:45 +00003263\subsection{Plain Integer Objects \label{intObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003264
Fred Drake659ebfa2000-04-03 15:42:13 +00003265\obindex{integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003266\begin{ctypedesc}{PyIntObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003267This subtype of \ctype{PyObject} represents a Python integer object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003268\end{ctypedesc}
3269
3270\begin{cvardesc}{PyTypeObject}{PyInt_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003271This instance of \ctype{PyTypeObject} represents the Python plain
Fred Drake659ebfa2000-04-03 15:42:13 +00003272integer type. This is the same object as \code{types.IntType}.
3273\withsubitem{(in modules types)}{\ttindex{IntType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003274\end{cvardesc}
3275
Fred Drake659ebfa2000-04-03 15:42:13 +00003276\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
3277Returns true if \var{o} is of type \cdata{PyInt_Type}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003278\end{cfuncdesc}
3279
Fred Drakec6fa34e1998-04-02 06:47:24 +00003280\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
Fred Drakee058b4f1998-02-16 06:15:35 +00003281Creates a new integer object with a value of \var{ival}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003282
3283The current implementation keeps an array of integer objects for all
Fred Drakee058b4f1998-02-16 06:15:35 +00003284integers between \code{-1} and \code{100}, when you create an int in
3285that range you actually just get back a reference to the existing
3286object. So it should be possible to change the value of \code{1}. I
Fred Drake7e9d3141998-04-03 05:02:28 +00003287suspect the behaviour of Python in this case is undefined. :-)
Fred Drakee5bf8b21998-02-12 21:22:28 +00003288\end{cfuncdesc}
3289
Fred Drakee5bf8b21998-02-12 21:22:28 +00003290\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
Fred Drakef8830d11998-04-23 14:06:01 +00003291Will first attempt to cast the object to a \ctype{PyIntObject}, if
Fred Drakee058b4f1998-02-16 06:15:35 +00003292it is not already one, and then return its value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003293\end{cfuncdesc}
3294
Fred Drake659ebfa2000-04-03 15:42:13 +00003295\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
3296Returns the value of the object \var{io}. No error checking is
3297performed.
3298\end{cfuncdesc}
3299
Fred Drakee5bf8b21998-02-12 21:22:28 +00003300\begin{cfuncdesc}{long}{PyInt_GetMax}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003301Returns the system's idea of the largest integer it can handle
3302(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
3303header files).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003304\end{cfuncdesc}
3305
3306
Fred Drakeefd146c1999-02-15 15:30:45 +00003307\subsection{Long Integer Objects \label{longObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003308
Fred Drake659ebfa2000-04-03 15:42:13 +00003309\obindex{long integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003310\begin{ctypedesc}{PyLongObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003311This subtype of \ctype{PyObject} represents a Python long integer
Fred Drakee058b4f1998-02-16 06:15:35 +00003312object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003313\end{ctypedesc}
3314
3315\begin{cvardesc}{PyTypeObject}{PyLong_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003316This instance of \ctype{PyTypeObject} represents the Python long
Fred Drake659ebfa2000-04-03 15:42:13 +00003317integer type. This is the same object as \code{types.LongType}.
3318\withsubitem{(in modules types)}{\ttindex{LongType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003319\end{cvardesc}
3320
3321\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003322Returns true if its argument is a \ctype{PyLongObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003323\end{cfuncdesc}
3324
Fred Drakec6fa34e1998-04-02 06:47:24 +00003325\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003326Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on
3327failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003328\end{cfuncdesc}
3329
Fred Drakec6fa34e1998-04-02 06:47:24 +00003330\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003331Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
3332long}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003333\end{cfuncdesc}
3334
Fred Drakec6fa34e1998-04-02 06:47:24 +00003335\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003336Returns a new \ctype{PyLongObject} object from the integer part of
3337\var{v}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003338\end{cfuncdesc}
3339
Fred Drakec6fa34e1998-04-02 06:47:24 +00003340\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003341Returns a C \ctype{long} representation of the contents of
3342\var{pylong}. If \var{pylong} is greater than
3343\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is
3344raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003345\end{cfuncdesc}
3346
Fred Drakec6fa34e1998-04-02 06:47:24 +00003347\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003348Returns a C \ctype{unsigned long} representation of the contents of
3349\var{pylong}. If \var{pylong} is greater than
3350\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError}
3351is raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003352\end{cfuncdesc}
3353
Fred Drakec6fa34e1998-04-02 06:47:24 +00003354\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003355Returns a C \ctype{double} representation of the contents of \var{pylong}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003356\end{cfuncdesc}
3357
Fred Drakec6fa34e1998-04-02 06:47:24 +00003358\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
3359 int base}
Fred Drake659ebfa2000-04-03 15:42:13 +00003360Return a new \ctype{PyLongObject} based on the string value in
3361\var{str}, which is interpreted according to the radix in \var{base}.
3362If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first
3363character in \var{str} which follows the representation of the
3364number. If \var{base} is \code{0}, the radix will be determined base
3365on the leading characters of \var{str}: if \var{str} starts with
3366\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts
3367with \code{'0'}, radix 8 will be used; otherwise radix 10 will be
3368used. If \var{base} is not \code{0}, it must be between \code{2} and
3369\code{36}, inclusive. Leading spaces are ignored. If there are no
3370digits, \exception{ValueError} will be raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003371\end{cfuncdesc}
3372
3373
Fred Drakeefd146c1999-02-15 15:30:45 +00003374\subsection{Floating Point Objects \label{floatObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003375
Fred Drake659ebfa2000-04-03 15:42:13 +00003376\obindex{floating point}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003377\begin{ctypedesc}{PyFloatObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003378This subtype of \ctype{PyObject} represents a Python floating point
Fred Drakee058b4f1998-02-16 06:15:35 +00003379object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003380\end{ctypedesc}
3381
3382\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003383This instance of \ctype{PyTypeObject} represents the Python floating
Fred Drake659ebfa2000-04-03 15:42:13 +00003384point type. This is the same object as \code{types.FloatType}.
3385\withsubitem{(in modules types)}{\ttindex{FloatType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003386\end{cvardesc}
3387
3388\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003389Returns true if its argument is a \ctype{PyFloatObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003390\end{cfuncdesc}
3391
Fred Drakec6fa34e1998-04-02 06:47:24 +00003392\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003393Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
3394failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003395\end{cfuncdesc}
3396
Fred Drakec6fa34e1998-04-02 06:47:24 +00003397\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003398Returns a C \ctype{double} representation of the contents of \var{pyfloat}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003399\end{cfuncdesc}
3400
Fred Drakec6fa34e1998-04-02 06:47:24 +00003401\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003402Returns a C \ctype{double} representation of the contents of
Fred Drakef8830d11998-04-23 14:06:01 +00003403\var{pyfloat}, but without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003404\end{cfuncdesc}
3405
3406
Fred Drakeefd146c1999-02-15 15:30:45 +00003407\subsection{Complex Number Objects \label{complexObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003408
Fred Drake659ebfa2000-04-03 15:42:13 +00003409\obindex{complex number}
3410Python's complex number objects are implemented as two distinct types
3411when viewed from the C API: one is the Python object exposed to
3412Python programs, and the other is a C structure which represents the
3413actual complex number value. The API provides functions for working
3414with both.
3415
3416\subsubsection{Complex Numbers as C Structures}
3417
3418Note that the functions which accept these structures as parameters
3419and return them as results do so \emph{by value} rather than
3420dereferencing them through pointers. This is consistent throughout
3421the API.
3422
Fred Drakee5bf8b21998-02-12 21:22:28 +00003423\begin{ctypedesc}{Py_complex}
Fred Drake659ebfa2000-04-03 15:42:13 +00003424The C structure which corresponds to the value portion of a Python
Fred Drake4de05a91998-02-16 14:25:26 +00003425complex number object. Most of the functions for dealing with complex
3426number objects use structures of this type as input or output values,
3427as appropriate. It is defined as:
3428
Fred Drakee058b4f1998-02-16 06:15:35 +00003429\begin{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003430typedef struct {
3431 double real;
3432 double imag;
Fred Drake4de05a91998-02-16 14:25:26 +00003433} Py_complex;
Fred Drakee058b4f1998-02-16 06:15:35 +00003434\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003435\end{ctypedesc}
3436
Fred Drake659ebfa2000-04-03 15:42:13 +00003437\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
3438Return the sum of two complex numbers, using the C
3439\ctype{Py_complex} representation.
3440\end{cfuncdesc}
3441
3442\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
3443Return the difference between two complex numbers, using the C
3444\ctype{Py_complex} representation.
3445\end{cfuncdesc}
3446
3447\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
3448Return the negation of the complex number \var{complex}, using the C
3449\ctype{Py_complex} representation.
3450\end{cfuncdesc}
3451
3452\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
3453Return the product of two complex numbers, using the C
3454\ctype{Py_complex} representation.
3455\end{cfuncdesc}
3456
3457\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
3458 Py_complex divisor}
3459Return the quotient of two complex numbers, using the C
3460\ctype{Py_complex} representation.
3461\end{cfuncdesc}
3462
3463\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
3464Return the exponentiation of \var{num} by \var{exp}, using the C
3465\ctype{Py_complex} representation.
3466\end{cfuncdesc}
3467
3468
3469\subsubsection{Complex Numbers as Python Objects}
3470
Fred Drakee5bf8b21998-02-12 21:22:28 +00003471\begin{ctypedesc}{PyComplexObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003472This subtype of \ctype{PyObject} represents a Python complex number object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003473\end{ctypedesc}
3474
3475\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003476This instance of \ctype{PyTypeObject} represents the Python complex
Fred Drakee5bf8b21998-02-12 21:22:28 +00003477number type.
3478\end{cvardesc}
3479
3480\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003481Returns true if its argument is a \ctype{PyComplexObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003482\end{cfuncdesc}
3483
Fred Drakec6fa34e1998-04-02 06:47:24 +00003484\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003485Create a new Python complex number object from a C
3486\ctype{Py_complex} value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003487\end{cfuncdesc}
3488
Fred Drakec6fa34e1998-04-02 06:47:24 +00003489\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
Fred Drakef8830d11998-04-23 14:06:01 +00003490Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003491\end{cfuncdesc}
3492
3493\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003494Returns the real part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003495\end{cfuncdesc}
3496
3497\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003498Returns the imaginary part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003499\end{cfuncdesc}
3500
3501\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003502Returns the \ctype{Py_complex} value of the complex number \var{op}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003503\end{cfuncdesc}
3504
3505
3506
Fred Drakeefd146c1999-02-15 15:30:45 +00003507\section{Other Objects \label{otherObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003508
Fred Drakeefd146c1999-02-15 15:30:45 +00003509\subsection{File Objects \label{fileObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003510
Fred Drake659ebfa2000-04-03 15:42:13 +00003511\obindex{file}
3512Python's built-in file objects are implemented entirely on the
3513\ctype{FILE*} support from the C standard library. This is an
3514implementation detail and may change in future releases of Python.
3515
Fred Drakee5bf8b21998-02-12 21:22:28 +00003516\begin{ctypedesc}{PyFileObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003517This subtype of \ctype{PyObject} represents a Python file object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003518\end{ctypedesc}
3519
3520\begin{cvardesc}{PyTypeObject}{PyFile_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003521This instance of \ctype{PyTypeObject} represents the Python file
3522type. This is exposed to Python programs as \code{types.FileType}.
3523\withsubitem{(in module types)}{\ttindex{FileType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003524\end{cvardesc}
3525
3526\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003527Returns true if its argument is a \ctype{PyFileObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003528\end{cfuncdesc}
3529
Fred Drake659ebfa2000-04-03 15:42:13 +00003530\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
3531On success, returns a new file object that is opened on the
3532file given by \var{filename}, with a file mode given by \var{mode},
3533where \var{mode} has the same semantics as the standard C routine
3534\cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003535\end{cfuncdesc}
3536
Fred Drakec6fa34e1998-04-02 06:47:24 +00003537\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
Fred Drake659ebfa2000-04-03 15:42:13 +00003538 char *name, char *mode,
3539 int (*close)(FILE*)}
3540Creates a new \ctype{PyFileObject} from the already-open standard C
3541file pointer, \var{fp}. The function \var{close} will be called when
3542the file should be closed. Returns \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003543\end{cfuncdesc}
3544
Fred Drake659ebfa2000-04-03 15:42:13 +00003545\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
3546Returns the file object associated with \var{p} as a \ctype{FILE*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003547\end{cfuncdesc}
3548
Fred Drakec6fa34e1998-04-02 06:47:24 +00003549\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003550Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
3551function reads one line from the object \var{p}. \var{p} may be a
3552file object or any object with a \method{readline()} method. If
3553\var{n} is \code{0}, exactly one line is read, regardless of the
3554length of the line. If \var{n} is greater than \code{0}, no more than
3555\var{n} bytes will be read from the file; a partial line can be
3556returned. In both cases, an empty string is returned if the end of
3557the file is reached immediately. If \var{n} is less than \code{0},
3558however, one line is read regardless of length, but
3559\exception{EOFError} is raised if the end of the file is reached
3560immediately.
3561\withsubitem{(built-in exception)}{\ttindex{EOFError}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003562\end{cfuncdesc}
3563
Fred Drakec6fa34e1998-04-02 06:47:24 +00003564\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003565Returns the name of the file specified by \var{p} as a string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003566\end{cfuncdesc}
3567
3568\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003569Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
3570only. This should only be called immediately after file object
3571creation.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003572\end{cfuncdesc}
3573
Fred Drake659ebfa2000-04-03 15:42:13 +00003574\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
3575This function exists for internal use by the interpreter.
3576Sets the \member{softspace} attribute of \var{p} to \var{newflag} and
3577\withsubitem{(file attribute)}{\ttindex{softspace}}returns the
3578previous value. \var{p} does not have to be a file object
3579for this function to work properly; any object is supported (thought
3580its only interesting if the \member{softspace} attribute can be set).
3581This function clears any errors, and will return \code{0} as the
3582previous value if the attribute either does not exist or if there were
3583errors in retrieving it. There is no way to detect errors from this
3584function, but doing so should not be needed.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003585\end{cfuncdesc}
3586
Fred Drakec6fa34e1998-04-02 06:47:24 +00003587\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
3588 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003589Writes object \var{obj} to file object \var{p}. The only supported
3590flag for \var{flags} is \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW};
3591if given, the \function{str()} of the object is written instead of the
3592\function{repr()}. Returns \code{0} on success or \code{-1} on
3593failure; the appropriate exception will be set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003594\end{cfuncdesc}
3595
Fred Drakec6fa34e1998-04-02 06:47:24 +00003596\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p,
3597 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003598Writes string \var{s} to file object \var{p}. Returns \code{0} on
3599success or \code{-1} on failure; the appropriate exception will be
3600set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003601\end{cfuncdesc}
3602
3603
Fred Drakeefd146c1999-02-15 15:30:45 +00003604\subsection{Module Objects \label{moduleObjects}}
3605
3606\obindex{module}
3607There are only a few functions special to module objects.
3608
Fred Drake659ebfa2000-04-03 15:42:13 +00003609\begin{cvardesc}{PyTypeObject}{PyModule_Type}
3610This instance of \ctype{PyTypeObject} represents the Python module
3611type. This is exposed to Python programs as \code{types.ModuleType}.
3612\withsubitem{(in module types)}{\ttindex{ModuleType}}
3613\end{cvardesc}
3614
3615\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
3616Returns true if its argument is a module object.
Fred Drakeefd146c1999-02-15 15:30:45 +00003617\end{cfuncdesc}
3618
Fred Drake659ebfa2000-04-03 15:42:13 +00003619\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
3620Return a new module object with the \member{__name__} attribute set to
3621\var{name}. Only the module's \member{__doc__} and
3622\member{__name__} attributes are filled in; the caller is responsible
3623for providing a \member{__file__} attribute.
3624\withsubitem{(module attribute)}{
3625 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
3626\end{cfuncdesc}
3627
3628\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003629Return the dictionary object that implements \var{module}'s namespace;
3630this object is the same as the \member{__dict__} attribute of the
3631module object. This function never fails.
Fred Drake659ebfa2000-04-03 15:42:13 +00003632\withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003633\end{cfuncdesc}
3634
Fred Drake659ebfa2000-04-03 15:42:13 +00003635\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003636Return \var{module}'s \member{__name__} value. If the module does not
Fred Drake659ebfa2000-04-03 15:42:13 +00003637provide one, or if it is not a string, \exception{SystemError} is
3638raised and \NULL{} is returned.
3639\withsubitem{(module attribute)}{\ttindex{__name__}}
3640\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003641\end{cfuncdesc}
3642
Fred Drake659ebfa2000-04-03 15:42:13 +00003643\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003644Return the name of the file from which \var{module} was loaded using
3645\var{module}'s \member{__file__} attribute. If this is not defined,
Fred Drake659ebfa2000-04-03 15:42:13 +00003646or if it is not a string, raise \exception{SystemError} and return
3647\NULL.
3648\withsubitem{(module attribute)}{\ttindex{__file__}}
3649\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003650\end{cfuncdesc}
3651
3652
3653\subsection{CObjects \label{cObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003654
Fred Drake659ebfa2000-04-03 15:42:13 +00003655\obindex{CObject}
3656Refer to \emph{Extending and Embedding the Python Interpreter},
3657section 1.12 (``Providing a C API for an Extension Module''), for more
3658information on using these objects.
3659
3660
Guido van Rossum44475131998-04-21 15:30:01 +00003661\begin{ctypedesc}{PyCObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003662This subtype of \ctype{PyObject} represents an opaque value, useful for
Fred Drake659ebfa2000-04-03 15:42:13 +00003663C extension modules who need to pass an opaque value (as a
3664\ctype{void*} pointer) through Python code to other C code. It is
Guido van Rossum44475131998-04-21 15:30:01 +00003665often used to make a C function pointer defined in one module
3666available to other modules, so the regular import mechanism can be
3667used to access C APIs defined in dynamically loaded modules.
3668\end{ctypedesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003669
Fred Drake659ebfa2000-04-03 15:42:13 +00003670\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
3671Returns true if its argument is a \ctype{PyCObject}.
3672\end{cfuncdesc}
3673
3674\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003675 void (*destr)(void *)}
Fred Drake1d158692000-06-18 05:21:21 +00003676Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drakedab44681999-05-13 18:41:14 +00003677\var{destr} function will be called when the object is reclaimed, unless
3678it is \NULL.
Guido van Rossum44475131998-04-21 15:30:01 +00003679\end{cfuncdesc}
3680
Fred Drake659ebfa2000-04-03 15:42:13 +00003681\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003682 void* desc, void (*destr)(void *, void *) }
Fred Drakef8830d11998-04-23 14:06:01 +00003683Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
3684\var{destr} function will be called when the object is reclaimed. The
3685\var{desc} argument can be used to pass extra callback data for the
3686destructor function.
Guido van Rossum44475131998-04-21 15:30:01 +00003687\end{cfuncdesc}
3688
Fred Drake659ebfa2000-04-03 15:42:13 +00003689\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
3690Returns the object \ctype{void *} that the
3691\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003692\end{cfuncdesc}
3693
Fred Drake659ebfa2000-04-03 15:42:13 +00003694\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
3695Returns the description \ctype{void *} that the
3696\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003697\end{cfuncdesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003698
Fred Drake659ebfa2000-04-03 15:42:13 +00003699
Fred Drakeefd146c1999-02-15 15:30:45 +00003700\chapter{Initialization, Finalization, and Threads
3701 \label{initialization}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003702
Guido van Rossum4a944d71997-08-14 20:35:38 +00003703\begin{cfuncdesc}{void}{Py_Initialize}{}
3704Initialize the Python interpreter. In an application embedding
3705Python, this should be called before using any other Python/C API
Fred Drake659ebfa2000-04-03 15:42:13 +00003706functions; with the exception of
3707\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
3708\cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
3709\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
3710and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
3711This initializes the table of loaded modules (\code{sys.modules}), and
3712\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}creates the
3713fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake4de05a91998-02-16 14:25:26 +00003714\module{__main__}\refbimodindex{__main__} and
3715\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drake659ebfa2000-04-03 15:42:13 +00003716search\indexiii{module}{search}{path} path (\code{sys.path}).
3717It does not set \code{sys.argv}; use
3718\cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
3719is a no-op when called for a second time (without calling
3720\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is no
3721return value; it is a fatal error if the initialization fails.
Guido van Rossum42cefd01997-10-05 15:27:29 +00003722\end{cfuncdesc}
3723
3724\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00003725Return true (nonzero) when the Python interpreter has been
Fred Drakee058b4f1998-02-16 06:15:35 +00003726initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
3727called, this returns false until \cfunction{Py_Initialize()} is called
Guido van Rossum42cefd01997-10-05 15:27:29 +00003728again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003729\end{cfuncdesc}
3730
3731\begin{cfuncdesc}{void}{Py_Finalize}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003732Undo all initializations made by \cfunction{Py_Initialize()} and
3733subsequent use of Python/C API functions, and destroy all
3734sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
3735created and not yet destroyed since the last call to
3736\cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
3737by the Python interpreter. This is a no-op when called for a second
3738time (without calling \cfunction{Py_Initialize()} again first). There
3739is no return value; errors during finalization are ignored.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003740
3741This function is provided for a number of reasons. An embedding
3742application might want to restart Python without having to restart the
3743application itself. An application that has loaded the Python
3744interpreter from a dynamically loadable library (or DLL) might want to
3745free all memory allocated by Python before unloading the DLL. During a
3746hunt for memory leaks in an application a developer might want to free
3747all memory allocated by Python before exiting from the application.
3748
Fred Drakee058b4f1998-02-16 06:15:35 +00003749\strong{Bugs and caveats:} The destruction of modules and objects in
Guido van Rossum4a944d71997-08-14 20:35:38 +00003750modules is done in random order; this may cause destructors
Fred Drakee058b4f1998-02-16 06:15:35 +00003751(\method{__del__()} methods) to fail when they depend on other objects
Guido van Rossum4a944d71997-08-14 20:35:38 +00003752(even functions) or modules. Dynamically loaded extension modules
3753loaded by Python are not unloaded. Small amounts of memory allocated
3754by the Python interpreter may not be freed (if you find a leak, please
3755report it). Memory tied up in circular references between objects is
3756not freed. Some memory allocated by extension modules may not be
3757freed. Some extension may not work properly if their initialization
3758routine is called more than once; this can happen if an applcation
Fred Drakee058b4f1998-02-16 06:15:35 +00003759calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
3760than once.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003761\end{cfuncdesc}
3762
Fred Drakec6fa34e1998-04-02 06:47:24 +00003763\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003764Create a new sub-interpreter. This is an (almost) totally separate
3765environment for the execution of Python code. In particular, the new
3766interpreter has separate, independent versions of all imported
3767modules, including the fundamental modules
3768\module{__builtin__}\refbimodindex{__builtin__},
3769\module{__main__}\refbimodindex{__main__} and
3770\module{sys}\refbimodindex{sys}. The table of loaded modules
3771(\code{sys.modules}) and the module search path (\code{sys.path}) are
3772also separate. The new environment has no \code{sys.argv} variable.
3773It has new standard I/O stream file objects \code{sys.stdin},
3774\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drake659ebfa2000-04-03 15:42:13 +00003775same underlying \ctype{FILE} structures in the C library).
3776\withsubitem{(in module sys)}{
3777 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003778
3779The return value points to the first thread state created in the new
3780sub-interpreter. This thread state is made the current thread state.
3781Note that no actual thread is created; see the discussion of thread
3782states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003783\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00003784is stored in the current thread state and there may not be a current
3785thread state. (Like all other Python/C API functions, the global
3786interpreter lock must be held before calling this function and is
3787still held when it returns; however, unlike most other Python/C API
3788functions, there needn't be a current thread state on entry.)
3789
3790Extension modules are shared between (sub-)interpreters as follows:
3791the first time a particular extension is imported, it is initialized
3792normally, and a (shallow) copy of its module's dictionary is
3793squirreled away. When the same extension is imported by another
3794(sub-)interpreter, a new module is initialized and filled with the
Fred Drakee058b4f1998-02-16 06:15:35 +00003795contents of this copy; the extension's \code{init} function is not
3796called. Note that this is different from what happens when an
3797extension is imported after the interpreter has been completely
Fred Drake659ebfa2000-04-03 15:42:13 +00003798re-initialized by calling
3799\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
3800\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
3801the extension's \code{init\var{module}} function \emph{is} called
3802again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003803
Fred Drakee058b4f1998-02-16 06:15:35 +00003804\strong{Bugs and caveats:} Because sub-interpreters (and the main
Guido van Rossum4a944d71997-08-14 20:35:38 +00003805interpreter) are part of the same process, the insulation between them
Fred Drakee058b4f1998-02-16 06:15:35 +00003806isn't perfect --- for example, using low-level file operations like
Fred Drake659ebfa2000-04-03 15:42:13 +00003807\withsubitem{(in module os)}{\ttindex{close()}}
Fred Drakef8830d11998-04-23 14:06:01 +00003808\function{os.close()} they can (accidentally or maliciously) affect each
Guido van Rossum4a944d71997-08-14 20:35:38 +00003809other's open files. Because of the way extensions are shared between
3810(sub-)interpreters, some extensions may not work properly; this is
3811especially likely when the extension makes use of (static) global
3812variables, or when the extension manipulates its module's dictionary
3813after its initialization. It is possible to insert objects created in
3814one sub-interpreter into a namespace of another sub-interpreter; this
3815should be done with great care to avoid sharing user-defined
3816functions, methods, instances or classes between sub-interpreters,
3817since import operations executed by such objects may affect the
3818wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
3819a hard-to-fix bug that will be addressed in a future release.)
3820\end{cfuncdesc}
3821
3822\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
3823Destroy the (sub-)interpreter represented by the given thread state.
3824The given thread state must be the current thread state. See the
3825discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003826thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00003827interpreted are destroyed. (The global interpreter lock must be held
3828before calling this function and is still held when it returns.)
Fred Drake659ebfa2000-04-03 15:42:13 +00003829\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will destroy all
3830sub-interpreters that haven't been explicitly destroyed at that point.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003831\end{cfuncdesc}
3832
3833\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00003834This function should be called before
3835\cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
Guido van Rossum4a944d71997-08-14 20:35:38 +00003836for the first time, if it is called at all. It tells the interpreter
Fred Drake659ebfa2000-04-03 15:42:13 +00003837the value of the \code{argv[0]} argument to the
3838\cfunction{main()}\ttindex{main()} function of the program. This is
3839used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some other
Guido van Rossum4a944d71997-08-14 20:35:38 +00003840functions below to find the Python run-time libraries relative to the
Fred Drakea8455ab2000-06-16 19:58:42 +00003841interpreter executable. The default value is \code{'python'}. The
Guido van Rossum4a944d71997-08-14 20:35:38 +00003842argument should point to a zero-terminated character string in static
3843storage whose contents will not change for the duration of the
3844program's execution. No code in the Python interpreter will change
3845the contents of this storage.
3846\end{cfuncdesc}
3847
Fred Drakec6fa34e1998-04-02 06:47:24 +00003848\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003849Return the program name set with
3850\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
Guido van Rossum4a944d71997-08-14 20:35:38 +00003851default. The returned string points into static storage; the caller
3852should not modify its value.
3853\end{cfuncdesc}
3854
Fred Drakec6fa34e1998-04-02 06:47:24 +00003855\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003856Return the \emph{prefix} for installed platform-independent files. This
Guido van Rossum4a944d71997-08-14 20:35:38 +00003857is derived through a number of complicated rules from the program name
Fred Drakee058b4f1998-02-16 06:15:35 +00003858set with \cfunction{Py_SetProgramName()} and some environment variables;
Fred Drakea8455ab2000-06-16 19:58:42 +00003859for example, if the program name is \code{'/usr/local/bin/python'},
3860the prefix is \code{'/usr/local'}. The returned string points into
Guido van Rossum4a944d71997-08-14 20:35:38 +00003861static storage; the caller should not modify its value. This
Fred Drakec94d9341998-04-12 02:39:13 +00003862corresponds to the \makevar{prefix} variable in the top-level
Fred Drakea8455ab2000-06-16 19:58:42 +00003863\file{Makefile} and the \longprogramopt{prefix} argument to the
Fred Drakee058b4f1998-02-16 06:15:35 +00003864\program{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00003865Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00003866also the next function.
3867\end{cfuncdesc}
3868
Fred Drakec6fa34e1998-04-02 06:47:24 +00003869\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003870Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
Guido van Rossum4a944d71997-08-14 20:35:38 +00003871files. This is derived through a number of complicated rules from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003872program name set with \cfunction{Py_SetProgramName()} and some environment
Guido van Rossum4a944d71997-08-14 20:35:38 +00003873variables; for example, if the program name is
Fred Drakea8455ab2000-06-16 19:58:42 +00003874\code{'/usr/local/bin/python'}, the exec-prefix is
3875\code{'/usr/local'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00003876the caller should not modify its value. This corresponds to the
Fred Drakec94d9341998-04-12 02:39:13 +00003877\makevar{exec_prefix} variable in the top-level \file{Makefile} and the
Fred Drakea8455ab2000-06-16 19:58:42 +00003878\longprogramopt{exec-prefix} argument to the
Fred Drake310ee611999-11-09 17:31:42 +00003879\program{configure} script at build time. The value is available to
3880Python code as \code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003881
3882Background: The exec-prefix differs from the prefix when platform
3883dependent files (such as executables and shared libraries) are
3884installed in a different directory tree. In a typical installation,
3885platform dependent files may be installed in the
Fred Drakea8455ab2000-06-16 19:58:42 +00003886\file{/usr/local/plat} subtree while platform independent may be
3887installed in \file{/usr/local}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003888
3889Generally speaking, a platform is a combination of hardware and
3890software families, e.g. Sparc machines running the Solaris 2.x
3891operating system are considered the same platform, but Intel machines
3892running Solaris 2.x are another platform, and Intel machines running
3893Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00003894operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003895operating systems are a different story; the installation strategies
3896on those systems are so different that the prefix and exec-prefix are
3897meaningless, and set to the empty string. Note that compiled Python
3898bytecode files are platform independent (but not independent from the
3899Python version by which they were compiled!).
3900
Fred Drakee058b4f1998-02-16 06:15:35 +00003901System administrators will know how to configure the \program{mount} or
Fred Drakea8455ab2000-06-16 19:58:42 +00003902\program{automount} programs to share \file{/usr/local} between platforms
3903while having \file{/usr/local/plat} be a different filesystem for each
Guido van Rossum4a944d71997-08-14 20:35:38 +00003904platform.
3905\end{cfuncdesc}
3906
Fred Drakec6fa34e1998-04-02 06:47:24 +00003907\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003908Return the full program name of the Python executable; this is
3909computed as a side-effect of deriving the default module search path
Fred Drake659ebfa2000-04-03 15:42:13 +00003910from the program name (set by
3911\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
3912The returned string points into static storage; the caller should not
Guido van Rossum4a944d71997-08-14 20:35:38 +00003913modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00003914\code{sys.executable}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003915\withsubitem{(in module sys)}{\ttindex{executable}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003916\end{cfuncdesc}
3917
Fred Drakec6fa34e1998-04-02 06:47:24 +00003918\begin{cfuncdesc}{char*}{Py_GetPath}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003919\indexiii{module}{search}{path}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003920Return the default module search path; this is computed from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003921program name (set by \cfunction{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00003922environment variables. The returned string consists of a series of
3923directory names separated by a platform dependent delimiter character.
Fred Drakef8830d11998-04-23 14:06:01 +00003924The delimiter character is \character{:} on \UNIX{}, \character{;} on
Fred Drake659ebfa2000-04-03 15:42:13 +00003925DOS/Windows, and \character{\e n} (the \ASCII{} newline character) on
Fred Drakee5bc4971998-02-12 23:36:49 +00003926Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00003927should not modify its value. The value is available to Python code
Fred Drake659ebfa2000-04-03 15:42:13 +00003928as the list \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}},
3929which may be modified to change the future search path for loaded
3930modules.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003931
3932% XXX should give the exact rules
3933\end{cfuncdesc}
3934
Fred Drakec6fa34e1998-04-02 06:47:24 +00003935\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003936Return the version of this Python interpreter. This is a string that
3937looks something like
3938
Guido van Rossum09270b51997-08-15 18:57:32 +00003939\begin{verbatim}
Fred Drakee058b4f1998-02-16 06:15:35 +00003940"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
Guido van Rossum09270b51997-08-15 18:57:32 +00003941\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003942
3943The first word (up to the first space character) is the current Python
3944version; the first three characters are the major and minor version
3945separated by a period. The returned string points into static storage;
3946the caller should not modify its value. The value is available to
3947Python code as the list \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003948\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003949\end{cfuncdesc}
3950
Fred Drakec6fa34e1998-04-02 06:47:24 +00003951\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00003952Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00003953this is formed from the ``official'' name of the operating system,
3954converted to lower case, followed by the major revision number; e.g.,
3955for Solaris 2.x, which is also known as SunOS 5.x, the value is
Fred Drakea8455ab2000-06-16 19:58:42 +00003956\code{'sunos5'}. On Macintosh, it is \code{'mac'}. On Windows, it
3957is \code{'win'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00003958the caller should not modify its value. The value is available to
3959Python code as \code{sys.platform}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003960\withsubitem{(in module sys)}{\ttindex{platform}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003961\end{cfuncdesc}
3962
Fred Drakec6fa34e1998-04-02 06:47:24 +00003963\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003964Return the official copyright string for the current Python version,
3965for example
3966
Fred Drakea8455ab2000-06-16 19:58:42 +00003967\code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003968
3969The returned string points into static storage; the caller should not
3970modify its value. The value is available to Python code as the list
3971\code{sys.copyright}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003972\withsubitem{(in module sys)}{\ttindex{copyright}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003973\end{cfuncdesc}
3974
Fred Drakec6fa34e1998-04-02 06:47:24 +00003975\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003976Return an indication of the compiler used to build the current Python
Fred Drakee058b4f1998-02-16 06:15:35 +00003977version, in square brackets, for example:
Guido van Rossum4a944d71997-08-14 20:35:38 +00003978
Fred Drakee058b4f1998-02-16 06:15:35 +00003979\begin{verbatim}
3980"[GCC 2.7.2.2]"
3981\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003982
3983The returned string points into static storage; the caller should not
3984modify its value. The value is available to Python code as part of
3985the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003986\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003987\end{cfuncdesc}
3988
Fred Drakec6fa34e1998-04-02 06:47:24 +00003989\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003990Return information about the sequence number and build date and time
3991of the current Python interpreter instance, for example
3992
Guido van Rossum09270b51997-08-15 18:57:32 +00003993\begin{verbatim}
3994"#67, Aug 1 1997, 22:34:28"
3995\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003996
3997The returned string points into static storage; the caller should not
3998modify its value. The value is available to Python code as part of
3999the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004000\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004001\end{cfuncdesc}
4002
4003\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
Fred Drake659ebfa2000-04-03 15:42:13 +00004004Set \code{sys.argv} based on \var{argc} and \var{argv}. These
4005parameters are similar to those passed to the program's
4006\cfunction{main()}\ttindex{main()} function with the difference that
4007the first entry should refer to the script file to be executed rather
4008than the executable hosting the Python interpreter. If there isn't a
4009script that will be run, the first entry in \var{argv} can be an empty
4010string. If this function fails to initialize \code{sys.argv}, a fatal
4011condition is signalled using
4012\cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
4013\withsubitem{(in module sys)}{\ttindex{argv}}
4014% XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
4015% check w/ Guido.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004016\end{cfuncdesc}
4017
4018% XXX Other PySys thingies (doesn't really belong in this chapter)
4019
Fred Drakeefd146c1999-02-15 15:30:45 +00004020\section{Thread State and the Global Interpreter Lock
4021 \label{threads}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004022
Fred Drake659ebfa2000-04-03 15:42:13 +00004023\index{global interpreter lock}
4024\index{interpreter lock}
4025\index{lock, interpreter}
4026
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004027The Python interpreter is not fully thread safe. In order to support
4028multi-threaded Python programs, there's a global lock that must be
4029held by the current thread before it can safely access Python objects.
4030Without the lock, even the simplest operations could cause problems in
Fred Drake7baf3d41998-02-20 00:45:52 +00004031a multi-threaded program: for example, when two threads simultaneously
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004032increment the reference count of the same object, the reference count
4033could end up being incremented only once instead of twice.
4034
4035Therefore, the rule exists that only the thread that has acquired the
4036global interpreter lock may operate on Python objects or call Python/C
4037API functions. In order to support multi-threaded Python programs,
Fred Drake659ebfa2000-04-03 15:42:13 +00004038the interpreter regularly releases and reacquires the lock --- by
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004039default, every ten bytecode instructions (this can be changed with
Fred Drake659ebfa2000-04-03 15:42:13 +00004040\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
Fred Drakee058b4f1998-02-16 06:15:35 +00004041\function{sys.setcheckinterval()}). The lock is also released and
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004042reacquired around potentially blocking I/O operations like reading or
4043writing a file, so that other threads can run while the thread that
4044requests the I/O is waiting for the I/O operation to complete.
4045
4046The Python interpreter needs to keep some bookkeeping information
Fred Drakee058b4f1998-02-16 06:15:35 +00004047separate per thread --- for this it uses a data structure called
Fred Drake659ebfa2000-04-03 15:42:13 +00004048\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
40491.5; in earlier versions, such state was stored in global variables,
4050and switching threads could cause problems. In particular, exception
4051handling is now thread safe, when the application uses
4052\withsubitem{(in module sys)}{\ttindex{exc_info()}}
4053\function{sys.exc_info()} to access the exception last raised in the
4054current thread.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004055
4056There's one global variable left, however: the pointer to the current
Fred Drake659ebfa2000-04-03 15:42:13 +00004057\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
4058thread packages have a way to store ``per-thread global data,''
4059Python's internal platform independent thread abstraction doesn't
4060support this yet. Therefore, the current thread state must be
4061manipulated explicitly.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004062
4063This is easy enough in most cases. Most code manipulating the global
4064interpreter lock has the following simple structure:
4065
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004066\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004067Save the thread state in a local variable.
4068Release the interpreter lock.
4069...Do some blocking I/O operation...
4070Reacquire the interpreter lock.
4071Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004072\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004073
4074This is so common that a pair of macros exists to simplify it:
4075
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004076\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004077Py_BEGIN_ALLOW_THREADS
4078...Do some blocking I/O operation...
4079Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004080\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004081
Fred Drake659ebfa2000-04-03 15:42:13 +00004082The \code{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS} macro
4083opens a new block and declares a hidden local variable; the
4084\code{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS} macro closes
Fred Drakee058b4f1998-02-16 06:15:35 +00004085the block. Another advantage of using these two macros is that when
4086Python is compiled without thread support, they are defined empty,
4087thus saving the thread state and lock manipulations.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004088
4089When thread support is enabled, the block above expands to the
4090following code:
4091
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004092\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004093 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004094
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004095 _save = PyEval_SaveThread();
4096 ...Do some blocking I/O operation...
4097 PyEval_RestoreThread(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004098\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004099
4100Using even lower level primitives, we can get roughly the same effect
4101as follows:
4102
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004103\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004104 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004105
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004106 _save = PyThreadState_Swap(NULL);
4107 PyEval_ReleaseLock();
4108 ...Do some blocking I/O operation...
4109 PyEval_AcquireLock();
4110 PyThreadState_Swap(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004111\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004112
4113There are some subtle differences; in particular,
Fred Drake659ebfa2000-04-03 15:42:13 +00004114\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
4115and restores the value of the global variable
4116\cdata{errno}\ttindex{errno}, since the lock manipulation does not
Fred Drakef8830d11998-04-23 14:06:01 +00004117guarantee that \cdata{errno} is left alone. Also, when thread support
Fred Drake659ebfa2000-04-03 15:42:13 +00004118is disabled,
4119\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
Fred Drakee058b4f1998-02-16 06:15:35 +00004120\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
Fred Drake659ebfa2000-04-03 15:42:13 +00004121case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
4122\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
4123available. This is done so that dynamically loaded extensions
4124compiled with thread support enabled can be loaded by an interpreter
4125that was compiled with disabled thread support.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004126
4127The global interpreter lock is used to protect the pointer to the
4128current thread state. When releasing the lock and saving the thread
4129state, the current thread state pointer must be retrieved before the
4130lock is released (since another thread could immediately acquire the
4131lock and store its own thread state in the global variable).
4132Reversely, when acquiring the lock and restoring the thread state, the
4133lock must be acquired before storing the thread state pointer.
4134
4135Why am I going on with so much detail about this? Because when
Fred Drake659ebfa2000-04-03 15:42:13 +00004136threads are created from C, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004137lock, nor is there a thread state data structure for them. Such
4138threads must bootstrap themselves into existence, by first creating a
4139thread state data structure, then acquiring the lock, and finally
4140storing their thread state pointer, before they can start using the
4141Python/C API. When they are done, they should reset the thread state
4142pointer, release the lock, and finally free their thread state data
4143structure.
4144
4145When creating a thread data structure, you need to provide an
4146interpreter state data structure. The interpreter state data
4147structure hold global data that is shared by all threads in an
4148interpreter, for example the module administration
4149(\code{sys.modules}). Depending on your needs, you can either create
4150a new interpreter state data structure, or share the interpreter state
4151data structure used by the Python main thread (to access the latter,
Fred Drakef8830d11998-04-23 14:06:01 +00004152you must obtain the thread state and access its \member{interp} member;
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004153this must be done by a thread that is created by Python or by the main
4154thread after Python is initialized).
4155
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004156
4157\begin{ctypedesc}{PyInterpreterState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004158This data structure represents the state shared by a number of
4159cooperating threads. Threads belonging to the same interpreter
4160share their module administration and a few other internal items.
4161There are no public members in this structure.
4162
4163Threads belonging to different interpreters initially share nothing,
4164except process state like available memory, open file descriptors and
4165such. The global interpreter lock is also shared by all threads,
4166regardless of to which interpreter they belong.
4167\end{ctypedesc}
4168
4169\begin{ctypedesc}{PyThreadState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004170This data structure represents the state of a single thread. The only
Fred Drakef8830d11998-04-23 14:06:01 +00004171public data member is \ctype{PyInterpreterState *}\member{interp},
4172which points to this thread's interpreter state.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004173\end{ctypedesc}
4174
4175\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
4176Initialize and acquire the global interpreter lock. It should be
4177called in the main thread before creating a second thread or engaging
Fred Drakee058b4f1998-02-16 06:15:35 +00004178in any other thread operations such as
Fred Drake659ebfa2000-04-03 15:42:13 +00004179\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
4180\code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
4181It is not needed before calling
4182\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
4183\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004184
4185This is a no-op when called for a second time. It is safe to call
Fred Drake659ebfa2000-04-03 15:42:13 +00004186this function before calling
4187\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004188
4189When only the main thread exists, no lock operations are needed. This
4190is a common situation (most Python programs do not use threads), and
4191the lock operations slow the interpreter down a bit. Therefore, the
4192lock is not created initially. This situation is equivalent to having
4193acquired the lock: when there is only a single thread, all object
4194accesses are safe. Therefore, when this function initializes the
Fred Drake4de05a91998-02-16 14:25:26 +00004195lock, it also acquires it. Before the Python
4196\module{thread}\refbimodindex{thread} module creates a new thread,
4197knowing that either it has the lock or the lock hasn't been created
4198yet, it calls \cfunction{PyEval_InitThreads()}. When this call
4199returns, it is guaranteed that the lock has been created and that it
4200has acquired it.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004201
4202It is \strong{not} safe to call this function when it is unknown which
4203thread (if any) currently has the global interpreter lock.
4204
4205This function is not available when thread support is disabled at
4206compile time.
4207\end{cfuncdesc}
4208
Guido van Rossum4a944d71997-08-14 20:35:38 +00004209\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004210Acquire the global interpreter lock. The lock must have been created
4211earlier. If this thread already has the lock, a deadlock ensues.
4212This function is not available when thread support is disabled at
4213compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004214\end{cfuncdesc}
4215
4216\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004217Release the global interpreter lock. The lock must have been created
4218earlier. This function is not available when thread support is
Fred Drakee058b4f1998-02-16 06:15:35 +00004219disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004220\end{cfuncdesc}
4221
4222\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004223Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004224state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004225have been created earlier. If this thread already has the lock,
4226deadlock ensues. This function is not available when thread support
Fred Drakee058b4f1998-02-16 06:15:35 +00004227is disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004228\end{cfuncdesc}
4229
4230\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004231Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004232interpreter lock. The lock must have been created earlier and must be
4233held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004234be \NULL{}, is only used to check that it represents the current
Fred Drakee058b4f1998-02-16 06:15:35 +00004235thread state --- if it isn't, a fatal error is reported. This
4236function is not available when thread support is disabled at compile
4237time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004238\end{cfuncdesc}
4239
Fred Drakec6fa34e1998-04-02 06:47:24 +00004240\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004241Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004242support is enabled) and reset the thread state to \NULL{},
4243returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004244the lock has been created, the current thread must have acquired it.
4245(This function is available even when thread support is disabled at
4246compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004247\end{cfuncdesc}
4248
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004249\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004250Acquire the interpreter lock (if it has been created and thread
4251support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004252must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004253thread must not have acquired it, otherwise deadlock ensues. (This
4254function is available even when thread support is disabled at compile
4255time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004256\end{cfuncdesc}
4257
Fred Drake659ebfa2000-04-03 15:42:13 +00004258The following macros are normally used without a trailing semicolon;
4259look for example usage in the Python source distribution.
4260
4261\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004262This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004263\samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004264Note that it contains an opening brace; it must be matched with a
4265following \code{Py_END_ALLOW_THREADS} macro. See above for further
4266discussion of this macro. It is a no-op when thread support is
4267disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004268\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004269
Fred Drake659ebfa2000-04-03 15:42:13 +00004270\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004271This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004272\samp{PyEval_RestoreThread(_save); \}}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004273Note that it contains a closing brace; it must be matched with an
4274earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
4275discussion of this macro. It is a no-op when thread support is
4276disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004277\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004278
Fred Drake659ebfa2000-04-03 15:42:13 +00004279\begin{csimplemacrodesc}{Py_BEGIN_BLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004280This macro expands to \samp{PyEval_RestoreThread(_save);} i.e. it
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004281is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
4282brace. It is a no-op when thread support is disabled at compile
4283time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004284\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004285
Fred Drake659ebfa2000-04-03 15:42:13 +00004286\begin{csimplemacrodesc}{Py_BEGIN_UNBLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004287This macro expands to \samp{_save = PyEval_SaveThread();} i.e. it is
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004288equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
4289and variable declaration. It is a no-op when thread support is
4290disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004291\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004292
4293All of the following functions are only available when thread support
4294is enabled at compile time, and must be called only when the
Fred Drake9d20ac31998-02-16 15:27:08 +00004295interpreter lock has been created.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004296
Fred Drakec6fa34e1998-04-02 06:47:24 +00004297\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004298Create a new interpreter state object. The interpreter lock need not
4299be held, but may be held if it is necessary to serialize calls to this
4300function.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004301\end{cfuncdesc}
4302
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004303\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
4304Reset all information in an interpreter state object. The interpreter
4305lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004306\end{cfuncdesc}
4307
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004308\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
4309Destroy an interpreter state object. The interpreter lock need not be
4310held. The interpreter state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004311call to \cfunction{PyInterpreterState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004312\end{cfuncdesc}
4313
Fred Drakec6fa34e1998-04-02 06:47:24 +00004314\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004315Create a new thread state object belonging to the given interpreter
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004316object. The interpreter lock need not be held, but may be held if it
4317is necessary to serialize calls to this function.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004318\end{cfuncdesc}
4319
4320\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
4321Reset all information in a thread state object. The interpreter lock
4322must be held.
4323\end{cfuncdesc}
4324
4325\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
4326Destroy a thread state object. The interpreter lock need not be
4327held. The thread state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004328call to \cfunction{PyThreadState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004329\end{cfuncdesc}
4330
Fred Drakec6fa34e1998-04-02 06:47:24 +00004331\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004332Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004333When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004334error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004335\end{cfuncdesc}
4336
Fred Drakec6fa34e1998-04-02 06:47:24 +00004337\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004338Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004339argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004340must be held.
4341\end{cfuncdesc}
4342
4343
Fred Drake659ebfa2000-04-03 15:42:13 +00004344\chapter{Memory Management \label{memory}}
4345\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
4346
4347
4348\section{Overview \label{memoryOverview}}
4349
4350Memory management in Python involves a private heap containing all
4351Python objects and data structures. The management of this private
4352heap is ensured internally by the \emph{Python memory manager}. The
4353Python memory manager has different components which deal with various
4354dynamic storage management aspects, like sharing, segmentation,
4355preallocation or caching.
4356
4357At the lowest level, a raw memory allocator ensures that there is
4358enough room in the private heap for storing all Python-related data
4359by interacting with the memory manager of the operating system. On top
4360of the raw memory allocator, several object-specific allocators
4361operate on the same heap and implement distinct memory management
4362policies adapted to the peculiarities of every object type. For
4363example, integer objects are managed differently within the heap than
4364strings, tuples or dictionaries because integers imply different
4365storage requirements and speed/space tradeoffs. The Python memory
4366manager thus delegates some of the work to the object-specific
4367allocators, but ensures that the latter operate within the bounds of
4368the private heap.
4369
4370It is important to understand that the management of the Python heap
4371is performed by the interpreter itself and that the user has no
4372control on it, even if she regularly manipulates object pointers to
4373memory blocks inside that heap. The allocation of heap space for
4374Python objects and other internal buffers is performed on demand by
4375the Python memory manager through the Python/C API functions listed in
4376this document.
4377
4378To avoid memory corruption, extension writers should never try to
4379operate on Python objects with the functions exported by the C
4380library: \cfunction{malloc()}\ttindex{malloc()},
4381\cfunction{calloc()}\ttindex{calloc()},
4382\cfunction{realloc()}\ttindex{realloc()} and
4383\cfunction{free()}\ttindex{free()}. This will result in
4384mixed calls between the C allocator and the Python memory manager
4385with fatal consequences, because they implement different algorithms
4386and operate on different heaps. However, one may safely allocate and
4387release memory blocks with the C library allocator for individual
4388purposes, as shown in the following example:
4389
4390\begin{verbatim}
4391 PyObject *res;
4392 char *buf = (char *) malloc(BUFSIZ); /* for I/O */
4393
4394 if (buf == NULL)
4395 return PyErr_NoMemory();
4396 ...Do some I/O operation involving buf...
4397 res = PyString_FromString(buf);
4398 free(buf); /* malloc'ed */
4399 return res;
4400\end{verbatim}
4401
4402In this example, the memory request for the I/O buffer is handled by
4403the C library allocator. The Python memory manager is involved only
4404in the allocation of the string object returned as a result.
4405
4406In most situations, however, it is recommended to allocate memory from
4407the Python heap specifically because the latter is under control of
4408the Python memory manager. For example, this is required when the
4409interpreter is extended with new object types written in C. Another
4410reason for using the Python heap is the desire to \emph{inform} the
4411Python memory manager about the memory needs of the extension module.
4412Even when the requested memory is used exclusively for internal,
4413highly-specific purposes, delegating all memory requests to the Python
4414memory manager causes the interpreter to have a more accurate image of
4415its memory footprint as a whole. Consequently, under certain
4416circumstances, the Python memory manager may or may not trigger
4417appropriate actions, like garbage collection, memory compaction or
4418other preventive procedures. Note that by using the C library
4419allocator as shown in the previous example, the allocated memory for
4420the I/O buffer escapes completely the Python memory manager.
4421
4422
4423\section{Memory Interface \label{memoryInterface}}
4424
4425The following function sets, modeled after the ANSI C standard, are
4426available for allocating and releasing memory from the Python heap:
4427
4428
Fred Drake7d45d342000-08-11 17:07:32 +00004429\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
4430Allocates \var{n} bytes and returns a pointer of type \ctype{void*} to
Fred Drake659ebfa2000-04-03 15:42:13 +00004431the allocated memory, or \NULL{} if the request fails. Requesting zero
4432bytes returns a non-\NULL{} pointer.
4433\end{cfuncdesc}
4434
Fred Drake7d45d342000-08-11 17:07:32 +00004435\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004436Resizes the memory block pointed to by \var{p} to \var{n} bytes. The
4437contents will be unchanged to the minimum of the old and the new
4438sizes. If \var{p} is \NULL{}, the call is equivalent to
4439\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the memory block
4440is resized but is not freed, and the returned pointer is non-\NULL{}.
4441Unless \var{p} is \NULL{}, it must have been returned by a previous
4442call to \cfunction{PyMem_Malloc()} or \cfunction{PyMem_Realloc()}.
4443\end{cfuncdesc}
4444
Fred Drake7d45d342000-08-11 17:07:32 +00004445\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004446Frees the memory block pointed to by \var{p}, which must have been
4447returned by a previous call to \cfunction{PyMem_Malloc()} or
4448\cfunction{PyMem_Realloc()}. Otherwise, or if
4449\cfunction{PyMem_Free(p)} has been called before, undefined behaviour
4450occurs. If \var{p} is \NULL{}, no operation is performed.
4451\end{cfuncdesc}
4452
Fred Drake659ebfa2000-04-03 15:42:13 +00004453The following type-oriented macros are provided for convenience. Note
4454that \var{TYPE} refers to any C type.
4455
Fred Drakef913e542000-09-12 20:17:17 +00004456\begin{cfuncdesc}{\var{TYPE}*}{PyMem_New}{TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004457Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
4458sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
4459\ctype{\var{TYPE}*}.
4460\end{cfuncdesc}
4461
Fred Drakef913e542000-09-12 20:17:17 +00004462\begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004463Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
4464to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
4465cast to \ctype{\var{TYPE}*}.
4466\end{cfuncdesc}
4467
Fred Drakef913e542000-09-12 20:17:17 +00004468\begin{cfuncdesc}{void}{PyMem_Del}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004469Same as \cfunction{PyMem_Free()}.
4470\end{cfuncdesc}
4471
Fred Drakef913e542000-09-12 20:17:17 +00004472In addition, the following macro sets are provided for calling the
4473Python memory allocator directly, without involving the C API functions
4474listed above. However, note that their use does not preserve binary
4475compatibility accross Python versions and is therefore deprecated in
4476extension modules.
4477
4478\cfunction{PyMem_MALLOC()}, \cfunction{PyMem_REALLOC()}, \cfunction{PyMem_FREE()}.
4479
4480\cfunction{PyMem_NEW()}, \cfunction{PyMem_RESIZE()}, \cfunction{PyMem_DEL()}.
4481
Fred Drake659ebfa2000-04-03 15:42:13 +00004482
4483\section{Examples \label{memoryExamples}}
4484
4485Here is the example from section \ref{memoryOverview}, rewritten so
4486that the I/O buffer is allocated from the Python heap by using the
4487first function set:
4488
4489\begin{verbatim}
4490 PyObject *res;
4491 char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
4492
4493 if (buf == NULL)
4494 return PyErr_NoMemory();
4495 /* ...Do some I/O operation involving buf... */
4496 res = PyString_FromString(buf);
4497 PyMem_Free(buf); /* allocated with PyMem_Malloc */
4498 return res;
4499\end{verbatim}
4500
Fred Drakef913e542000-09-12 20:17:17 +00004501The same code using the type-oriented function set:
Fred Drake659ebfa2000-04-03 15:42:13 +00004502
4503\begin{verbatim}
4504 PyObject *res;
Fred Drakef913e542000-09-12 20:17:17 +00004505 char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
Fred Drake659ebfa2000-04-03 15:42:13 +00004506
4507 if (buf == NULL)
4508 return PyErr_NoMemory();
4509 /* ...Do some I/O operation involving buf... */
4510 res = PyString_FromString(buf);
Fred Drakef913e542000-09-12 20:17:17 +00004511 PyMem_Del(buf); /* allocated with PyMem_New */
Fred Drake659ebfa2000-04-03 15:42:13 +00004512 return res;
4513\end{verbatim}
4514
Fred Drakef913e542000-09-12 20:17:17 +00004515Note that in the two examples above, the buffer is always
4516manipulated via functions belonging to the same set. Indeed, it
Fred Drake659ebfa2000-04-03 15:42:13 +00004517is required to use the same memory API family for a given
4518memory block, so that the risk of mixing different allocators is
4519reduced to a minimum. The following code sequence contains two errors,
4520one of which is labeled as \emph{fatal} because it mixes two different
4521allocators operating on different heaps.
4522
4523\begin{verbatim}
Fred Drakef913e542000-09-12 20:17:17 +00004524char *buf1 = PyMem_New(char, BUFSIZ);
Fred Drake659ebfa2000-04-03 15:42:13 +00004525char *buf2 = (char *) malloc(BUFSIZ);
4526char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
4527...
Fred Drakef913e542000-09-12 20:17:17 +00004528PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004529free(buf2); /* Right -- allocated via malloc() */
Fred Drakef913e542000-09-12 20:17:17 +00004530free(buf1); /* Fatal -- should be PyMem_Del() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004531\end{verbatim}
4532
4533In addition to the functions aimed at handling raw memory blocks from
4534the Python heap, objects in Python are allocated and released with
Fred Drakef913e542000-09-12 20:17:17 +00004535\cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()} and
4536\cfunction{PyObject_Del()}, or with their corresponding macros
4537\cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()} and
Fred Drakee06f0f92000-06-30 15:52:39 +00004538\cfunction{PyObject_DEL()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004539
Fred Drakee06f0f92000-06-30 15:52:39 +00004540These will be explained in the next chapter on defining and
4541implementing new object types in C.
Fred Drake659ebfa2000-04-03 15:42:13 +00004542
4543
Fred Drakeefd146c1999-02-15 15:30:45 +00004544\chapter{Defining New Object Types \label{newTypes}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004545
Fred Drakec6fa34e1998-04-02 06:47:24 +00004546\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00004547\end{cfuncdesc}
4548
Fred Drakef913e542000-09-12 20:17:17 +00004549\begin{cfuncdesc}{PyVarObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00004550\end{cfuncdesc}
4551
Fred Drakef913e542000-09-12 20:17:17 +00004552\begin{cfuncdesc}{void}{_PyObject_Del}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004553\end{cfuncdesc}
4554
Fred Drakef913e542000-09-12 20:17:17 +00004555\begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op,
4556 PyTypeObject *type}
4557\end{cfuncdesc}
4558
4559\begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op,
4560 PyTypeObject *type, int size}
4561\end{cfuncdesc}
4562
4563\begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type}
4564\end{cfuncdesc}
4565
4566\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type,
4567 int size}
4568\end{cfuncdesc}
4569
4570\begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op}
4571\end{cfuncdesc}
4572
4573\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW}{TYPE, PyTypeObject *type}
4574\end{cfuncdesc}
4575
4576\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
4577 int size}
4578\end{cfuncdesc}
4579
4580\begin{cfuncdesc}{void}{PyObject_DEL}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004581\end{cfuncdesc}
4582
Guido van Rossum3c4378b1998-04-14 20:21:10 +00004583Py_InitModule (!!!)
4584
4585PyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse
4586
4587Py_BuildValue
Guido van Rossumae110af1997-05-22 20:11:52 +00004588
Fred Drake659ebfa2000-04-03 15:42:13 +00004589DL_IMPORT
4590
4591Py*_Check
4592
4593_Py_NoneStruct
4594
4595
4596\section{Common Object Structures \label{common-structs}}
4597
Guido van Rossumae110af1997-05-22 20:11:52 +00004598PyObject, PyVarObject
4599
4600PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
4601
4602Typedefs:
4603unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
4604intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
Guido van Rossumae110af1997-05-22 20:11:52 +00004605destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
4606setattrofunc, cmpfunc, reprfunc, hashfunc
4607
Fred Drakea8455ab2000-06-16 19:58:42 +00004608\begin{ctypedesc}{PyCFunction}
4609Type of the functions used to implement most Python callables in C.
4610\end{ctypedesc}
4611
4612\begin{ctypedesc}{PyMethodDef}
4613Structure used to describe a method of an extension type. This
4614structure has four fields:
4615
4616\begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
4617 \lineiii{ml_name}{char *}{name of the method}
4618 \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
4619 \lineiii{ml_flags}{int}{flag bits indicating how the call should be
4620 constructed}
4621 \lineiii{ml_doc}{char *}{points to the contents of the docstring}
4622\end{tableiii}
4623\end{ctypedesc}
4624
4625\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef[] table,
4626 PyObject *ob, char *name}
4627Return a bound method object for an extension type implemented in C.
4628This function also handles the special attribute \member{__methods__},
4629returning a list of all the method names defined in \var{table}.
4630\end{cfuncdesc}
4631
Fred Drake659ebfa2000-04-03 15:42:13 +00004632
4633\section{Mapping Object Structures \label{mapping-structs}}
4634
4635\begin{ctypedesc}{PyMappingMethods}
4636Structure used to hold pointers to the functions used to implement the
4637mapping protocol for an extension type.
4638\end{ctypedesc}
4639
4640
4641\section{Number Object Structures \label{number-structs}}
4642
4643\begin{ctypedesc}{PyNumberMethods}
4644Structure used to hold pointers to the functions an extension type
4645uses to implement the number protocol.
4646\end{ctypedesc}
4647
4648
4649\section{Sequence Object Structures \label{sequence-structs}}
4650
4651\begin{ctypedesc}{PySequenceMethods}
4652Structure used to hold pointers to the functions which an object uses
4653to implement the sequence protocol.
4654\end{ctypedesc}
4655
4656
4657\section{Buffer Object Structures \label{buffer-structs}}
4658\sectionauthor{Greg J. Stein}{greg@lyra.org}
4659
4660The buffer interface exports a model where an object can expose its
4661internal data as a set of chunks of data, where each chunk is
4662specified as a pointer/length pair. These chunks are called
4663\dfn{segments} and are presumed to be non-contiguous in memory.
4664
4665If an object does not export the buffer interface, then its
4666\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
4667should be \NULL{}. Otherwise, the \member{tp_as_buffer} will point to
4668a \ctype{PyBufferProcs} structure.
4669
4670\strong{Note:} It is very important that your
4671\ctype{PyTypeObject} structure uses \code{Py_TPFLAGS_DEFAULT} for the
4672value of the \member{tp_flags} member rather than \code{0}. This
4673tells the Python runtime that your \ctype{PyBufferProcs} structure
4674contains the \member{bf_getcharbuffer} slot. Older versions of Python
4675did not have this member, so a new Python interpreter using an old
4676extension needs to be able to test for its presence before using it.
4677
4678\begin{ctypedesc}{PyBufferProcs}
4679Structure used to hold the function pointers which define an
4680implementation of the buffer protocol.
4681
4682The first slot is \member{bf_getreadbuffer}, of type
4683\ctype{getreadbufferproc}. If this slot is \NULL{}, then the object
4684does not support reading from the internal data. This is
4685non-sensical, so implementors should fill this in, but callers should
4686test that the slot contains a non-\NULL{} value.
4687
4688The next slot is \member{bf_getwritebuffer} having type
4689\ctype{getwritebufferproc}. This slot may be \NULL{} if the object
4690does not allow writing into its returned buffers.
4691
4692The third slot is \member{bf_getsegcount}, with type
4693\ctype{getsegcountproc}. This slot must not be \NULL{} and is used to
4694inform the caller how many segments the object contains. Simple
4695objects such as \ctype{PyString_Type} and
4696\ctype{PyBuffer_Type} objects contain a single segment.
4697
4698The last slot is \member{bf_getcharbuffer}, of type
4699\ctype{getcharbufferproc}. This slot will only be present if the
4700\code{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
4701\member{tp_flags} field of the object's \ctype{PyTypeObject}. Before using
4702this slot, the caller should test whether it is present by using the
4703\cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()} function.
4704If present, it may be \NULL, indicating that the object's contents
4705cannot be used as \emph{8-bit characters}.
4706The slot function may also raise an error if the object's contents
4707cannot be interpreted as 8-bit characters. For example, if the object
4708is an array which is configured to hold floating point values, an
4709exception may be raised if a caller attempts to use
4710\member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
4711This notion of exporting the internal buffers as ``text'' is used to
4712distinguish between objects that are binary in nature, and those which
4713have character-based content.
4714
4715\strong{Note:} The current policy seems to state that these characters
4716may be multi-byte characters. This implies that a buffer size of
4717\var{N} does not mean there are \var{N} characters present.
4718\end{ctypedesc}
4719
4720\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
4721Flag bit set in the type structure to indicate that the
4722\member{bf_getcharbuffer} slot is known. This being set does not
4723indicate that the object supports the buffer interface or that the
4724\member{bf_getcharbuffer} slot is non-\NULL.
4725\end{datadesc}
4726
4727\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
4728 (PyObject *self, int segment, void **ptrptr)}
4729Return a pointer to a readable segment of the buffer. This function
4730is allowed to raise an exception, in which case it must return
4731\code{-1}. The \var{segment} which is passed must be zero or
4732positive, and strictly less than the number of segments returned by
4733the \member{bf_getsegcount} slot function. On success, returns
4734\code{0} and sets \code{*\var{ptrptr}} to a pointer to the buffer
4735memory.
4736\end{ctypedesc}
4737
4738\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
4739 (PyObject *self, int segment, void **ptrptr)}
Fred Drake58c5a2a1999-08-04 13:13:24 +00004740Return a pointer to a writable memory buffer in \code{*\var{ptrptr}};
4741the memory buffer must correspond to buffer segment \var{segment}.
4742Must return \code{-1} and set an exception on error.
4743\exception{TypeError} should be raised if the object only supports
4744read-only buffers, and \exception{SystemError} should be raised when
4745\var{segment} specifies a segment that doesn't exist.
4746% Why doesn't it raise ValueError for this one?
Fred Drake659ebfa2000-04-03 15:42:13 +00004747% GJS: because you shouldn't be calling it with an invalid
4748% segment. That indicates a blatant programming error in the C
4749% code.
Fred Drake58c5a2a1999-08-04 13:13:24 +00004750\end{ctypedesc}
4751
Fred Drake659ebfa2000-04-03 15:42:13 +00004752\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
4753 (PyObject *self, int *lenp)}
4754Return the number of memory segments which comprise the buffer. If
4755\var{lenp} is not \NULL, the implementation must report the sum of the
4756sizes (in bytes) of all segments in \code{*\var{lenp}}.
4757The function cannot fail.
4758\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004759
Fred Drake659ebfa2000-04-03 15:42:13 +00004760\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
4761 (PyObject *self, int segment, const char **ptrptr)}
4762\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004763
Guido van Rossumae110af1997-05-22 20:11:52 +00004764
Fred Drake659ebfa2000-04-03 15:42:13 +00004765% \chapter{Debugging \label{debugging}}
4766%
4767% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004768
4769
Fred Drakef3aa0e01998-03-17 06:23:13 +00004770\input{api.ind} % Index -- must be last
Guido van Rossum9231c8f1997-05-15 21:43:21 +00004771
4772\end{document}