blob: f926facb95be4db6a30e51a9725ec71cd3a3f1da [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 Draked5d04352000-09-14 20:24:17 +0000105\samp{\#include <python\shortversion/Python.h>}; this will break on
Fred Drake659ebfa2000-04-03 15:42:13 +0000106multi-platform builds since the platform independent headers under
107\envvar{prefix} include the platform specific headers from
108\envvar{exec_prefix}.
109
Fred Drakeefd146c1999-02-15 15:30:45 +0000110
111\section{Objects, Types and Reference Counts \label{objects}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000112
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000113Most Python/C API functions have one or more arguments as well as a
Fred Drake659ebfa2000-04-03 15:42:13 +0000114return value of type \ctype{PyObject*}. This type is a pointer
Fred Drakee058b4f1998-02-16 06:15:35 +0000115to an opaque data type representing an arbitrary Python
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000116object. Since all Python object types are treated the same way by the
117Python language in most situations (e.g., assignments, scope rules,
118and argument passing), it is only fitting that they should be
Fred Drake659ebfa2000-04-03 15:42:13 +0000119represented by a single C type. Almost all Python objects live on the
120heap: you never declare an automatic or static variable of type
121\ctype{PyObject}, only pointer variables of type \ctype{PyObject*} can
122be declared. The sole exception are the type objects\obindex{type};
123since these must never be deallocated, they are typically static
124\ctype{PyTypeObject} objects.
Guido van Rossum59a61351997-08-14 20:34:33 +0000125
Fred Drakee058b4f1998-02-16 06:15:35 +0000126All Python objects (even Python integers) have a \dfn{type} and a
127\dfn{reference count}. An object's type determines what kind of object
Guido van Rossum4a944d71997-08-14 20:35:38 +0000128it is (e.g., an integer, a list, or a user-defined function; there are
Fred Drakebe486461999-11-09 17:03:03 +0000129many more as explained in the \citetitle[../ref/ref.html]{Python
130Reference Manual}). For each of the well-known types there is a macro
131to check whether an object is of that type; for instance,
Fred Drake659ebfa2000-04-03 15:42:13 +0000132\samp{PyList_Check(\var{a})} is true if (and only if) the object
133pointed to by \var{a} is a Python list.
Guido van Rossum59a61351997-08-14 20:34:33 +0000134
Fred Drakeefd146c1999-02-15 15:30:45 +0000135
136\subsection{Reference Counts \label{refcounts}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000137
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000138The reference count is important because today's computers have a
Fred Drake003d8da1998-04-13 00:53:42 +0000139finite (and often severely limited) memory size; it counts how many
Guido van Rossum4a944d71997-08-14 20:35:38 +0000140different places there are that have a reference to an object. Such a
Fred Drake659ebfa2000-04-03 15:42:13 +0000141place could be another object, or a global (or static) C variable, or
142a local variable in some C function. When an object's reference count
Guido van Rossum4a944d71997-08-14 20:35:38 +0000143becomes zero, the object is deallocated. If it contains references to
144other objects, their reference count is decremented. Those other
145objects may be deallocated in turn, if this decrement makes their
146reference count become zero, and so on. (There's an obvious problem
147with objects that reference each other here; for now, the solution is
Fred Drake659ebfa2000-04-03 15:42:13 +0000148``don't do that.'')
Guido van Rossum59a61351997-08-14 20:34:33 +0000149
Guido van Rossum4a944d71997-08-14 20:35:38 +0000150Reference counts are always manipulated explicitly. The normal way is
Fred Drake659ebfa2000-04-03 15:42:13 +0000151to use the macro \cfunction{Py_INCREF()}\ttindex{Py_INCREF()} to
152increment an object's reference count by one, and
153\cfunction{Py_DECREF()}\ttindex{Py_DECREF()} to decrement it by
154one. The \cfunction{Py_DECREF()} macro is considerably more complex
155than the incref one, since it must check whether the reference count
156becomes zero and then cause the object's deallocator to be called.
157The deallocator is a function pointer contained in the object's type
158structure. The type-specific deallocator takes care of decrementing
159the reference counts for other objects contained in the object if this
160is a compound object type, such as a list, as well as performing any
161additional finalization that's needed. There's no chance that the
162reference count can overflow; at least as many bits are used to hold
163the reference count as there are distinct memory locations in virtual
164memory (assuming \code{sizeof(long) >= sizeof(char*)}). Thus, the
165reference count increment is a simple operation.
Guido van Rossum59a61351997-08-14 20:34:33 +0000166
Guido van Rossum4a944d71997-08-14 20:35:38 +0000167It is not necessary to increment an object's reference count for every
168local variable that contains a pointer to an object. In theory, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000169object's reference count goes up by one when the variable is made to
Guido van Rossum4a944d71997-08-14 20:35:38 +0000170point to it and it goes down by one when the variable goes out of
171scope. However, these two cancel each other out, so at the end the
172reference count hasn't changed. The only real reason to use the
173reference count is to prevent the object from being deallocated as
174long as our variable is pointing to it. If we know that there is at
175least one other reference to the object that lives at least as long as
176our variable, there is no need to increment the reference count
177temporarily. An important situation where this arises is in objects
Fred Drake659ebfa2000-04-03 15:42:13 +0000178that are passed as arguments to C functions in an extension module
Guido van Rossum4a944d71997-08-14 20:35:38 +0000179that are called from Python; the call mechanism guarantees to hold a
Guido van Rossum59a61351997-08-14 20:34:33 +0000180reference to every argument for the duration of the call.
181
Fred Drakee058b4f1998-02-16 06:15:35 +0000182However, a common pitfall is to extract an object from a list and
183hold on to it for a while without incrementing its reference count.
184Some other operation might conceivably remove the object from the
185list, decrementing its reference count and possible deallocating it.
186The real danger is that innocent-looking operations may invoke
187arbitrary Python code which could do this; there is a code path which
188allows control to flow back to the user from a \cfunction{Py_DECREF()},
189so almost any operation is potentially dangerous.
Guido van Rossum59a61351997-08-14 20:34:33 +0000190
Guido van Rossum4a944d71997-08-14 20:35:38 +0000191A safe approach is to always use the generic operations (functions
Fred Drake659ebfa2000-04-03 15:42:13 +0000192whose name begins with \samp{PyObject_}, \samp{PyNumber_},
193\samp{PySequence_} or \samp{PyMapping_}). These operations always
194increment the reference count of the object they return. This leaves
195the caller with the responsibility to call
196\cfunction{Py_DECREF()} when they are done with the result; this soon
197becomes second nature.
Guido van Rossum59a61351997-08-14 20:34:33 +0000198
Fred Drakeefd146c1999-02-15 15:30:45 +0000199
200\subsubsection{Reference Count Details \label{refcountDetails}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000201
202The reference count behavior of functions in the Python/C API is best
Fred Drake659ebfa2000-04-03 15:42:13 +0000203explained in terms of \emph{ownership of references}. Note that we
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000204talk of owning references, never of owning objects; objects are always
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000205shared! When a function owns a reference, it has to dispose of it
Fred Drakee058b4f1998-02-16 06:15:35 +0000206properly --- either by passing ownership on (usually to its caller) or
207by calling \cfunction{Py_DECREF()} or \cfunction{Py_XDECREF()}. When
208a function passes ownership of a reference on to its caller, the
209caller is said to receive a \emph{new} reference. When no ownership
210is transferred, the caller is said to \emph{borrow} the reference.
211Nothing needs to be done for a borrowed reference.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000212
Fred Drakea8455ab2000-06-16 19:58:42 +0000213Conversely, when a calling function passes it a reference to an
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000214object, there are two possibilities: the function \emph{steals} a
215reference to the object, or it does not. Few functions steal
Fred Drakee058b4f1998-02-16 06:15:35 +0000216references; the two notable exceptions are
Fred Drake659ebfa2000-04-03 15:42:13 +0000217\cfunction{PyList_SetItem()}\ttindex{PyList_SetItem()} and
218\cfunction{PyTuple_SetItem()}\ttindex{PyTuple_SetItem()}, which
Fred Drakee058b4f1998-02-16 06:15:35 +0000219steal a reference to the item (but not to the tuple or list into which
Fred Drake003d8da1998-04-13 00:53:42 +0000220the item is put!). These functions were designed to steal a reference
Fred Drakee058b4f1998-02-16 06:15:35 +0000221because of a common idiom for populating a tuple or list with newly
222created objects; for example, the code to create the tuple \code{(1,
2232, "three")} could look like this (forgetting about error handling for
Fred Drake659ebfa2000-04-03 15:42:13 +0000224the moment; a better way to code this is shown below):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000225
226\begin{verbatim}
227PyObject *t;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000228
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000229t = PyTuple_New(3);
230PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
231PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
232PyTuple_SetItem(t, 2, PyString_FromString("three"));
233\end{verbatim}
234
Fred Drakee058b4f1998-02-16 06:15:35 +0000235Incidentally, \cfunction{PyTuple_SetItem()} is the \emph{only} way to
236set tuple items; \cfunction{PySequence_SetItem()} and
237\cfunction{PyObject_SetItem()} refuse to do this since tuples are an
238immutable data type. You should only use
239\cfunction{PyTuple_SetItem()} for tuples that you are creating
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000240yourself.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000241
242Equivalent code for populating a list can be written using
Fred Drakee058b4f1998-02-16 06:15:35 +0000243\cfunction{PyList_New()} and \cfunction{PyList_SetItem()}. Such code
244can also use \cfunction{PySequence_SetItem()}; this illustrates the
245difference between the two (the extra \cfunction{Py_DECREF()} calls):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000246
247\begin{verbatim}
248PyObject *l, *x;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000249
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000250l = PyList_New(3);
251x = PyInt_FromLong(1L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000252PySequence_SetItem(l, 0, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000253x = PyInt_FromLong(2L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000254PySequence_SetItem(l, 1, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000255x = PyString_FromString("three");
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000256PySequence_SetItem(l, 2, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000257\end{verbatim}
258
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000259You might find it strange that the ``recommended'' approach takes more
260code. However, in practice, you will rarely use these ways of
261creating and populating a tuple or list. There's a generic function,
Fred Drakee058b4f1998-02-16 06:15:35 +0000262\cfunction{Py_BuildValue()}, that can create most common objects from
Fred Drake659ebfa2000-04-03 15:42:13 +0000263C values, directed by a \dfn{format string}. For example, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000264above two blocks of code could be replaced by the following (which
265also takes care of the error checking):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000266
267\begin{verbatim}
268PyObject *t, *l;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000269
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000270t = Py_BuildValue("(iis)", 1, 2, "three");
271l = Py_BuildValue("[iis]", 1, 2, "three");
272\end{verbatim}
273
Fred Drakee058b4f1998-02-16 06:15:35 +0000274It is much more common to use \cfunction{PyObject_SetItem()} and
275friends with items whose references you are only borrowing, like
276arguments that were passed in to the function you are writing. In
277that case, their behaviour regarding reference counts is much saner,
278since you don't have to increment a reference count so you can give a
279reference away (``have it be stolen''). For example, this function
280sets all items of a list (actually, any mutable sequence) to a given
281item:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000282
283\begin{verbatim}
284int set_all(PyObject *target, PyObject *item)
285{
286 int i, n;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000287
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000288 n = PyObject_Length(target);
289 if (n < 0)
290 return -1;
291 for (i = 0; i < n; i++) {
292 if (PyObject_SetItem(target, i, item) < 0)
293 return -1;
294 }
295 return 0;
296}
297\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000298\ttindex{set_all()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000299
300The situation is slightly different for function return values.
301While passing a reference to most functions does not change your
302ownership responsibilities for that reference, many functions that
303return a referece to an object give you ownership of the reference.
304The reason is simple: in many cases, the returned object is created
305on the fly, and the reference you get is the only reference to the
Fred Drakee058b4f1998-02-16 06:15:35 +0000306object. Therefore, the generic functions that return object
307references, like \cfunction{PyObject_GetItem()} and
308\cfunction{PySequence_GetItem()}, always return a new reference (i.e.,
309the caller becomes the owner of the reference).
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000310
311It is important to realize that whether you own a reference returned
Fred Drakee058b4f1998-02-16 06:15:35 +0000312by a function depends on which function you call only --- \emph{the
313plumage} (i.e., the type of the type of the object passed as an
314argument to the function) \emph{doesn't enter into it!} Thus, if you
315extract an item from a list using \cfunction{PyList_GetItem()}, you
316don't own the reference --- but if you obtain the same item from the
317same list using \cfunction{PySequence_GetItem()} (which happens to
318take exactly the same arguments), you do own a reference to the
319returned object.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000320
Fred Drakee058b4f1998-02-16 06:15:35 +0000321Here is an example of how you could write a function that computes the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000322sum of the items in a list of integers; once using
Fred Drake659ebfa2000-04-03 15:42:13 +0000323\cfunction{PyList_GetItem()}\ttindex{PyList_GetItem()}, and once using
324\cfunction{PySequence_GetItem()}\ttindex{PySequence_GetItem()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000325
326\begin{verbatim}
327long sum_list(PyObject *list)
328{
329 int i, n;
330 long total = 0;
331 PyObject *item;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000332
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000333 n = PyList_Size(list);
334 if (n < 0)
335 return -1; /* Not a list */
336 for (i = 0; i < n; i++) {
337 item = PyList_GetItem(list, i); /* Can't fail */
338 if (!PyInt_Check(item)) continue; /* Skip non-integers */
339 total += PyInt_AsLong(item);
340 }
341 return total;
342}
343\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000344\ttindex{sum_list()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000345
346\begin{verbatim}
347long sum_sequence(PyObject *sequence)
348{
349 int i, n;
350 long total = 0;
351 PyObject *item;
Fred Drake659ebfa2000-04-03 15:42:13 +0000352 n = PySequence_Length(sequence);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000353 if (n < 0)
354 return -1; /* Has no length */
355 for (i = 0; i < n; i++) {
Fred Drake659ebfa2000-04-03 15:42:13 +0000356 item = PySequence_GetItem(sequence, i);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000357 if (item == NULL)
358 return -1; /* Not a sequence, or other failure */
359 if (PyInt_Check(item))
360 total += PyInt_AsLong(item);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000361 Py_DECREF(item); /* Discard reference ownership */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000362 }
363 return total;
364}
365\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000366\ttindex{sum_sequence()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000367
Fred Drakeefd146c1999-02-15 15:30:45 +0000368
369\subsection{Types \label{types}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000370
371There are few other data types that play a significant role in
Fred Drake659ebfa2000-04-03 15:42:13 +0000372the Python/C API; most are simple C types such as \ctype{int},
373\ctype{long}, \ctype{double} and \ctype{char*}. A few structure types
Guido van Rossum4a944d71997-08-14 20:35:38 +0000374are used to describe static tables used to list the functions exported
Fred Drake659ebfa2000-04-03 15:42:13 +0000375by a module or the data attributes of a new object type, and another
376is used to describe the value of a complex number. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000377be discussed together with the functions that use them.
378
Fred Drakeefd146c1999-02-15 15:30:45 +0000379
380\section{Exceptions \label{exceptions}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000381
Guido van Rossum4a944d71997-08-14 20:35:38 +0000382The Python programmer only needs to deal with exceptions if specific
383error handling is required; unhandled exceptions are automatically
Fred Drake659ebfa2000-04-03 15:42:13 +0000384propagated to the caller, then to the caller's caller, and so on, until
Guido van Rossum4a944d71997-08-14 20:35:38 +0000385they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000386user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000387
Fred Drake659ebfa2000-04-03 15:42:13 +0000388For C programmers, however, error checking always has to be explicit.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000389All functions in the Python/C API can raise exceptions, unless an
390explicit claim is made otherwise in a function's documentation. In
391general, when a function encounters an error, it sets an exception,
392discards any object references that it owns, and returns an
Fred Drakee058b4f1998-02-16 06:15:35 +0000393error indicator --- usually \NULL{} or \code{-1}. A few functions
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000394return a Boolean true/false result, with false indicating an error.
395Very few functions return no explicit error indicator or have an
396ambiguous return value, and require explicit testing for errors with
Fred Drake659ebfa2000-04-03 15:42:13 +0000397\cfunction{PyErr_Occurred()}\ttindex{PyErr_Occurred()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000398
399Exception state is maintained in per-thread storage (this is
400equivalent to using global storage in an unthreaded application). A
Fred Drakec6fa34e1998-04-02 06:47:24 +0000401thread can be in one of two states: an exception has occurred, or not.
Fred Drakee058b4f1998-02-16 06:15:35 +0000402The function \cfunction{PyErr_Occurred()} can be used to check for
403this: it returns a borrowed reference to the exception type object
404when an exception has occurred, and \NULL{} otherwise. There are a
405number of functions to set the exception state:
Fred Drake659ebfa2000-04-03 15:42:13 +0000406\cfunction{PyErr_SetString()}\ttindex{PyErr_SetString()} is the most
407common (though not the most general) function to set the exception
408state, and \cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} clears the
409exception state.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000410
411The full exception state consists of three objects (all of which can
Fred Drakee058b4f1998-02-16 06:15:35 +0000412be \NULL{}): the exception type, the corresponding exception
Fred Drake659ebfa2000-04-03 15:42:13 +0000413value, and the traceback. These have the same meanings as the Python
414\withsubitem{(in module sys)}{
415 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
416objects \code{sys.exc_type}, \code{sys.exc_value}, and
417\code{sys.exc_traceback}; however, they are not the same: the Python
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000418objects represent the last exception being handled by a Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000419\keyword{try} \ldots\ \keyword{except} statement, while the C level
Fred Drakee058b4f1998-02-16 06:15:35 +0000420exception state only exists while an exception is being passed on
Fred Drake659ebfa2000-04-03 15:42:13 +0000421between C functions until it reaches the Python bytecode interpreter's
422main loop, which takes care of transferring it to \code{sys.exc_type}
423and friends.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000424
Fred Drakec6fa34e1998-04-02 06:47:24 +0000425Note that starting with Python 1.5, the preferred, thread-safe way to
Fred Drake659ebfa2000-04-03 15:42:13 +0000426access the exception state from Python code is to call the function
427\withsubitem{(in module sys)}{\ttindex{exc_info()}}
Fred Drakee058b4f1998-02-16 06:15:35 +0000428\function{sys.exc_info()}, which returns the per-thread exception state
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000429for Python code. Also, the semantics of both ways to access the
430exception state have changed so that a function which catches an
431exception will save and restore its thread's exception state so as to
432preserve the exception state of its caller. This prevents common bugs
433in exception handling code caused by an innocent-looking function
434overwriting the exception being handled; it also reduces the often
435unwanted lifetime extension for objects that are referenced by the
Fred Drakec6fa34e1998-04-02 06:47:24 +0000436stack frames in the traceback.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000437
438As a general principle, a function that calls another function to
439perform some task should check whether the called function raised an
440exception, and if so, pass the exception state on to its caller. It
Fred Drake659ebfa2000-04-03 15:42:13 +0000441should discard any object references that it owns, and return an
Fred Drakee058b4f1998-02-16 06:15:35 +0000442error indicator, but it should \emph{not} set another exception ---
443that would overwrite the exception that was just raised, and lose
444important information about the exact cause of the error.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000445
Fred Drake659ebfa2000-04-03 15:42:13 +0000446A simple example of detecting exceptions and passing them on is shown
447in the \cfunction{sum_sequence()}\ttindex{sum_sequence()} example
448above. It so happens that that example doesn't need to clean up any
449owned references when it detects an error. The following example
450function shows some error cleanup. First, to remind you why you like
451Python, we show the equivalent Python code:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000452
453\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000454def incr_item(dict, key):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000455 try:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000456 item = dict[key]
457 except KeyError:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000458 item = 0
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 Draked5d04352000-09-14 20:24:17 +0000553\file{lib/python\shortversion} relative to the parent directory where
554the executable named \file{python} is found on the shell command
555search path (the environment variable \envvar{PATH}).
Guido van Rossum42cefd01997-10-05 15:27:29 +0000556
557For instance, if the Python executable is found in
Fred Drakee058b4f1998-02-16 06:15:35 +0000558\file{/usr/local/bin/python}, it will assume that the libraries are in
Fred Draked5d04352000-09-14 20:24:17 +0000559\file{/usr/local/lib/python\shortversion}. (In fact, this particular path
Fred Drakee058b4f1998-02-16 06:15:35 +0000560is also the ``fallback'' location, used when no executable file named
Fred Drakec6fa34e1998-04-02 06:47:24 +0000561\file{python} is found along \envvar{PATH}.) The user can override
562this behavior by setting the environment variable \envvar{PYTHONHOME},
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000563or insert additional directories in front of the standard path by
Fred Drakec6fa34e1998-04-02 06:47:24 +0000564setting \envvar{PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000565
Guido van Rossum4a944d71997-08-14 20:35:38 +0000566The embedding application can steer the search by calling
Fred Drake659ebfa2000-04-03 15:42:13 +0000567\code{Py_SetProgramName(\var{file})}\ttindex{Py_SetProgramName()} \emph{before} calling
Fred Drakec6fa34e1998-04-02 06:47:24 +0000568\cfunction{Py_Initialize()}. Note that \envvar{PYTHONHOME} still
569overrides this and \envvar{PYTHONPATH} is still inserted in front of
Fred Drakee058b4f1998-02-16 06:15:35 +0000570the standard path. An application that requires total control has to
Fred Drake659ebfa2000-04-03 15:42:13 +0000571provide its own implementation of
572\cfunction{Py_GetPath()}\ttindex{Py_GetPath()},
573\cfunction{Py_GetPrefix()}\ttindex{Py_GetPrefix()},
574\cfunction{Py_GetExecPrefix()}\ttindex{Py_GetExecPrefix()}, and
575\cfunction{Py_GetProgramFullPath()}\ttindex{Py_GetProgramFullPath()} (all
576defined in \file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000577
Guido van Rossum4a944d71997-08-14 20:35:38 +0000578Sometimes, it is desirable to ``uninitialize'' Python. For instance,
579the application may want to start over (make another call to
Fred Drakee058b4f1998-02-16 06:15:35 +0000580\cfunction{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000581use of Python and wants to free all memory allocated by Python. This
Fred Drakee058b4f1998-02-16 06:15:35 +0000582can be accomplished by calling \cfunction{Py_Finalize()}. The function
Fred Drake659ebfa2000-04-03 15:42:13 +0000583\cfunction{Py_IsInitialized()}\ttindex{Py_IsInitialized()} returns
584true if Python is currently in the initialized state. More
585information about these functions is given in a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000586
Guido van Rossum4a944d71997-08-14 20:35:38 +0000587
Fred Drakeefd146c1999-02-15 15:30:45 +0000588\chapter{The Very High Level Layer \label{veryhigh}}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000589
Fred Drakee5bf8b21998-02-12 21:22:28 +0000590The functions in this chapter will let you execute Python source code
591given in a file or a buffer, but they will not let you interact in a
592more detailed way with the interpreter.
Guido van Rossum4a944d71997-08-14 20:35:38 +0000593
Fred Drake659ebfa2000-04-03 15:42:13 +0000594Several of these functions accept a start symbol from the grammar as a
595parameter. The available start symbols are \constant{Py_eval_input},
596\constant{Py_file_input}, and \constant{Py_single_input}. These are
597described following the functions which accept them as parameters.
598
Fred Drake510d08b2000-08-14 02:50:21 +0000599Note also that several of these functions take \ctype{FILE*}
600parameters. On particular issue which needs to be handled carefully
601is that the \ctype{FILE} structure for different C libraries can be
602different and incompatible. Under Windows (at least), it is possible
603for dynamically linked extensions to actually use different libraries,
604so care should be taken that \ctype{FILE*} parameters are only passed
605to these functions if it is certain that they were created by the same
606library that the Python runtime is using.
607
Fred Drakec6fa34e1998-04-02 06:47:24 +0000608\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000609 If \var{fp} refers to a file associated with an interactive device
610 (console or terminal input or \UNIX{} pseudo-terminal), return the
611 value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
612 result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
Fred Drakea8d73412000-08-11 20:39:29 +0000613 \NULL{}, this function uses \code{"???"} as the filename.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000614\end{cfuncdesc}
615
Fred Drakec6fa34e1998-04-02 06:47:24 +0000616\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
Fred Drake0041a941999-04-29 04:20:46 +0000617 Executes the Python source code from \var{command} in the
618 \module{__main__} module. If \module{__main__} does not already
619 exist, it is created. Returns \code{0} on success or \code{-1} if
620 an exception was raised. If there was an error, there is no way to
621 get the exception information.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000622\end{cfuncdesc}
623
Fred Drakec6fa34e1998-04-02 06:47:24 +0000624\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000625 Similar to \cfunction{PyRun_SimpleString()}, but the Python source
626 code is read from \var{fp} instead of an in-memory string.
627 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000628\end{cfuncdesc}
629
Fred Drakec6fa34e1998-04-02 06:47:24 +0000630\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000631 Read and execute a single statement from a file associated with an
632 interactive device. If \var{filename} is \NULL, \code{"???"} is
633 used instead. The user will be prompted using \code{sys.ps1} and
634 \code{sys.ps2}. Returns \code{0} when the input was executed
635 successfully, \code{-1} if there was an exception, or an error code
636 from the \file{errcode.h} include file distributed as part of Python
637 in case of a parse error. (Note that \file{errcode.h} is not
638 included by \file{Python.h}, so must be included specifically if
639 needed.)
Fred Drakee5bf8b21998-02-12 21:22:28 +0000640\end{cfuncdesc}
641
Fred Drakec6fa34e1998-04-02 06:47:24 +0000642\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000643 Read and execute statements from a file associated with an
644 interactive device until \EOF{} is reached. If \var{filename} is
645 \NULL, \code{"???"} is used instead. The user will be prompted
646 using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000647\end{cfuncdesc}
648
Fred Drakec6fa34e1998-04-02 06:47:24 +0000649\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
650 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000651 Parse Python source code from \var{str} using the start token
652 \var{start}. The result can be used to create a code object which
653 can be evaluated efficiently. This is useful if a code fragment
654 must be evaluated many times.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000655\end{cfuncdesc}
656
Fred Drakec6fa34e1998-04-02 06:47:24 +0000657\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
658 char *filename, int start}
Fred Drake0041a941999-04-29 04:20:46 +0000659 Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
660 source code is read from \var{fp} instead of an in-memory string.
661 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000662\end{cfuncdesc}
663
Fred Drakec6fa34e1998-04-02 06:47:24 +0000664\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
665 PyObject *globals,
666 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000667 Execute Python source code from \var{str} in the context specified
668 by the dictionaries \var{globals} and \var{locals}. The parameter
669 \var{start} specifies the start token that should be used to parse
670 the source code.
671
672 Returns the result of executing the code as a Python object, or
673 \NULL{} if an exception was raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000674\end{cfuncdesc}
675
Fred Drakec6fa34e1998-04-02 06:47:24 +0000676\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
677 int start, PyObject *globals,
678 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000679 Similar to \cfunction{PyRun_String()}, but the Python source code is
Fred Drake659ebfa2000-04-03 15:42:13 +0000680 read from \var{fp} instead of an in-memory string.
681 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000682\end{cfuncdesc}
683
Fred Drakec6fa34e1998-04-02 06:47:24 +0000684\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
685 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000686 Parse and compile the Python source code in \var{str}, returning the
687 resulting code object. The start token is given by \var{start};
Fred Drakec924b8d1999-08-23 18:57:25 +0000688 this can be used to constrain the code which can be compiled and should
689 be \constant{Py_eval_input}, \constant{Py_file_input}, or
690 \constant{Py_single_input}. The filename specified by
691 \var{filename} is used to construct the code object and may appear
692 in tracebacks or \exception{SyntaxError} exception messages. This
693 returns \NULL{} if the code cannot be parsed or compiled.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000694\end{cfuncdesc}
695
Fred Drakec924b8d1999-08-23 18:57:25 +0000696\begin{cvardesc}{int}{Py_eval_input}
697 The start symbol from the Python grammar for isolated expressions;
Fred Drake659ebfa2000-04-03 15:42:13 +0000698 for use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
Fred Drakec924b8d1999-08-23 18:57:25 +0000699\end{cvardesc}
700
701\begin{cvardesc}{int}{Py_file_input}
702 The start symbol from the Python grammar for sequences of statements
703 as read from a file or other source; for use with
Fred Drake659ebfa2000-04-03 15:42:13 +0000704 \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
705 the symbol to use when compiling arbitrarily long Python source code.
Fred Drakec924b8d1999-08-23 18:57:25 +0000706\end{cvardesc}
707
708\begin{cvardesc}{int}{Py_single_input}
709 The start symbol from the Python grammar for a single statement; for
Fred Drake659ebfa2000-04-03 15:42:13 +0000710 use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
711 This is the symbol used for the interactive interpreter loop.
Fred Drakec924b8d1999-08-23 18:57:25 +0000712\end{cvardesc}
713
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000714
Fred Drakeefd146c1999-02-15 15:30:45 +0000715\chapter{Reference Counting \label{countingRefs}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000716
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000717The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000718of Python objects.
719
720\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
Fred Drakec6fa34e1998-04-02 06:47:24 +0000721Increment the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000722not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000723\cfunction{Py_XINCREF()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000724\end{cfuncdesc}
725
726\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000727Increment the reference count for object \var{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000728\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000729\end{cfuncdesc}
730
731\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000732Decrement the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000733not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000734\cfunction{Py_XDECREF()}. If the reference count reaches zero, the
735object's type's deallocation function (which must not be \NULL{}) is
736invoked.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000737
738\strong{Warning:} The deallocation function can cause arbitrary Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000739code to be invoked (e.g. when a class instance with a
740\method{__del__()} method is deallocated). While exceptions in such
741code are not propagated, the executed code has free access to all
742Python global variables. This means that any object that is reachable
743from a global variable should be in a consistent state before
744\cfunction{Py_DECREF()} is invoked. For example, code to delete an
745object from a list should copy a reference to the deleted object in a
746temporary variable, update the list data structure, and then call
747\cfunction{Py_DECREF()} for the temporary variable.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000748\end{cfuncdesc}
749
750\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000751Decrement the reference count for object \var{o}. The object may be
752\NULL{}, in which case the macro has no effect; otherwise the effect
753is the same as for \cfunction{Py_DECREF()}, and the same warning
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000754applies.
755\end{cfuncdesc}
756
Fred Drake659ebfa2000-04-03 15:42:13 +0000757The following functions or macros are only for use within the
758interpreter core: \cfunction{_Py_Dealloc()},
759\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
760well as the global variable \cdata{_Py_RefTotal}.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000761
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000762
Fred Drakeefd146c1999-02-15 15:30:45 +0000763\chapter{Exception Handling \label{exceptionHandling}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000764
Fred Drake659ebfa2000-04-03 15:42:13 +0000765The functions described in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000766exceptions. It is important to understand some of the basics of
Fred Drake659ebfa2000-04-03 15:42:13 +0000767Python exception handling. It works somewhat like the
768\UNIX{} \cdata{errno} variable: there is a global indicator (per
769thread) of the last error that occurred. Most functions don't clear
770this on success, but will set it to indicate the cause of the error on
771failure. Most functions also return an error indicator, usually
772\NULL{} if they are supposed to return a pointer, or \code{-1} if they
773return an integer (exception: the \cfunction{PyArg_Parse*()} functions
774return \code{1} for success and \code{0} for failure). When a
775function must fail because some function it called failed, it
776generally doesn't set the error indicator; the function it called
777already set it.
Guido van Rossumae110af1997-05-22 20:11:52 +0000778
779The error indicator consists of three Python objects corresponding to
Fred Drake659ebfa2000-04-03 15:42:13 +0000780\withsubitem{(in module sys)}{
781 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000782the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
783\code{sys.exc_traceback}. API functions exist to interact with the
784error indicator in various ways. There is a separate error indicator
785for each thread.
786
787% XXX Order of these should be more thoughtful.
788% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000789
790\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000791Print a standard traceback to \code{sys.stderr} and clear the error
792indicator. Call this function only when the error indicator is set.
793(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000794\end{cfuncdesc}
795
Fred Drakec6fa34e1998-04-02 06:47:24 +0000796\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000797Test whether the error indicator is set. If set, return the exception
Fred Drakee058b4f1998-02-16 06:15:35 +0000798\emph{type} (the first argument to the last call to one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000799\cfunction{PyErr_Set*()} functions or to \cfunction{PyErr_Restore()}). If
Fred Drakee058b4f1998-02-16 06:15:35 +0000800not set, return \NULL{}. You do not own a reference to the return
801value, so you do not need to \cfunction{Py_DECREF()} it.
Fred Drake659ebfa2000-04-03 15:42:13 +0000802\strong{Note:} Do not compare the return value to a specific
Fred Drakee058b4f1998-02-16 06:15:35 +0000803exception; use \cfunction{PyErr_ExceptionMatches()} instead, shown
Fred Drake659ebfa2000-04-03 15:42:13 +0000804below. (The comparison could easily fail since the exception may be
805an instance instead of a class, in the case of a class exception, or
806it may the a subclass of the expected exception.)
Guido van Rossum42cefd01997-10-05 15:27:29 +0000807\end{cfuncdesc}
808
809\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000810Equivalent to
Fred Drakee058b4f1998-02-16 06:15:35 +0000811\samp{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
Fred Drake659ebfa2000-04-03 15:42:13 +0000812This should only be called when an exception is actually set; a memory
813access violation will occur if no exception has been raised.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000814\end{cfuncdesc}
815
816\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000817Return true if the \var{given} exception matches the exception in
818\var{exc}. If \var{exc} is a class object, this also returns true
Fred Drake659ebfa2000-04-03 15:42:13 +0000819when \var{given} is an instance of a subclass. If \var{exc} is a tuple, all
Guido van Rossum42cefd01997-10-05 15:27:29 +0000820exceptions in the tuple (and recursively in subtuples) are searched
Fred Drake659ebfa2000-04-03 15:42:13 +0000821for a match. If \var{given} is \NULL, a memory access violation will
822occur.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000823\end{cfuncdesc}
824
825\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000826Under certain circumstances, the values returned by
Fred Drakee058b4f1998-02-16 06:15:35 +0000827\cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning that
828\code{*\var{exc}} is a class object but \code{*\var{val}} is not an
829instance of the same class. This function can be used to instantiate
830the class in that case. If the values are already normalized, nothing
Fred Drake659ebfa2000-04-03 15:42:13 +0000831happens. The delayed normalization is implemented to improve
832performance.
Guido van Rossumae110af1997-05-22 20:11:52 +0000833\end{cfuncdesc}
834
835\begin{cfuncdesc}{void}{PyErr_Clear}{}
836Clear the error indicator. If the error indicator is not set, there
837is no effect.
838\end{cfuncdesc}
839
Fred Drake659ebfa2000-04-03 15:42:13 +0000840\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
841 PyObject **ptraceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000842Retrieve the error indicator into three variables whose addresses are
843passed. If the error indicator is not set, set all three variables to
844\NULL{}. If it is set, it will be cleared and you own a reference to
Fred Drake659ebfa2000-04-03 15:42:13 +0000845each object retrieved. The value and traceback object may be
846\NULL{} even when the type object is not. \strong{Note:} This
847function is normally only used by code that needs to handle exceptions
848or by code that needs to save and restore the error indicator
849temporarily.
Guido van Rossumae110af1997-05-22 20:11:52 +0000850\end{cfuncdesc}
851
Fred Drake17e63432000-08-31 05:50:40 +0000852\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
853 PyObject *traceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000854Set the error indicator from the three objects. If the error
855indicator is already set, it is cleared first. If the objects are
856\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
857and non-\NULL{} value or traceback. The exception type should be a
858string or class; if it is a class, the value should be an instance of
859that class. Do not pass an invalid exception type or value.
860(Violating these rules will cause subtle problems later.) This call
Fred Drake17e63432000-08-31 05:50:40 +0000861takes away a reference to each object, i.e.\ you must own a reference
Guido van Rossumae110af1997-05-22 20:11:52 +0000862to each object before the call and after the call you no longer own
863these references. (If you don't understand this, don't use this
Fred Drake659ebfa2000-04-03 15:42:13 +0000864function. I warned you.) \strong{Note:} This function is normally
Guido van Rossumae110af1997-05-22 20:11:52 +0000865only used by code that needs to save and restore the error indicator
866temporarily.
867\end{cfuncdesc}
868
869\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
870This is the most common way to set the error indicator. The first
871argument specifies the exception type; it is normally one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000872standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
Guido van Rossumae110af1997-05-22 20:11:52 +0000873increment its reference count. The second argument is an error
874message; it is converted to a string object.
875\end{cfuncdesc}
876
877\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +0000878This function is similar to \cfunction{PyErr_SetString()} but lets you
Guido van Rossumae110af1997-05-22 20:11:52 +0000879specify an arbitrary Python object for the ``value'' of the exception.
880You need not increment its reference count.
881\end{cfuncdesc}
882
Fred Drake73577702000-04-10 18:50:14 +0000883\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
Moshe Zadka57a59322000-09-01 09:47:20 +0000884 const char *format, \moreargs}
885This function sets the error indicator.
886\var{exception} should be a Python object.
887\var{fmt} should be a string, containing format codes, similar to
888\cfunction{printf}. The \code{width.precision} before a format code
889is parsed, but the width part is ignored.
890
891\begin{tableii}{c|l}{character}{Character}{Meaning}
892 \lineii{c}{Character, as an \ctype{int} parameter}
893 \lineii{d}{Number in decimal, as an \ctype{int} parameter}
894 \lineii{x}{Number in hexadecimal, as an \ctype{int} parameter}
895 \lineii{x}{A string, as a \ctype{char *} parameter}
896\end{tableii}
897
898An unrecognized format character causes all the rest of
899the format string to be copied as-is to the result string,
900and any extra arguments discarded.
901
902A new reference is returned, which is owned by the caller.
Jeremy Hylton98605b52000-04-10 18:40:57 +0000903\end{cfuncdesc}
904
Guido van Rossumae110af1997-05-22 20:11:52 +0000905\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +0000906This is a shorthand for \samp{PyErr_SetObject(\var{type}, Py_None)}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000907\end{cfuncdesc}
908
909\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000910This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000911\var{message})}, where \var{message} indicates that a built-in operation
912was invoked with an illegal argument. It is mostly for internal use.
913\end{cfuncdesc}
914
Fred Drakec6fa34e1998-04-02 06:47:24 +0000915\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000916This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
Guido van Rossumae110af1997-05-22 20:11:52 +0000917returns \NULL{} so an object allocation function can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000918\samp{return PyErr_NoMemory();} when it runs out of memory.
Guido van Rossumae110af1997-05-22 20:11:52 +0000919\end{cfuncdesc}
920
Fred Drakec6fa34e1998-04-02 06:47:24 +0000921\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
Fred Drake659ebfa2000-04-03 15:42:13 +0000922This is a convenience function to raise an exception when a C library
923function has returned an error and set the C variable \cdata{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000924It constructs a tuple object whose first item is the integer
Fred Drakef8830d11998-04-23 14:06:01 +0000925\cdata{errno} value and whose second item is the corresponding error
Fred Drake659ebfa2000-04-03 15:42:13 +0000926message (gotten from \cfunction{strerror()}\ttindex{strerror()}), and
927then calls
Fred Drakee058b4f1998-02-16 06:15:35 +0000928\samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
Fred Drakef8830d11998-04-23 14:06:01 +0000929the \cdata{errno} value is \constant{EINTR}, indicating an interrupted
Fred Drakee058b4f1998-02-16 06:15:35 +0000930system call, this calls \cfunction{PyErr_CheckSignals()}, and if that set
Guido van Rossumae110af1997-05-22 20:11:52 +0000931the error indicator, leaves it set to that. The function always
932returns \NULL{}, so a wrapper function around a system call can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000933\samp{return PyErr_SetFromErrno();} when the system call returns an
934error.
Guido van Rossumae110af1997-05-22 20:11:52 +0000935\end{cfuncdesc}
936
937\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000938This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000939\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000940operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000941argument. It is mostly for internal use.
942\end{cfuncdesc}
943
944\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
945This function interacts with Python's signal handling. It checks
946whether a signal has been sent to the processes and if so, invokes the
Fred Drake4de05a91998-02-16 14:25:26 +0000947corresponding signal handler. If the
948\module{signal}\refbimodindex{signal} module is supported, this can
949invoke a signal handler written in Python. In all cases, the default
Fred Drake659ebfa2000-04-03 15:42:13 +0000950effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
951\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
952\exception{KeyboardInterrupt} exception. If an exception is raised the
Fred Drakee058b4f1998-02-16 06:15:35 +0000953error indicator is set and the function returns \code{1}; otherwise
954the function returns \code{0}. The error indicator may or may not be
955cleared if it was previously set.
Guido van Rossumae110af1997-05-22 20:11:52 +0000956\end{cfuncdesc}
957
958\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
Fred Drake659ebfa2000-04-03 15:42:13 +0000959This function is obsolete. It simulates the effect of a
960\constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
Fred Drakee058b4f1998-02-16 06:15:35 +0000961\cfunction{PyErr_CheckSignals()} is called,
Fred Drake659ebfa2000-04-03 15:42:13 +0000962\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
963\exception{KeyboardInterrupt} will be raised.
964It may be called without holding the interpreter lock.
Guido van Rossumae110af1997-05-22 20:11:52 +0000965\end{cfuncdesc}
966
Fred Drakec6fa34e1998-04-02 06:47:24 +0000967\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
968 PyObject *base,
969 PyObject *dict}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000970This utility function creates and returns a new exception object. The
Fred Drake659ebfa2000-04-03 15:42:13 +0000971\var{name} argument must be the name of the new exception, a C string
972of the form \code{module.class}. The \var{base} and
Fred Draked04038d2000-06-29 20:15:14 +0000973\var{dict} arguments are normally \NULL{}. This creates a
Fred Drake659ebfa2000-04-03 15:42:13 +0000974class object derived from the root for all exceptions, the built-in
975name \exception{Exception} (accessible in C as
Fred Draked04038d2000-06-29 20:15:14 +0000976\cdata{PyExc_Exception}). The \member{__module__} attribute of the
977new class is set to the first part (up to the last dot) of the
978\var{name} argument, and the class name is set to the last part (after
979the last dot). The \var{base} argument can be used to specify an
980alternate base class. The \var{dict} argument can be used to specify
981a dictionary of class variables and methods.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000982\end{cfuncdesc}
983
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000984\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
985This utility function prints a warning message to \var{sys.stderr}
986when an exception has been set but it is impossible for the
987interpreter to actually raise the exception. It is used, for example,
988when an exception occurs in an \member{__del__} method.
989
990The function is called with a single argument \var{obj} that
991identifies where the context in which the unraisable exception
992occurred. The repr of \var{obj} will be printed in the warning
993message.
994\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000995
Fred Drakeefd146c1999-02-15 15:30:45 +0000996\section{Standard Exceptions \label{standardExceptions}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000997
998All standard Python exceptions are available as global variables whose
Fred Drake659ebfa2000-04-03 15:42:13 +0000999names are \samp{PyExc_} followed by the Python exception name. These
1000have the type \ctype{PyObject*}; they are all class objects. For
1001completeness, here are all the variables:
1002
1003\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
1004 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
1005 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
1006 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
1007 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
1008 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
1009 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
1010 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
1011 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
1012 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
1013 \lineiii{PyExc_IOError}{\exception{IOError}}{}
1014 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
1015 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
1016 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
1017 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
1018 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
1019 \lineiii{PyExc_NameError}{\exception{NameError}}{}
1020 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
1021 \lineiii{PyExc_OSError}{\exception{OSError}}{}
1022 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
1023 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
1024 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
1025 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
1026 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
1027 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
1028 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
Fred Drakea8d73412000-08-11 20:39:29 +00001029 \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(2)}
Fred Drake659ebfa2000-04-03 15:42:13 +00001030 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
1031\end{tableiii}
1032
1033\noindent
Fred Drakea8d73412000-08-11 20:39:29 +00001034Notes:
Fred Drake659ebfa2000-04-03 15:42:13 +00001035\begin{description}
1036\item[(1)]
Fred Draked04038d2000-06-29 20:15:14 +00001037 This is a base class for other standard exceptions.
Fred Drakea8d73412000-08-11 20:39:29 +00001038
1039\item[(2)]
1040 Only defined on Windows; protect code that uses this by testing that
1041 the preprocessor macro \code{MS_WINDOWS} is defined.
Fred Drake659ebfa2000-04-03 15:42:13 +00001042\end{description}
1043
1044
1045\section{Deprecation of String Exceptions}
1046
Fred Draked04038d2000-06-29 20:15:14 +00001047All exceptions built into Python or provided in the standard library
1048are derived from \exception{Exception}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001049\withsubitem{(built-in exception)}{\ttindex{Exception}}
Fred Drake659ebfa2000-04-03 15:42:13 +00001050
Fred Draked04038d2000-06-29 20:15:14 +00001051String exceptions are still supported in the interpreter to allow
Fred Drake659ebfa2000-04-03 15:42:13 +00001052existing code to run unmodified, but this will also change in a future
1053release.
Guido van Rossumae110af1997-05-22 20:11:52 +00001054
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001055
Fred Drakeefd146c1999-02-15 15:30:45 +00001056\chapter{Utilities \label{utilities}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001057
1058The functions in this chapter perform various utility tasks, such as
Fred Drake659ebfa2000-04-03 15:42:13 +00001059parsing function arguments and constructing Python values from C
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001060values.
1061
Fred Drakeefd146c1999-02-15 15:30:45 +00001062\section{OS Utilities \label{os}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001063
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001064\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001065Return true (nonzero) if the standard I/O file \var{fp} with name
1066\var{filename} is deemed interactive. This is the case for files for
1067which \samp{isatty(fileno(\var{fp}))} is true. If the global flag
Fred Drakef8830d11998-04-23 14:06:01 +00001068\cdata{Py_InteractiveFlag} is true, this function also returns true if
Fred Drakee058b4f1998-02-16 06:15:35 +00001069the \var{name} pointer is \NULL{} or if the name is equal to one of
Fred Drakea8455ab2000-06-16 19:58:42 +00001070the strings \code{'<stdin>'} or \code{'???'}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001071\end{cfuncdesc}
1072
1073\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001074Return the time of last modification of the file \var{filename}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001075The result is encoded in the same way as the timestamp returned by
Fred Drake659ebfa2000-04-03 15:42:13 +00001076the standard C library function \cfunction{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001077\end{cfuncdesc}
1078
Fred Drakecabbc3b2000-06-28 15:53:13 +00001079\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
1080Function to update some internal state after a process fork; this
1081should be called in the new process if the Python interpreter will
1082continue to be used. If a new executable is loaded into the new
1083process, this function does not need to be called.
1084\end{cfuncdesc}
1085
Fred Drake17e63432000-08-31 05:50:40 +00001086\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
1087Return true when the interpreter runs out of stack space. This is a
1088reliable check, but is only available when \code{USE_STACKCHECK} is
1089defined (currently on Windows using the Microsoft Visual C++ compiler
1090and on the Macintosh). \code{USE_CHECKSTACK} will be defined
1091automatically; you should never change the definition in your own
1092code.
1093\end{cfuncdesc}
1094
Guido van Rossumc96ec6e2000-09-16 16:30:48 +00001095\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i}
1096Return the current signal handler for signal \var{i}.
1097This is a thin wrapper around either \cfunction{sigaction} or
1098\cfunction{signal}. Do not call those functions directly!
1099\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1100\end{cfuncdesc}
1101
1102\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h}
1103Set the signal handler for signal \var{i} to be \var{h};
1104return the old signal handler.
1105This is a thin wrapper around either \cfunction{sigaction} or
1106\cfunction{signal}. Do not call those functions directly!
1107\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1108\end{cfuncdesc}
1109
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001110
Fred Drakeefd146c1999-02-15 15:30:45 +00001111\section{Process Control \label{processControl}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001112
1113\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
1114Print a fatal error message and kill the process. No cleanup is
1115performed. This function should only be invoked when a condition is
1116detected that would make it dangerous to continue using the Python
1117interpreter; e.g., when the object administration appears to be
Fred Drake659ebfa2000-04-03 15:42:13 +00001118corrupted. On \UNIX{}, the standard C library function
1119\cfunction{abort()}\ttindex{abort()} is called which will attempt to
1120produce a \file{core} file.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001121\end{cfuncdesc}
1122
1123\begin{cfuncdesc}{void}{Py_Exit}{int status}
Fred Drake659ebfa2000-04-03 15:42:13 +00001124Exit the current process. This calls
1125\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
1126then calls the standard C library function
1127\code{exit(\var{status})}\ttindex{exit()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001128\end{cfuncdesc}
1129
1130\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drake659ebfa2000-04-03 15:42:13 +00001131Register a cleanup function to be called by
1132\cfunction{Py_Finalize()}\ttindex{Py_Finalize()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001133The cleanup function will be called with no arguments and should
Fred Drake659ebfa2000-04-03 15:42:13 +00001134return no value. At most 32 \index{cleanup functions}cleanup
1135functions can be registered.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001136When the registration is successful, \cfunction{Py_AtExit()} returns
1137\code{0}; on failure, it returns \code{-1}. The cleanup function
1138registered last is called first. Each cleanup function will be called
1139at most once. Since Python's internal finallization will have
1140completed before the cleanup function, no Python APIs should be called
1141by \var{func}.
1142\end{cfuncdesc}
1143
1144
Fred Drakeefd146c1999-02-15 15:30:45 +00001145\section{Importing Modules \label{importing}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001146
Fred Drakec6fa34e1998-04-02 06:47:24 +00001147\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00001148This is a simplified interface to
1149\cfunction{PyImport_ImportModuleEx()} below, leaving the
1150\var{globals} and \var{locals} arguments set to \NULL{}. When the
1151\var{name} argument contains a dot (i.e., when it specifies a
1152submodule of a package), the \var{fromlist} argument is set to the
1153list \code{['*']} so that the return value is the named module rather
1154than the top-level package containing it as would otherwise be the
1155case. (Unfortunately, this has an additional side effect when
1156\var{name} in fact specifies a subpackage instead of a submodule: the
1157submodules specified in the package's \code{__all__} variable are
1158\index{package variable!\code{__all__}}
1159\withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a
1160new reference to the imported module, or
1161\NULL{} with an exception set on failure (the module may still be
1162created in this case --- examine \code{sys.modules} to find out).
1163\withsubitem{(in module sys)}{\ttindex{modules}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001164\end{cfuncdesc}
1165
Fred Drakec6fa34e1998-04-02 06:47:24 +00001166\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001167Import a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001168Python function \function{__import__()}\bifuncindex{__import__}, as
1169the standard \function{__import__()} function calls this function
1170directly.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001171
Guido van Rossum42cefd01997-10-05 15:27:29 +00001172The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001173top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001174(the module may still be created in this case). Like for
Fred Drakee058b4f1998-02-16 06:15:35 +00001175\function{__import__()}, the return value when a submodule of a
1176package was requested is normally the top-level package, unless a
1177non-empty \var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001178\end{cfuncdesc}
1179
Fred Drakec6fa34e1998-04-02 06:47:24 +00001180\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001181This is a higher-level interface that calls the current ``import hook
Fred Drakee058b4f1998-02-16 06:15:35 +00001182function''. It invokes the \function{__import__()} function from the
Guido van Rossum42cefd01997-10-05 15:27:29 +00001183\code{__builtins__} of the current globals. This means that the
1184import is done using whatever import hooks are installed in the
Fred Drake4de05a91998-02-16 14:25:26 +00001185current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
1186\module{ihooks}\refstmodindex{ihooks}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001187\end{cfuncdesc}
1188
Fred Drakec6fa34e1998-04-02 06:47:24 +00001189\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001190Reload a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001191Python function \function{reload()}\bifuncindex{reload}, as the standard
Fred Drakee058b4f1998-02-16 06:15:35 +00001192\function{reload()} function calls this function directly. Return a
1193new reference to the reloaded module, or \NULL{} with an exception set
1194on failure (the module still exists in this case).
Guido van Rossum42cefd01997-10-05 15:27:29 +00001195\end{cfuncdesc}
1196
Fred Drakec6fa34e1998-04-02 06:47:24 +00001197\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001198Return the module object corresponding to a module name. The
1199\var{name} argument may be of the form \code{package.module}). First
1200check the modules dictionary if there's one there, and if not, create
Fred Drake659ebfa2000-04-03 15:42:13 +00001201a new one and insert in in the modules dictionary.
Guido van Rossuma096a2e1998-11-02 17:02:42 +00001202Warning: this function does not load or import the module; if the
1203module wasn't already loaded, you will get an empty module object.
1204Use \cfunction{PyImport_ImportModule()} or one of its variants to
1205import a module.
Fred Drake659ebfa2000-04-03 15:42:13 +00001206Return \NULL{} with an exception set on failure.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001207\end{cfuncdesc}
1208
Fred Drakec6fa34e1998-04-02 06:47:24 +00001209\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001210Given a module name (possibly of the form \code{package.module}) and a
1211code object read from a Python bytecode file or obtained from the
Fred Drake53fb7721998-02-16 06:23:20 +00001212built-in function \function{compile()}\bifuncindex{compile}, load the
1213module. Return a new reference to the module object, or \NULL{} with
1214an exception set if an error occurred (the module may still be created
1215in this case). (This function would reload the module if it was
1216already imported.)
Guido van Rossum42cefd01997-10-05 15:27:29 +00001217\end{cfuncdesc}
1218
1219\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001220Return the magic number for Python bytecode files (a.k.a.
1221\file{.pyc} and \file{.pyo} files). The magic number should be
1222present in the first four bytes of the bytecode file, in little-endian
1223byte order.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001224\end{cfuncdesc}
1225
Fred Drakec6fa34e1998-04-02 06:47:24 +00001226\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001227Return the dictionary used for the module administration
1228(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1229variable.
1230\end{cfuncdesc}
1231
1232\begin{cfuncdesc}{void}{_PyImport_Init}{}
1233Initialize the import mechanism. For internal use only.
1234\end{cfuncdesc}
1235
1236\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1237Empty the module table. For internal use only.
1238\end{cfuncdesc}
1239
1240\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1241Finalize the import mechanism. For internal use only.
1242\end{cfuncdesc}
1243
Fred Drakec6fa34e1998-04-02 06:47:24 +00001244\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001245For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001246\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001247
Fred Drakec6fa34e1998-04-02 06:47:24 +00001248\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001249For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001250\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001251
Fred Drake1d158692000-06-18 05:21:21 +00001252\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
1253Load a frozen module named \var{name}. Return \code{1} for success,
1254\code{0} if the module is not found, and \code{-1} with an exception
1255set if the initialization failed. To access the imported module on a
1256successful load, use \cfunction{PyImport_ImportModule()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00001257(Note the misnomer --- this function would reload the module if it was
Guido van Rossum42cefd01997-10-05 15:27:29 +00001258already imported.)
1259\end{cfuncdesc}
1260
Fred Drake659ebfa2000-04-03 15:42:13 +00001261\begin{ctypedesc}[_frozen]{struct _frozen}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001262This is the structure type definition for frozen module descriptors,
Fred Drakec6fa34e1998-04-02 06:47:24 +00001263as generated by the \program{freeze}\index{freeze utility} utility
1264(see \file{Tools/freeze/} in the Python source distribution). Its
Fred Drakee0d9a832000-09-01 05:30:00 +00001265definition, found in \file{Include/import.h}, is:
Fred Drakec6fa34e1998-04-02 06:47:24 +00001266
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001267\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001268struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001269 char *name;
1270 unsigned char *code;
1271 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001272};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001273\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001274\end{ctypedesc}
1275
Fred Drakec6fa34e1998-04-02 06:47:24 +00001276\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
Fred Drakef8830d11998-04-23 14:06:01 +00001277This pointer is initialized to point to an array of \ctype{struct
Fred Drake659ebfa2000-04-03 15:42:13 +00001278_frozen} records, terminated by one whose members are all
1279\NULL{} or zero. When a frozen module is imported, it is searched in
1280this table. Third-party code could play tricks with this to provide a
Guido van Rossum42cefd01997-10-05 15:27:29 +00001281dynamically created collection of frozen modules.
1282\end{cvardesc}
1283
Fred Drakee0d9a832000-09-01 05:30:00 +00001284\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
1285 void (*initfunc)(void)}
1286Add a single module to the existing table of built-in modules. This
1287is a convenience wrapper around \cfunction{PyImport_ExtendInittab()},
1288returning \code{-1} if the table could not be extended. The new
1289module can be imported by the name \var{name}, and uses the function
1290\var{initfunc} as the initialization function called on the first
1291attempted import. This should be called before
1292\cfunction{Py_Initialize()}.
1293\end{cfuncdesc}
1294
1295\begin{ctypedesc}[_inittab]{struct _inittab}
1296Structure describing a single entry in the list of built-in modules.
1297Each of these structures gives the name and initialization function
1298for a module built into the interpreter. Programs which embed Python
1299may use an array of these structures in conjunction with
1300\cfunction{PyImport_ExtendInittab()} to provide additional built-in
1301modules. The structure is defined in \file{Include/import.h} as:
1302
1303\begin{verbatim}
1304struct _inittab {
1305 char *name;
1306 void (*initfunc)(void);
1307};
1308\end{verbatim}
1309\end{ctypedesc}
1310
1311\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
1312Add a collection of modules to the table of built-in modules. The
1313\var{newtab} array must end with a sentinel entry which contains
1314\NULL{} for the \member{name} field; failure to provide the sentinel
1315value can result in a memory fault. Returns \code{0} on success or
1316\code{-1} if insufficient memory could be allocated to extend the
1317internal table. In the event of failure, no modules are added to the
1318internal table. This should be called before
1319\cfunction{Py_Initialize()}.
1320\end{cfuncdesc}
1321
Guido van Rossum42cefd01997-10-05 15:27:29 +00001322
Fred Drakeefd146c1999-02-15 15:30:45 +00001323\chapter{Abstract Objects Layer \label{abstract}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001324
1325The functions in this chapter interact with Python objects regardless
1326of their type, or with wide classes of object types (e.g. all
1327numerical types, or all sequence types). When used on object types
Fred Drake659ebfa2000-04-03 15:42:13 +00001328for which they do not apply, they will raise a Python exception.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001329
Fred Drakeefd146c1999-02-15 15:30:45 +00001330\section{Object Protocol \label{object}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001331
1332\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00001333Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error.
1334The flags argument is used to enable certain printing options. The
1335only option currently supported is \constant{Py_PRINT_RAW}; if given,
1336the \function{str()} of the object is written instead of the
1337\function{repr()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001338\end{cfuncdesc}
1339
1340\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001341Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1342\code{0} otherwise. This is equivalent to the Python expression
1343\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001344This function always succeeds.
1345\end{cfuncdesc}
1346
Fred Drake659ebfa2000-04-03 15:42:13 +00001347\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
1348 char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001349Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001350Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001351This is the equivalent of the Python expression
1352\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001353\end{cfuncdesc}
1354
1355
1356\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001357Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1358\code{0} otherwise. This is equivalent to the Python expression
1359\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001360This function always succeeds.
1361\end{cfuncdesc}
1362
1363
Fred Drake659ebfa2000-04-03 15:42:13 +00001364\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
1365 PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001366Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001367Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001368This is the equivalent of the Python expression
1369\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001370\end{cfuncdesc}
1371
1372
1373\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001374Set the value of the attribute named \var{attr_name}, for object
1375\var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1376the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1377\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001378\end{cfuncdesc}
1379
1380
1381\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001382Set the value of the attribute named \var{attr_name}, for
1383object \var{o},
1384to the value \var{v}. Returns \code{-1} on failure. This is
1385the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1386\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001387\end{cfuncdesc}
1388
1389
1390\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001391Delete attribute named \var{attr_name}, for object \var{o}. Returns
1392\code{-1} on failure. This is the equivalent of the Python
1393statement: \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001394\end{cfuncdesc}
1395
1396
1397\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001398Delete attribute named \var{attr_name}, for object \var{o}. Returns
1399\code{-1} on failure. This is the equivalent of the Python
1400statement \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001401\end{cfuncdesc}
1402
1403
1404\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
Fred Drakee058b4f1998-02-16 06:15:35 +00001405Compare the values of \var{o1} and \var{o2} using a routine provided
1406by \var{o1}, if one exists, otherwise with a routine provided by
1407\var{o2}. The result of the comparison is returned in \var{result}.
1408Returns \code{-1} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001409statement\bifuncindex{cmp} \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001410\end{cfuncdesc}
1411
1412
1413\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001414Compare the values of \var{o1} and \var{o2} using a routine provided
1415by \var{o1}, if one exists, otherwise with a routine provided by
1416\var{o2}. Returns the result of the comparison on success. On error,
1417the value returned is undefined; use \cfunction{PyErr_Occurred()} to
Fred Drake659ebfa2000-04-03 15:42:13 +00001418detect an error. This is equivalent to the Python
1419expression\bifuncindex{cmp} \samp{cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001420\end{cfuncdesc}
1421
1422
1423\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001424Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001425string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001426the equivalent of the Python expression \samp{repr(\var{o})}.
1427Called by the \function{repr()}\bifuncindex{repr} built-in function
1428and by reverse quotes.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001429\end{cfuncdesc}
1430
1431
1432\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001433Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001434string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001435the equivalent of the Python expression \samp{str(\var{o})}.
1436Called by the \function{str()}\bifuncindex{str} built-in function and
1437by the \keyword{print} statement.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001438\end{cfuncdesc}
1439
1440
1441\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001442Determine if the object \var{o} is callable. Return \code{1} if the
Fred Drakee058b4f1998-02-16 06:15:35 +00001443object is callable and \code{0} otherwise.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001444This function always succeeds.
1445\end{cfuncdesc}
1446
1447
Fred Drake659ebfa2000-04-03 15:42:13 +00001448\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
1449 PyObject *args}
Fred Drakee058b4f1998-02-16 06:15:35 +00001450Call a callable Python object \var{callable_object}, with
1451arguments given by the tuple \var{args}. If no arguments are
Fred Drake659ebfa2000-04-03 15:42:13 +00001452needed, then \var{args} may be \NULL{}. Returns the result of the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001453call on success, or \NULL{} on failure. This is the equivalent
Fred Drakee058b4f1998-02-16 06:15:35 +00001454of the Python expression \samp{apply(\var{o}, \var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001455\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001456\end{cfuncdesc}
1457
1458\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001459Call a callable Python object \var{callable_object}, with a
Fred Drake659ebfa2000-04-03 15:42:13 +00001460variable number of C arguments. The C arguments are described
Fred Drakee058b4f1998-02-16 06:15:35 +00001461using a \cfunction{Py_BuildValue()} style format string. The format may
1462be \NULL{}, indicating that no arguments are provided. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001463result of the call on success, or \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001464the equivalent of the Python expression \samp{apply(\var{o},
Fred Drake659ebfa2000-04-03 15:42:13 +00001465\var{args})}.\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001466\end{cfuncdesc}
1467
1468
1469\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001470Call the method named \var{m} of object \var{o} with a variable number
Fred Drake659ebfa2000-04-03 15:42:13 +00001471of C arguments. The C arguments are described by a
Fred Drakee058b4f1998-02-16 06:15:35 +00001472\cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1473indicating that no arguments are provided. Returns the result of the
1474call on success, or \NULL{} on failure. This is the equivalent of the
1475Python expression \samp{\var{o}.\var{method}(\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001476Note that special method names, such as \method{__add__()},
1477\method{__getitem__()}, and so on are not supported. The specific
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001478abstract-object routines for these must be used.
1479\end{cfuncdesc}
1480
1481
1482\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001483Compute and return the hash value of an object \var{o}. On
1484failure, return \code{-1}. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001485expression \samp{hash(\var{o})}.\bifuncindex{hash}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001486\end{cfuncdesc}
1487
1488
1489\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001490Returns \code{1} if the object \var{o} is considered to be true, and
1491\code{0} otherwise. This is equivalent to the Python expression
1492\samp{not not \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001493This function always succeeds.
1494\end{cfuncdesc}
1495
1496
1497\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1498On success, returns a type object corresponding to the object
Fred Drakee058b4f1998-02-16 06:15:35 +00001499type of object \var{o}. On failure, returns \NULL{}. This is
1500equivalent to the Python expression \samp{type(\var{o})}.
Fred Drake53fb7721998-02-16 06:23:20 +00001501\bifuncindex{type}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001502\end{cfuncdesc}
1503
1504\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001505Return the length of object \var{o}. If the object \var{o} provides
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001506both sequence and mapping protocols, the sequence length is
Fred Drake659ebfa2000-04-03 15:42:13 +00001507returned. On error, \code{-1} is returned. This is the equivalent
1508to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001509\end{cfuncdesc}
1510
1511
1512\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001513Return element of \var{o} corresponding to the object \var{key} or
1514\NULL{} on failure. This is the equivalent of the Python expression
1515\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001516\end{cfuncdesc}
1517
1518
1519\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001520Map the object \var{key} to the value \var{v}.
1521Returns \code{-1} on failure. This is the equivalent
1522of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001523\end{cfuncdesc}
1524
1525
Guido van Rossumd1dbf631999-01-22 20:10:49 +00001526\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001527Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1528failure. This is the equivalent of the Python statement \samp{del
1529\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001530\end{cfuncdesc}
1531
Andrew M. Kuchling8c46b302000-07-13 23:58:16 +00001532\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
1533Derives a file-descriptor from a Python object. If the object
1534is an integer or long integer, its value is returned. If not, the
1535object's \method{fileno()} method is called if it exists; the method
1536must return an integer or long integer, which is returned as the file
1537descriptor value. Returns \code{-1} on failure.
1538\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001539
Fred Drakeefd146c1999-02-15 15:30:45 +00001540\section{Number Protocol \label{number}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001541
1542\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001543Returns \code{1} if the object \var{o} provides numeric protocols, and
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001544false otherwise.
1545This function always succeeds.
1546\end{cfuncdesc}
1547
1548
1549\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001550Returns the result of adding \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_Subtract}{PyObject *o1, PyObject *o2}
Fred Drake659ebfa2000-04-03 15:42:13 +00001557Returns the result of subtracting \var{o2} from \var{o1}, or
1558\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001559\samp{\var{o1} - \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001560\end{cfuncdesc}
1561
1562
1563\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001564Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1565failure. This is the equivalent of the Python expression
1566\samp{\var{o1} * \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001567\end{cfuncdesc}
1568
1569
1570\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001571Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1572failure.
1573This is the equivalent of the Python expression \samp{\var{o1} /
1574\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001575\end{cfuncdesc}
1576
1577
1578\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001579Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1580failure. This is the equivalent of the Python expression
Fred Drake659ebfa2000-04-03 15:42:13 +00001581\samp{\var{o1} \%\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001582\end{cfuncdesc}
1583
1584
1585\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
Fred Drake53fb7721998-02-16 06:23:20 +00001586See the built-in function \function{divmod()}\bifuncindex{divmod}.
1587Returns \NULL{} on failure. This is the equivalent of the Python
1588expression \samp{divmod(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001589\end{cfuncdesc}
1590
1591
1592\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
Fred Drake53fb7721998-02-16 06:23:20 +00001593See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1594\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001595\samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
Fred Drake659ebfa2000-04-03 15:42:13 +00001596If \var{o3} is to be ignored, pass \cdata{Py_None} in its place
1597(passing \NULL{} for \var{o3} would cause an illegal memory access).
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001598\end{cfuncdesc}
1599
1600
1601\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001602Returns the negation of \var{o} on success, or \NULL{} on failure.
1603This is the equivalent of the Python expression \samp{-\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001604\end{cfuncdesc}
1605
1606
1607\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001608Returns \var{o} on success, or \NULL{} on failure.
1609This is the equivalent of the Python expression \samp{+\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001610\end{cfuncdesc}
1611
1612
1613\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001614Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1615the equivalent of the Python expression \samp{abs(\var{o})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001616\bifuncindex{abs}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001617\end{cfuncdesc}
1618
1619
1620\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001621Returns the bitwise negation of \var{o} on success, or \NULL{} on
1622failure. This is the equivalent of the Python expression
1623\samp{\~\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001624\end{cfuncdesc}
1625
1626
1627\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001628Returns the result of left shifting \var{o1} by \var{o2} on success,
1629or \NULL{} on failure. This is the equivalent of the Python
1630expression \samp{\var{o1} << \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001631\end{cfuncdesc}
1632
1633
1634\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001635Returns the result of right shifting \var{o1} by \var{o2} on success,
1636or \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
1641\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001642Returns the ``bitwise and'' of \var{o2} and \var{o2} on success and
1643\NULL{} on failure. This is the equivalent of the Python expression
1644\samp{\var{o1} \& \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001645\end{cfuncdesc}
1646
1647
1648\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001649Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success,
Fred Drakee058b4f1998-02-16 06:15:35 +00001650or \NULL{} on failure. This is the equivalent of the Python
1651expression \samp{\var{o1} \^{ }\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001652\end{cfuncdesc}
1653
1654\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001655Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
1656\NULL{} on failure. This is the equivalent of the Python expression
1657\samp{\var{o1} | \var{o2}}.
1658\end{cfuncdesc}
1659
1660
1661\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAdd}{PyObject *o1, PyObject *o2}
1662Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on failure.
1663The operation is done \emph{in-place} when \var{o1} supports it. This is the
1664equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1665\end{cfuncdesc}
1666
1667
1668\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceSubtract}{PyObject *o1, PyObject *o2}
1669Returns the result of subtracting \var{o2} from \var{o1}, or
1670\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1671supports it. This is the equivalent of the Python expression \samp{\var{o1}
1672-= \var{o2}}.
1673\end{cfuncdesc}
1674
1675
1676\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceMultiply}{PyObject *o1, PyObject *o2}
1677Returns the result of multiplying \var{o1} and \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_InPlaceDivide}{PyObject *o1, PyObject *o2}
1684Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on failure.
1685The operation is done \emph{in-place} when \var{o1} supports it. This is the
1686equivalent of the Python expression \samp{\var{o1} /= \var{o2}}.
1687\end{cfuncdesc}
1688
1689
1690\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRemainder}{PyObject *o1, PyObject *o2}
1691Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1692failure. The operation is done \emph{in-place} when \var{o1} supports it.
1693This is the equivalent of the Python expression \samp{\var{o1} \%= \var{o2}}.
1694\end{cfuncdesc}
1695
1696
1697\begin{cfuncdesc}{PyObject*}{PyNumber_InPlacePower}{PyObject *o1, PyObject *o2, PyObject *o3}
1698See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1699\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1700supports it. This is the equivalent of the Python expression \samp{\var{o1}
1701**= \var{o2}} when o3 is \cdata{Py_None}, or an in-place variant of
1702\samp{pow(\var{o1}, \var{o2}, var{o3})} otherwise. If \var{o3} is to be
1703ignored, pass \cdata{Py_None} in its place (passing \NULL{} for \var{o3}
1704would cause an illegal memory access).
1705\end{cfuncdesc}
1706
1707\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceLshift}{PyObject *o1, PyObject *o2}
1708Returns the result of left shifting \var{o1} by \var{o2} on success, or
1709\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1710supports it. This is the equivalent of the Python expression \samp{\var{o1}
1711<<= \var{o2}}.
1712\end{cfuncdesc}
1713
1714
1715\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRshift}{PyObject *o1, PyObject *o2}
1716Returns the result of right shifting \var{o1} by \var{o2} on success, or
1717\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1718supports it. This is the equivalent of the Python expression \samp{\var{o1}
1719>>= \var{o2}}.
1720\end{cfuncdesc}
1721
1722
1723\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAnd}{PyObject *o1, PyObject *o2}
1724Returns the ``bitwise and'' of \var{o2} and \var{o2} on success
1725and \NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1726supports it. This is the equivalent of the Python expression \samp{\var{o1}
1727\&= \var{o2}}.
1728\end{cfuncdesc}
1729
1730
1731\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceXor}{PyObject *o1, PyObject *o2}
1732Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success, or
1733\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1734supports it. This is the equivalent of the Python expression \samp{\var{o1}
1735\^= \var{o2}}.
1736\end{cfuncdesc}
1737
1738\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2}
1739Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or \NULL{}
1740on failure. The operation is done \emph{in-place} when \var{o1} supports
1741it. This is the equivalent of the Python expression \samp{\var{o1} |=
1742\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001743\end{cfuncdesc}
1744
Fred Drakee058b4f1998-02-16 06:15:35 +00001745\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001746This function takes the addresses of two variables of type
Fred Drake659ebfa2000-04-03 15:42:13 +00001747\ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} and
1748\code{*\var{p2}} have the same type, increment their reference count
1749and return \code{0} (success). If the objects can be converted to a
1750common numeric type, replace \code{*p1} and \code{*p2} by their
1751converted value (with 'new' reference counts), and return \code{0}.
1752If no conversion is possible, or if some other error occurs, return
1753\code{-1} (failure) and don't increment the reference counts. The
1754call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1755statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
1756\bifuncindex{coerce}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001757\end{cfuncdesc}
1758
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001759\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001760Returns the \var{o} converted to an integer object on success, or
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001761\NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001762expression \samp{int(\var{o})}.\bifuncindex{int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001763\end{cfuncdesc}
1764
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001765\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001766Returns the \var{o} converted to a long integer object on success,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001767or \NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001768expression \samp{long(\var{o})}.\bifuncindex{long}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001769\end{cfuncdesc}
1770
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001771\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001772Returns the \var{o} converted to a float object on success, or
1773\NULL{} on failure. This is the equivalent of the Python expression
1774\samp{float(\var{o})}.\bifuncindex{float}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001775\end{cfuncdesc}
1776
1777
Fred Drakeefd146c1999-02-15 15:30:45 +00001778\section{Sequence Protocol \label{sequence}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001779
1780\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001781Return \code{1} if the object provides sequence protocol, and
1782\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001783\end{cfuncdesc}
1784
Fred Drake659ebfa2000-04-03 15:42:13 +00001785\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
1786Returns the number of objects in sequence \var{o} on success, and
1787\code{-1} on failure. For objects that do not provide sequence
1788protocol, this is equivalent to the Python expression
1789\samp{len(\var{o})}.\bifuncindex{len}
1790\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001791
1792\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001793Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001794failure. This is the equivalent of the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001795expression \samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001796\end{cfuncdesc}
1797
1798
1799\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Fred Drake659ebfa2000-04-03 15:42:13 +00001800Return the result of repeating sequence object
1801\var{o} \var{count} times, or \NULL{} on failure. This is the
1802equivalent of the Python expression \samp{\var{o} * \var{count}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001803\end{cfuncdesc}
1804
Fred Drake7740a012000-09-12 20:27:05 +00001805\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceConcat}{PyObject *o1, PyObject *o2}
1806Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
1807failure. The operation is done \emph{in-place} when \var{o1} supports it.
1808This is the equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1809\end{cfuncdesc}
1810
1811
1812\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceRepeat}{PyObject *o, int count}
1813Return the result of repeating sequence object \var{o} \var{count} times, or
1814\NULL{} on failure. The operation is done \emph{in-place} when \var{o}
1815supports it. This is the equivalent of the Python expression \samp{\var{o}
1816*= \var{count}}.
1817\end{cfuncdesc}
1818
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001819
1820\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001821Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
1822is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001823\end{cfuncdesc}
1824
1825
1826\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001827Return the slice of sequence object \var{o} between \var{i1} and
1828\var{i2}, or \NULL{} on failure. This is the equivalent of the Python
1829expression \samp{\var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001830\end{cfuncdesc}
1831
1832
1833\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001834Assign object \var{v} to the \var{i}th element of \var{o}.
1835Returns \code{-1} on failure. This is the equivalent of the Python
1836statement \samp{\var{o}[\var{i}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001837\end{cfuncdesc}
1838
1839\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001840Delete the \var{i}th element of object \var{v}. Returns
1841\code{-1} on failure. This is the equivalent of the Python
1842statement \samp{del \var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001843\end{cfuncdesc}
1844
Fred Drake659ebfa2000-04-03 15:42:13 +00001845\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
1846 int i2, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001847Assign the sequence object \var{v} to the slice in sequence
1848object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
1849the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001850\end{cfuncdesc}
1851
1852\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001853Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
1854Returns \code{-1} on failure. This is the equivalent of the Python
1855statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001856\end{cfuncdesc}
1857
1858\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001859Returns the \var{o} as a tuple on success, and \NULL{} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00001860This is equivalent to the Python expression \samp{tuple(\var{o})}.
1861\bifuncindex{tuple}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001862\end{cfuncdesc}
1863
1864\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001865Return the number of occurrences of \var{value} in \var{o}, that is,
1866return the number of keys for which \code{\var{o}[\var{key}] ==
1867\var{value}}. On failure, return \code{-1}. This is equivalent to
1868the Python expression \samp{\var{o}.count(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001869\end{cfuncdesc}
1870
Fred Drake659ebfa2000-04-03 15:42:13 +00001871\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001872Determine if \var{o} contains \var{value}. If an item in \var{o} is
1873equal to \var{value}, return \code{1}, otherwise return \code{0}. On
1874error, return \code{-1}. This is equivalent to the Python expression
1875\samp{\var{value} in \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001876\end{cfuncdesc}
1877
1878\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001879Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
1880\var{value}}. On error, return \code{-1}. This is equivalent to
1881the Python expression \samp{\var{o}.index(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001882\end{cfuncdesc}
1883
Fred Drakea8455ab2000-06-16 19:58:42 +00001884\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
1885Return a list object with the same contents as the arbitrary sequence
1886\var{o}. The returned list is guaranteed to be new.
1887\end{cfuncdesc}
1888
1889\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1890Return a tuple object with the same contents as the arbitrary sequence
1891\var{o}. If \var{o} is a tuple, a new reference will be returned,
1892otherwise a tuple will be constructed with the appropriate contents.
1893\end{cfuncdesc}
1894
Fred Drakef39ed671998-02-26 22:01:23 +00001895
Fred Drake81cccb72000-09-12 15:22:05 +00001896\begin{cfuncdesc}{PyObject*}{PySequence_Fast}{PyObject *o, const char *m}
1897Returns the sequence \var{o} as a tuple, unless it is already a
1898tuple or list, in which case \var{o} is returned. Use
1899\cfunction{PySequence_Fast_GET_ITEM()} to access the members of the
1900result. Returns \NULL{} on failure. If the object is not a sequence,
1901raises \exception{TypeError} with \var{m} as the message text.
1902\end{cfuncdesc}
1903
1904\begin{cfuncdesc}{PyObject*}{PySequence_Fast_GET_ITEM}{PyObject *o, int i}
1905Return the \var{i}th element of \var{o}, assuming that \var{o} was
1906returned by \cfunction{PySequence_Fast()}, and that \var{i} is within
1907bounds. The caller is expected to get the length of the sequence by
1908calling \cfunction{PyObject_Size()} on \var{o}, since lists and tuples
1909are guaranteed to always return their true length.
1910\end{cfuncdesc}
1911
1912
Fred Drakeefd146c1999-02-15 15:30:45 +00001913\section{Mapping Protocol \label{mapping}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001914
1915\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001916Return \code{1} if the object provides mapping protocol, and
1917\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001918\end{cfuncdesc}
1919
1920
1921\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001922Returns the number of keys in object \var{o} on success, and
1923\code{-1} on failure. For objects that do not provide mapping
1924protocol, this is equivalent to the Python expression
1925\samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001926\end{cfuncdesc}
1927
1928
1929\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001930Remove the mapping for object \var{key} from the object \var{o}.
1931Return \code{-1} on failure. This is equivalent to
1932the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001933\end{cfuncdesc}
1934
1935
1936\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001937Remove the mapping for object \var{key} from the object \var{o}.
1938Return \code{-1} on failure. This is equivalent to
1939the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001940\end{cfuncdesc}
1941
1942
1943\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
Fred Drake659ebfa2000-04-03 15:42:13 +00001944On success, return \code{1} if the mapping object has the key
1945\var{key} and \code{0} otherwise. This is equivalent to the Python
1946expression \samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001947This function always succeeds.
1948\end{cfuncdesc}
1949
1950
1951\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001952Return \code{1} if the mapping object has the key \var{key} and
1953\code{0} otherwise. This is equivalent to the Python expression
1954\samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001955This function always succeeds.
1956\end{cfuncdesc}
1957
1958
1959\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001960On success, return a list of the keys in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001961failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001962expression \samp{\var{o}.keys()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001963\end{cfuncdesc}
1964
1965
1966\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001967On success, return a list of the values in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001968failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001969expression \samp{\var{o}.values()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001970\end{cfuncdesc}
1971
1972
1973\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001974On success, return a list of the items in object \var{o}, where
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001975each item is a tuple containing a key-value pair. On
1976failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001977expression \samp{\var{o}.items()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001978\end{cfuncdesc}
1979
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001980
1981\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001982Return element of \var{o} corresponding to the object \var{key} or
1983\NULL{} on failure. This is the equivalent of the Python expression
1984\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001985\end{cfuncdesc}
1986
Guido van Rossum0a0f11b1998-10-16 17:43:53 +00001987\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001988Map the object \var{key} to the value \var{v} in object \var{o}.
1989Returns \code{-1} on failure. This is the equivalent of the Python
1990statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001991\end{cfuncdesc}
1992
1993
Fred Drakeefd146c1999-02-15 15:30:45 +00001994\chapter{Concrete Objects Layer \label{concrete}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001995
1996The functions in this chapter are specific to certain Python object
1997types. Passing them an object of the wrong type is not a good idea;
1998if you receive an object from a Python program and you are not sure
1999that it has the right type, you must perform a type check first;
Fred Drake659ebfa2000-04-03 15:42:13 +00002000for example. to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00002001\cfunction{PyDict_Check()}. The chapter is structured like the
2002``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002003
2004
Fred Drakeefd146c1999-02-15 15:30:45 +00002005\section{Fundamental Objects \label{fundamental}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002006
Fred Drakee5bf8b21998-02-12 21:22:28 +00002007This section describes Python type objects and the singleton object
2008\code{None}.
2009
2010
Fred Drakeefd146c1999-02-15 15:30:45 +00002011\subsection{Type Objects \label{typeObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002012
Fred Drake659ebfa2000-04-03 15:42:13 +00002013\obindex{type}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002014\begin{ctypedesc}{PyTypeObject}
Fred Drake659ebfa2000-04-03 15:42:13 +00002015The C structure of the objects used to describe built-in types.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002016\end{ctypedesc}
2017
Fred Drake659ebfa2000-04-03 15:42:13 +00002018\begin{cvardesc}{PyObject*}{PyType_Type}
Fred Drakeefd146c1999-02-15 15:30:45 +00002019This is the type object for type objects; it is the same object as
2020\code{types.TypeType} in the Python layer.
Fred Drake659ebfa2000-04-03 15:42:13 +00002021\withsubitem{(in module types)}{\ttindex{TypeType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002022\end{cvardesc}
2023
Fred Drake659ebfa2000-04-03 15:42:13 +00002024\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
2025Returns true is the object \var{o} is a type object.
2026\end{cfuncdesc}
2027
2028\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
2029Returns true if the type object \var{o} sets the feature
2030\var{feature}. Type features are denoted by single bit flags. The
2031only defined feature flag is \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER},
2032described in section \ref{buffer-structs}.
2033\end{cfuncdesc}
2034
Fred Drakee5bf8b21998-02-12 21:22:28 +00002035
Fred Drakeefd146c1999-02-15 15:30:45 +00002036\subsection{The None Object \label{noneObject}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002037
Fred Drake659ebfa2000-04-03 15:42:13 +00002038\obindex{None@\texttt{None}}
2039Note that the \ctype{PyTypeObject} for \code{None} is not directly
2040exposed in the Python/C API. Since \code{None} is a singleton,
2041testing for object identity (using \samp{==} in C) is sufficient.
2042There is no \cfunction{PyNone_Check()} function for the same reason.
2043
2044\begin{cvardesc}{PyObject*}{Py_None}
Guido van Rossum44475131998-04-21 15:30:01 +00002045The Python \code{None} object, denoting lack of value. This object has
2046no methods.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002047\end{cvardesc}
2048
2049
Fred Drakeefd146c1999-02-15 15:30:45 +00002050\section{Sequence Objects \label{sequenceObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002051
Fred Drake659ebfa2000-04-03 15:42:13 +00002052\obindex{sequence}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002053Generic operations on sequence objects were discussed in the previous
2054chapter; this section deals with the specific kinds of sequence
2055objects that are intrinsic to the Python language.
2056
2057
Fred Drakeefd146c1999-02-15 15:30:45 +00002058\subsection{String Objects \label{stringObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002059
Fred Drake659ebfa2000-04-03 15:42:13 +00002060\obindex{string}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002061\begin{ctypedesc}{PyStringObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002062This subtype of \ctype{PyObject} represents a Python string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002063\end{ctypedesc}
2064
2065\begin{cvardesc}{PyTypeObject}{PyString_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002066This instance of \ctype{PyTypeObject} represents the Python string
2067type; it is the same object as \code{types.TypeType} in the Python
2068layer.\withsubitem{(in module types)}{\ttindex{StringType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002069\end{cvardesc}
2070
2071\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002072Returns true if the object \var{o} is a string object.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002073\end{cfuncdesc}
2074
Fred Drakec6fa34e1998-04-02 06:47:24 +00002075\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002076Returns a new string object with the value \var{v} on success, and
2077\NULL{} on failure.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002078\end{cfuncdesc}
2079
Fred Drake659ebfa2000-04-03 15:42:13 +00002080\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
2081 int len}
2082Returns a new string object with the value \var{v} and length
2083\var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
2084the contents of the string are uninitialized.
2085\end{cfuncdesc}
2086
Fred Drakec6fa34e1998-04-02 06:47:24 +00002087\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002088Returns the length of the string in string object \var{string}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002089\end{cfuncdesc}
2090
Fred Drake659ebfa2000-04-03 15:42:13 +00002091\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
2092Macro form of \cfunction{PyString_GetSize()} but without error
2093checking.
2094\end{cfuncdesc}
2095
Fred Drakec6fa34e1998-04-02 06:47:24 +00002096\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
Fred Drake659ebfa2000-04-03 15:42:13 +00002097Returns a null-terminated representation of the contents of
2098\var{string}. The pointer refers to the internal buffer of
2099\var{string}, not a copy. The data must not be modified in any way.
2100It must not be de-allocated.
2101\end{cfuncdesc}
2102
2103\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
2104Macro form of \cfunction{PyString_AsString()} but without error
2105checking.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002106\end{cfuncdesc}
2107
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002108\begin{cfuncdesc}{int}{PyString_AsStringAndSize}{PyObject *obj,
2109 char **buffer,
2110 int *length}
2111Returns a null-terminated representation of the contents of the object
2112\var{obj} through the output variables \var{buffer} and \var{length}.
2113
2114The function accepts both string and Unicode objects as input. For
2115Unicode objects it returns the default encoded version of the object.
2116If \var{length} is set to \NULL{}, the resulting buffer may not contain
2117null characters; if it does, the function returns -1 and a
2118TypeError is raised.
2119
2120The buffer refers to an internal string buffer of \var{obj}, not a
2121copy. The data must not be modified in any way. It must not be
2122de-allocated.
2123\end{cfuncdesc}
2124
Fred Drakec6fa34e1998-04-02 06:47:24 +00002125\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
2126 PyObject *newpart}
Fred Drake66b989c1999-02-15 20:15:39 +00002127Creates a new string object in \var{*string} containing the
Fred Drakeddc6c272000-03-31 18:22:38 +00002128contents of \var{newpart} appended to \var{string}; the caller will
2129own the new reference. The reference to the old value of \var{string}
2130will be stolen. If the new string
Fred Drake66b989c1999-02-15 20:15:39 +00002131cannot be created, the old reference to \var{string} will still be
2132discarded and the value of \var{*string} will be set to
2133\NULL{}; the appropriate exception will be set.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002134\end{cfuncdesc}
2135
2136\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
2137 PyObject *newpart}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002138Creates a new string object in \var{*string} containing the contents
Guido van Rossum44475131998-04-21 15:30:01 +00002139of \var{newpart} appended to \var{string}. This version decrements
2140the reference count of \var{newpart}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002141\end{cfuncdesc}
2142
2143\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
Guido van Rossum44475131998-04-21 15:30:01 +00002144A way to resize a string object even though it is ``immutable''.
2145Only use this to build up a brand new string object; don't use this if
2146the string may already be known in other parts of the code.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002147\end{cfuncdesc}
2148
2149\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
2150 PyObject *args}
Guido van Rossum44475131998-04-21 15:30:01 +00002151Returns a new string object from \var{format} and \var{args}. Analogous
Fred Drake659ebfa2000-04-03 15:42:13 +00002152to \code{\var{format} \%\ \var{args}}. The \var{args} argument must be
Guido van Rossum44475131998-04-21 15:30:01 +00002153a tuple.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002154\end{cfuncdesc}
2155
2156\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
Guido van Rossum44475131998-04-21 15:30:01 +00002157Intern the argument \var{*string} in place. The argument must be the
2158address of a pointer variable pointing to a Python string object.
2159If there is an existing interned string that is the same as
2160\var{*string}, it sets \var{*string} to it (decrementing the reference
2161count of the old string object and incrementing the reference count of
2162the interned string object), otherwise it leaves \var{*string} alone
2163and interns it (incrementing its reference count). (Clarification:
2164even though there is a lot of talk about reference counts, think of
Fred Drakef8830d11998-04-23 14:06:01 +00002165this function as reference-count-neutral; you own the object after
2166the call if and only if you owned it before the call.)
Fred Drakec6fa34e1998-04-02 06:47:24 +00002167\end{cfuncdesc}
2168
2169\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
Fred Drakef8830d11998-04-23 14:06:01 +00002170A combination of \cfunction{PyString_FromString()} and
2171\cfunction{PyString_InternInPlace()}, returning either a new string object
Guido van Rossum44475131998-04-21 15:30:01 +00002172that has been interned, or a new (``owned'') reference to an earlier
2173interned string object with the same value.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002174\end{cfuncdesc}
2175
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002176\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
2177 int size,
2178 const char *encoding,
2179 const char *errors}
2180Create a string object by decoding \var{size} bytes of the encoded
2181buffer \var{s}. \var{encoding} and \var{errors} have the same meaning
2182as the parameters of the same name in the unicode() builtin
2183function. The codec to be used is looked up using the Python codec
2184registry. Returns \NULL{} in case an exception was raised by the
2185codec.
2186\end{cfuncdesc}
2187
2188\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const Py_UNICODE *s,
2189 int size,
2190 const char *encoding,
2191 const char *errors}
2192Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2193Python string object. \var{encoding} and \var{errors} have the same
2194meaning as the parameters of the same name in the string .encode()
2195method. The codec to be used is looked up using the Python codec
2196registry. Returns \NULL{} in case an exception was raised by the
2197codec.
2198\end{cfuncdesc}
2199
2200\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedString}{PyObject *unicode,
2201 const char *encoding,
2202 const char *errors}
2203Encodes a string object and returns the result as Python string
2204object. \var{encoding} and \var{errors} have the same meaning as the
2205parameters of the same name in the string .encode() method. The codec
2206to be used is looked up using the Python codec registry. Returns
2207\NULL{} in case an exception was raised by the codec.
2208\end{cfuncdesc}
2209
Fred Drakee5bf8b21998-02-12 21:22:28 +00002210
Fred Drakea4cd2612000-04-06 14:10:29 +00002211\subsection{Unicode Objects \label{unicodeObjects}}
2212\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
2213
2214%--- Unicode Type -------------------------------------------------------
2215
2216These are the basic Unicode object types used for the Unicode
2217implementation in Python:
2218
2219\begin{ctypedesc}{Py_UNICODE}
2220This type represents a 16-bit unsigned storage type which is used by
2221Python internally as basis for holding Unicode ordinals. On platforms
2222where \ctype{wchar_t} is available and also has 16-bits,
2223\ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
2224native platform compatibility. On all other platforms,
2225\ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
2226\end{ctypedesc}
2227
2228\begin{ctypedesc}{PyUnicodeObject}
2229This subtype of \ctype{PyObject} represents a Python Unicode object.
2230\end{ctypedesc}
2231
2232\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
2233This instance of \ctype{PyTypeObject} represents the Python Unicode type.
2234\end{cvardesc}
2235
2236%--- These are really C macros... is there a macrodesc TeX macro ?
2237
2238The following APIs are really C macros and can be used to do fast
2239checks and to access internal read-only data of Unicode objects:
2240
2241\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
2242Returns true if the object \var{o} is a Unicode object.
2243\end{cfuncdesc}
2244
2245\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
2246Returns the size of the object. o has to be a
2247PyUnicodeObject (not checked).
2248\end{cfuncdesc}
2249
2250\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
2251Returns the size of the object's internal buffer in bytes. o has to be
2252a PyUnicodeObject (not checked).
2253\end{cfuncdesc}
2254
Fred Drake992fe5a2000-06-16 21:04:15 +00002255\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002256Returns a pointer to the internal Py_UNICODE buffer of the object. o
2257has to be a PyUnicodeObject (not checked).
2258\end{cfuncdesc}
2259
Fred Drake992fe5a2000-06-16 21:04:15 +00002260\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002261Returns a (const char *) pointer to the internal buffer of the object.
2262o has to be a PyUnicodeObject (not checked).
2263\end{cfuncdesc}
2264
2265% --- Unicode character properties ---------------------------------------
2266
2267Unicode provides many different character properties. The most often
2268needed ones are available through these macros which are mapped to C
2269functions depending on the Python configuration.
2270
2271\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
2272Returns 1/0 depending on whether \var{ch} is a whitespace character.
2273\end{cfuncdesc}
2274
2275\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
2276Returns 1/0 depending on whether \var{ch} is a lowercase character.
2277\end{cfuncdesc}
2278
2279\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
Fred Drakeae96aab2000-07-03 13:38:10 +00002280Returns 1/0 depending on whether \var{ch} is an uppercase character.
Fred Drakea4cd2612000-04-06 14:10:29 +00002281\end{cfuncdesc}
2282
2283\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
2284Returns 1/0 depending on whether \var{ch} is a titlecase character.
2285\end{cfuncdesc}
2286
2287\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
2288Returns 1/0 depending on whether \var{ch} is a linebreak character.
2289\end{cfuncdesc}
2290
2291\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
2292Returns 1/0 depending on whether \var{ch} is a decimal character.
2293\end{cfuncdesc}
2294
2295\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
2296Returns 1/0 depending on whether \var{ch} is a digit character.
2297\end{cfuncdesc}
2298
2299\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
2300Returns 1/0 depending on whether \var{ch} is a numeric character.
2301\end{cfuncdesc}
2302
Fred Drakeae96aab2000-07-03 13:38:10 +00002303\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
2304Returns 1/0 depending on whether \var{ch} is an alphabetic character.
2305\end{cfuncdesc}
2306
2307\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
2308Returns 1/0 depending on whether \var{ch} is an alphanumeric character.
2309\end{cfuncdesc}
2310
Fred Drakea4cd2612000-04-06 14:10:29 +00002311These APIs can be used for fast direct character conversions:
2312
2313\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
2314Returns the character \var{ch} converted to lower case.
2315\end{cfuncdesc}
2316
2317\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
2318Returns the character \var{ch} converted to upper case.
2319\end{cfuncdesc}
2320
2321\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
2322Returns the character \var{ch} converted to title case.
2323\end{cfuncdesc}
2324
2325\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
2326Returns the character \var{ch} converted to a decimal positive integer.
2327Returns -1 in case this is not possible. Does not raise exceptions.
2328\end{cfuncdesc}
2329
2330\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
2331Returns the character \var{ch} converted to a single digit integer.
2332Returns -1 in case this is not possible. Does not raise exceptions.
2333\end{cfuncdesc}
2334
2335\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
2336Returns the character \var{ch} converted to a (positive) double.
2337Returns -1.0 in case this is not possible. Does not raise exceptions.
2338\end{cfuncdesc}
2339
2340% --- Plain Py_UNICODE ---------------------------------------------------
2341
2342To create Unicode objects and access their basic sequence properties,
2343use these APIs:
2344
2345\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
2346 int size}
2347
2348Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
2349given size. \var{u} may be \NULL{} which causes the contents to be
2350undefined. It is the user's responsibility to fill in the needed data.
2351The buffer is copied into the new object.
2352\end{cfuncdesc}
2353
Fred Drake1d158692000-06-18 05:21:21 +00002354\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002355Return a read-only pointer to the Unicode object's internal
2356\ctype{Py_UNICODE} buffer.
2357\end{cfuncdesc}
2358
2359\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
2360Return the length of the Unicode object.
2361\end{cfuncdesc}
2362
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002363\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
2364 const char *encoding,
2365 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002366
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002367Coerce an encoded object obj to an Unicode object and return a
2368reference with incremented refcount.
Fred Drakea4cd2612000-04-06 14:10:29 +00002369
2370Coercion is done in the following way:
2371\begin{enumerate}
2372\item Unicode objects are passed back as-is with incremented
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002373 refcount. Note: these cannot be decoded; passing a non-NULL
2374 value for encoding will result in a TypeError.
Fred Drakea4cd2612000-04-06 14:10:29 +00002375
2376\item String and other char buffer compatible objects are decoded
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002377 according to the given encoding and using the error handling
2378 defined by errors. Both can be NULL to have the interface use
2379 the default values (see the next section for details).
Fred Drakea4cd2612000-04-06 14:10:29 +00002380
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002381\item All other objects cause an exception.
Fred Drakea4cd2612000-04-06 14:10:29 +00002382\end{enumerate}
2383The API returns NULL in case of an error. The caller is responsible
2384for decref'ing the returned objects.
2385\end{cfuncdesc}
2386
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002387\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
2388
2389Shortcut for PyUnicode_FromEncodedObject(obj, NULL, ``strict'')
2390which is used throughout the interpreter whenever coercion to
2391Unicode is needed.
2392\end{cfuncdesc}
2393
Fred Drakea4cd2612000-04-06 14:10:29 +00002394% --- wchar_t support for platforms which support it ---------------------
2395
2396If the platform supports \ctype{wchar_t} and provides a header file
2397wchar.h, Python can interface directly to this type using the
2398following functions. Support is optimized if Python's own
2399\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
2400
2401\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
2402 int size}
2403Create a Unicode Object from the \ctype{whcar_t} buffer \var{w} of the
2404given size. Returns \NULL{} on failure.
2405\end{cfuncdesc}
2406
2407\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
2408 wchar_t *w,
2409 int size}
Fred Drakea4cd2612000-04-06 14:10:29 +00002410Copies the Unicode Object contents into the \ctype{whcar_t} buffer
2411\var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
2412Returns the number of \ctype{whcar_t} characters copied or -1 in case
2413of an error.
2414\end{cfuncdesc}
2415
2416
2417\subsubsection{Builtin Codecs \label{builtinCodecs}}
2418
2419Python provides a set of builtin codecs which are written in C
2420for speed. All of these codecs are directly usable via the
2421following functions.
2422
2423Many of the following APIs take two arguments encoding and
2424errors. These parameters encoding and errors have the same semantics
2425as the ones of the builtin unicode() Unicode object constructor.
2426
2427Setting encoding to NULL causes the default encoding to be used which
2428is UTF-8.
2429
2430Error handling is set by errors which may also be set to NULL meaning
2431to use the default handling defined for the codec. Default error
2432handling for all builtin codecs is ``strict'' (ValueErrors are raised).
2433
2434The codecs all use a similar interface. Only deviation from the
2435following generic ones are documented for simplicity.
2436
2437% --- Generic Codecs -----------------------------------------------------
2438
2439These are the generic codec APIs:
2440
2441\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
2442 int size,
2443 const char *encoding,
2444 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002445Create a Unicode object by decoding \var{size} bytes of the encoded
2446string \var{s}. \var{encoding} and \var{errors} have the same meaning
2447as the parameters of the same name in the unicode() builtin
2448function. The codec to be used is looked up using the Python codec
2449registry. Returns \NULL{} in case an exception was raised by the
2450codec.
2451\end{cfuncdesc}
2452
2453\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
2454 int size,
2455 const char *encoding,
2456 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002457Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2458Python string object. \var{encoding} and \var{errors} have the same
2459meaning as the parameters of the same name in the Unicode .encode()
2460method. The codec to be used is looked up using the Python codec
2461registry. Returns \NULL{} in case an exception was raised by the
2462codec.
2463\end{cfuncdesc}
2464
2465\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
2466 const char *encoding,
2467 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002468Encodes a Unicode object and returns the result as Python string
2469object. \var{encoding} and \var{errors} have the same meaning as the
2470parameters of the same name in the Unicode .encode() method. The codec
2471to be used is looked up using the Python codec registry. Returns
2472\NULL{} in case an exception was raised by the codec.
2473\end{cfuncdesc}
2474
2475% --- UTF-8 Codecs -------------------------------------------------------
2476
2477These are the UTF-8 codec APIs:
2478
2479\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
2480 int size,
2481 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002482Creates a Unicode object by decoding \var{size} bytes of the UTF-8
2483encoded string \var{s}. Returns \NULL{} in case an exception was
2484raised by the codec.
2485\end{cfuncdesc}
2486
2487\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
2488 int size,
2489 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002490Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
2491and returns a Python string object. Returns \NULL{} in case an
2492exception was raised by the codec.
2493\end{cfuncdesc}
2494
2495\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002496Encodes a Unicode objects using UTF-8 and returns the result as Python
2497string object. Error handling is ``strict''. Returns
2498\NULL{} in case an exception was raised by the codec.
2499\end{cfuncdesc}
2500
2501% --- UTF-16 Codecs ------------------------------------------------------ */
2502
2503These are the UTF-16 codec APIs:
2504
2505\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
2506 int size,
2507 const char *errors,
2508 int *byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002509Decodes \var{length} bytes from a UTF-16 encoded buffer string and
2510returns the corresponding Unicode object.
2511
2512\var{errors} (if non-NULL) defines the error handling. It defaults
2513to ``strict''.
2514
2515If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
2516the given byte order:
2517
2518\begin{verbatim}
2519 *byteorder == -1: little endian
2520 *byteorder == 0: native order
2521 *byteorder == 1: big endian
2522\end{verbatim}
2523
2524and then switches according to all byte order marks (BOM) it finds in
2525the input data. BOM marks are not copied into the resulting Unicode
2526string. After completion, \var{*byteorder} is set to the current byte
2527order at the end of input data.
2528
2529If \var{byteorder} is \NULL{}, the codec starts in native order mode.
2530
2531Returns \NULL{} in case an exception was raised by the codec.
2532\end{cfuncdesc}
2533
2534\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
2535 int size,
2536 const char *errors,
2537 int byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002538Returns a Python string object holding the UTF-16 encoded value of the
2539Unicode data in \var{s}.
2540
Fred Drakea8455ab2000-06-16 19:58:42 +00002541If \var{byteorder} is not \code{0}, output is written according to the
Fred Drakea4cd2612000-04-06 14:10:29 +00002542following byte order:
2543
2544\begin{verbatim}
2545 byteorder == -1: little endian
2546 byteorder == 0: native byte order (writes a BOM mark)
2547 byteorder == 1: big endian
2548\end{verbatim}
2549
Fred Drakea8455ab2000-06-16 19:58:42 +00002550If byteorder is \code{0}, the output string will always start with the
Fred Drakea4cd2612000-04-06 14:10:29 +00002551Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
2552prepended.
2553
2554Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
2555reduced to UCS-2. This trick makes it possible to add full UTF-16
2556capabilities at a later point without comprimising the APIs.
2557
2558Returns \NULL{} in case an exception was raised by the codec.
2559\end{cfuncdesc}
2560
2561\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002562Returns a Python string using the UTF-16 encoding in native byte
2563order. The string always starts with a BOM mark. Error handling is
2564``strict''. Returns \NULL{} in case an exception was raised by the
2565codec.
2566\end{cfuncdesc}
2567
2568% --- Unicode-Escape Codecs ----------------------------------------------
2569
2570These are the ``Unicode Esacpe'' codec APIs:
2571
2572\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
2573 int size,
2574 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002575Creates a Unicode object by decoding \var{size} bytes of the Unicode-Esacpe
2576encoded string \var{s}. Returns \NULL{} in case an exception was
2577raised by the codec.
2578\end{cfuncdesc}
2579
2580\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
2581 int size,
2582 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002583Encodes the \ctype{Py_UNICODE} buffer of the given size using Unicode-Escape
2584and returns a Python string object. Returns \NULL{} in case an
2585exception was raised by the codec.
2586\end{cfuncdesc}
2587
2588\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002589Encodes a Unicode objects using Unicode-Escape and returns the result
2590as Python string object. Error handling is ``strict''. Returns
2591\NULL{} in case an exception was raised by the codec.
2592\end{cfuncdesc}
2593
2594% --- Raw-Unicode-Escape Codecs ------------------------------------------
2595
2596These are the ``Raw Unicode Esacpe'' codec APIs:
2597
2598\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
2599 int size,
2600 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002601Creates a Unicode object by decoding \var{size} bytes of the Raw-Unicode-Esacpe
2602encoded string \var{s}. Returns \NULL{} in case an exception was
2603raised by the codec.
2604\end{cfuncdesc}
2605
2606\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
2607 int size,
2608 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002609Encodes the \ctype{Py_UNICODE} buffer of the given size using Raw-Unicode-Escape
2610and returns a Python string object. Returns \NULL{} in case an
2611exception was raised by the codec.
2612\end{cfuncdesc}
2613
2614\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002615Encodes a Unicode objects using Raw-Unicode-Escape and returns the result
2616as Python string object. Error handling is ``strict''. Returns
2617\NULL{} in case an exception was raised by the codec.
2618\end{cfuncdesc}
2619
2620% --- Latin-1 Codecs -----------------------------------------------------
2621
2622These are the Latin-1 codec APIs:
2623
2624Latin-1 corresponds to the first 256 Unicode ordinals and only these
2625are accepted by the codecs during encoding.
2626
2627\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002628 int size,
2629 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002630Creates a Unicode object by decoding \var{size} bytes of the Latin-1
2631encoded string \var{s}. Returns \NULL{} in case an exception was
2632raised by the codec.
2633\end{cfuncdesc}
2634
2635\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002636 int size,
2637 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002638Encodes the \ctype{Py_UNICODE} buffer of the given size using Latin-1
2639and returns a Python string object. Returns \NULL{} in case an
2640exception was raised by the codec.
2641\end{cfuncdesc}
2642
2643\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002644Encodes a Unicode objects using Latin-1 and returns the result as
2645Python string object. Error handling is ``strict''. Returns
2646\NULL{} in case an exception was raised by the codec.
2647\end{cfuncdesc}
2648
2649% --- ASCII Codecs -------------------------------------------------------
2650
Fred Drake1d158692000-06-18 05:21:21 +00002651These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
2652accepted. All other codes generate errors.
Fred Drakea4cd2612000-04-06 14:10:29 +00002653
2654\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002655 int size,
2656 const char *errors}
2657Creates a Unicode object by decoding \var{size} bytes of the
2658\ASCII{} encoded string \var{s}. Returns \NULL{} in case an exception
2659was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002660\end{cfuncdesc}
2661
2662\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002663 int size,
2664 const char *errors}
2665Encodes the \ctype{Py_UNICODE} buffer of the given size using
2666\ASCII{} and returns a Python string object. Returns \NULL{} in case
2667an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002668\end{cfuncdesc}
2669
2670\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
Fred Drake1d158692000-06-18 05:21:21 +00002671Encodes a Unicode objects using \ASCII{} and returns the result as Python
Fred Drakea4cd2612000-04-06 14:10:29 +00002672string object. Error handling is ``strict''. Returns
2673\NULL{} in case an exception was raised by the codec.
2674\end{cfuncdesc}
2675
2676% --- Character Map Codecs -----------------------------------------------
2677
2678These are the mapping codec APIs:
2679
2680This codec is special in that it can be used to implement many
2681different codecs (and this is in fact what was done to obtain most of
2682the standard codecs included in the \module{encodings} package). The
2683codec uses mapping to encode and decode characters.
2684
2685Decoding mappings must map single string characters to single Unicode
2686characters, integers (which are then interpreted as Unicode ordinals)
2687or None (meaning "undefined mapping" and causing an error).
2688
2689Encoding mappings must map single Unicode characters to single string
2690characters, integers (which are then interpreted as Latin-1 ordinals)
2691or None (meaning "undefined mapping" and causing an error).
2692
2693The mapping objects provided must only support the __getitem__ mapping
2694interface.
2695
2696If a character lookup fails with a LookupError, the character is
2697copied as-is meaning that its ordinal value will be interpreted as
2698Unicode or Latin-1 ordinal resp. Because of this, mappings only need
2699to contain those mappings which map characters to different code
2700points.
2701
2702\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
2703 int size,
2704 PyObject *mapping,
2705 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002706Creates a Unicode object by decoding \var{size} bytes of the encoded
2707string \var{s} using the given \var{mapping} object. Returns \NULL{}
2708in case an exception was raised by the codec.
2709\end{cfuncdesc}
2710
2711\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
2712 int size,
2713 PyObject *mapping,
2714 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002715Encodes the \ctype{Py_UNICODE} buffer of the given size using the
2716given \var{mapping} object and returns a Python string object.
2717Returns \NULL{} in case an exception was raised by the codec.
2718\end{cfuncdesc}
2719
2720\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
2721 PyObject *mapping}
Fred Drakea4cd2612000-04-06 14:10:29 +00002722Encodes a Unicode objects using the given \var{mapping} object and
2723returns the result as Python string object. Error handling is
2724``strict''. Returns \NULL{} in case an exception was raised by the
2725codec.
2726\end{cfuncdesc}
2727
2728The following codec API is special in that maps Unicode to Unicode.
2729
2730\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
2731 int size,
2732 PyObject *table,
2733 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002734Translates a \ctype{Py_UNICODE} buffer of the given length by applying
2735a character mapping \var{table} to it and returns the resulting
Fred Drake1d158692000-06-18 05:21:21 +00002736Unicode object. Returns \NULL{} when an exception was raised by the
2737codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002738
2739The \var{mapping} table must map Unicode ordinal integers to Unicode
2740ordinal integers or None (causing deletion of the character).
2741
2742Mapping tables must only provide the __getitem__ interface,
2743e.g. dictionaries or sequences. Unmapped character ordinals (ones
2744which cause a LookupError) are left untouched and are copied as-is.
Fred Drakea4cd2612000-04-06 14:10:29 +00002745\end{cfuncdesc}
2746
2747% --- MBCS codecs for Windows --------------------------------------------
2748
Fred Drake1d158692000-06-18 05:21:21 +00002749These are the MBCS codec APIs. They are currently only available on
Fred Drakea4cd2612000-04-06 14:10:29 +00002750Windows and use the Win32 MBCS converters to implement the
Fred Drake1d158692000-06-18 05:21:21 +00002751conversions. Note that MBCS (or DBCS) is a class of encodings, not
2752just one. The target encoding is defined by the user settings on the
2753machine running the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002754
2755\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
2756 int size,
2757 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002758Creates a Unicode object by decoding \var{size} bytes of the MBCS
Fred Drake1d158692000-06-18 05:21:21 +00002759encoded string \var{s}. Returns \NULL{} in case an exception was
Fred Drakea4cd2612000-04-06 14:10:29 +00002760raised by the codec.
2761\end{cfuncdesc}
2762
2763\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
2764 int size,
2765 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002766Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
2767and returns a Python string object. Returns \NULL{} in case an
2768exception was raised by the codec.
2769\end{cfuncdesc}
2770
2771\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002772Encodes a Unicode objects using MBCS and returns the result as Python
Fred Drake1d158692000-06-18 05:21:21 +00002773string object. Error handling is ``strict''. Returns \NULL{} in case
2774an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002775\end{cfuncdesc}
2776
2777% --- Methods & Slots ----------------------------------------------------
2778
2779\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
2780
2781The following APIs are capable of handling Unicode objects and strings
2782on input (we refer to them as strings in the descriptions) and return
2783Unicode objects or integers as apporpriate.
2784
2785They all return \NULL{} or -1 in case an exception occurrs.
2786
2787\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
2788 PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002789Concat two strings giving a new Unicode string.
2790\end{cfuncdesc}
2791
2792\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
2793 PyObject *sep,
2794 int maxsplit}
Fred Drakea4cd2612000-04-06 14:10:29 +00002795Split a string giving a list of Unicode strings.
2796
2797If sep is NULL, splitting will be done at all whitespace
2798substrings. Otherwise, splits occur at the given separator.
2799
2800At most maxsplit splits will be done. If negative, no limit is set.
2801
2802Separators are not included in the resulting list.
2803\end{cfuncdesc}
2804
2805\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
2806 int maxsplit}
Fred Drake1d158692000-06-18 05:21:21 +00002807Split a Unicode string at line breaks, returning a list of Unicode
2808strings. CRLF is considered to be one line break. The Line break
2809characters are not included in the resulting strings.
Fred Drakea4cd2612000-04-06 14:10:29 +00002810\end{cfuncdesc}
2811
2812\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
2813 PyObject *table,
2814 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002815Translate a string by applying a character mapping table to it and
2816return the resulting Unicode object.
2817
2818The mapping table must map Unicode ordinal integers to Unicode ordinal
2819integers or None (causing deletion of the character).
2820
2821Mapping tables must only provide the __getitem__ interface,
2822e.g. dictionaries or sequences. Unmapped character ordinals (ones
2823which cause a LookupError) are left untouched and are copied as-is.
2824
2825\var{errors} has the usual meaning for codecs. It may be \NULL{}
2826which indicates to use the default error handling.
Fred Drakea4cd2612000-04-06 14:10:29 +00002827\end{cfuncdesc}
2828
2829\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
2830 PyObject *seq}
Fred Drakea4cd2612000-04-06 14:10:29 +00002831Join a sequence of strings using the given separator and return
2832the resulting Unicode string.
2833\end{cfuncdesc}
2834
2835\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
2836 PyObject *substr,
2837 int start,
2838 int end,
2839 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002840Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
2841the given tail end (\var{direction} == -1 means to do a prefix match,
2842\var{direction} == 1 a suffix match), 0 otherwise.
2843\end{cfuncdesc}
2844
2845\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
2846 PyObject *substr,
2847 int start,
2848 int end,
2849 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002850Return the first position of \var{substr} in
2851\var{str}[\var{start}:\var{end}] using the given \var{direction}
2852(\var{direction} == 1 means to do a forward search,
2853\var{direction} == -1 a backward search), 0 otherwise.
2854\end{cfuncdesc}
2855
2856\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
2857 PyObject *substr,
2858 int start,
2859 int end}
Fred Drakea4cd2612000-04-06 14:10:29 +00002860Count the number of occurrences of \var{substr} in
2861\var{str}[\var{start}:\var{end}]
2862\end{cfuncdesc}
2863
2864\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
2865 PyObject *substr,
2866 PyObject *replstr,
2867 int maxcount}
Fred Drakea4cd2612000-04-06 14:10:29 +00002868Replace at most \var{maxcount} occurrences of \var{substr} in
2869\var{str} with \var{replstr} and return the resulting Unicode object.
2870\var{maxcount} == -1 means: replace all occurrences.
2871\end{cfuncdesc}
2872
Fred Drake1d158692000-06-18 05:21:21 +00002873\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002874Compare two strings and return -1, 0, 1 for less than, equal,
2875greater than resp.
2876\end{cfuncdesc}
2877
2878\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
2879 PyObject *args}
Fred Drake1d158692000-06-18 05:21:21 +00002880Returns a new string object from \var{format} and \var{args}; this is
2881analogous to \code{\var{format} \%\ \var{args}}. The
2882\var{args} argument must be a tuple.
Fred Drakea4cd2612000-04-06 14:10:29 +00002883\end{cfuncdesc}
2884
2885\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
2886 PyObject *element}
Fred Drakea4cd2612000-04-06 14:10:29 +00002887Checks whether \var{element} is contained in \var{container} and
Fred Drake1d158692000-06-18 05:21:21 +00002888returns true or false accordingly.
Fred Drakea4cd2612000-04-06 14:10:29 +00002889
Fred Drake1d158692000-06-18 05:21:21 +00002890\var{element} has to coerce to a one element Unicode string. \code{-1} is
Fred Drakea4cd2612000-04-06 14:10:29 +00002891returned in case of an error.
2892\end{cfuncdesc}
2893
2894
Fred Drake58c5a2a1999-08-04 13:13:24 +00002895\subsection{Buffer Objects \label{bufferObjects}}
Fred Drake659ebfa2000-04-03 15:42:13 +00002896\sectionauthor{Greg Stein}{gstein@lyra.org}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002897
Fred Drake659ebfa2000-04-03 15:42:13 +00002898\obindex{buffer}
2899Python objects implemented in C can export a group of functions called
2900the ``buffer\index{buffer interface} interface.'' These functions can
2901be used by an object to expose its data in a raw, byte-oriented
2902format. Clients of the object can use the buffer interface to access
2903the object data directly, without needing to copy it first.
2904
2905Two examples of objects that support
2906the buffer interface are strings and arrays. The string object exposes
2907the character contents in the buffer interface's byte-oriented
2908form. An array can also expose its contents, but it should be noted
2909that array elements may be multi-byte values.
2910
2911An example user of the buffer interface is the file object's
2912\method{write()} method. Any object that can export a series of bytes
2913through the buffer interface can be written to a file. There are a
2914number of format codes to \cfunction{PyArgs_ParseTuple()} that operate
2915against an object's buffer interface, returning data from the target
2916object.
2917
2918More information on the buffer interface is provided in the section
2919``Buffer Object Structures'' (section \ref{buffer-structs}), under
2920the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
2921
2922A ``buffer object'' is defined in the \file{bufferobject.h} header
2923(included by \file{Python.h}). These objects look very similar to
2924string objects at the Python programming level: they support slicing,
2925indexing, concatenation, and some other standard string
2926operations. However, their data can come from one of two sources: from
2927a block of memory, or from another object which exports the buffer
2928interface.
2929
2930Buffer objects are useful as a way to expose the data from another
2931object's buffer interface to the Python programmer. They can also be
2932used as a zero-copy slicing mechanism. Using their ability to
2933reference a block of memory, it is possible to expose any data to the
2934Python programmer quite easily. The memory could be a large, constant
2935array in a C extension, it could be a raw block of memory for
2936manipulation before passing to an operating system library, or it
2937could be used to pass around structured data in its native, in-memory
2938format.
2939
2940\begin{ctypedesc}{PyBufferObject}
2941This subtype of \ctype{PyObject} represents a buffer object.
2942\end{ctypedesc}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002943
2944\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
2945The instance of \ctype{PyTypeObject} which represents the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00002946buffer type; it is the same object as \code{types.BufferType} in the
2947Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002948\end{cvardesc}
2949
2950\begin{cvardesc}{int}{Py_END_OF_BUFFER}
Fred Drake659ebfa2000-04-03 15:42:13 +00002951This constant may be passed as the \var{size} parameter to
2952\cfunction{PyBuffer_FromObject()} or
2953\cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the new
2954\ctype{PyBufferObject} should refer to \var{base} object from the
2955specified \var{offset} to the end of its exported buffer. Using this
2956enables the caller to avoid querying the \var{base} object for its
2957length.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002958\end{cvardesc}
2959
2960\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
2961Return true if the argument has type \cdata{PyBuffer_Type}.
2962\end{cfuncdesc}
2963
2964\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
2965 int offset, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002966Return a new read-only buffer object. This raises
2967\exception{TypeError} if \var{base} doesn't support the read-only
2968buffer protocol or doesn't provide exactly one buffer segment, or it
2969raises \exception{ValueError} if \var{offset} is less than zero. The
2970buffer will hold a reference to the \var{base} object, and the
2971buffer's contents will refer to the \var{base} object's buffer
2972interface, starting as position \var{offset} and extending for
2973\var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
2974the new buffer's contents extend to the length of the
2975\var{base} object's exported buffer data.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002976\end{cfuncdesc}
2977
2978\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
2979 int offset,
2980 int size}
2981Return a new writable buffer object. Parameters and exceptions are
2982similar to those for \cfunction{PyBuffer_FromObject()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00002983If the \var{base} object does not export the writeable buffer
2984protocol, then \exception{TypeError} is raised.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002985\end{cfuncdesc}
2986
2987\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002988Return a new read-only buffer object that reads from a specified
2989location in memory, with a specified size.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002990The caller is responsible for ensuring that the memory buffer, passed
2991in as \var{ptr}, is not deallocated while the returned buffer object
2992exists. Raises \exception{ValueError} if \var{size} is less than
Fred Drake659ebfa2000-04-03 15:42:13 +00002993zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be passed
2994for the \var{size} parameter; \exception{ValueError} will be raised in
2995that case.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002996\end{cfuncdesc}
2997
2998\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002999Similar to \cfunction{PyBuffer_FromMemory()}, but the returned buffer
3000is writable.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003001\end{cfuncdesc}
3002
3003\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
3004Returns a new writable buffer object that maintains its own memory
Fred Drake659ebfa2000-04-03 15:42:13 +00003005buffer of \var{size} bytes. \exception{ValueError} is returned if
3006\var{size} is not zero or positive.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003007\end{cfuncdesc}
3008
Guido van Rossum44475131998-04-21 15:30:01 +00003009
Fred Drakeefd146c1999-02-15 15:30:45 +00003010\subsection{Tuple Objects \label{tupleObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003011
Fred Drake659ebfa2000-04-03 15:42:13 +00003012\obindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003013\begin{ctypedesc}{PyTupleObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003014This subtype of \ctype{PyObject} represents a Python tuple object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003015\end{ctypedesc}
3016
3017\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003018This instance of \ctype{PyTypeObject} represents the Python tuple
3019type; it is the same object as \code{types.TupleType} in the Python
3020layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003021\end{cvardesc}
3022
3023\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
3024Return true if the argument is a tuple object.
3025\end{cfuncdesc}
3026
Fred Drake659ebfa2000-04-03 15:42:13 +00003027\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
3028Return a new tuple object of size \var{len}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003029\end{cfuncdesc}
3030
3031\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
Fred Drakee058b4f1998-02-16 06:15:35 +00003032Takes a pointer to a tuple object, and returns the size
Fred Drakee5bf8b21998-02-12 21:22:28 +00003033of that tuple.
3034\end{cfuncdesc}
3035
Fred Drakec6fa34e1998-04-02 06:47:24 +00003036\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003037Returns the object at position \var{pos} in the tuple pointed
3038to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003039sets an \exception{IndexError} exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003040\end{cfuncdesc}
3041
Fred Drakec6fa34e1998-04-02 06:47:24 +00003042\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003043Does the same, but does no checking of its arguments.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003044\end{cfuncdesc}
3045
Fred Drakec6fa34e1998-04-02 06:47:24 +00003046\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyTupleObject *p,
Fred Drakee5bf8b21998-02-12 21:22:28 +00003047 int low,
3048 int high}
Fred Drakee058b4f1998-02-16 06:15:35 +00003049Takes a slice of the tuple pointed to by \var{p} from
3050\var{low} to \var{high} and returns it as a new tuple.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003051\end{cfuncdesc}
3052
Fred Drake659ebfa2000-04-03 15:42:13 +00003053\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
3054 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003055Inserts a reference to object \var{o} at position \var{pos} of
3056the tuple pointed to by \var{p}. It returns \code{0} on success.
Fred Drake659ebfa2000-04-03 15:42:13 +00003057\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003058\end{cfuncdesc}
3059
Fred Drake659ebfa2000-04-03 15:42:13 +00003060\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
3061 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003062Does the same, but does no error checking, and
Fred Drakee5bf8b21998-02-12 21:22:28 +00003063should \emph{only} be used to fill in brand new tuples.
Fred Drake659ebfa2000-04-03 15:42:13 +00003064\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003065\end{cfuncdesc}
3066
Fred Drakec6fa34e1998-04-02 06:47:24 +00003067\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyTupleObject *p,
Fred Drake659ebfa2000-04-03 15:42:13 +00003068 int newsize, int last_is_sticky}
3069Can be used to resize a tuple. \var{newsize} will be the new length
3070of the tuple. Because tuples are \emph{supposed} to be immutable,
3071this should only be used if there is only one reference to the object.
3072Do \emph{not} use this if the tuple may already be known to some other
3073part of the code. \var{last_is_sticky} is a flag --- if true, the
3074tuple will grow or shrink at the front, otherwise it will grow or
3075shrink at the end. Think of this as destroying the old tuple and
3076creating a new one, only more efficiently. Returns \code{0} on
3077success and \code{-1} on failure (in which case a
3078\exception{MemoryError} or \exception{SystemError} will be raised).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003079\end{cfuncdesc}
3080
3081
Fred Drakeefd146c1999-02-15 15:30:45 +00003082\subsection{List Objects \label{listObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003083
Fred Drake659ebfa2000-04-03 15:42:13 +00003084\obindex{list}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003085\begin{ctypedesc}{PyListObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003086This subtype of \ctype{PyObject} represents a Python list object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003087\end{ctypedesc}
3088
3089\begin{cvardesc}{PyTypeObject}{PyList_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003090This instance of \ctype{PyTypeObject} represents the Python list
3091type. This is the same object as \code{types.ListType}.
3092\withsubitem{(in module types)}{\ttindex{ListType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003093\end{cvardesc}
3094
3095\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003096Returns true if its argument is a \ctype{PyListObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003097\end{cfuncdesc}
3098
Fred Drake659ebfa2000-04-03 15:42:13 +00003099\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
3100Returns a new list of length \var{len} on success, or \NULL{} on
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003101failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003102\end{cfuncdesc}
3103
Fred Drakec6fa34e1998-04-02 06:47:24 +00003104\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003105Returns the length of the list object in \var{list}; this is
3106equivalent to \samp{len(\var{list})} on a list object.
3107\bifuncindex{len}
3108\end{cfuncdesc}
3109
3110\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
3111Macro form of \cfunction{PyList_GetSize()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003112\end{cfuncdesc}
3113
Fred Drakec6fa34e1998-04-02 06:47:24 +00003114\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
Guido van Rossum44475131998-04-21 15:30:01 +00003115Returns the object at position \var{pos} in the list pointed
3116to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003117sets an \exception{IndexError} exception.
3118\end{cfuncdesc}
3119
3120\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
3121Macro form of \cfunction{PyList_GetItem()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003122\end{cfuncdesc}
3123
Fred Drakec6fa34e1998-04-02 06:47:24 +00003124\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
3125 PyObject *item}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003126Sets the item at index \var{index} in list to \var{item}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003127\strong{Note:} This function ``steals'' a reference to \var{item}.
3128\end{cfuncdesc}
3129
3130\begin{cfuncdesc}{PyObject*}{PyList_SET_ITEM}{PyObject *list, int i,
3131 PyObject *o}
3132Macro form of \cfunction{PyList_SetItem()} without error checking.
3133\strong{Note:} This function ``steals'' a reference to \var{item}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003134\end{cfuncdesc}
3135
Fred Drakec6fa34e1998-04-02 06:47:24 +00003136\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
Guido van Rossum44475131998-04-21 15:30:01 +00003137 PyObject *item}
3138Inserts the item \var{item} into list \var{list} in front of index
Fred Drake659ebfa2000-04-03 15:42:13 +00003139\var{index}. Returns \code{0} if successful; returns \code{-1} and
3140raises an exception if unsuccessful. Analogous to
3141\code{\var{list}.insert(\var{index}, \var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003142\end{cfuncdesc}
3143
Fred Drakec6fa34e1998-04-02 06:47:24 +00003144\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
Guido van Rossum44475131998-04-21 15:30:01 +00003145Appends the object \var{item} at the end of list \var{list}. Returns
Fred Drake659ebfa2000-04-03 15:42:13 +00003146\code{0} if successful; returns \code{-1} and sets an exception if
3147unsuccessful. Analogous to \code{\var{list}.append(\var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003148\end{cfuncdesc}
3149
Fred Drakec6fa34e1998-04-02 06:47:24 +00003150\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
3151 int low, int high}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003152Returns a list of the objects in \var{list} containing the objects
Guido van Rossum44475131998-04-21 15:30:01 +00003153\emph{between} \var{low} and \var{high}. Returns NULL and sets an
3154exception if unsuccessful.
Fred Drake659ebfa2000-04-03 15:42:13 +00003155Analogous to \code{\var{list}[\var{low}:\var{high}]}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003156\end{cfuncdesc}
3157
Fred Drakec6fa34e1998-04-02 06:47:24 +00003158\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
3159 int low, int high,
3160 PyObject *itemlist}
Fred Drake659ebfa2000-04-03 15:42:13 +00003161Sets the slice of \var{list} between \var{low} and \var{high} to the
3162contents of \var{itemlist}. Analogous to
3163\code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
3164\code{0} on success, \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003165\end{cfuncdesc}
3166
Fred Drakec6fa34e1998-04-02 06:47:24 +00003167\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003168Sorts the items of \var{list} in place. Returns \code{0} on success,
3169\code{-1} on failure. This is equivalent to
3170\samp{\var{list}.sort()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003171\end{cfuncdesc}
3172
Fred Drakec6fa34e1998-04-02 06:47:24 +00003173\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003174Reverses the items of \var{list} in place. Returns \code{0} on
3175success, \code{-1} on failure. This is the equivalent of
3176\samp{\var{list}.reverse()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003177\end{cfuncdesc}
3178
Fred Drakec6fa34e1998-04-02 06:47:24 +00003179\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003180Returns a new tuple object containing the contents of \var{list};
3181equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003182\end{cfuncdesc}
3183
3184
Fred Drakeefd146c1999-02-15 15:30:45 +00003185\section{Mapping Objects \label{mapObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003186
Fred Drake659ebfa2000-04-03 15:42:13 +00003187\obindex{mapping}
3188
3189
Fred Drakeefd146c1999-02-15 15:30:45 +00003190\subsection{Dictionary Objects \label{dictObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003191
Fred Drake659ebfa2000-04-03 15:42:13 +00003192\obindex{dictionary}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003193\begin{ctypedesc}{PyDictObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003194This subtype of \ctype{PyObject} represents a Python dictionary object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003195\end{ctypedesc}
3196
3197\begin{cvardesc}{PyTypeObject}{PyDict_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003198This instance of \ctype{PyTypeObject} represents the Python dictionary
3199type. This is exposed to Python programs as \code{types.DictType} and
3200\code{types.DictionaryType}.
3201\withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003202\end{cvardesc}
3203
3204\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003205Returns true if its argument is a \ctype{PyDictObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003206\end{cfuncdesc}
3207
Fred Drakec6fa34e1998-04-02 06:47:24 +00003208\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003209Returns a new empty dictionary, or \NULL{} on failure.
3210\end{cfuncdesc}
3211
3212\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
3213Empties an existing dictionary of all key-value pairs.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003214\end{cfuncdesc}
3215
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003216\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003217Returns a new dictionary that contains the same key-value pairs as p.
3218Empties an existing dictionary of all key-value pairs.
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003219\end{cfuncdesc}
3220
Fred Drake659ebfa2000-04-03 15:42:13 +00003221\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
3222 PyObject *val}
3223Inserts \var{value} into the dictionary with a key of \var{key}.
3224\var{key} must be hashable; if it isn't, \exception{TypeError} will be
3225raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003226\end{cfuncdesc}
3227
3228\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
3229 char *key,
3230 PyObject *val}
Fred Drakee058b4f1998-02-16 06:15:35 +00003231Inserts \var{value} into the dictionary using \var{key}
Fred Drake1d158692000-06-18 05:21:21 +00003232as a key. \var{key} should be a \ctype{char*}. The key object is
Fred Drakee058b4f1998-02-16 06:15:35 +00003233created using \code{PyString_FromString(\var{key})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003234\ttindex{PyString_FromString()}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003235\end{cfuncdesc}
3236
Fred Drake659ebfa2000-04-03 15:42:13 +00003237\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003238Removes the entry in dictionary \var{p} with key \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003239\var{key} must be hashable; if it isn't, \exception{TypeError} is
3240raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003241\end{cfuncdesc}
3242
Fred Drake659ebfa2000-04-03 15:42:13 +00003243\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003244Removes the entry in dictionary \var{p} which has a key
Fred Drake659ebfa2000-04-03 15:42:13 +00003245specified by the string \var{key}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003246\end{cfuncdesc}
3247
Fred Drake659ebfa2000-04-03 15:42:13 +00003248\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003249Returns the object from dictionary \var{p} which has a key
Guido van Rossum44475131998-04-21 15:30:01 +00003250\var{key}. Returns \NULL{} if the key \var{key} is not present, but
Fred Drake659ebfa2000-04-03 15:42:13 +00003251\emph{without} setting an exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003252\end{cfuncdesc}
3253
Fred Drake659ebfa2000-04-03 15:42:13 +00003254\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
Fred Drakef8830d11998-04-23 14:06:01 +00003255This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
Fred Drake659ebfa2000-04-03 15:42:13 +00003256specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003257\end{cfuncdesc}
3258
Fred Drake659ebfa2000-04-03 15:42:13 +00003259\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003260Returns a \ctype{PyListObject} containing all the items
Guido van Rossum44475131998-04-21 15:30:01 +00003261from the dictionary, as in the dictinoary method \method{items()} (see
Fred Drakebe486461999-11-09 17:03:03 +00003262the \citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003263\end{cfuncdesc}
3264
Fred Drake659ebfa2000-04-03 15:42:13 +00003265\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003266Returns a \ctype{PyListObject} containing all the keys
Guido van Rossum44475131998-04-21 15:30:01 +00003267from the dictionary, as in the dictionary method \method{keys()} (see the
Fred Drakebe486461999-11-09 17:03:03 +00003268\citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003269\end{cfuncdesc}
3270
Fred Drake659ebfa2000-04-03 15:42:13 +00003271\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003272Returns a \ctype{PyListObject} containing all the values
Guido van Rossum44475131998-04-21 15:30:01 +00003273from the dictionary \var{p}, as in the dictionary method
Fred Drakebe486461999-11-09 17:03:03 +00003274\method{values()} (see the \citetitle[../lib/lib.html]{Python Library
3275Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003276\end{cfuncdesc}
3277
Fred Drake659ebfa2000-04-03 15:42:13 +00003278\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
3279Returns the number of items in the dictionary. This is equivalent to
3280\samp{len(\var{p})} on a dictionary.\bifuncindex{len}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003281\end{cfuncdesc}
3282
Fred Drake7d45d342000-08-11 17:07:32 +00003283\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p, int *ppos,
3284 PyObject **pkey, PyObject **pvalue}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003285
3286\end{cfuncdesc}
3287
3288
Fred Drakeefd146c1999-02-15 15:30:45 +00003289\section{Numeric Objects \label{numericObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003290
Fred Drake659ebfa2000-04-03 15:42:13 +00003291\obindex{numeric}
3292
3293
Fred Drakeefd146c1999-02-15 15:30:45 +00003294\subsection{Plain Integer Objects \label{intObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003295
Fred Drake659ebfa2000-04-03 15:42:13 +00003296\obindex{integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003297\begin{ctypedesc}{PyIntObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003298This subtype of \ctype{PyObject} represents a Python integer object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003299\end{ctypedesc}
3300
3301\begin{cvardesc}{PyTypeObject}{PyInt_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003302This instance of \ctype{PyTypeObject} represents the Python plain
Fred Drake659ebfa2000-04-03 15:42:13 +00003303integer type. This is the same object as \code{types.IntType}.
3304\withsubitem{(in modules types)}{\ttindex{IntType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003305\end{cvardesc}
3306
Fred Drake659ebfa2000-04-03 15:42:13 +00003307\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
3308Returns true if \var{o} is of type \cdata{PyInt_Type}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003309\end{cfuncdesc}
3310
Fred Drakec6fa34e1998-04-02 06:47:24 +00003311\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
Fred Drakee058b4f1998-02-16 06:15:35 +00003312Creates a new integer object with a value of \var{ival}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003313
3314The current implementation keeps an array of integer objects for all
Fred Drakee058b4f1998-02-16 06:15:35 +00003315integers between \code{-1} and \code{100}, when you create an int in
3316that range you actually just get back a reference to the existing
3317object. So it should be possible to change the value of \code{1}. I
Fred Drake7e9d3141998-04-03 05:02:28 +00003318suspect the behaviour of Python in this case is undefined. :-)
Fred Drakee5bf8b21998-02-12 21:22:28 +00003319\end{cfuncdesc}
3320
Fred Drakee5bf8b21998-02-12 21:22:28 +00003321\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
Fred Drakef8830d11998-04-23 14:06:01 +00003322Will first attempt to cast the object to a \ctype{PyIntObject}, if
Fred Drakee058b4f1998-02-16 06:15:35 +00003323it is not already one, and then return its value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003324\end{cfuncdesc}
3325
Fred Drake659ebfa2000-04-03 15:42:13 +00003326\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
3327Returns the value of the object \var{io}. No error checking is
3328performed.
3329\end{cfuncdesc}
3330
Fred Drakee5bf8b21998-02-12 21:22:28 +00003331\begin{cfuncdesc}{long}{PyInt_GetMax}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003332Returns the system's idea of the largest integer it can handle
3333(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
3334header files).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003335\end{cfuncdesc}
3336
3337
Fred Drakeefd146c1999-02-15 15:30:45 +00003338\subsection{Long Integer Objects \label{longObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003339
Fred Drake659ebfa2000-04-03 15:42:13 +00003340\obindex{long integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003341\begin{ctypedesc}{PyLongObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003342This subtype of \ctype{PyObject} represents a Python long integer
Fred Drakee058b4f1998-02-16 06:15:35 +00003343object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003344\end{ctypedesc}
3345
3346\begin{cvardesc}{PyTypeObject}{PyLong_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003347This instance of \ctype{PyTypeObject} represents the Python long
Fred Drake659ebfa2000-04-03 15:42:13 +00003348integer type. This is the same object as \code{types.LongType}.
3349\withsubitem{(in modules types)}{\ttindex{LongType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003350\end{cvardesc}
3351
3352\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003353Returns true if its argument is a \ctype{PyLongObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003354\end{cfuncdesc}
3355
Fred Drakec6fa34e1998-04-02 06:47:24 +00003356\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003357Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on
3358failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003359\end{cfuncdesc}
3360
Fred Drakec6fa34e1998-04-02 06:47:24 +00003361\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003362Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
3363long}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003364\end{cfuncdesc}
3365
Fred Drakec6fa34e1998-04-02 06:47:24 +00003366\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003367Returns a new \ctype{PyLongObject} object from the integer part of
3368\var{v}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003369\end{cfuncdesc}
3370
Fred Drakec6fa34e1998-04-02 06:47:24 +00003371\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003372Returns a C \ctype{long} representation of the contents of
3373\var{pylong}. If \var{pylong} is greater than
3374\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is
3375raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003376\end{cfuncdesc}
3377
Fred Drakec6fa34e1998-04-02 06:47:24 +00003378\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003379Returns a C \ctype{unsigned long} representation of the contents of
3380\var{pylong}. If \var{pylong} is greater than
3381\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError}
3382is raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003383\end{cfuncdesc}
3384
Fred Drakec6fa34e1998-04-02 06:47:24 +00003385\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003386Returns a C \ctype{double} representation of the contents of \var{pylong}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003387\end{cfuncdesc}
3388
Fred Drakec6fa34e1998-04-02 06:47:24 +00003389\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
3390 int base}
Fred Drake659ebfa2000-04-03 15:42:13 +00003391Return a new \ctype{PyLongObject} based on the string value in
3392\var{str}, which is interpreted according to the radix in \var{base}.
3393If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first
3394character in \var{str} which follows the representation of the
3395number. If \var{base} is \code{0}, the radix will be determined base
3396on the leading characters of \var{str}: if \var{str} starts with
3397\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts
3398with \code{'0'}, radix 8 will be used; otherwise radix 10 will be
3399used. If \var{base} is not \code{0}, it must be between \code{2} and
3400\code{36}, inclusive. Leading spaces are ignored. If there are no
3401digits, \exception{ValueError} will be raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003402\end{cfuncdesc}
3403
3404
Fred Drakeefd146c1999-02-15 15:30:45 +00003405\subsection{Floating Point Objects \label{floatObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003406
Fred Drake659ebfa2000-04-03 15:42:13 +00003407\obindex{floating point}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003408\begin{ctypedesc}{PyFloatObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003409This subtype of \ctype{PyObject} represents a Python floating point
Fred Drakee058b4f1998-02-16 06:15:35 +00003410object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003411\end{ctypedesc}
3412
3413\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003414This instance of \ctype{PyTypeObject} represents the Python floating
Fred Drake659ebfa2000-04-03 15:42:13 +00003415point type. This is the same object as \code{types.FloatType}.
3416\withsubitem{(in modules types)}{\ttindex{FloatType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003417\end{cvardesc}
3418
3419\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003420Returns true if its argument is a \ctype{PyFloatObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003421\end{cfuncdesc}
3422
Fred Drakec6fa34e1998-04-02 06:47:24 +00003423\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003424Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
3425failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003426\end{cfuncdesc}
3427
Fred Drakec6fa34e1998-04-02 06:47:24 +00003428\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003429Returns a C \ctype{double} representation of the contents of \var{pyfloat}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003430\end{cfuncdesc}
3431
Fred Drakec6fa34e1998-04-02 06:47:24 +00003432\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003433Returns a C \ctype{double} representation of the contents of
Fred Drakef8830d11998-04-23 14:06:01 +00003434\var{pyfloat}, but without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003435\end{cfuncdesc}
3436
3437
Fred Drakeefd146c1999-02-15 15:30:45 +00003438\subsection{Complex Number Objects \label{complexObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003439
Fred Drake659ebfa2000-04-03 15:42:13 +00003440\obindex{complex number}
3441Python's complex number objects are implemented as two distinct types
3442when viewed from the C API: one is the Python object exposed to
3443Python programs, and the other is a C structure which represents the
3444actual complex number value. The API provides functions for working
3445with both.
3446
3447\subsubsection{Complex Numbers as C Structures}
3448
3449Note that the functions which accept these structures as parameters
3450and return them as results do so \emph{by value} rather than
3451dereferencing them through pointers. This is consistent throughout
3452the API.
3453
Fred Drakee5bf8b21998-02-12 21:22:28 +00003454\begin{ctypedesc}{Py_complex}
Fred Drake659ebfa2000-04-03 15:42:13 +00003455The C structure which corresponds to the value portion of a Python
Fred Drake4de05a91998-02-16 14:25:26 +00003456complex number object. Most of the functions for dealing with complex
3457number objects use structures of this type as input or output values,
3458as appropriate. It is defined as:
3459
Fred Drakee058b4f1998-02-16 06:15:35 +00003460\begin{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003461typedef struct {
3462 double real;
3463 double imag;
Fred Drake4de05a91998-02-16 14:25:26 +00003464} Py_complex;
Fred Drakee058b4f1998-02-16 06:15:35 +00003465\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003466\end{ctypedesc}
3467
Fred Drake659ebfa2000-04-03 15:42:13 +00003468\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
3469Return the sum of two complex numbers, using the C
3470\ctype{Py_complex} representation.
3471\end{cfuncdesc}
3472
3473\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
3474Return the difference between two complex numbers, using the C
3475\ctype{Py_complex} representation.
3476\end{cfuncdesc}
3477
3478\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
3479Return the negation of the complex number \var{complex}, using the C
3480\ctype{Py_complex} representation.
3481\end{cfuncdesc}
3482
3483\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
3484Return the product of two complex numbers, using the C
3485\ctype{Py_complex} representation.
3486\end{cfuncdesc}
3487
3488\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
3489 Py_complex divisor}
3490Return the quotient of two complex numbers, using the C
3491\ctype{Py_complex} representation.
3492\end{cfuncdesc}
3493
3494\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
3495Return the exponentiation of \var{num} by \var{exp}, using the C
3496\ctype{Py_complex} representation.
3497\end{cfuncdesc}
3498
3499
3500\subsubsection{Complex Numbers as Python Objects}
3501
Fred Drakee5bf8b21998-02-12 21:22:28 +00003502\begin{ctypedesc}{PyComplexObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003503This subtype of \ctype{PyObject} represents a Python complex number object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003504\end{ctypedesc}
3505
3506\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003507This instance of \ctype{PyTypeObject} represents the Python complex
Fred Drakee5bf8b21998-02-12 21:22:28 +00003508number type.
3509\end{cvardesc}
3510
3511\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003512Returns true if its argument is a \ctype{PyComplexObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003513\end{cfuncdesc}
3514
Fred Drakec6fa34e1998-04-02 06:47:24 +00003515\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003516Create a new Python complex number object from a C
3517\ctype{Py_complex} value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003518\end{cfuncdesc}
3519
Fred Drakec6fa34e1998-04-02 06:47:24 +00003520\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
Fred Drakef8830d11998-04-23 14:06:01 +00003521Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003522\end{cfuncdesc}
3523
3524\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003525Returns the real part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003526\end{cfuncdesc}
3527
3528\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003529Returns the imaginary part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003530\end{cfuncdesc}
3531
3532\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003533Returns the \ctype{Py_complex} value of the complex number \var{op}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003534\end{cfuncdesc}
3535
3536
3537
Fred Drakeefd146c1999-02-15 15:30:45 +00003538\section{Other Objects \label{otherObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003539
Fred Drakeefd146c1999-02-15 15:30:45 +00003540\subsection{File Objects \label{fileObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003541
Fred Drake659ebfa2000-04-03 15:42:13 +00003542\obindex{file}
3543Python's built-in file objects are implemented entirely on the
3544\ctype{FILE*} support from the C standard library. This is an
3545implementation detail and may change in future releases of Python.
3546
Fred Drakee5bf8b21998-02-12 21:22:28 +00003547\begin{ctypedesc}{PyFileObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003548This subtype of \ctype{PyObject} represents a Python file object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003549\end{ctypedesc}
3550
3551\begin{cvardesc}{PyTypeObject}{PyFile_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003552This instance of \ctype{PyTypeObject} represents the Python file
3553type. This is exposed to Python programs as \code{types.FileType}.
3554\withsubitem{(in module types)}{\ttindex{FileType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003555\end{cvardesc}
3556
3557\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003558Returns true if its argument is a \ctype{PyFileObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003559\end{cfuncdesc}
3560
Fred Drake659ebfa2000-04-03 15:42:13 +00003561\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
3562On success, returns a new file object that is opened on the
3563file given by \var{filename}, with a file mode given by \var{mode},
3564where \var{mode} has the same semantics as the standard C routine
3565\cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003566\end{cfuncdesc}
3567
Fred Drakec6fa34e1998-04-02 06:47:24 +00003568\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
Fred Drake659ebfa2000-04-03 15:42:13 +00003569 char *name, char *mode,
3570 int (*close)(FILE*)}
3571Creates a new \ctype{PyFileObject} from the already-open standard C
3572file pointer, \var{fp}. The function \var{close} will be called when
3573the file should be closed. Returns \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003574\end{cfuncdesc}
3575
Fred Drake659ebfa2000-04-03 15:42:13 +00003576\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
3577Returns the file object associated with \var{p} as a \ctype{FILE*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003578\end{cfuncdesc}
3579
Fred Drakec6fa34e1998-04-02 06:47:24 +00003580\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003581Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
3582function reads one line from the object \var{p}. \var{p} may be a
3583file object or any object with a \method{readline()} method. If
3584\var{n} is \code{0}, exactly one line is read, regardless of the
3585length of the line. If \var{n} is greater than \code{0}, no more than
3586\var{n} bytes will be read from the file; a partial line can be
3587returned. In both cases, an empty string is returned if the end of
3588the file is reached immediately. If \var{n} is less than \code{0},
3589however, one line is read regardless of length, but
3590\exception{EOFError} is raised if the end of the file is reached
3591immediately.
3592\withsubitem{(built-in exception)}{\ttindex{EOFError}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003593\end{cfuncdesc}
3594
Fred Drakec6fa34e1998-04-02 06:47:24 +00003595\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003596Returns the name of the file specified by \var{p} as a string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003597\end{cfuncdesc}
3598
3599\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003600Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
3601only. This should only be called immediately after file object
3602creation.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003603\end{cfuncdesc}
3604
Fred Drake659ebfa2000-04-03 15:42:13 +00003605\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
3606This function exists for internal use by the interpreter.
3607Sets the \member{softspace} attribute of \var{p} to \var{newflag} and
3608\withsubitem{(file attribute)}{\ttindex{softspace}}returns the
3609previous value. \var{p} does not have to be a file object
3610for this function to work properly; any object is supported (thought
3611its only interesting if the \member{softspace} attribute can be set).
3612This function clears any errors, and will return \code{0} as the
3613previous value if the attribute either does not exist or if there were
3614errors in retrieving it. There is no way to detect errors from this
3615function, but doing so should not be needed.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003616\end{cfuncdesc}
3617
Fred Drakec6fa34e1998-04-02 06:47:24 +00003618\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
3619 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003620Writes object \var{obj} to file object \var{p}. The only supported
3621flag for \var{flags} is \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW};
3622if given, the \function{str()} of the object is written instead of the
3623\function{repr()}. Returns \code{0} on success or \code{-1} on
3624failure; the appropriate exception will be set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003625\end{cfuncdesc}
3626
Fred Drakec6fa34e1998-04-02 06:47:24 +00003627\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p,
3628 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003629Writes string \var{s} to file object \var{p}. Returns \code{0} on
3630success or \code{-1} on failure; the appropriate exception will be
3631set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003632\end{cfuncdesc}
3633
3634
Fred Drakeefd146c1999-02-15 15:30:45 +00003635\subsection{Module Objects \label{moduleObjects}}
3636
3637\obindex{module}
3638There are only a few functions special to module objects.
3639
Fred Drake659ebfa2000-04-03 15:42:13 +00003640\begin{cvardesc}{PyTypeObject}{PyModule_Type}
3641This instance of \ctype{PyTypeObject} represents the Python module
3642type. This is exposed to Python programs as \code{types.ModuleType}.
3643\withsubitem{(in module types)}{\ttindex{ModuleType}}
3644\end{cvardesc}
3645
3646\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
3647Returns true if its argument is a module object.
Fred Drakeefd146c1999-02-15 15:30:45 +00003648\end{cfuncdesc}
3649
Fred Drake659ebfa2000-04-03 15:42:13 +00003650\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
3651Return a new module object with the \member{__name__} attribute set to
3652\var{name}. Only the module's \member{__doc__} and
3653\member{__name__} attributes are filled in; the caller is responsible
3654for providing a \member{__file__} attribute.
3655\withsubitem{(module attribute)}{
3656 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
3657\end{cfuncdesc}
3658
3659\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003660Return the dictionary object that implements \var{module}'s namespace;
3661this object is the same as the \member{__dict__} attribute of the
3662module object. This function never fails.
Fred Drake659ebfa2000-04-03 15:42:13 +00003663\withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003664\end{cfuncdesc}
3665
Fred Drake659ebfa2000-04-03 15:42:13 +00003666\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003667Return \var{module}'s \member{__name__} value. If the module does not
Fred Drake659ebfa2000-04-03 15:42:13 +00003668provide one, or if it is not a string, \exception{SystemError} is
3669raised and \NULL{} is returned.
3670\withsubitem{(module attribute)}{\ttindex{__name__}}
3671\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003672\end{cfuncdesc}
3673
Fred Drake659ebfa2000-04-03 15:42:13 +00003674\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003675Return the name of the file from which \var{module} was loaded using
3676\var{module}'s \member{__file__} attribute. If this is not defined,
Fred Drake659ebfa2000-04-03 15:42:13 +00003677or if it is not a string, raise \exception{SystemError} and return
3678\NULL.
3679\withsubitem{(module attribute)}{\ttindex{__file__}}
3680\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003681\end{cfuncdesc}
3682
3683
3684\subsection{CObjects \label{cObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003685
Fred Drake659ebfa2000-04-03 15:42:13 +00003686\obindex{CObject}
3687Refer to \emph{Extending and Embedding the Python Interpreter},
3688section 1.12 (``Providing a C API for an Extension Module''), for more
3689information on using these objects.
3690
3691
Guido van Rossum44475131998-04-21 15:30:01 +00003692\begin{ctypedesc}{PyCObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003693This subtype of \ctype{PyObject} represents an opaque value, useful for
Fred Drake659ebfa2000-04-03 15:42:13 +00003694C extension modules who need to pass an opaque value (as a
3695\ctype{void*} pointer) through Python code to other C code. It is
Guido van Rossum44475131998-04-21 15:30:01 +00003696often used to make a C function pointer defined in one module
3697available to other modules, so the regular import mechanism can be
3698used to access C APIs defined in dynamically loaded modules.
3699\end{ctypedesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003700
Fred Drake659ebfa2000-04-03 15:42:13 +00003701\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
3702Returns true if its argument is a \ctype{PyCObject}.
3703\end{cfuncdesc}
3704
3705\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003706 void (*destr)(void *)}
Fred Drake1d158692000-06-18 05:21:21 +00003707Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drakedab44681999-05-13 18:41:14 +00003708\var{destr} function will be called when the object is reclaimed, unless
3709it is \NULL.
Guido van Rossum44475131998-04-21 15:30:01 +00003710\end{cfuncdesc}
3711
Fred Drake659ebfa2000-04-03 15:42:13 +00003712\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003713 void* desc, void (*destr)(void *, void *) }
Fred Drakef8830d11998-04-23 14:06:01 +00003714Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
3715\var{destr} function will be called when the object is reclaimed. The
3716\var{desc} argument can be used to pass extra callback data for the
3717destructor function.
Guido van Rossum44475131998-04-21 15:30:01 +00003718\end{cfuncdesc}
3719
Fred Drake659ebfa2000-04-03 15:42:13 +00003720\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
3721Returns the object \ctype{void *} that the
3722\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003723\end{cfuncdesc}
3724
Fred Drake659ebfa2000-04-03 15:42:13 +00003725\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
3726Returns the description \ctype{void *} that the
3727\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003728\end{cfuncdesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003729
Fred Drake659ebfa2000-04-03 15:42:13 +00003730
Fred Drakeefd146c1999-02-15 15:30:45 +00003731\chapter{Initialization, Finalization, and Threads
3732 \label{initialization}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003733
Guido van Rossum4a944d71997-08-14 20:35:38 +00003734\begin{cfuncdesc}{void}{Py_Initialize}{}
3735Initialize the Python interpreter. In an application embedding
3736Python, this should be called before using any other Python/C API
Fred Drake659ebfa2000-04-03 15:42:13 +00003737functions; with the exception of
3738\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
3739\cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
3740\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
3741and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
3742This initializes the table of loaded modules (\code{sys.modules}), and
3743\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}creates the
3744fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake4de05a91998-02-16 14:25:26 +00003745\module{__main__}\refbimodindex{__main__} and
3746\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drake659ebfa2000-04-03 15:42:13 +00003747search\indexiii{module}{search}{path} path (\code{sys.path}).
3748It does not set \code{sys.argv}; use
3749\cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
3750is a no-op when called for a second time (without calling
3751\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is no
3752return value; it is a fatal error if the initialization fails.
Guido van Rossum42cefd01997-10-05 15:27:29 +00003753\end{cfuncdesc}
3754
3755\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00003756Return true (nonzero) when the Python interpreter has been
Fred Drakee058b4f1998-02-16 06:15:35 +00003757initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
3758called, this returns false until \cfunction{Py_Initialize()} is called
Guido van Rossum42cefd01997-10-05 15:27:29 +00003759again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003760\end{cfuncdesc}
3761
3762\begin{cfuncdesc}{void}{Py_Finalize}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003763Undo all initializations made by \cfunction{Py_Initialize()} and
3764subsequent use of Python/C API functions, and destroy all
3765sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
3766created and not yet destroyed since the last call to
3767\cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
3768by the Python interpreter. This is a no-op when called for a second
3769time (without calling \cfunction{Py_Initialize()} again first). There
3770is no return value; errors during finalization are ignored.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003771
3772This function is provided for a number of reasons. An embedding
3773application might want to restart Python without having to restart the
3774application itself. An application that has loaded the Python
3775interpreter from a dynamically loadable library (or DLL) might want to
3776free all memory allocated by Python before unloading the DLL. During a
3777hunt for memory leaks in an application a developer might want to free
3778all memory allocated by Python before exiting from the application.
3779
Fred Drakee058b4f1998-02-16 06:15:35 +00003780\strong{Bugs and caveats:} The destruction of modules and objects in
Guido van Rossum4a944d71997-08-14 20:35:38 +00003781modules is done in random order; this may cause destructors
Fred Drakee058b4f1998-02-16 06:15:35 +00003782(\method{__del__()} methods) to fail when they depend on other objects
Guido van Rossum4a944d71997-08-14 20:35:38 +00003783(even functions) or modules. Dynamically loaded extension modules
3784loaded by Python are not unloaded. Small amounts of memory allocated
3785by the Python interpreter may not be freed (if you find a leak, please
3786report it). Memory tied up in circular references between objects is
3787not freed. Some memory allocated by extension modules may not be
3788freed. Some extension may not work properly if their initialization
3789routine is called more than once; this can happen if an applcation
Fred Drakee058b4f1998-02-16 06:15:35 +00003790calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
3791than once.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003792\end{cfuncdesc}
3793
Fred Drakec6fa34e1998-04-02 06:47:24 +00003794\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003795Create a new sub-interpreter. This is an (almost) totally separate
3796environment for the execution of Python code. In particular, the new
3797interpreter has separate, independent versions of all imported
3798modules, including the fundamental modules
3799\module{__builtin__}\refbimodindex{__builtin__},
3800\module{__main__}\refbimodindex{__main__} and
3801\module{sys}\refbimodindex{sys}. The table of loaded modules
3802(\code{sys.modules}) and the module search path (\code{sys.path}) are
3803also separate. The new environment has no \code{sys.argv} variable.
3804It has new standard I/O stream file objects \code{sys.stdin},
3805\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drake659ebfa2000-04-03 15:42:13 +00003806same underlying \ctype{FILE} structures in the C library).
3807\withsubitem{(in module sys)}{
3808 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003809
3810The return value points to the first thread state created in the new
3811sub-interpreter. This thread state is made the current thread state.
3812Note that no actual thread is created; see the discussion of thread
3813states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003814\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00003815is stored in the current thread state and there may not be a current
3816thread state. (Like all other Python/C API functions, the global
3817interpreter lock must be held before calling this function and is
3818still held when it returns; however, unlike most other Python/C API
3819functions, there needn't be a current thread state on entry.)
3820
3821Extension modules are shared between (sub-)interpreters as follows:
3822the first time a particular extension is imported, it is initialized
3823normally, and a (shallow) copy of its module's dictionary is
3824squirreled away. When the same extension is imported by another
3825(sub-)interpreter, a new module is initialized and filled with the
Fred Drakee058b4f1998-02-16 06:15:35 +00003826contents of this copy; the extension's \code{init} function is not
3827called. Note that this is different from what happens when an
3828extension is imported after the interpreter has been completely
Fred Drake659ebfa2000-04-03 15:42:13 +00003829re-initialized by calling
3830\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
3831\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
3832the extension's \code{init\var{module}} function \emph{is} called
3833again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003834
Fred Drakee058b4f1998-02-16 06:15:35 +00003835\strong{Bugs and caveats:} Because sub-interpreters (and the main
Guido van Rossum4a944d71997-08-14 20:35:38 +00003836interpreter) are part of the same process, the insulation between them
Fred Drakee058b4f1998-02-16 06:15:35 +00003837isn't perfect --- for example, using low-level file operations like
Fred Drake659ebfa2000-04-03 15:42:13 +00003838\withsubitem{(in module os)}{\ttindex{close()}}
Fred Drakef8830d11998-04-23 14:06:01 +00003839\function{os.close()} they can (accidentally or maliciously) affect each
Guido van Rossum4a944d71997-08-14 20:35:38 +00003840other's open files. Because of the way extensions are shared between
3841(sub-)interpreters, some extensions may not work properly; this is
3842especially likely when the extension makes use of (static) global
3843variables, or when the extension manipulates its module's dictionary
3844after its initialization. It is possible to insert objects created in
3845one sub-interpreter into a namespace of another sub-interpreter; this
3846should be done with great care to avoid sharing user-defined
3847functions, methods, instances or classes between sub-interpreters,
3848since import operations executed by such objects may affect the
3849wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
3850a hard-to-fix bug that will be addressed in a future release.)
3851\end{cfuncdesc}
3852
3853\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
3854Destroy the (sub-)interpreter represented by the given thread state.
3855The given thread state must be the current thread state. See the
3856discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003857thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00003858interpreted are destroyed. (The global interpreter lock must be held
3859before calling this function and is still held when it returns.)
Fred Drake659ebfa2000-04-03 15:42:13 +00003860\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will destroy all
3861sub-interpreters that haven't been explicitly destroyed at that point.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003862\end{cfuncdesc}
3863
3864\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00003865This function should be called before
3866\cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
Guido van Rossum4a944d71997-08-14 20:35:38 +00003867for the first time, if it is called at all. It tells the interpreter
Fred Drake659ebfa2000-04-03 15:42:13 +00003868the value of the \code{argv[0]} argument to the
3869\cfunction{main()}\ttindex{main()} function of the program. This is
3870used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some other
Guido van Rossum4a944d71997-08-14 20:35:38 +00003871functions below to find the Python run-time libraries relative to the
Fred Drakea8455ab2000-06-16 19:58:42 +00003872interpreter executable. The default value is \code{'python'}. The
Guido van Rossum4a944d71997-08-14 20:35:38 +00003873argument should point to a zero-terminated character string in static
3874storage whose contents will not change for the duration of the
3875program's execution. No code in the Python interpreter will change
3876the contents of this storage.
3877\end{cfuncdesc}
3878
Fred Drakec6fa34e1998-04-02 06:47:24 +00003879\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003880Return the program name set with
3881\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
Guido van Rossum4a944d71997-08-14 20:35:38 +00003882default. The returned string points into static storage; the caller
3883should not modify its value.
3884\end{cfuncdesc}
3885
Fred Drakec6fa34e1998-04-02 06:47:24 +00003886\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003887Return the \emph{prefix} for installed platform-independent files. This
Guido van Rossum4a944d71997-08-14 20:35:38 +00003888is derived through a number of complicated rules from the program name
Fred Drakee058b4f1998-02-16 06:15:35 +00003889set with \cfunction{Py_SetProgramName()} and some environment variables;
Fred Drakea8455ab2000-06-16 19:58:42 +00003890for example, if the program name is \code{'/usr/local/bin/python'},
3891the prefix is \code{'/usr/local'}. The returned string points into
Guido van Rossum4a944d71997-08-14 20:35:38 +00003892static storage; the caller should not modify its value. This
Fred Drakec94d9341998-04-12 02:39:13 +00003893corresponds to the \makevar{prefix} variable in the top-level
Fred Drakea8455ab2000-06-16 19:58:42 +00003894\file{Makefile} and the \longprogramopt{prefix} argument to the
Fred Drakee058b4f1998-02-16 06:15:35 +00003895\program{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00003896Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00003897also the next function.
3898\end{cfuncdesc}
3899
Fred Drakec6fa34e1998-04-02 06:47:24 +00003900\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003901Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
Guido van Rossum4a944d71997-08-14 20:35:38 +00003902files. This is derived through a number of complicated rules from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003903program name set with \cfunction{Py_SetProgramName()} and some environment
Guido van Rossum4a944d71997-08-14 20:35:38 +00003904variables; for example, if the program name is
Fred Drakea8455ab2000-06-16 19:58:42 +00003905\code{'/usr/local/bin/python'}, the exec-prefix is
3906\code{'/usr/local'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00003907the caller should not modify its value. This corresponds to the
Fred Drakec94d9341998-04-12 02:39:13 +00003908\makevar{exec_prefix} variable in the top-level \file{Makefile} and the
Fred Drakea8455ab2000-06-16 19:58:42 +00003909\longprogramopt{exec-prefix} argument to the
Fred Drake310ee611999-11-09 17:31:42 +00003910\program{configure} script at build time. The value is available to
3911Python code as \code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003912
3913Background: The exec-prefix differs from the prefix when platform
3914dependent files (such as executables and shared libraries) are
3915installed in a different directory tree. In a typical installation,
3916platform dependent files may be installed in the
Fred Drakea8455ab2000-06-16 19:58:42 +00003917\file{/usr/local/plat} subtree while platform independent may be
3918installed in \file{/usr/local}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003919
3920Generally speaking, a platform is a combination of hardware and
3921software families, e.g. Sparc machines running the Solaris 2.x
3922operating system are considered the same platform, but Intel machines
3923running Solaris 2.x are another platform, and Intel machines running
3924Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00003925operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003926operating systems are a different story; the installation strategies
3927on those systems are so different that the prefix and exec-prefix are
3928meaningless, and set to the empty string. Note that compiled Python
3929bytecode files are platform independent (but not independent from the
3930Python version by which they were compiled!).
3931
Fred Drakee058b4f1998-02-16 06:15:35 +00003932System administrators will know how to configure the \program{mount} or
Fred Drakea8455ab2000-06-16 19:58:42 +00003933\program{automount} programs to share \file{/usr/local} between platforms
3934while having \file{/usr/local/plat} be a different filesystem for each
Guido van Rossum4a944d71997-08-14 20:35:38 +00003935platform.
3936\end{cfuncdesc}
3937
Fred Drakec6fa34e1998-04-02 06:47:24 +00003938\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003939Return the full program name of the Python executable; this is
3940computed as a side-effect of deriving the default module search path
Fred Drake659ebfa2000-04-03 15:42:13 +00003941from the program name (set by
3942\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
3943The returned string points into static storage; the caller should not
Guido van Rossum4a944d71997-08-14 20:35:38 +00003944modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00003945\code{sys.executable}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003946\withsubitem{(in module sys)}{\ttindex{executable}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003947\end{cfuncdesc}
3948
Fred Drakec6fa34e1998-04-02 06:47:24 +00003949\begin{cfuncdesc}{char*}{Py_GetPath}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003950\indexiii{module}{search}{path}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003951Return the default module search path; this is computed from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003952program name (set by \cfunction{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00003953environment variables. The returned string consists of a series of
3954directory names separated by a platform dependent delimiter character.
Fred Drakef8830d11998-04-23 14:06:01 +00003955The delimiter character is \character{:} on \UNIX{}, \character{;} on
Fred Drake659ebfa2000-04-03 15:42:13 +00003956DOS/Windows, and \character{\e n} (the \ASCII{} newline character) on
Fred Drakee5bc4971998-02-12 23:36:49 +00003957Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00003958should not modify its value. The value is available to Python code
Fred Drake659ebfa2000-04-03 15:42:13 +00003959as the list \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}},
3960which may be modified to change the future search path for loaded
3961modules.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003962
3963% XXX should give the exact rules
3964\end{cfuncdesc}
3965
Fred Drakec6fa34e1998-04-02 06:47:24 +00003966\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003967Return the version of this Python interpreter. This is a string that
3968looks something like
3969
Guido van Rossum09270b51997-08-15 18:57:32 +00003970\begin{verbatim}
Fred Drakee058b4f1998-02-16 06:15:35 +00003971"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
Guido van Rossum09270b51997-08-15 18:57:32 +00003972\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003973
3974The first word (up to the first space character) is the current Python
3975version; the first three characters are the major and minor version
3976separated by a period. The returned string points into static storage;
3977the caller should not modify its value. The value is available to
3978Python code as the list \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003979\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003980\end{cfuncdesc}
3981
Fred Drakec6fa34e1998-04-02 06:47:24 +00003982\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00003983Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00003984this is formed from the ``official'' name of the operating system,
3985converted to lower case, followed by the major revision number; e.g.,
3986for Solaris 2.x, which is also known as SunOS 5.x, the value is
Fred Drakea8455ab2000-06-16 19:58:42 +00003987\code{'sunos5'}. On Macintosh, it is \code{'mac'}. On Windows, it
3988is \code{'win'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00003989the caller should not modify its value. The value is available to
3990Python code as \code{sys.platform}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003991\withsubitem{(in module sys)}{\ttindex{platform}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003992\end{cfuncdesc}
3993
Fred Drakec6fa34e1998-04-02 06:47:24 +00003994\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003995Return the official copyright string for the current Python version,
3996for example
3997
Fred Drakea8455ab2000-06-16 19:58:42 +00003998\code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003999
4000The returned string points into static storage; the caller should not
4001modify its value. The value is available to Python code as the list
4002\code{sys.copyright}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004003\withsubitem{(in module sys)}{\ttindex{copyright}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004004\end{cfuncdesc}
4005
Fred Drakec6fa34e1998-04-02 06:47:24 +00004006\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004007Return an indication of the compiler used to build the current Python
Fred Drakee058b4f1998-02-16 06:15:35 +00004008version, in square brackets, for example:
Guido van Rossum4a944d71997-08-14 20:35:38 +00004009
Fred Drakee058b4f1998-02-16 06:15:35 +00004010\begin{verbatim}
4011"[GCC 2.7.2.2]"
4012\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004013
4014The returned string points into static storage; the caller should not
4015modify its value. The value is available to Python code as part of
4016the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004017\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004018\end{cfuncdesc}
4019
Fred Drakec6fa34e1998-04-02 06:47:24 +00004020\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004021Return information about the sequence number and build date and time
4022of the current Python interpreter instance, for example
4023
Guido van Rossum09270b51997-08-15 18:57:32 +00004024\begin{verbatim}
4025"#67, Aug 1 1997, 22:34:28"
4026\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004027
4028The returned string points into static storage; the caller should not
4029modify its value. The value is available to Python code as part of
4030the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004031\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004032\end{cfuncdesc}
4033
4034\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
Fred Drake659ebfa2000-04-03 15:42:13 +00004035Set \code{sys.argv} based on \var{argc} and \var{argv}. These
4036parameters are similar to those passed to the program's
4037\cfunction{main()}\ttindex{main()} function with the difference that
4038the first entry should refer to the script file to be executed rather
4039than the executable hosting the Python interpreter. If there isn't a
4040script that will be run, the first entry in \var{argv} can be an empty
4041string. If this function fails to initialize \code{sys.argv}, a fatal
4042condition is signalled using
4043\cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
4044\withsubitem{(in module sys)}{\ttindex{argv}}
4045% XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
4046% check w/ Guido.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004047\end{cfuncdesc}
4048
4049% XXX Other PySys thingies (doesn't really belong in this chapter)
4050
Fred Drakeefd146c1999-02-15 15:30:45 +00004051\section{Thread State and the Global Interpreter Lock
4052 \label{threads}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004053
Fred Drake659ebfa2000-04-03 15:42:13 +00004054\index{global interpreter lock}
4055\index{interpreter lock}
4056\index{lock, interpreter}
4057
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004058The Python interpreter is not fully thread safe. In order to support
4059multi-threaded Python programs, there's a global lock that must be
4060held by the current thread before it can safely access Python objects.
4061Without the lock, even the simplest operations could cause problems in
Fred Drake7baf3d41998-02-20 00:45:52 +00004062a multi-threaded program: for example, when two threads simultaneously
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004063increment the reference count of the same object, the reference count
4064could end up being incremented only once instead of twice.
4065
4066Therefore, the rule exists that only the thread that has acquired the
4067global interpreter lock may operate on Python objects or call Python/C
4068API functions. In order to support multi-threaded Python programs,
Fred Drake659ebfa2000-04-03 15:42:13 +00004069the interpreter regularly releases and reacquires the lock --- by
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004070default, every ten bytecode instructions (this can be changed with
Fred Drake659ebfa2000-04-03 15:42:13 +00004071\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
Fred Drakee058b4f1998-02-16 06:15:35 +00004072\function{sys.setcheckinterval()}). The lock is also released and
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004073reacquired around potentially blocking I/O operations like reading or
4074writing a file, so that other threads can run while the thread that
4075requests the I/O is waiting for the I/O operation to complete.
4076
4077The Python interpreter needs to keep some bookkeeping information
Fred Drakee058b4f1998-02-16 06:15:35 +00004078separate per thread --- for this it uses a data structure called
Fred Drake659ebfa2000-04-03 15:42:13 +00004079\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
40801.5; in earlier versions, such state was stored in global variables,
4081and switching threads could cause problems. In particular, exception
4082handling is now thread safe, when the application uses
4083\withsubitem{(in module sys)}{\ttindex{exc_info()}}
4084\function{sys.exc_info()} to access the exception last raised in the
4085current thread.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004086
4087There's one global variable left, however: the pointer to the current
Fred Drake659ebfa2000-04-03 15:42:13 +00004088\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
4089thread packages have a way to store ``per-thread global data,''
4090Python's internal platform independent thread abstraction doesn't
4091support this yet. Therefore, the current thread state must be
4092manipulated explicitly.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004093
4094This is easy enough in most cases. Most code manipulating the global
4095interpreter lock has the following simple structure:
4096
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004097\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004098Save the thread state in a local variable.
4099Release the interpreter lock.
4100...Do some blocking I/O operation...
4101Reacquire the interpreter lock.
4102Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004103\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004104
4105This is so common that a pair of macros exists to simplify it:
4106
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004107\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004108Py_BEGIN_ALLOW_THREADS
4109...Do some blocking I/O operation...
4110Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004111\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004112
Fred Drake659ebfa2000-04-03 15:42:13 +00004113The \code{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS} macro
4114opens a new block and declares a hidden local variable; the
4115\code{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS} macro closes
Fred Drakee058b4f1998-02-16 06:15:35 +00004116the block. Another advantage of using these two macros is that when
4117Python is compiled without thread support, they are defined empty,
4118thus saving the thread state and lock manipulations.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004119
4120When thread support is enabled, the block above expands to the
4121following code:
4122
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004123\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004124 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004125
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004126 _save = PyEval_SaveThread();
4127 ...Do some blocking I/O operation...
4128 PyEval_RestoreThread(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004129\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004130
4131Using even lower level primitives, we can get roughly the same effect
4132as follows:
4133
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004134\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004135 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004136
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004137 _save = PyThreadState_Swap(NULL);
4138 PyEval_ReleaseLock();
4139 ...Do some blocking I/O operation...
4140 PyEval_AcquireLock();
4141 PyThreadState_Swap(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004142\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004143
4144There are some subtle differences; in particular,
Fred Drake659ebfa2000-04-03 15:42:13 +00004145\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
4146and restores the value of the global variable
4147\cdata{errno}\ttindex{errno}, since the lock manipulation does not
Fred Drakef8830d11998-04-23 14:06:01 +00004148guarantee that \cdata{errno} is left alone. Also, when thread support
Fred Drake659ebfa2000-04-03 15:42:13 +00004149is disabled,
4150\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
Fred Drakee058b4f1998-02-16 06:15:35 +00004151\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
Fred Drake659ebfa2000-04-03 15:42:13 +00004152case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
4153\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
4154available. This is done so that dynamically loaded extensions
4155compiled with thread support enabled can be loaded by an interpreter
4156that was compiled with disabled thread support.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004157
4158The global interpreter lock is used to protect the pointer to the
4159current thread state. When releasing the lock and saving the thread
4160state, the current thread state pointer must be retrieved before the
4161lock is released (since another thread could immediately acquire the
4162lock and store its own thread state in the global variable).
4163Reversely, when acquiring the lock and restoring the thread state, the
4164lock must be acquired before storing the thread state pointer.
4165
4166Why am I going on with so much detail about this? Because when
Fred Drake659ebfa2000-04-03 15:42:13 +00004167threads are created from C, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004168lock, nor is there a thread state data structure for them. Such
4169threads must bootstrap themselves into existence, by first creating a
4170thread state data structure, then acquiring the lock, and finally
4171storing their thread state pointer, before they can start using the
4172Python/C API. When they are done, they should reset the thread state
4173pointer, release the lock, and finally free their thread state data
4174structure.
4175
4176When creating a thread data structure, you need to provide an
4177interpreter state data structure. The interpreter state data
4178structure hold global data that is shared by all threads in an
4179interpreter, for example the module administration
4180(\code{sys.modules}). Depending on your needs, you can either create
4181a new interpreter state data structure, or share the interpreter state
4182data structure used by the Python main thread (to access the latter,
Fred Drakef8830d11998-04-23 14:06:01 +00004183you must obtain the thread state and access its \member{interp} member;
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004184this must be done by a thread that is created by Python or by the main
4185thread after Python is initialized).
4186
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004187
4188\begin{ctypedesc}{PyInterpreterState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004189This data structure represents the state shared by a number of
4190cooperating threads. Threads belonging to the same interpreter
4191share their module administration and a few other internal items.
4192There are no public members in this structure.
4193
4194Threads belonging to different interpreters initially share nothing,
4195except process state like available memory, open file descriptors and
4196such. The global interpreter lock is also shared by all threads,
4197regardless of to which interpreter they belong.
4198\end{ctypedesc}
4199
4200\begin{ctypedesc}{PyThreadState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004201This data structure represents the state of a single thread. The only
Fred Drakef8830d11998-04-23 14:06:01 +00004202public data member is \ctype{PyInterpreterState *}\member{interp},
4203which points to this thread's interpreter state.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004204\end{ctypedesc}
4205
4206\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
4207Initialize and acquire the global interpreter lock. It should be
4208called in the main thread before creating a second thread or engaging
Fred Drakee058b4f1998-02-16 06:15:35 +00004209in any other thread operations such as
Fred Drake659ebfa2000-04-03 15:42:13 +00004210\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
4211\code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
4212It is not needed before calling
4213\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
4214\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004215
4216This is a no-op when called for a second time. It is safe to call
Fred Drake659ebfa2000-04-03 15:42:13 +00004217this function before calling
4218\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004219
4220When only the main thread exists, no lock operations are needed. This
4221is a common situation (most Python programs do not use threads), and
4222the lock operations slow the interpreter down a bit. Therefore, the
4223lock is not created initially. This situation is equivalent to having
4224acquired the lock: when there is only a single thread, all object
4225accesses are safe. Therefore, when this function initializes the
Fred Drake4de05a91998-02-16 14:25:26 +00004226lock, it also acquires it. Before the Python
4227\module{thread}\refbimodindex{thread} module creates a new thread,
4228knowing that either it has the lock or the lock hasn't been created
4229yet, it calls \cfunction{PyEval_InitThreads()}. When this call
4230returns, it is guaranteed that the lock has been created and that it
4231has acquired it.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004232
4233It is \strong{not} safe to call this function when it is unknown which
4234thread (if any) currently has the global interpreter lock.
4235
4236This function is not available when thread support is disabled at
4237compile time.
4238\end{cfuncdesc}
4239
Guido van Rossum4a944d71997-08-14 20:35:38 +00004240\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004241Acquire the global interpreter lock. The lock must have been created
4242earlier. If this thread already has the lock, a deadlock ensues.
4243This function is not available when thread support is disabled at
4244compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004245\end{cfuncdesc}
4246
4247\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004248Release the global interpreter lock. The lock must have been created
4249earlier. This function is not available when thread support is
Fred Drakee058b4f1998-02-16 06:15:35 +00004250disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004251\end{cfuncdesc}
4252
4253\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004254Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004255state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004256have been created earlier. If this thread already has the lock,
4257deadlock ensues. This function is not available when thread support
Fred Drakee058b4f1998-02-16 06:15:35 +00004258is disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004259\end{cfuncdesc}
4260
4261\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004262Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004263interpreter lock. The lock must have been created earlier and must be
4264held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004265be \NULL{}, is only used to check that it represents the current
Fred Drakee058b4f1998-02-16 06:15:35 +00004266thread state --- if it isn't, a fatal error is reported. This
4267function is not available when thread support is disabled at compile
4268time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004269\end{cfuncdesc}
4270
Fred Drakec6fa34e1998-04-02 06:47:24 +00004271\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004272Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004273support is enabled) and reset the thread state to \NULL{},
4274returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004275the lock has been created, the current thread must have acquired it.
4276(This function is available even when thread support is disabled at
4277compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004278\end{cfuncdesc}
4279
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004280\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004281Acquire the interpreter lock (if it has been created and thread
4282support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004283must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004284thread must not have acquired it, otherwise deadlock ensues. (This
4285function is available even when thread support is disabled at compile
4286time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004287\end{cfuncdesc}
4288
Fred Drake659ebfa2000-04-03 15:42:13 +00004289The following macros are normally used without a trailing semicolon;
4290look for example usage in the Python source distribution.
4291
4292\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004293This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004294\samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004295Note that it contains an opening brace; it must be matched with a
4296following \code{Py_END_ALLOW_THREADS} macro. See above for further
4297discussion of this macro. It is a no-op when thread support is
4298disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004299\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004300
Fred Drake659ebfa2000-04-03 15:42:13 +00004301\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004302This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004303\samp{PyEval_RestoreThread(_save); \}}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004304Note that it contains a closing brace; it must be matched with an
4305earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
4306discussion of this macro. It is a no-op when thread support is
4307disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004308\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004309
Fred Drake659ebfa2000-04-03 15:42:13 +00004310\begin{csimplemacrodesc}{Py_BEGIN_BLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004311This macro expands to \samp{PyEval_RestoreThread(_save);} i.e. it
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004312is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
4313brace. It is a no-op when thread support is disabled at compile
4314time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004315\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004316
Fred Drake659ebfa2000-04-03 15:42:13 +00004317\begin{csimplemacrodesc}{Py_BEGIN_UNBLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004318This macro expands to \samp{_save = PyEval_SaveThread();} i.e. it is
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004319equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
4320and variable declaration. It is a no-op when thread support is
4321disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004322\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004323
4324All of the following functions are only available when thread support
4325is enabled at compile time, and must be called only when the
Fred Drake9d20ac31998-02-16 15:27:08 +00004326interpreter lock has been created.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004327
Fred Drakec6fa34e1998-04-02 06:47:24 +00004328\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004329Create a new interpreter state object. The interpreter lock need not
4330be held, but may be held if it is necessary to serialize calls to this
4331function.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004332\end{cfuncdesc}
4333
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004334\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
4335Reset all information in an interpreter state object. The interpreter
4336lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004337\end{cfuncdesc}
4338
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004339\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
4340Destroy an interpreter state object. The interpreter lock need not be
4341held. The interpreter state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004342call to \cfunction{PyInterpreterState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004343\end{cfuncdesc}
4344
Fred Drakec6fa34e1998-04-02 06:47:24 +00004345\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004346Create a new thread state object belonging to the given interpreter
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004347object. The interpreter lock need not be held, but may be held if it
4348is necessary to serialize calls to this function.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004349\end{cfuncdesc}
4350
4351\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
4352Reset all information in a thread state object. The interpreter lock
4353must be held.
4354\end{cfuncdesc}
4355
4356\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
4357Destroy a thread state object. The interpreter lock need not be
4358held. The thread state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004359call to \cfunction{PyThreadState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004360\end{cfuncdesc}
4361
Fred Drakec6fa34e1998-04-02 06:47:24 +00004362\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004363Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004364When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004365error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004366\end{cfuncdesc}
4367
Fred Drakec6fa34e1998-04-02 06:47:24 +00004368\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004369Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004370argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004371must be held.
4372\end{cfuncdesc}
4373
4374
Fred Drake659ebfa2000-04-03 15:42:13 +00004375\chapter{Memory Management \label{memory}}
4376\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
4377
4378
4379\section{Overview \label{memoryOverview}}
4380
4381Memory management in Python involves a private heap containing all
4382Python objects and data structures. The management of this private
4383heap is ensured internally by the \emph{Python memory manager}. The
4384Python memory manager has different components which deal with various
4385dynamic storage management aspects, like sharing, segmentation,
4386preallocation or caching.
4387
4388At the lowest level, a raw memory allocator ensures that there is
4389enough room in the private heap for storing all Python-related data
4390by interacting with the memory manager of the operating system. On top
4391of the raw memory allocator, several object-specific allocators
4392operate on the same heap and implement distinct memory management
4393policies adapted to the peculiarities of every object type. For
4394example, integer objects are managed differently within the heap than
4395strings, tuples or dictionaries because integers imply different
4396storage requirements and speed/space tradeoffs. The Python memory
4397manager thus delegates some of the work to the object-specific
4398allocators, but ensures that the latter operate within the bounds of
4399the private heap.
4400
4401It is important to understand that the management of the Python heap
4402is performed by the interpreter itself and that the user has no
4403control on it, even if she regularly manipulates object pointers to
4404memory blocks inside that heap. The allocation of heap space for
4405Python objects and other internal buffers is performed on demand by
4406the Python memory manager through the Python/C API functions listed in
4407this document.
4408
4409To avoid memory corruption, extension writers should never try to
4410operate on Python objects with the functions exported by the C
4411library: \cfunction{malloc()}\ttindex{malloc()},
4412\cfunction{calloc()}\ttindex{calloc()},
4413\cfunction{realloc()}\ttindex{realloc()} and
4414\cfunction{free()}\ttindex{free()}. This will result in
4415mixed calls between the C allocator and the Python memory manager
4416with fatal consequences, because they implement different algorithms
4417and operate on different heaps. However, one may safely allocate and
4418release memory blocks with the C library allocator for individual
4419purposes, as shown in the following example:
4420
4421\begin{verbatim}
4422 PyObject *res;
4423 char *buf = (char *) malloc(BUFSIZ); /* for I/O */
4424
4425 if (buf == NULL)
4426 return PyErr_NoMemory();
4427 ...Do some I/O operation involving buf...
4428 res = PyString_FromString(buf);
4429 free(buf); /* malloc'ed */
4430 return res;
4431\end{verbatim}
4432
4433In this example, the memory request for the I/O buffer is handled by
4434the C library allocator. The Python memory manager is involved only
4435in the allocation of the string object returned as a result.
4436
4437In most situations, however, it is recommended to allocate memory from
4438the Python heap specifically because the latter is under control of
4439the Python memory manager. For example, this is required when the
4440interpreter is extended with new object types written in C. Another
4441reason for using the Python heap is the desire to \emph{inform} the
4442Python memory manager about the memory needs of the extension module.
4443Even when the requested memory is used exclusively for internal,
4444highly-specific purposes, delegating all memory requests to the Python
4445memory manager causes the interpreter to have a more accurate image of
4446its memory footprint as a whole. Consequently, under certain
4447circumstances, the Python memory manager may or may not trigger
4448appropriate actions, like garbage collection, memory compaction or
4449other preventive procedures. Note that by using the C library
4450allocator as shown in the previous example, the allocated memory for
4451the I/O buffer escapes completely the Python memory manager.
4452
4453
4454\section{Memory Interface \label{memoryInterface}}
4455
4456The following function sets, modeled after the ANSI C standard, are
4457available for allocating and releasing memory from the Python heap:
4458
4459
Fred Drake7d45d342000-08-11 17:07:32 +00004460\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
4461Allocates \var{n} bytes and returns a pointer of type \ctype{void*} to
Fred Drake659ebfa2000-04-03 15:42:13 +00004462the allocated memory, or \NULL{} if the request fails. Requesting zero
4463bytes returns a non-\NULL{} pointer.
4464\end{cfuncdesc}
4465
Fred Drake7d45d342000-08-11 17:07:32 +00004466\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004467Resizes the memory block pointed to by \var{p} to \var{n} bytes. The
4468contents will be unchanged to the minimum of the old and the new
4469sizes. If \var{p} is \NULL{}, the call is equivalent to
4470\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the memory block
4471is resized but is not freed, and the returned pointer is non-\NULL{}.
4472Unless \var{p} is \NULL{}, it must have been returned by a previous
4473call to \cfunction{PyMem_Malloc()} or \cfunction{PyMem_Realloc()}.
4474\end{cfuncdesc}
4475
Fred Drake7d45d342000-08-11 17:07:32 +00004476\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004477Frees the memory block pointed to by \var{p}, which must have been
4478returned by a previous call to \cfunction{PyMem_Malloc()} or
4479\cfunction{PyMem_Realloc()}. Otherwise, or if
4480\cfunction{PyMem_Free(p)} has been called before, undefined behaviour
4481occurs. If \var{p} is \NULL{}, no operation is performed.
4482\end{cfuncdesc}
4483
Fred Drake659ebfa2000-04-03 15:42:13 +00004484The following type-oriented macros are provided for convenience. Note
4485that \var{TYPE} refers to any C type.
4486
Fred Drakef913e542000-09-12 20:17:17 +00004487\begin{cfuncdesc}{\var{TYPE}*}{PyMem_New}{TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004488Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
4489sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
4490\ctype{\var{TYPE}*}.
4491\end{cfuncdesc}
4492
Fred Drakef913e542000-09-12 20:17:17 +00004493\begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004494Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
4495to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
4496cast to \ctype{\var{TYPE}*}.
4497\end{cfuncdesc}
4498
Fred Drakef913e542000-09-12 20:17:17 +00004499\begin{cfuncdesc}{void}{PyMem_Del}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004500Same as \cfunction{PyMem_Free()}.
4501\end{cfuncdesc}
4502
Fred Drakef913e542000-09-12 20:17:17 +00004503In addition, the following macro sets are provided for calling the
4504Python memory allocator directly, without involving the C API functions
4505listed above. However, note that their use does not preserve binary
4506compatibility accross Python versions and is therefore deprecated in
4507extension modules.
4508
4509\cfunction{PyMem_MALLOC()}, \cfunction{PyMem_REALLOC()}, \cfunction{PyMem_FREE()}.
4510
4511\cfunction{PyMem_NEW()}, \cfunction{PyMem_RESIZE()}, \cfunction{PyMem_DEL()}.
4512
Fred Drake659ebfa2000-04-03 15:42:13 +00004513
4514\section{Examples \label{memoryExamples}}
4515
4516Here is the example from section \ref{memoryOverview}, rewritten so
4517that the I/O buffer is allocated from the Python heap by using the
4518first function set:
4519
4520\begin{verbatim}
4521 PyObject *res;
4522 char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
4523
4524 if (buf == NULL)
4525 return PyErr_NoMemory();
4526 /* ...Do some I/O operation involving buf... */
4527 res = PyString_FromString(buf);
4528 PyMem_Free(buf); /* allocated with PyMem_Malloc */
4529 return res;
4530\end{verbatim}
4531
Fred Drakef913e542000-09-12 20:17:17 +00004532The same code using the type-oriented function set:
Fred Drake659ebfa2000-04-03 15:42:13 +00004533
4534\begin{verbatim}
4535 PyObject *res;
Fred Drakef913e542000-09-12 20:17:17 +00004536 char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
Fred Drake659ebfa2000-04-03 15:42:13 +00004537
4538 if (buf == NULL)
4539 return PyErr_NoMemory();
4540 /* ...Do some I/O operation involving buf... */
4541 res = PyString_FromString(buf);
Fred Drakef913e542000-09-12 20:17:17 +00004542 PyMem_Del(buf); /* allocated with PyMem_New */
Fred Drake659ebfa2000-04-03 15:42:13 +00004543 return res;
4544\end{verbatim}
4545
Fred Drakef913e542000-09-12 20:17:17 +00004546Note that in the two examples above, the buffer is always
4547manipulated via functions belonging to the same set. Indeed, it
Fred Drake659ebfa2000-04-03 15:42:13 +00004548is required to use the same memory API family for a given
4549memory block, so that the risk of mixing different allocators is
4550reduced to a minimum. The following code sequence contains two errors,
4551one of which is labeled as \emph{fatal} because it mixes two different
4552allocators operating on different heaps.
4553
4554\begin{verbatim}
Fred Drakef913e542000-09-12 20:17:17 +00004555char *buf1 = PyMem_New(char, BUFSIZ);
Fred Drake659ebfa2000-04-03 15:42:13 +00004556char *buf2 = (char *) malloc(BUFSIZ);
4557char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
4558...
Fred Drakef913e542000-09-12 20:17:17 +00004559PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004560free(buf2); /* Right -- allocated via malloc() */
Fred Drakef913e542000-09-12 20:17:17 +00004561free(buf1); /* Fatal -- should be PyMem_Del() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004562\end{verbatim}
4563
4564In addition to the functions aimed at handling raw memory blocks from
4565the Python heap, objects in Python are allocated and released with
Fred Drakef913e542000-09-12 20:17:17 +00004566\cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()} and
4567\cfunction{PyObject_Del()}, or with their corresponding macros
4568\cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()} and
Fred Drakee06f0f92000-06-30 15:52:39 +00004569\cfunction{PyObject_DEL()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004570
Fred Drakee06f0f92000-06-30 15:52:39 +00004571These will be explained in the next chapter on defining and
4572implementing new object types in C.
Fred Drake659ebfa2000-04-03 15:42:13 +00004573
4574
Fred Drakeefd146c1999-02-15 15:30:45 +00004575\chapter{Defining New Object Types \label{newTypes}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004576
Fred Drakec6fa34e1998-04-02 06:47:24 +00004577\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00004578\end{cfuncdesc}
4579
Fred Drakef913e542000-09-12 20:17:17 +00004580\begin{cfuncdesc}{PyVarObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00004581\end{cfuncdesc}
4582
Fred Drakef913e542000-09-12 20:17:17 +00004583\begin{cfuncdesc}{void}{_PyObject_Del}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004584\end{cfuncdesc}
4585
Fred Drakef913e542000-09-12 20:17:17 +00004586\begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op,
4587 PyTypeObject *type}
4588\end{cfuncdesc}
4589
4590\begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op,
4591 PyTypeObject *type, int size}
4592\end{cfuncdesc}
4593
4594\begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type}
4595\end{cfuncdesc}
4596
4597\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type,
4598 int size}
4599\end{cfuncdesc}
4600
4601\begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op}
4602\end{cfuncdesc}
4603
4604\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW}{TYPE, PyTypeObject *type}
4605\end{cfuncdesc}
4606
4607\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
4608 int size}
4609\end{cfuncdesc}
4610
4611\begin{cfuncdesc}{void}{PyObject_DEL}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004612\end{cfuncdesc}
4613
Guido van Rossum3c4378b1998-04-14 20:21:10 +00004614Py_InitModule (!!!)
4615
4616PyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse
4617
4618Py_BuildValue
Guido van Rossumae110af1997-05-22 20:11:52 +00004619
Fred Drake659ebfa2000-04-03 15:42:13 +00004620DL_IMPORT
4621
4622Py*_Check
4623
4624_Py_NoneStruct
4625
4626
4627\section{Common Object Structures \label{common-structs}}
4628
Guido van Rossumae110af1997-05-22 20:11:52 +00004629PyObject, PyVarObject
4630
4631PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
4632
4633Typedefs:
4634unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
4635intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
Guido van Rossumae110af1997-05-22 20:11:52 +00004636destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
4637setattrofunc, cmpfunc, reprfunc, hashfunc
4638
Fred Drakea8455ab2000-06-16 19:58:42 +00004639\begin{ctypedesc}{PyCFunction}
4640Type of the functions used to implement most Python callables in C.
4641\end{ctypedesc}
4642
4643\begin{ctypedesc}{PyMethodDef}
4644Structure used to describe a method of an extension type. This
4645structure has four fields:
4646
4647\begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
4648 \lineiii{ml_name}{char *}{name of the method}
4649 \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
4650 \lineiii{ml_flags}{int}{flag bits indicating how the call should be
4651 constructed}
4652 \lineiii{ml_doc}{char *}{points to the contents of the docstring}
4653\end{tableiii}
4654\end{ctypedesc}
4655
4656\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef[] table,
4657 PyObject *ob, char *name}
4658Return a bound method object for an extension type implemented in C.
4659This function also handles the special attribute \member{__methods__},
4660returning a list of all the method names defined in \var{table}.
4661\end{cfuncdesc}
4662
Fred Drake659ebfa2000-04-03 15:42:13 +00004663
4664\section{Mapping Object Structures \label{mapping-structs}}
4665
4666\begin{ctypedesc}{PyMappingMethods}
4667Structure used to hold pointers to the functions used to implement the
4668mapping protocol for an extension type.
4669\end{ctypedesc}
4670
4671
4672\section{Number Object Structures \label{number-structs}}
4673
4674\begin{ctypedesc}{PyNumberMethods}
4675Structure used to hold pointers to the functions an extension type
4676uses to implement the number protocol.
4677\end{ctypedesc}
4678
4679
4680\section{Sequence Object Structures \label{sequence-structs}}
4681
4682\begin{ctypedesc}{PySequenceMethods}
4683Structure used to hold pointers to the functions which an object uses
4684to implement the sequence protocol.
4685\end{ctypedesc}
4686
4687
4688\section{Buffer Object Structures \label{buffer-structs}}
4689\sectionauthor{Greg J. Stein}{greg@lyra.org}
4690
4691The buffer interface exports a model where an object can expose its
4692internal data as a set of chunks of data, where each chunk is
4693specified as a pointer/length pair. These chunks are called
4694\dfn{segments} and are presumed to be non-contiguous in memory.
4695
4696If an object does not export the buffer interface, then its
4697\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
4698should be \NULL{}. Otherwise, the \member{tp_as_buffer} will point to
4699a \ctype{PyBufferProcs} structure.
4700
4701\strong{Note:} It is very important that your
4702\ctype{PyTypeObject} structure uses \code{Py_TPFLAGS_DEFAULT} for the
4703value of the \member{tp_flags} member rather than \code{0}. This
4704tells the Python runtime that your \ctype{PyBufferProcs} structure
4705contains the \member{bf_getcharbuffer} slot. Older versions of Python
4706did not have this member, so a new Python interpreter using an old
4707extension needs to be able to test for its presence before using it.
4708
4709\begin{ctypedesc}{PyBufferProcs}
4710Structure used to hold the function pointers which define an
4711implementation of the buffer protocol.
4712
4713The first slot is \member{bf_getreadbuffer}, of type
4714\ctype{getreadbufferproc}. If this slot is \NULL{}, then the object
4715does not support reading from the internal data. This is
4716non-sensical, so implementors should fill this in, but callers should
4717test that the slot contains a non-\NULL{} value.
4718
4719The next slot is \member{bf_getwritebuffer} having type
4720\ctype{getwritebufferproc}. This slot may be \NULL{} if the object
4721does not allow writing into its returned buffers.
4722
4723The third slot is \member{bf_getsegcount}, with type
4724\ctype{getsegcountproc}. This slot must not be \NULL{} and is used to
4725inform the caller how many segments the object contains. Simple
4726objects such as \ctype{PyString_Type} and
4727\ctype{PyBuffer_Type} objects contain a single segment.
4728
4729The last slot is \member{bf_getcharbuffer}, of type
4730\ctype{getcharbufferproc}. This slot will only be present if the
4731\code{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
4732\member{tp_flags} field of the object's \ctype{PyTypeObject}. Before using
4733this slot, the caller should test whether it is present by using the
4734\cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()} function.
4735If present, it may be \NULL, indicating that the object's contents
4736cannot be used as \emph{8-bit characters}.
4737The slot function may also raise an error if the object's contents
4738cannot be interpreted as 8-bit characters. For example, if the object
4739is an array which is configured to hold floating point values, an
4740exception may be raised if a caller attempts to use
4741\member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
4742This notion of exporting the internal buffers as ``text'' is used to
4743distinguish between objects that are binary in nature, and those which
4744have character-based content.
4745
4746\strong{Note:} The current policy seems to state that these characters
4747may be multi-byte characters. This implies that a buffer size of
4748\var{N} does not mean there are \var{N} characters present.
4749\end{ctypedesc}
4750
4751\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
4752Flag bit set in the type structure to indicate that the
4753\member{bf_getcharbuffer} slot is known. This being set does not
4754indicate that the object supports the buffer interface or that the
4755\member{bf_getcharbuffer} slot is non-\NULL.
4756\end{datadesc}
4757
4758\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
4759 (PyObject *self, int segment, void **ptrptr)}
4760Return a pointer to a readable segment of the buffer. This function
4761is allowed to raise an exception, in which case it must return
4762\code{-1}. The \var{segment} which is passed must be zero or
4763positive, and strictly less than the number of segments returned by
4764the \member{bf_getsegcount} slot function. On success, returns
4765\code{0} and sets \code{*\var{ptrptr}} to a pointer to the buffer
4766memory.
4767\end{ctypedesc}
4768
4769\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
4770 (PyObject *self, int segment, void **ptrptr)}
Fred Drake58c5a2a1999-08-04 13:13:24 +00004771Return a pointer to a writable memory buffer in \code{*\var{ptrptr}};
4772the memory buffer must correspond to buffer segment \var{segment}.
4773Must return \code{-1} and set an exception on error.
4774\exception{TypeError} should be raised if the object only supports
4775read-only buffers, and \exception{SystemError} should be raised when
4776\var{segment} specifies a segment that doesn't exist.
4777% Why doesn't it raise ValueError for this one?
Fred Drake659ebfa2000-04-03 15:42:13 +00004778% GJS: because you shouldn't be calling it with an invalid
4779% segment. That indicates a blatant programming error in the C
4780% code.
Fred Drake58c5a2a1999-08-04 13:13:24 +00004781\end{ctypedesc}
4782
Fred Drake659ebfa2000-04-03 15:42:13 +00004783\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
4784 (PyObject *self, int *lenp)}
4785Return the number of memory segments which comprise the buffer. If
4786\var{lenp} is not \NULL, the implementation must report the sum of the
4787sizes (in bytes) of all segments in \code{*\var{lenp}}.
4788The function cannot fail.
4789\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004790
Fred Drake659ebfa2000-04-03 15:42:13 +00004791\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
4792 (PyObject *self, int segment, const char **ptrptr)}
4793\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004794
Guido van Rossumae110af1997-05-22 20:11:52 +00004795
Fred Drake659ebfa2000-04-03 15:42:13 +00004796% \chapter{Debugging \label{debugging}}
4797%
4798% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004799
4800
Fred Drakeed773ef2000-09-21 21:35:22 +00004801\appendix
4802\chapter{Reporting Bugs}
4803\input{reportingbugs}
4804
Fred Drakef3aa0e01998-03-17 06:23:13 +00004805\input{api.ind} % Index -- must be last
Guido van Rossum9231c8f1997-05-15 21:43:21 +00004806
4807\end{document}