blob: d9e7feae1ac5e39ac3e4bea6c498f23d3911eea9 [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
105\samp{\#include <python1.5/Python.h>}; this will break on
106multi-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
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000213Conversely, when calling a 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 Drake2de75ec1998-04-09 14:12:11 +0000553\file{lib/python1.5} (replacing \file{1.5} with the current
Guido van Rossum42cefd01997-10-05 15:27:29 +0000554interpreter version) relative to the parent directory where the
Fred Drakee058b4f1998-02-16 06:15:35 +0000555executable named \file{python} is found on the shell command search
Fred Drakec6fa34e1998-04-02 06:47:24 +0000556path (the environment variable \envvar{PATH}).
Guido van Rossum42cefd01997-10-05 15:27:29 +0000557
558For instance, if the Python executable is found in
Fred Drakee058b4f1998-02-16 06:15:35 +0000559\file{/usr/local/bin/python}, it will assume that the libraries are in
Fred Drake2de75ec1998-04-09 14:12:11 +0000560\file{/usr/local/lib/python1.5}. (In fact, this particular path
Fred Drakee058b4f1998-02-16 06:15:35 +0000561is also the ``fallback'' location, used when no executable file named
Fred Drakec6fa34e1998-04-02 06:47:24 +0000562\file{python} is found along \envvar{PATH}.) The user can override
563this behavior by setting the environment variable \envvar{PYTHONHOME},
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000564or insert additional directories in front of the standard path by
Fred Drakec6fa34e1998-04-02 06:47:24 +0000565setting \envvar{PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000566
Guido van Rossum4a944d71997-08-14 20:35:38 +0000567The embedding application can steer the search by calling
Fred Drake659ebfa2000-04-03 15:42:13 +0000568\code{Py_SetProgramName(\var{file})}\ttindex{Py_SetProgramName()} \emph{before} calling
Fred Drakec6fa34e1998-04-02 06:47:24 +0000569\cfunction{Py_Initialize()}. Note that \envvar{PYTHONHOME} still
570overrides this and \envvar{PYTHONPATH} is still inserted in front of
Fred Drakee058b4f1998-02-16 06:15:35 +0000571the standard path. An application that requires total control has to
Fred Drake659ebfa2000-04-03 15:42:13 +0000572provide its own implementation of
573\cfunction{Py_GetPath()}\ttindex{Py_GetPath()},
574\cfunction{Py_GetPrefix()}\ttindex{Py_GetPrefix()},
575\cfunction{Py_GetExecPrefix()}\ttindex{Py_GetExecPrefix()}, and
576\cfunction{Py_GetProgramFullPath()}\ttindex{Py_GetProgramFullPath()} (all
577defined in \file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000578
Guido van Rossum4a944d71997-08-14 20:35:38 +0000579Sometimes, it is desirable to ``uninitialize'' Python. For instance,
580the application may want to start over (make another call to
Fred Drakee058b4f1998-02-16 06:15:35 +0000581\cfunction{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000582use of Python and wants to free all memory allocated by Python. This
Fred Drakee058b4f1998-02-16 06:15:35 +0000583can be accomplished by calling \cfunction{Py_Finalize()}. The function
Fred Drake659ebfa2000-04-03 15:42:13 +0000584\cfunction{Py_IsInitialized()}\ttindex{Py_IsInitialized()} returns
585true if Python is currently in the initialized state. More
586information about these functions is given in a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000587
Guido van Rossum4a944d71997-08-14 20:35:38 +0000588
Fred Drakeefd146c1999-02-15 15:30:45 +0000589\chapter{The Very High Level Layer \label{veryhigh}}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000590
Fred Drakee5bf8b21998-02-12 21:22:28 +0000591The functions in this chapter will let you execute Python source code
592given in a file or a buffer, but they will not let you interact in a
593more detailed way with the interpreter.
Guido van Rossum4a944d71997-08-14 20:35:38 +0000594
Fred Drake659ebfa2000-04-03 15:42:13 +0000595Several of these functions accept a start symbol from the grammar as a
596parameter. The available start symbols are \constant{Py_eval_input},
597\constant{Py_file_input}, and \constant{Py_single_input}. These are
598described following the functions which accept them as parameters.
599
Fred Drakec6fa34e1998-04-02 06:47:24 +0000600\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000601 If \var{fp} refers to a file associated with an interactive device
602 (console or terminal input or \UNIX{} pseudo-terminal), return the
603 value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
604 result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
Fred Drake659ebfa2000-04-03 15:42:13 +0000605 \NULL{}, this function uses \code{"???"} as the filename.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000606\end{cfuncdesc}
607
Fred Drakec6fa34e1998-04-02 06:47:24 +0000608\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
Fred Drake0041a941999-04-29 04:20:46 +0000609 Executes the Python source code from \var{command} in the
610 \module{__main__} module. If \module{__main__} does not already
611 exist, it is created. Returns \code{0} on success or \code{-1} if
612 an exception was raised. If there was an error, there is no way to
613 get the exception information.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000614\end{cfuncdesc}
615
Fred Drakec6fa34e1998-04-02 06:47:24 +0000616\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000617 Similar to \cfunction{PyRun_SimpleString()}, but the Python source
618 code is read from \var{fp} instead of an in-memory string.
619 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000620\end{cfuncdesc}
621
Fred Drakec6fa34e1998-04-02 06:47:24 +0000622\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
Fred Drakee5bf8b21998-02-12 21:22:28 +0000623\end{cfuncdesc}
624
Fred Drakec6fa34e1998-04-02 06:47:24 +0000625\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
Fred Drakee5bf8b21998-02-12 21:22:28 +0000626\end{cfuncdesc}
627
Fred Drakec6fa34e1998-04-02 06:47:24 +0000628\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
629 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000630 Parse Python source code from \var{str} using the start token
631 \var{start}. The result can be used to create a code object which
632 can be evaluated efficiently. This is useful if a code fragment
633 must be evaluated many times.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000634\end{cfuncdesc}
635
Fred Drakec6fa34e1998-04-02 06:47:24 +0000636\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
637 char *filename, int start}
Fred Drake0041a941999-04-29 04:20:46 +0000638 Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
639 source code is read from \var{fp} instead of an in-memory string.
640 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000641\end{cfuncdesc}
642
Fred Drakec6fa34e1998-04-02 06:47:24 +0000643\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
644 PyObject *globals,
645 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000646 Execute Python source code from \var{str} in the context specified
647 by the dictionaries \var{globals} and \var{locals}. The parameter
648 \var{start} specifies the start token that should be used to parse
649 the source code.
650
651 Returns the result of executing the code as a Python object, or
652 \NULL{} if an exception was raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000653\end{cfuncdesc}
654
Fred Drakec6fa34e1998-04-02 06:47:24 +0000655\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
656 int start, PyObject *globals,
657 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000658 Similar to \cfunction{PyRun_String()}, but the Python source code is
Fred Drake659ebfa2000-04-03 15:42:13 +0000659 read from \var{fp} instead of an in-memory string.
660 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000661\end{cfuncdesc}
662
Fred Drakec6fa34e1998-04-02 06:47:24 +0000663\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
664 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000665 Parse and compile the Python source code in \var{str}, returning the
666 resulting code object. The start token is given by \var{start};
Fred Drakec924b8d1999-08-23 18:57:25 +0000667 this can be used to constrain the code which can be compiled and should
668 be \constant{Py_eval_input}, \constant{Py_file_input}, or
669 \constant{Py_single_input}. The filename specified by
670 \var{filename} is used to construct the code object and may appear
671 in tracebacks or \exception{SyntaxError} exception messages. This
672 returns \NULL{} if the code cannot be parsed or compiled.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000673\end{cfuncdesc}
674
Fred Drakec924b8d1999-08-23 18:57:25 +0000675\begin{cvardesc}{int}{Py_eval_input}
676 The start symbol from the Python grammar for isolated expressions;
Fred Drake659ebfa2000-04-03 15:42:13 +0000677 for use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
Fred Drakec924b8d1999-08-23 18:57:25 +0000678\end{cvardesc}
679
680\begin{cvardesc}{int}{Py_file_input}
681 The start symbol from the Python grammar for sequences of statements
682 as read from a file or other source; for use with
Fred Drake659ebfa2000-04-03 15:42:13 +0000683 \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
684 the symbol to use when compiling arbitrarily long Python source code.
Fred Drakec924b8d1999-08-23 18:57:25 +0000685\end{cvardesc}
686
687\begin{cvardesc}{int}{Py_single_input}
688 The start symbol from the Python grammar for a single statement; for
Fred Drake659ebfa2000-04-03 15:42:13 +0000689 use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
690 This is the symbol used for the interactive interpreter loop.
Fred Drakec924b8d1999-08-23 18:57:25 +0000691\end{cvardesc}
692
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000693
Fred Drakeefd146c1999-02-15 15:30:45 +0000694\chapter{Reference Counting \label{countingRefs}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000695
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000696The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000697of Python objects.
698
699\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
Fred Drakec6fa34e1998-04-02 06:47:24 +0000700Increment the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000701not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000702\cfunction{Py_XINCREF()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000703\end{cfuncdesc}
704
705\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000706Increment the reference count for object \var{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000707\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000708\end{cfuncdesc}
709
710\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000711Decrement the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000712not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000713\cfunction{Py_XDECREF()}. If the reference count reaches zero, the
714object's type's deallocation function (which must not be \NULL{}) is
715invoked.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000716
717\strong{Warning:} The deallocation function can cause arbitrary Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000718code to be invoked (e.g. when a class instance with a
719\method{__del__()} method is deallocated). While exceptions in such
720code are not propagated, the executed code has free access to all
721Python global variables. This means that any object that is reachable
722from a global variable should be in a consistent state before
723\cfunction{Py_DECREF()} is invoked. For example, code to delete an
724object from a list should copy a reference to the deleted object in a
725temporary variable, update the list data structure, and then call
726\cfunction{Py_DECREF()} for the temporary variable.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000727\end{cfuncdesc}
728
729\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000730Decrement the reference count for object \var{o}. The object may be
731\NULL{}, in which case the macro has no effect; otherwise the effect
732is the same as for \cfunction{Py_DECREF()}, and the same warning
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000733applies.
734\end{cfuncdesc}
735
Fred Drake659ebfa2000-04-03 15:42:13 +0000736The following functions or macros are only for use within the
737interpreter core: \cfunction{_Py_Dealloc()},
738\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
739well as the global variable \cdata{_Py_RefTotal}.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000740
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000741
Fred Drakeefd146c1999-02-15 15:30:45 +0000742\chapter{Exception Handling \label{exceptionHandling}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000743
Fred Drake659ebfa2000-04-03 15:42:13 +0000744The functions described in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000745exceptions. It is important to understand some of the basics of
Fred Drake659ebfa2000-04-03 15:42:13 +0000746Python exception handling. It works somewhat like the
747\UNIX{} \cdata{errno} variable: there is a global indicator (per
748thread) of the last error that occurred. Most functions don't clear
749this on success, but will set it to indicate the cause of the error on
750failure. Most functions also return an error indicator, usually
751\NULL{} if they are supposed to return a pointer, or \code{-1} if they
752return an integer (exception: the \cfunction{PyArg_Parse*()} functions
753return \code{1} for success and \code{0} for failure). When a
754function must fail because some function it called failed, it
755generally doesn't set the error indicator; the function it called
756already set it.
Guido van Rossumae110af1997-05-22 20:11:52 +0000757
758The error indicator consists of three Python objects corresponding to
Fred Drake659ebfa2000-04-03 15:42:13 +0000759\withsubitem{(in module sys)}{
760 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000761the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
762\code{sys.exc_traceback}. API functions exist to interact with the
763error indicator in various ways. There is a separate error indicator
764for each thread.
765
766% XXX Order of these should be more thoughtful.
767% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000768
769\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000770Print a standard traceback to \code{sys.stderr} and clear the error
771indicator. Call this function only when the error indicator is set.
772(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000773\end{cfuncdesc}
774
Fred Drakec6fa34e1998-04-02 06:47:24 +0000775\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000776Test whether the error indicator is set. If set, return the exception
Fred Drakee058b4f1998-02-16 06:15:35 +0000777\emph{type} (the first argument to the last call to one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000778\cfunction{PyErr_Set*()} functions or to \cfunction{PyErr_Restore()}). If
Fred Drakee058b4f1998-02-16 06:15:35 +0000779not set, return \NULL{}. You do not own a reference to the return
780value, so you do not need to \cfunction{Py_DECREF()} it.
Fred Drake659ebfa2000-04-03 15:42:13 +0000781\strong{Note:} Do not compare the return value to a specific
Fred Drakee058b4f1998-02-16 06:15:35 +0000782exception; use \cfunction{PyErr_ExceptionMatches()} instead, shown
Fred Drake659ebfa2000-04-03 15:42:13 +0000783below. (The comparison could easily fail since the exception may be
784an instance instead of a class, in the case of a class exception, or
785it may the a subclass of the expected exception.)
Guido van Rossum42cefd01997-10-05 15:27:29 +0000786\end{cfuncdesc}
787
788\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000789Equivalent to
Fred Drakee058b4f1998-02-16 06:15:35 +0000790\samp{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
Fred Drake659ebfa2000-04-03 15:42:13 +0000791This should only be called when an exception is actually set; a memory
792access violation will occur if no exception has been raised.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000793\end{cfuncdesc}
794
795\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000796Return true if the \var{given} exception matches the exception in
797\var{exc}. If \var{exc} is a class object, this also returns true
Fred Drake659ebfa2000-04-03 15:42:13 +0000798when \var{given} is an instance of a subclass. If \var{exc} is a tuple, all
Guido van Rossum42cefd01997-10-05 15:27:29 +0000799exceptions in the tuple (and recursively in subtuples) are searched
Fred Drake659ebfa2000-04-03 15:42:13 +0000800for a match. If \var{given} is \NULL, a memory access violation will
801occur.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000802\end{cfuncdesc}
803
804\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000805Under certain circumstances, the values returned by
Fred Drakee058b4f1998-02-16 06:15:35 +0000806\cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning that
807\code{*\var{exc}} is a class object but \code{*\var{val}} is not an
808instance of the same class. This function can be used to instantiate
809the class in that case. If the values are already normalized, nothing
Fred Drake659ebfa2000-04-03 15:42:13 +0000810happens. The delayed normalization is implemented to improve
811performance.
Guido van Rossumae110af1997-05-22 20:11:52 +0000812\end{cfuncdesc}
813
814\begin{cfuncdesc}{void}{PyErr_Clear}{}
815Clear the error indicator. If the error indicator is not set, there
816is no effect.
817\end{cfuncdesc}
818
Fred Drake659ebfa2000-04-03 15:42:13 +0000819\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
820 PyObject **ptraceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000821Retrieve the error indicator into three variables whose addresses are
822passed. If the error indicator is not set, set all three variables to
823\NULL{}. If it is set, it will be cleared and you own a reference to
Fred Drake659ebfa2000-04-03 15:42:13 +0000824each object retrieved. The value and traceback object may be
825\NULL{} even when the type object is not. \strong{Note:} This
826function is normally only used by code that needs to handle exceptions
827or by code that needs to save and restore the error indicator
828temporarily.
Guido van Rossumae110af1997-05-22 20:11:52 +0000829\end{cfuncdesc}
830
831\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value, PyObject *traceback}
832Set the error indicator from the three objects. If the error
833indicator is already set, it is cleared first. If the objects are
834\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
835and non-\NULL{} value or traceback. The exception type should be a
836string or class; if it is a class, the value should be an instance of
837that class. Do not pass an invalid exception type or value.
838(Violating these rules will cause subtle problems later.) This call
839takes away a reference to each object, i.e. you must own a reference
840to each object before the call and after the call you no longer own
841these references. (If you don't understand this, don't use this
Fred Drake659ebfa2000-04-03 15:42:13 +0000842function. I warned you.) \strong{Note:} This function is normally
Guido van Rossumae110af1997-05-22 20:11:52 +0000843only used by code that needs to save and restore the error indicator
844temporarily.
845\end{cfuncdesc}
846
847\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
848This is the most common way to set the error indicator. The first
849argument specifies the exception type; it is normally one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000850standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
Guido van Rossumae110af1997-05-22 20:11:52 +0000851increment its reference count. The second argument is an error
852message; it is converted to a string object.
853\end{cfuncdesc}
854
855\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +0000856This function is similar to \cfunction{PyErr_SetString()} but lets you
Guido van Rossumae110af1997-05-22 20:11:52 +0000857specify an arbitrary Python object for the ``value'' of the exception.
858You need not increment its reference count.
859\end{cfuncdesc}
860
861\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +0000862This is a shorthand for \samp{PyErr_SetObject(\var{type}, Py_None)}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000863\end{cfuncdesc}
864
865\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000866This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000867\var{message})}, where \var{message} indicates that a built-in operation
868was invoked with an illegal argument. It is mostly for internal use.
869\end{cfuncdesc}
870
Fred Drakec6fa34e1998-04-02 06:47:24 +0000871\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000872This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
Guido van Rossumae110af1997-05-22 20:11:52 +0000873returns \NULL{} so an object allocation function can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000874\samp{return PyErr_NoMemory();} when it runs out of memory.
Guido van Rossumae110af1997-05-22 20:11:52 +0000875\end{cfuncdesc}
876
Fred Drakec6fa34e1998-04-02 06:47:24 +0000877\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
Fred Drake659ebfa2000-04-03 15:42:13 +0000878This is a convenience function to raise an exception when a C library
879function has returned an error and set the C variable \cdata{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000880It constructs a tuple object whose first item is the integer
Fred Drakef8830d11998-04-23 14:06:01 +0000881\cdata{errno} value and whose second item is the corresponding error
Fred Drake659ebfa2000-04-03 15:42:13 +0000882message (gotten from \cfunction{strerror()}\ttindex{strerror()}), and
883then calls
Fred Drakee058b4f1998-02-16 06:15:35 +0000884\samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
Fred Drakef8830d11998-04-23 14:06:01 +0000885the \cdata{errno} value is \constant{EINTR}, indicating an interrupted
Fred Drakee058b4f1998-02-16 06:15:35 +0000886system call, this calls \cfunction{PyErr_CheckSignals()}, and if that set
Guido van Rossumae110af1997-05-22 20:11:52 +0000887the error indicator, leaves it set to that. The function always
888returns \NULL{}, so a wrapper function around a system call can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000889\samp{return PyErr_SetFromErrno();} when the system call returns an
890error.
Guido van Rossumae110af1997-05-22 20:11:52 +0000891\end{cfuncdesc}
892
893\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000894This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000895\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000896operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000897argument. It is mostly for internal use.
898\end{cfuncdesc}
899
900\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
901This function interacts with Python's signal handling. It checks
902whether a signal has been sent to the processes and if so, invokes the
Fred Drake4de05a91998-02-16 14:25:26 +0000903corresponding signal handler. If the
904\module{signal}\refbimodindex{signal} module is supported, this can
905invoke a signal handler written in Python. In all cases, the default
Fred Drake659ebfa2000-04-03 15:42:13 +0000906effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
907\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
908\exception{KeyboardInterrupt} exception. If an exception is raised the
Fred Drakee058b4f1998-02-16 06:15:35 +0000909error indicator is set and the function returns \code{1}; otherwise
910the function returns \code{0}. The error indicator may or may not be
911cleared if it was previously set.
Guido van Rossumae110af1997-05-22 20:11:52 +0000912\end{cfuncdesc}
913
914\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
Fred Drake659ebfa2000-04-03 15:42:13 +0000915This function is obsolete. It simulates the effect of a
916\constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
Fred Drakee058b4f1998-02-16 06:15:35 +0000917\cfunction{PyErr_CheckSignals()} is called,
Fred Drake659ebfa2000-04-03 15:42:13 +0000918\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
919\exception{KeyboardInterrupt} will be raised.
920It may be called without holding the interpreter lock.
Guido van Rossumae110af1997-05-22 20:11:52 +0000921\end{cfuncdesc}
922
Fred Drakec6fa34e1998-04-02 06:47:24 +0000923\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
924 PyObject *base,
925 PyObject *dict}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000926This utility function creates and returns a new exception object. The
Fred Drake659ebfa2000-04-03 15:42:13 +0000927\var{name} argument must be the name of the new exception, a C string
928of the form \code{module.class}. The \var{base} and
929\var{dict} arguments are normally \NULL{}. Normally, this creates a
930class object derived from the root for all exceptions, the built-in
931name \exception{Exception} (accessible in C as
932\cdata{PyExc_Exception}). In this case the \member{__module__}
933attribute of the new class is set to the first part (up to the last
934dot) of the \var{name} argument, and the class name is set to the last
935part (after the last dot). The
Guido van Rossum42cefd01997-10-05 15:27:29 +0000936\var{base} argument can be used to specify an alternate base class.
937The \var{dict} argument can be used to specify a dictionary of class
938variables and methods.
939\end{cfuncdesc}
940
941
Fred Drakeefd146c1999-02-15 15:30:45 +0000942\section{Standard Exceptions \label{standardExceptions}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000943
944All standard Python exceptions are available as global variables whose
Fred Drake659ebfa2000-04-03 15:42:13 +0000945names are \samp{PyExc_} followed by the Python exception name. These
946have the type \ctype{PyObject*}; they are all class objects. For
947completeness, here are all the variables:
948
949\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
950 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
951 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
952 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
953 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
954 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
955 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
956 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
957 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
958 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
959 \lineiii{PyExc_IOError}{\exception{IOError}}{}
960 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
961 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
962 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
963 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
964 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
965 \lineiii{PyExc_NameError}{\exception{NameError}}{}
966 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
967 \lineiii{PyExc_OSError}{\exception{OSError}}{}
968 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
969 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
970 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
971 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
972 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
973 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
974 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
975 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
976\end{tableiii}
977
978\noindent
979Note:
980\begin{description}
981\item[(1)]
982 This is a base class for other standard exceptions. If the
983 \code{-X} interpreter option is used, these will be tuples
984 containing the string exceptions which would have otherwise been
985 subclasses.
986\end{description}
987
988
989\section{Deprecation of String Exceptions}
990
991The \code{-X} command-line option will be removed in Python 1.6. All
992exceptions built into Python or provided in the standard library will
993\withsubitem{(built-in exception)}{\ttindex{Exception}}
994be classes derived from \exception{Exception}.
995
996String exceptions will still be supported in the interpreter to allow
997existing code to run unmodified, but this will also change in a future
998release.
Guido van Rossumae110af1997-05-22 20:11:52 +0000999
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001000
Fred Drakeefd146c1999-02-15 15:30:45 +00001001\chapter{Utilities \label{utilities}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001002
1003The functions in this chapter perform various utility tasks, such as
Fred Drake659ebfa2000-04-03 15:42:13 +00001004parsing function arguments and constructing Python values from C
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001005values.
1006
Fred Drakeefd146c1999-02-15 15:30:45 +00001007\section{OS Utilities \label{os}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001008
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001009\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001010Return true (nonzero) if the standard I/O file \var{fp} with name
1011\var{filename} is deemed interactive. This is the case for files for
1012which \samp{isatty(fileno(\var{fp}))} is true. If the global flag
Fred Drakef8830d11998-04-23 14:06:01 +00001013\cdata{Py_InteractiveFlag} is true, this function also returns true if
Fred Drakee058b4f1998-02-16 06:15:35 +00001014the \var{name} pointer is \NULL{} or if the name is equal to one of
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001015the strings \code{"<stdin>"} or \code{"???"}.
1016\end{cfuncdesc}
1017
1018\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001019Return the time of last modification of the file \var{filename}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001020The result is encoded in the same way as the timestamp returned by
Fred Drake659ebfa2000-04-03 15:42:13 +00001021the standard C library function \cfunction{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001022\end{cfuncdesc}
1023
1024
Fred Drakeefd146c1999-02-15 15:30:45 +00001025\section{Process Control \label{processControl}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001026
1027\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
1028Print a fatal error message and kill the process. No cleanup is
1029performed. This function should only be invoked when a condition is
1030detected that would make it dangerous to continue using the Python
1031interpreter; e.g., when the object administration appears to be
Fred Drake659ebfa2000-04-03 15:42:13 +00001032corrupted. On \UNIX{}, the standard C library function
1033\cfunction{abort()}\ttindex{abort()} is called which will attempt to
1034produce a \file{core} file.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001035\end{cfuncdesc}
1036
1037\begin{cfuncdesc}{void}{Py_Exit}{int status}
Fred Drake659ebfa2000-04-03 15:42:13 +00001038Exit the current process. This calls
1039\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
1040then calls the standard C library function
1041\code{exit(\var{status})}\ttindex{exit()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001042\end{cfuncdesc}
1043
1044\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drake659ebfa2000-04-03 15:42:13 +00001045Register a cleanup function to be called by
1046\cfunction{Py_Finalize()}\ttindex{Py_Finalize()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001047The cleanup function will be called with no arguments and should
Fred Drake659ebfa2000-04-03 15:42:13 +00001048return no value. At most 32 \index{cleanup functions}cleanup
1049functions can be registered.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001050When the registration is successful, \cfunction{Py_AtExit()} returns
1051\code{0}; on failure, it returns \code{-1}. The cleanup function
1052registered last is called first. Each cleanup function will be called
1053at most once. Since Python's internal finallization will have
1054completed before the cleanup function, no Python APIs should be called
1055by \var{func}.
1056\end{cfuncdesc}
1057
1058
Fred Drakeefd146c1999-02-15 15:30:45 +00001059\section{Importing Modules \label{importing}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001060
Fred Drakec6fa34e1998-04-02 06:47:24 +00001061\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00001062This is a simplified interface to
1063\cfunction{PyImport_ImportModuleEx()} below, leaving the
1064\var{globals} and \var{locals} arguments set to \NULL{}. When the
1065\var{name} argument contains a dot (i.e., when it specifies a
1066submodule of a package), the \var{fromlist} argument is set to the
1067list \code{['*']} so that the return value is the named module rather
1068than the top-level package containing it as would otherwise be the
1069case. (Unfortunately, this has an additional side effect when
1070\var{name} in fact specifies a subpackage instead of a submodule: the
1071submodules specified in the package's \code{__all__} variable are
1072\index{package variable!\code{__all__}}
1073\withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a
1074new reference to the imported module, or
1075\NULL{} with an exception set on failure (the module may still be
1076created in this case --- examine \code{sys.modules} to find out).
1077\withsubitem{(in module sys)}{\ttindex{modules}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001078\end{cfuncdesc}
1079
Fred Drakec6fa34e1998-04-02 06:47:24 +00001080\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001081Import a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001082Python function \function{__import__()}\bifuncindex{__import__}, as
1083the standard \function{__import__()} function calls this function
1084directly.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001085
Guido van Rossum42cefd01997-10-05 15:27:29 +00001086The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001087top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001088(the module may still be created in this case). Like for
Fred Drakee058b4f1998-02-16 06:15:35 +00001089\function{__import__()}, the return value when a submodule of a
1090package was requested is normally the top-level package, unless a
1091non-empty \var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001092\end{cfuncdesc}
1093
Fred Drakec6fa34e1998-04-02 06:47:24 +00001094\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001095This is a higher-level interface that calls the current ``import hook
Fred Drakee058b4f1998-02-16 06:15:35 +00001096function''. It invokes the \function{__import__()} function from the
Guido van Rossum42cefd01997-10-05 15:27:29 +00001097\code{__builtins__} of the current globals. This means that the
1098import is done using whatever import hooks are installed in the
Fred Drake4de05a91998-02-16 14:25:26 +00001099current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
1100\module{ihooks}\refstmodindex{ihooks}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001101\end{cfuncdesc}
1102
Fred Drakec6fa34e1998-04-02 06:47:24 +00001103\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001104Reload a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001105Python function \function{reload()}\bifuncindex{reload}, as the standard
Fred Drakee058b4f1998-02-16 06:15:35 +00001106\function{reload()} function calls this function directly. Return a
1107new reference to the reloaded module, or \NULL{} with an exception set
1108on failure (the module still exists in this case).
Guido van Rossum42cefd01997-10-05 15:27:29 +00001109\end{cfuncdesc}
1110
Fred Drakec6fa34e1998-04-02 06:47:24 +00001111\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001112Return the module object corresponding to a module name. The
1113\var{name} argument may be of the form \code{package.module}). First
1114check the modules dictionary if there's one there, and if not, create
Fred Drake659ebfa2000-04-03 15:42:13 +00001115a new one and insert in in the modules dictionary.
Guido van Rossuma096a2e1998-11-02 17:02:42 +00001116Warning: this function does not load or import the module; if the
1117module wasn't already loaded, you will get an empty module object.
1118Use \cfunction{PyImport_ImportModule()} or one of its variants to
1119import a module.
Fred Drake659ebfa2000-04-03 15:42:13 +00001120Return \NULL{} with an exception set on failure.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001121\end{cfuncdesc}
1122
Fred Drakec6fa34e1998-04-02 06:47:24 +00001123\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001124Given a module name (possibly of the form \code{package.module}) and a
1125code object read from a Python bytecode file or obtained from the
Fred Drake53fb7721998-02-16 06:23:20 +00001126built-in function \function{compile()}\bifuncindex{compile}, load the
1127module. Return a new reference to the module object, or \NULL{} with
1128an exception set if an error occurred (the module may still be created
1129in this case). (This function would reload the module if it was
1130already imported.)
Guido van Rossum42cefd01997-10-05 15:27:29 +00001131\end{cfuncdesc}
1132
1133\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001134Return the magic number for Python bytecode files (a.k.a.
1135\file{.pyc} and \file{.pyo} files). The magic number should be
1136present in the first four bytes of the bytecode file, in little-endian
1137byte order.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001138\end{cfuncdesc}
1139
Fred Drakec6fa34e1998-04-02 06:47:24 +00001140\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001141Return the dictionary used for the module administration
1142(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1143variable.
1144\end{cfuncdesc}
1145
1146\begin{cfuncdesc}{void}{_PyImport_Init}{}
1147Initialize the import mechanism. For internal use only.
1148\end{cfuncdesc}
1149
1150\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1151Empty the module table. For internal use only.
1152\end{cfuncdesc}
1153
1154\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1155Finalize the import mechanism. For internal use only.
1156\end{cfuncdesc}
1157
Fred Drakec6fa34e1998-04-02 06:47:24 +00001158\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001159For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001160\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001161
Fred Drakec6fa34e1998-04-02 06:47:24 +00001162\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001163For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001164\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001165
1166\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *}
1167Load a frozen module. Return \code{1} for success, \code{0} if the
1168module is not found, and \code{-1} with an exception set if the
1169initialization failed. To access the imported module on a successful
Fred Drakee058b4f1998-02-16 06:15:35 +00001170load, use \cfunction{PyImport_ImportModule()}.
1171(Note the misnomer --- this function would reload the module if it was
Guido van Rossum42cefd01997-10-05 15:27:29 +00001172already imported.)
1173\end{cfuncdesc}
1174
Fred Drake659ebfa2000-04-03 15:42:13 +00001175\begin{ctypedesc}[_frozen]{struct _frozen}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001176This is the structure type definition for frozen module descriptors,
Fred Drakec6fa34e1998-04-02 06:47:24 +00001177as generated by the \program{freeze}\index{freeze utility} utility
1178(see \file{Tools/freeze/} in the Python source distribution). Its
1179definition is:
1180
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001181\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001182struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001183 char *name;
1184 unsigned char *code;
1185 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001186};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001187\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001188\end{ctypedesc}
1189
Fred Drakec6fa34e1998-04-02 06:47:24 +00001190\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
Fred Drakef8830d11998-04-23 14:06:01 +00001191This pointer is initialized to point to an array of \ctype{struct
Fred Drake659ebfa2000-04-03 15:42:13 +00001192_frozen} records, terminated by one whose members are all
1193\NULL{} or zero. When a frozen module is imported, it is searched in
1194this table. Third-party code could play tricks with this to provide a
Guido van Rossum42cefd01997-10-05 15:27:29 +00001195dynamically created collection of frozen modules.
1196\end{cvardesc}
1197
1198
Fred Drakeefd146c1999-02-15 15:30:45 +00001199\chapter{Abstract Objects Layer \label{abstract}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001200
1201The functions in this chapter interact with Python objects regardless
1202of their type, or with wide classes of object types (e.g. all
1203numerical types, or all sequence types). When used on object types
Fred Drake659ebfa2000-04-03 15:42:13 +00001204for which they do not apply, they will raise a Python exception.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001205
Fred Drakeefd146c1999-02-15 15:30:45 +00001206\section{Object Protocol \label{object}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001207
1208\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00001209Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error.
1210The flags argument is used to enable certain printing options. The
1211only option currently supported is \constant{Py_PRINT_RAW}; if given,
1212the \function{str()} of the object is written instead of the
1213\function{repr()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001214\end{cfuncdesc}
1215
1216\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001217Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1218\code{0} otherwise. This is equivalent to the Python expression
1219\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001220This function always succeeds.
1221\end{cfuncdesc}
1222
Fred Drake659ebfa2000-04-03 15:42:13 +00001223\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
1224 char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001225Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001226Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001227This is the equivalent of the Python expression
1228\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001229\end{cfuncdesc}
1230
1231
1232\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001233Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1234\code{0} otherwise. This is equivalent to the Python expression
1235\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001236This function always succeeds.
1237\end{cfuncdesc}
1238
1239
Fred Drake659ebfa2000-04-03 15:42:13 +00001240\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
1241 PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001242Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001243Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001244This is the equivalent of the Python expression
1245\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001246\end{cfuncdesc}
1247
1248
1249\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001250Set the value of the attribute named \var{attr_name}, for object
1251\var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1252the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1253\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001254\end{cfuncdesc}
1255
1256
1257\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001258Set the value of the attribute named \var{attr_name}, for
1259object \var{o},
1260to the value \var{v}. Returns \code{-1} on failure. This is
1261the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1262\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001263\end{cfuncdesc}
1264
1265
1266\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001267Delete attribute named \var{attr_name}, for object \var{o}. Returns
1268\code{-1} on failure. This is the equivalent of the Python
1269statement: \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001270\end{cfuncdesc}
1271
1272
1273\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001274Delete attribute named \var{attr_name}, for object \var{o}. Returns
1275\code{-1} on failure. This is the equivalent of the Python
1276statement \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001277\end{cfuncdesc}
1278
1279
1280\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
Fred Drakee058b4f1998-02-16 06:15:35 +00001281Compare the values of \var{o1} and \var{o2} using a routine provided
1282by \var{o1}, if one exists, otherwise with a routine provided by
1283\var{o2}. The result of the comparison is returned in \var{result}.
1284Returns \code{-1} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001285statement\bifuncindex{cmp} \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001286\end{cfuncdesc}
1287
1288
1289\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001290Compare the values of \var{o1} and \var{o2} using a routine provided
1291by \var{o1}, if one exists, otherwise with a routine provided by
1292\var{o2}. Returns the result of the comparison on success. On error,
1293the value returned is undefined; use \cfunction{PyErr_Occurred()} to
Fred Drake659ebfa2000-04-03 15:42:13 +00001294detect an error. This is equivalent to the Python
1295expression\bifuncindex{cmp} \samp{cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001296\end{cfuncdesc}
1297
1298
1299\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001300Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001301string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001302the equivalent of the Python expression \samp{repr(\var{o})}.
1303Called by the \function{repr()}\bifuncindex{repr} built-in function
1304and by reverse quotes.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001305\end{cfuncdesc}
1306
1307
1308\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001309Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001310string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001311the equivalent of the Python expression \samp{str(\var{o})}.
1312Called by the \function{str()}\bifuncindex{str} built-in function and
1313by the \keyword{print} statement.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001314\end{cfuncdesc}
1315
1316
1317\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001318Determine if the object \var{o} is callable. Return \code{1} if the
Fred Drakee058b4f1998-02-16 06:15:35 +00001319object is callable and \code{0} otherwise.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001320This function always succeeds.
1321\end{cfuncdesc}
1322
1323
Fred Drake659ebfa2000-04-03 15:42:13 +00001324\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
1325 PyObject *args}
Fred Drakee058b4f1998-02-16 06:15:35 +00001326Call a callable Python object \var{callable_object}, with
1327arguments given by the tuple \var{args}. If no arguments are
Fred Drake659ebfa2000-04-03 15:42:13 +00001328needed, then \var{args} may be \NULL{}. Returns the result of the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001329call on success, or \NULL{} on failure. This is the equivalent
Fred Drakee058b4f1998-02-16 06:15:35 +00001330of the Python expression \samp{apply(\var{o}, \var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001331\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001332\end{cfuncdesc}
1333
1334\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001335Call a callable Python object \var{callable_object}, with a
Fred Drake659ebfa2000-04-03 15:42:13 +00001336variable number of C arguments. The C arguments are described
Fred Drakee058b4f1998-02-16 06:15:35 +00001337using a \cfunction{Py_BuildValue()} style format string. The format may
1338be \NULL{}, indicating that no arguments are provided. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001339result of the call on success, or \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001340the equivalent of the Python expression \samp{apply(\var{o},
Fred Drake659ebfa2000-04-03 15:42:13 +00001341\var{args})}.\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001342\end{cfuncdesc}
1343
1344
1345\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001346Call the method named \var{m} of object \var{o} with a variable number
Fred Drake659ebfa2000-04-03 15:42:13 +00001347of C arguments. The C arguments are described by a
Fred Drakee058b4f1998-02-16 06:15:35 +00001348\cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1349indicating that no arguments are provided. Returns the result of the
1350call on success, or \NULL{} on failure. This is the equivalent of the
1351Python expression \samp{\var{o}.\var{method}(\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001352Note that special method names, such as \method{__add__()},
1353\method{__getitem__()}, and so on are not supported. The specific
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001354abstract-object routines for these must be used.
1355\end{cfuncdesc}
1356
1357
1358\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001359Compute and return the hash value of an object \var{o}. On
1360failure, return \code{-1}. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001361expression \samp{hash(\var{o})}.\bifuncindex{hash}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001362\end{cfuncdesc}
1363
1364
1365\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001366Returns \code{1} if the object \var{o} is considered to be true, and
1367\code{0} otherwise. This is equivalent to the Python expression
1368\samp{not not \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001369This function always succeeds.
1370\end{cfuncdesc}
1371
1372
1373\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1374On success, returns a type object corresponding to the object
Fred Drakee058b4f1998-02-16 06:15:35 +00001375type of object \var{o}. On failure, returns \NULL{}. This is
1376equivalent to the Python expression \samp{type(\var{o})}.
Fred Drake53fb7721998-02-16 06:23:20 +00001377\bifuncindex{type}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001378\end{cfuncdesc}
1379
1380\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001381Return the length of object \var{o}. If the object \var{o} provides
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001382both sequence and mapping protocols, the sequence length is
Fred Drake659ebfa2000-04-03 15:42:13 +00001383returned. On error, \code{-1} is returned. This is the equivalent
1384to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001385\end{cfuncdesc}
1386
1387
1388\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001389Return element of \var{o} corresponding to the object \var{key} or
1390\NULL{} on failure. This is the equivalent of the Python expression
1391\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001392\end{cfuncdesc}
1393
1394
1395\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001396Map the object \var{key} to the value \var{v}.
1397Returns \code{-1} on failure. This is the equivalent
1398of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001399\end{cfuncdesc}
1400
1401
Guido van Rossumd1dbf631999-01-22 20:10:49 +00001402\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001403Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1404failure. This is the equivalent of the Python statement \samp{del
1405\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001406\end{cfuncdesc}
1407
1408
Fred Drakeefd146c1999-02-15 15:30:45 +00001409\section{Number Protocol \label{number}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001410
1411\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001412Returns \code{1} if the object \var{o} provides numeric protocols, and
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001413false otherwise.
1414This function always succeeds.
1415\end{cfuncdesc}
1416
1417
1418\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001419Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1420failure. This is the equivalent of the Python expression
1421\samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001422\end{cfuncdesc}
1423
1424
1425\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
Fred Drake659ebfa2000-04-03 15:42:13 +00001426Returns the result of subtracting \var{o2} from \var{o1}, or
1427\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001428\samp{\var{o1} - \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001429\end{cfuncdesc}
1430
1431
1432\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001433Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1434failure. This is the equivalent of the Python expression
1435\samp{\var{o1} * \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001436\end{cfuncdesc}
1437
1438
1439\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001440Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1441failure.
1442This is the equivalent of the Python expression \samp{\var{o1} /
1443\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001444\end{cfuncdesc}
1445
1446
1447\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001448Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1449failure. This is the equivalent of the Python expression
Fred Drake659ebfa2000-04-03 15:42:13 +00001450\samp{\var{o1} \%\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001451\end{cfuncdesc}
1452
1453
1454\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
Fred Drake53fb7721998-02-16 06:23:20 +00001455See the built-in function \function{divmod()}\bifuncindex{divmod}.
1456Returns \NULL{} on failure. This is the equivalent of the Python
1457expression \samp{divmod(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001458\end{cfuncdesc}
1459
1460
1461\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
Fred Drake53fb7721998-02-16 06:23:20 +00001462See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1463\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001464\samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
Fred Drake659ebfa2000-04-03 15:42:13 +00001465If \var{o3} is to be ignored, pass \cdata{Py_None} in its place
1466(passing \NULL{} for \var{o3} would cause an illegal memory access).
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001467\end{cfuncdesc}
1468
1469
1470\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001471Returns the negation of \var{o} on success, or \NULL{} on failure.
1472This is the equivalent of the Python expression \samp{-\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001473\end{cfuncdesc}
1474
1475
1476\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001477Returns \var{o} on success, or \NULL{} on failure.
1478This is the equivalent of the Python expression \samp{+\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001479\end{cfuncdesc}
1480
1481
1482\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001483Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1484the equivalent of the Python expression \samp{abs(\var{o})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001485\bifuncindex{abs}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001486\end{cfuncdesc}
1487
1488
1489\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001490Returns the bitwise negation of \var{o} on success, or \NULL{} on
1491failure. This is the equivalent of the Python expression
1492\samp{\~\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001493\end{cfuncdesc}
1494
1495
1496\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001497Returns the result of left shifting \var{o1} by \var{o2} on success,
1498or \NULL{} on failure. This is the equivalent of the Python
1499expression \samp{\var{o1} << \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001500\end{cfuncdesc}
1501
1502
1503\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001504Returns the result of right shifting \var{o1} by \var{o2} on success,
1505or \NULL{} on failure. This is the equivalent of the Python
1506expression \samp{\var{o1} >> \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001507\end{cfuncdesc}
1508
1509
1510\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001511Returns the result of ``anding'' \var{o2} and \var{o2} on success and
1512\NULL{} on failure. This is the equivalent of the Python
1513expression \samp{\var{o1} and \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001514\end{cfuncdesc}
1515
1516
1517\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001518Returns the bitwise exclusive or of \var{o1} by \var{o2} on success,
1519or \NULL{} on failure. This is the equivalent of the Python
1520expression \samp{\var{o1} \^{ }\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001521\end{cfuncdesc}
1522
1523\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001524Returns the result of \var{o1} and \var{o2} on success, or \NULL{} on
1525failure. This is the equivalent of the Python expression
1526\samp{\var{o1} or \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001527\end{cfuncdesc}
1528
Fred Drakee058b4f1998-02-16 06:15:35 +00001529\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001530This function takes the addresses of two variables of type
Fred Drake659ebfa2000-04-03 15:42:13 +00001531\ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} and
1532\code{*\var{p2}} have the same type, increment their reference count
1533and return \code{0} (success). If the objects can be converted to a
1534common numeric type, replace \code{*p1} and \code{*p2} by their
1535converted value (with 'new' reference counts), and return \code{0}.
1536If no conversion is possible, or if some other error occurs, return
1537\code{-1} (failure) and don't increment the reference counts. The
1538call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1539statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
1540\bifuncindex{coerce}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001541\end{cfuncdesc}
1542
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001543\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001544Returns the \var{o} converted to an integer object on success, or
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001545\NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001546expression \samp{int(\var{o})}.\bifuncindex{int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001547\end{cfuncdesc}
1548
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001549\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001550Returns the \var{o} converted to a long integer object on success,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001551or \NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001552expression \samp{long(\var{o})}.\bifuncindex{long}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001553\end{cfuncdesc}
1554
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001555\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001556Returns the \var{o} converted to a float object on success, or
1557\NULL{} on failure. This is the equivalent of the Python expression
1558\samp{float(\var{o})}.\bifuncindex{float}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001559\end{cfuncdesc}
1560
1561
Fred Drakeefd146c1999-02-15 15:30:45 +00001562\section{Sequence Protocol \label{sequence}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001563
1564\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001565Return \code{1} if the object provides sequence protocol, and
1566\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001567\end{cfuncdesc}
1568
Fred Drake659ebfa2000-04-03 15:42:13 +00001569\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
1570Returns the number of objects in sequence \var{o} on success, and
1571\code{-1} on failure. For objects that do not provide sequence
1572protocol, this is equivalent to the Python expression
1573\samp{len(\var{o})}.\bifuncindex{len}
1574\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001575
1576\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001577Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001578failure. This is the equivalent of the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001579expression \samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001580\end{cfuncdesc}
1581
1582
1583\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Fred Drake659ebfa2000-04-03 15:42:13 +00001584Return the result of repeating sequence object
1585\var{o} \var{count} times, or \NULL{} on failure. This is the
1586equivalent of the Python expression \samp{\var{o} * \var{count}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001587\end{cfuncdesc}
1588
1589
1590\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001591Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
1592is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001593\end{cfuncdesc}
1594
1595
1596\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001597Return the slice of sequence object \var{o} between \var{i1} and
1598\var{i2}, or \NULL{} on failure. This is the equivalent of the Python
1599expression \samp{\var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001600\end{cfuncdesc}
1601
1602
1603\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001604Assign object \var{v} to the \var{i}th element of \var{o}.
1605Returns \code{-1} on failure. This is the equivalent of the Python
1606statement \samp{\var{o}[\var{i}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001607\end{cfuncdesc}
1608
1609\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001610Delete the \var{i}th element of object \var{v}. Returns
1611\code{-1} on failure. This is the equivalent of the Python
1612statement \samp{del \var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001613\end{cfuncdesc}
1614
Fred Drake659ebfa2000-04-03 15:42:13 +00001615\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
1616 int i2, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001617Assign the sequence object \var{v} to the slice in sequence
1618object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
1619the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001620\end{cfuncdesc}
1621
1622\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001623Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
1624Returns \code{-1} on failure. This is the equivalent of the Python
1625statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001626\end{cfuncdesc}
1627
1628\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001629Returns the \var{o} as a tuple on success, and \NULL{} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00001630This is equivalent to the Python expression \samp{tuple(\var{o})}.
1631\bifuncindex{tuple}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001632\end{cfuncdesc}
1633
1634\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001635Return the number of occurrences of \var{value} in \var{o}, that is,
1636return the number of keys for which \code{\var{o}[\var{key}] ==
1637\var{value}}. On failure, return \code{-1}. This is equivalent to
1638the Python expression \samp{\var{o}.count(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001639\end{cfuncdesc}
1640
Fred Drake659ebfa2000-04-03 15:42:13 +00001641\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001642Determine if \var{o} contains \var{value}. If an item in \var{o} is
1643equal to \var{value}, return \code{1}, otherwise return \code{0}. On
1644error, return \code{-1}. This is equivalent to the Python expression
1645\samp{\var{value} in \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001646\end{cfuncdesc}
1647
1648\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001649Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
1650\var{value}}. On error, return \code{-1}. This is equivalent to
1651the Python expression \samp{\var{o}.index(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001652\end{cfuncdesc}
1653
Fred Drakef39ed671998-02-26 22:01:23 +00001654
Fred Drakeefd146c1999-02-15 15:30:45 +00001655\section{Mapping Protocol \label{mapping}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001656
1657\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001658Return \code{1} if the object provides mapping protocol, and
1659\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001660\end{cfuncdesc}
1661
1662
1663\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001664Returns the number of keys in object \var{o} on success, and
1665\code{-1} on failure. For objects that do not provide mapping
1666protocol, this is equivalent to the Python expression
1667\samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001668\end{cfuncdesc}
1669
1670
1671\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001672Remove the mapping for object \var{key} from the object \var{o}.
1673Return \code{-1} on failure. This is equivalent to
1674the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001675\end{cfuncdesc}
1676
1677
1678\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001679Remove the mapping for object \var{key} from the object \var{o}.
1680Return \code{-1} on failure. This is equivalent to
1681the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001682\end{cfuncdesc}
1683
1684
1685\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
Fred Drake659ebfa2000-04-03 15:42:13 +00001686On success, return \code{1} if the mapping object has the key
1687\var{key} and \code{0} otherwise. This is equivalent to the Python
1688expression \samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001689This function always succeeds.
1690\end{cfuncdesc}
1691
1692
1693\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001694Return \code{1} if the mapping object has the key \var{key} and
1695\code{0} otherwise. This is equivalent to the Python expression
1696\samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001697This function always succeeds.
1698\end{cfuncdesc}
1699
1700
1701\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001702On success, return a list of the keys in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001703failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001704expression \samp{\var{o}.keys()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001705\end{cfuncdesc}
1706
1707
1708\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001709On success, return a list of the values in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001710failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001711expression \samp{\var{o}.values()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001712\end{cfuncdesc}
1713
1714
1715\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001716On success, return a list of the items in object \var{o}, where
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001717each item is a tuple containing a key-value pair. On
1718failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001719expression \samp{\var{o}.items()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001720\end{cfuncdesc}
1721
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001722
1723\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001724Return element of \var{o} corresponding to the object \var{key} or
1725\NULL{} on failure. This is the equivalent of the Python expression
1726\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001727\end{cfuncdesc}
1728
Guido van Rossum0a0f11b1998-10-16 17:43:53 +00001729\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001730Map the object \var{key} to the value \var{v} in object \var{o}.
1731Returns \code{-1} on failure. This is the equivalent of the Python
1732statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001733\end{cfuncdesc}
1734
1735
Fred Drakeefd146c1999-02-15 15:30:45 +00001736\chapter{Concrete Objects Layer \label{concrete}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001737
1738The functions in this chapter are specific to certain Python object
1739types. Passing them an object of the wrong type is not a good idea;
1740if you receive an object from a Python program and you are not sure
1741that it has the right type, you must perform a type check first;
Fred Drake659ebfa2000-04-03 15:42:13 +00001742for example. to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00001743\cfunction{PyDict_Check()}. The chapter is structured like the
1744``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001745
1746
Fred Drakeefd146c1999-02-15 15:30:45 +00001747\section{Fundamental Objects \label{fundamental}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001748
Fred Drakee5bf8b21998-02-12 21:22:28 +00001749This section describes Python type objects and the singleton object
1750\code{None}.
1751
1752
Fred Drakeefd146c1999-02-15 15:30:45 +00001753\subsection{Type Objects \label{typeObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001754
Fred Drake659ebfa2000-04-03 15:42:13 +00001755\obindex{type}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001756\begin{ctypedesc}{PyTypeObject}
Fred Drake659ebfa2000-04-03 15:42:13 +00001757The C structure of the objects used to describe built-in types.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001758\end{ctypedesc}
1759
Fred Drake659ebfa2000-04-03 15:42:13 +00001760\begin{cvardesc}{PyObject*}{PyType_Type}
Fred Drakeefd146c1999-02-15 15:30:45 +00001761This is the type object for type objects; it is the same object as
1762\code{types.TypeType} in the Python layer.
Fred Drake659ebfa2000-04-03 15:42:13 +00001763\withsubitem{(in module types)}{\ttindex{TypeType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001764\end{cvardesc}
1765
Fred Drake659ebfa2000-04-03 15:42:13 +00001766\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
1767Returns true is the object \var{o} is a type object.
1768\end{cfuncdesc}
1769
1770\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
1771Returns true if the type object \var{o} sets the feature
1772\var{feature}. Type features are denoted by single bit flags. The
1773only defined feature flag is \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER},
1774described in section \ref{buffer-structs}.
1775\end{cfuncdesc}
1776
Fred Drakee5bf8b21998-02-12 21:22:28 +00001777
Fred Drakeefd146c1999-02-15 15:30:45 +00001778\subsection{The None Object \label{noneObject}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001779
Fred Drake659ebfa2000-04-03 15:42:13 +00001780\obindex{None@\texttt{None}}
1781Note that the \ctype{PyTypeObject} for \code{None} is not directly
1782exposed in the Python/C API. Since \code{None} is a singleton,
1783testing for object identity (using \samp{==} in C) is sufficient.
1784There is no \cfunction{PyNone_Check()} function for the same reason.
1785
1786\begin{cvardesc}{PyObject*}{Py_None}
Guido van Rossum44475131998-04-21 15:30:01 +00001787The Python \code{None} object, denoting lack of value. This object has
1788no methods.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001789\end{cvardesc}
1790
1791
Fred Drakeefd146c1999-02-15 15:30:45 +00001792\section{Sequence Objects \label{sequenceObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001793
Fred Drake659ebfa2000-04-03 15:42:13 +00001794\obindex{sequence}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001795Generic operations on sequence objects were discussed in the previous
1796chapter; this section deals with the specific kinds of sequence
1797objects that are intrinsic to the Python language.
1798
1799
Fred Drakeefd146c1999-02-15 15:30:45 +00001800\subsection{String Objects \label{stringObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001801
Fred Drake659ebfa2000-04-03 15:42:13 +00001802\obindex{string}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001803\begin{ctypedesc}{PyStringObject}
Fred Drakef8830d11998-04-23 14:06:01 +00001804This subtype of \ctype{PyObject} represents a Python string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001805\end{ctypedesc}
1806
1807\begin{cvardesc}{PyTypeObject}{PyString_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00001808This instance of \ctype{PyTypeObject} represents the Python string
1809type; it is the same object as \code{types.TypeType} in the Python
1810layer.\withsubitem{(in module types)}{\ttindex{StringType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001811\end{cvardesc}
1812
1813\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00001814Returns true if the object \var{o} is a string object.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001815\end{cfuncdesc}
1816
Fred Drakec6fa34e1998-04-02 06:47:24 +00001817\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00001818Returns a new string object with the value \var{v} on success, and
1819\NULL{} on failure.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001820\end{cfuncdesc}
1821
Fred Drake659ebfa2000-04-03 15:42:13 +00001822\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
1823 int len}
1824Returns a new string object with the value \var{v} and length
1825\var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
1826the contents of the string are uninitialized.
1827\end{cfuncdesc}
1828
Fred Drakec6fa34e1998-04-02 06:47:24 +00001829\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00001830Returns the length of the string in string object \var{string}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001831\end{cfuncdesc}
1832
Fred Drake659ebfa2000-04-03 15:42:13 +00001833\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
1834Macro form of \cfunction{PyString_GetSize()} but without error
1835checking.
1836\end{cfuncdesc}
1837
Fred Drakec6fa34e1998-04-02 06:47:24 +00001838\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
Fred Drake659ebfa2000-04-03 15:42:13 +00001839Returns a null-terminated representation of the contents of
1840\var{string}. The pointer refers to the internal buffer of
1841\var{string}, not a copy. The data must not be modified in any way.
1842It must not be de-allocated.
1843\end{cfuncdesc}
1844
1845\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
1846Macro form of \cfunction{PyString_AsString()} but without error
1847checking.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001848\end{cfuncdesc}
1849
1850\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
1851 PyObject *newpart}
Fred Drake66b989c1999-02-15 20:15:39 +00001852Creates a new string object in \var{*string} containing the
Fred Drakeddc6c272000-03-31 18:22:38 +00001853contents of \var{newpart} appended to \var{string}; the caller will
1854own the new reference. The reference to the old value of \var{string}
1855will be stolen. If the new string
Fred Drake66b989c1999-02-15 20:15:39 +00001856cannot be created, the old reference to \var{string} will still be
1857discarded and the value of \var{*string} will be set to
1858\NULL{}; the appropriate exception will be set.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001859\end{cfuncdesc}
1860
1861\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
1862 PyObject *newpart}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00001863Creates a new string object in \var{*string} containing the contents
Guido van Rossum44475131998-04-21 15:30:01 +00001864of \var{newpart} appended to \var{string}. This version decrements
1865the reference count of \var{newpart}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001866\end{cfuncdesc}
1867
1868\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
Guido van Rossum44475131998-04-21 15:30:01 +00001869A way to resize a string object even though it is ``immutable''.
1870Only use this to build up a brand new string object; don't use this if
1871the string may already be known in other parts of the code.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001872\end{cfuncdesc}
1873
1874\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
1875 PyObject *args}
Guido van Rossum44475131998-04-21 15:30:01 +00001876Returns a new string object from \var{format} and \var{args}. Analogous
Fred Drake659ebfa2000-04-03 15:42:13 +00001877to \code{\var{format} \%\ \var{args}}. The \var{args} argument must be
Guido van Rossum44475131998-04-21 15:30:01 +00001878a tuple.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001879\end{cfuncdesc}
1880
1881\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
Guido van Rossum44475131998-04-21 15:30:01 +00001882Intern the argument \var{*string} in place. The argument must be the
1883address of a pointer variable pointing to a Python string object.
1884If there is an existing interned string that is the same as
1885\var{*string}, it sets \var{*string} to it (decrementing the reference
1886count of the old string object and incrementing the reference count of
1887the interned string object), otherwise it leaves \var{*string} alone
1888and interns it (incrementing its reference count). (Clarification:
1889even though there is a lot of talk about reference counts, think of
Fred Drakef8830d11998-04-23 14:06:01 +00001890this function as reference-count-neutral; you own the object after
1891the call if and only if you owned it before the call.)
Fred Drakec6fa34e1998-04-02 06:47:24 +00001892\end{cfuncdesc}
1893
1894\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
Fred Drakef8830d11998-04-23 14:06:01 +00001895A combination of \cfunction{PyString_FromString()} and
1896\cfunction{PyString_InternInPlace()}, returning either a new string object
Guido van Rossum44475131998-04-21 15:30:01 +00001897that has been interned, or a new (``owned'') reference to an earlier
1898interned string object with the same value.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001899\end{cfuncdesc}
1900
Fred Drakee5bf8b21998-02-12 21:22:28 +00001901
Fred Drakea4cd2612000-04-06 14:10:29 +00001902\subsection{Unicode Objects \label{unicodeObjects}}
1903\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
1904
1905%--- Unicode Type -------------------------------------------------------
1906
1907These are the basic Unicode object types used for the Unicode
1908implementation in Python:
1909
1910\begin{ctypedesc}{Py_UNICODE}
1911This type represents a 16-bit unsigned storage type which is used by
1912Python internally as basis for holding Unicode ordinals. On platforms
1913where \ctype{wchar_t} is available and also has 16-bits,
1914\ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
1915native platform compatibility. On all other platforms,
1916\ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
1917\end{ctypedesc}
1918
1919\begin{ctypedesc}{PyUnicodeObject}
1920This subtype of \ctype{PyObject} represents a Python Unicode object.
1921\end{ctypedesc}
1922
1923\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
1924This instance of \ctype{PyTypeObject} represents the Python Unicode type.
1925\end{cvardesc}
1926
1927%--- These are really C macros... is there a macrodesc TeX macro ?
1928
1929The following APIs are really C macros and can be used to do fast
1930checks and to access internal read-only data of Unicode objects:
1931
1932\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
1933Returns true if the object \var{o} is a Unicode object.
1934\end{cfuncdesc}
1935
1936\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
1937Returns the size of the object. o has to be a
1938PyUnicodeObject (not checked).
1939\end{cfuncdesc}
1940
1941\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
1942Returns the size of the object's internal buffer in bytes. o has to be
1943a PyUnicodeObject (not checked).
1944\end{cfuncdesc}
1945
1946\begin{cfuncdesc}{int}{PyUnicode_AS_UNICODE}{PyObject *o}
1947Returns a pointer to the internal Py_UNICODE buffer of the object. o
1948has to be a PyUnicodeObject (not checked).
1949\end{cfuncdesc}
1950
1951\begin{cfuncdesc}{int}{PyUnicode_AS_DATA}{PyObject *o}
1952Returns a (const char *) pointer to the internal buffer of the object.
1953o has to be a PyUnicodeObject (not checked).
1954\end{cfuncdesc}
1955
1956% --- Unicode character properties ---------------------------------------
1957
1958Unicode provides many different character properties. The most often
1959needed ones are available through these macros which are mapped to C
1960functions depending on the Python configuration.
1961
1962\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
1963Returns 1/0 depending on whether \var{ch} is a whitespace character.
1964\end{cfuncdesc}
1965
1966\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
1967Returns 1/0 depending on whether \var{ch} is a lowercase character.
1968\end{cfuncdesc}
1969
1970\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
1971Returns 1/0 depending on whether \var{ch} is a uppercase character.
1972\end{cfuncdesc}
1973
1974\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
1975Returns 1/0 depending on whether \var{ch} is a titlecase character.
1976\end{cfuncdesc}
1977
1978\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
1979Returns 1/0 depending on whether \var{ch} is a linebreak character.
1980\end{cfuncdesc}
1981
1982\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
1983Returns 1/0 depending on whether \var{ch} is a decimal character.
1984\end{cfuncdesc}
1985
1986\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
1987Returns 1/0 depending on whether \var{ch} is a digit character.
1988\end{cfuncdesc}
1989
1990\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
1991Returns 1/0 depending on whether \var{ch} is a numeric character.
1992\end{cfuncdesc}
1993
1994These APIs can be used for fast direct character conversions:
1995
1996\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
1997Returns the character \var{ch} converted to lower case.
1998\end{cfuncdesc}
1999
2000\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
2001Returns the character \var{ch} converted to upper case.
2002\end{cfuncdesc}
2003
2004\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
2005Returns the character \var{ch} converted to title case.
2006\end{cfuncdesc}
2007
2008\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
2009Returns the character \var{ch} converted to a decimal positive integer.
2010Returns -1 in case this is not possible. Does not raise exceptions.
2011\end{cfuncdesc}
2012
2013\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
2014Returns the character \var{ch} converted to a single digit integer.
2015Returns -1 in case this is not possible. Does not raise exceptions.
2016\end{cfuncdesc}
2017
2018\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
2019Returns the character \var{ch} converted to a (positive) double.
2020Returns -1.0 in case this is not possible. Does not raise exceptions.
2021\end{cfuncdesc}
2022
2023% --- Plain Py_UNICODE ---------------------------------------------------
2024
2025To create Unicode objects and access their basic sequence properties,
2026use these APIs:
2027
2028\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
2029 int size}
2030
2031Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
2032given size. \var{u} may be \NULL{} which causes the contents to be
2033undefined. It is the user's responsibility to fill in the needed data.
2034The buffer is copied into the new object.
2035\end{cfuncdesc}
2036
2037\begin{cfuncdesc}{Py_UNICODE *}{PyUnicode_AsUnicode}{PyObject *unicode}
2038Return a read-only pointer to the Unicode object's internal
2039\ctype{Py_UNICODE} buffer.
2040\end{cfuncdesc}
2041
2042\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
2043Return the length of the Unicode object.
2044\end{cfuncdesc}
2045
2046\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
2047
2048Coerce obj to an Unicode object and return a reference with
2049incremented refcount.
2050
2051Coercion is done in the following way:
2052\begin{enumerate}
2053\item Unicode objects are passed back as-is with incremented
2054 refcount.
2055
2056\item String and other char buffer compatible objects are decoded
2057 under the assumptions that they contain UTF-8 data. Decoding
2058 is done in "strict" mode.
2059
2060\item All other objects raise an exception.
2061\end{enumerate}
2062The API returns NULL in case of an error. The caller is responsible
2063for decref'ing the returned objects.
2064\end{cfuncdesc}
2065
2066% --- wchar_t support for platforms which support it ---------------------
2067
2068If the platform supports \ctype{wchar_t} and provides a header file
2069wchar.h, Python can interface directly to this type using the
2070following functions. Support is optimized if Python's own
2071\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
2072
2073\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
2074 int size}
2075Create a Unicode Object from the \ctype{whcar_t} buffer \var{w} of the
2076given size. Returns \NULL{} on failure.
2077\end{cfuncdesc}
2078
2079\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
2080 wchar_t *w,
2081 int size}
2082
2083Copies the Unicode Object contents into the \ctype{whcar_t} buffer
2084\var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
2085Returns the number of \ctype{whcar_t} characters copied or -1 in case
2086of an error.
2087\end{cfuncdesc}
2088
2089
2090\subsubsection{Builtin Codecs \label{builtinCodecs}}
2091
2092Python provides a set of builtin codecs which are written in C
2093for speed. All of these codecs are directly usable via the
2094following functions.
2095
2096Many of the following APIs take two arguments encoding and
2097errors. These parameters encoding and errors have the same semantics
2098as the ones of the builtin unicode() Unicode object constructor.
2099
2100Setting encoding to NULL causes the default encoding to be used which
2101is UTF-8.
2102
2103Error handling is set by errors which may also be set to NULL meaning
2104to use the default handling defined for the codec. Default error
2105handling for all builtin codecs is ``strict'' (ValueErrors are raised).
2106
2107The codecs all use a similar interface. Only deviation from the
2108following generic ones are documented for simplicity.
2109
2110% --- Generic Codecs -----------------------------------------------------
2111
2112These are the generic codec APIs:
2113
2114\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
2115 int size,
2116 const char *encoding,
2117 const char *errors}
2118
2119Create a Unicode object by decoding \var{size} bytes of the encoded
2120string \var{s}. \var{encoding} and \var{errors} have the same meaning
2121as the parameters of the same name in the unicode() builtin
2122function. The codec to be used is looked up using the Python codec
2123registry. Returns \NULL{} in case an exception was raised by the
2124codec.
2125\end{cfuncdesc}
2126
2127\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
2128 int size,
2129 const char *encoding,
2130 const char *errors}
2131
2132Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2133Python string object. \var{encoding} and \var{errors} have the same
2134meaning as the parameters of the same name in the Unicode .encode()
2135method. The codec to be used is looked up using the Python codec
2136registry. Returns \NULL{} in case an exception was raised by the
2137codec.
2138\end{cfuncdesc}
2139
2140\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
2141 const char *encoding,
2142 const char *errors}
2143
2144Encodes a Unicode object and returns the result as Python string
2145object. \var{encoding} and \var{errors} have the same meaning as the
2146parameters of the same name in the Unicode .encode() method. The codec
2147to be used is looked up using the Python codec registry. Returns
2148\NULL{} in case an exception was raised by the codec.
2149\end{cfuncdesc}
2150
2151% --- UTF-8 Codecs -------------------------------------------------------
2152
2153These are the UTF-8 codec APIs:
2154
2155\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
2156 int size,
2157 const char *errors}
2158
2159Creates a Unicode object by decoding \var{size} bytes of the UTF-8
2160encoded string \var{s}. Returns \NULL{} in case an exception was
2161raised by the codec.
2162\end{cfuncdesc}
2163
2164\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
2165 int size,
2166 const char *errors}
2167
2168Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
2169and returns a Python string object. Returns \NULL{} in case an
2170exception was raised by the codec.
2171\end{cfuncdesc}
2172
2173\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
2174
2175Encodes a Unicode objects using UTF-8 and returns the result as Python
2176string object. Error handling is ``strict''. Returns
2177\NULL{} in case an exception was raised by the codec.
2178\end{cfuncdesc}
2179
2180% --- UTF-16 Codecs ------------------------------------------------------ */
2181
2182These are the UTF-16 codec APIs:
2183
2184\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
2185 int size,
2186 const char *errors,
2187 int *byteorder}
2188
2189Decodes \var{length} bytes from a UTF-16 encoded buffer string and
2190returns the corresponding Unicode object.
2191
2192\var{errors} (if non-NULL) defines the error handling. It defaults
2193to ``strict''.
2194
2195If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
2196the given byte order:
2197
2198\begin{verbatim}
2199 *byteorder == -1: little endian
2200 *byteorder == 0: native order
2201 *byteorder == 1: big endian
2202\end{verbatim}
2203
2204and then switches according to all byte order marks (BOM) it finds in
2205the input data. BOM marks are not copied into the resulting Unicode
2206string. After completion, \var{*byteorder} is set to the current byte
2207order at the end of input data.
2208
2209If \var{byteorder} is \NULL{}, the codec starts in native order mode.
2210
2211Returns \NULL{} in case an exception was raised by the codec.
2212\end{cfuncdesc}
2213
2214\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
2215 int size,
2216 const char *errors,
2217 int byteorder}
2218
2219Returns a Python string object holding the UTF-16 encoded value of the
2220Unicode data in \var{s}.
2221
2222If \var{byteorder} is not 0, output is written according to the
2223following byte order:
2224
2225\begin{verbatim}
2226 byteorder == -1: little endian
2227 byteorder == 0: native byte order (writes a BOM mark)
2228 byteorder == 1: big endian
2229\end{verbatim}
2230
2231If byteorder is 0, the output string will always start with the
2232Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
2233prepended.
2234
2235Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
2236reduced to UCS-2. This trick makes it possible to add full UTF-16
2237capabilities at a later point without comprimising the APIs.
2238
2239Returns \NULL{} in case an exception was raised by the codec.
2240\end{cfuncdesc}
2241
2242\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
2243
2244Returns a Python string using the UTF-16 encoding in native byte
2245order. The string always starts with a BOM mark. Error handling is
2246``strict''. Returns \NULL{} in case an exception was raised by the
2247codec.
2248\end{cfuncdesc}
2249
2250% --- Unicode-Escape Codecs ----------------------------------------------
2251
2252These are the ``Unicode Esacpe'' codec APIs:
2253
2254\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
2255 int size,
2256 const char *errors}
2257
2258Creates a Unicode object by decoding \var{size} bytes of the Unicode-Esacpe
2259encoded string \var{s}. Returns \NULL{} in case an exception was
2260raised by the codec.
2261\end{cfuncdesc}
2262
2263\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
2264 int size,
2265 const char *errors}
2266
2267Encodes the \ctype{Py_UNICODE} buffer of the given size using Unicode-Escape
2268and returns a Python string object. Returns \NULL{} in case an
2269exception was raised by the codec.
2270\end{cfuncdesc}
2271
2272\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
2273
2274Encodes a Unicode objects using Unicode-Escape and returns the result
2275as Python string object. Error handling is ``strict''. Returns
2276\NULL{} in case an exception was raised by the codec.
2277\end{cfuncdesc}
2278
2279% --- Raw-Unicode-Escape Codecs ------------------------------------------
2280
2281These are the ``Raw Unicode Esacpe'' codec APIs:
2282
2283\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
2284 int size,
2285 const char *errors}
2286
2287Creates a Unicode object by decoding \var{size} bytes of the Raw-Unicode-Esacpe
2288encoded string \var{s}. Returns \NULL{} in case an exception was
2289raised by the codec.
2290\end{cfuncdesc}
2291
2292\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
2293 int size,
2294 const char *errors}
2295
2296Encodes the \ctype{Py_UNICODE} buffer of the given size using Raw-Unicode-Escape
2297and returns a Python string object. Returns \NULL{} in case an
2298exception was raised by the codec.
2299\end{cfuncdesc}
2300
2301\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
2302
2303Encodes a Unicode objects using Raw-Unicode-Escape and returns the result
2304as Python string object. Error handling is ``strict''. Returns
2305\NULL{} in case an exception was raised by the codec.
2306\end{cfuncdesc}
2307
2308% --- Latin-1 Codecs -----------------------------------------------------
2309
2310These are the Latin-1 codec APIs:
2311
2312Latin-1 corresponds to the first 256 Unicode ordinals and only these
2313are accepted by the codecs during encoding.
2314
2315\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
2316 int size,
2317 const char *errors}
2318
2319Creates a Unicode object by decoding \var{size} bytes of the Latin-1
2320encoded string \var{s}. Returns \NULL{} in case an exception was
2321raised by the codec.
2322\end{cfuncdesc}
2323
2324\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
2325 int size,
2326 const char *errors}
2327
2328Encodes the \ctype{Py_UNICODE} buffer of the given size using Latin-1
2329and returns a Python string object. Returns \NULL{} in case an
2330exception was raised by the codec.
2331\end{cfuncdesc}
2332
2333\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
2334
2335Encodes a Unicode objects using Latin-1 and returns the result as
2336Python string object. Error handling is ``strict''. Returns
2337\NULL{} in case an exception was raised by the codec.
2338\end{cfuncdesc}
2339
2340% --- ASCII Codecs -------------------------------------------------------
2341
2342These are the ASCII codec APIs:
2343
2344Only 7-bit ASCII data is excepted. All other codes generate errors.
2345
2346\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
2347 int size,
2348 const char *errors}
2349
2350Creates a Unicode object by decoding \var{size} bytes of the ASCII
2351encoded string \var{s}. Returns \NULL{} in case an exception was
2352raised by the codec.
2353\end{cfuncdesc}
2354
2355\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
2356 int size,
2357 const char *errors}
2358
2359Encodes the \ctype{Py_UNICODE} buffer of the given size using ASCII
2360and returns a Python string object. Returns \NULL{} in case an
2361exception was raised by the codec.
2362\end{cfuncdesc}
2363
2364\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
2365
2366Encodes a Unicode objects using ASCII and returns the result as Python
2367string object. Error handling is ``strict''. Returns
2368\NULL{} in case an exception was raised by the codec.
2369\end{cfuncdesc}
2370
2371% --- Character Map Codecs -----------------------------------------------
2372
2373These are the mapping codec APIs:
2374
2375This codec is special in that it can be used to implement many
2376different codecs (and this is in fact what was done to obtain most of
2377the standard codecs included in the \module{encodings} package). The
2378codec uses mapping to encode and decode characters.
2379
2380Decoding mappings must map single string characters to single Unicode
2381characters, integers (which are then interpreted as Unicode ordinals)
2382or None (meaning "undefined mapping" and causing an error).
2383
2384Encoding mappings must map single Unicode characters to single string
2385characters, integers (which are then interpreted as Latin-1 ordinals)
2386or None (meaning "undefined mapping" and causing an error).
2387
2388The mapping objects provided must only support the __getitem__ mapping
2389interface.
2390
2391If a character lookup fails with a LookupError, the character is
2392copied as-is meaning that its ordinal value will be interpreted as
2393Unicode or Latin-1 ordinal resp. Because of this, mappings only need
2394to contain those mappings which map characters to different code
2395points.
2396
2397\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
2398 int size,
2399 PyObject *mapping,
2400 const char *errors}
2401
2402Creates a Unicode object by decoding \var{size} bytes of the encoded
2403string \var{s} using the given \var{mapping} object. Returns \NULL{}
2404in case an exception was raised by the codec.
2405\end{cfuncdesc}
2406
2407\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
2408 int size,
2409 PyObject *mapping,
2410 const char *errors}
2411
2412Encodes the \ctype{Py_UNICODE} buffer of the given size using the
2413given \var{mapping} object and returns a Python string object.
2414Returns \NULL{} in case an exception was raised by the codec.
2415\end{cfuncdesc}
2416
2417\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
2418 PyObject *mapping}
2419
2420Encodes a Unicode objects using the given \var{mapping} object and
2421returns the result as Python string object. Error handling is
2422``strict''. Returns \NULL{} in case an exception was raised by the
2423codec.
2424\end{cfuncdesc}
2425
2426The following codec API is special in that maps Unicode to Unicode.
2427
2428\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
2429 int size,
2430 PyObject *table,
2431 const char *errors}
2432
2433Translates a \ctype{Py_UNICODE} buffer of the given length by applying
2434a character mapping \var{table} to it and returns the resulting
2435Unicode object.
2436
2437The \var{mapping} table must map Unicode ordinal integers to Unicode
2438ordinal integers or None (causing deletion of the character).
2439
2440Mapping tables must only provide the __getitem__ interface,
2441e.g. dictionaries or sequences. Unmapped character ordinals (ones
2442which cause a LookupError) are left untouched and are copied as-is.
2443
2444Returns \NULL{} in case an exception was raised by the codec.
2445\end{cfuncdesc}
2446
2447% --- MBCS codecs for Windows --------------------------------------------
2448
2449These are the MBCS codec APIs. They are currently only available
2450Windows and use the Win32 MBCS converters to implement the
2451conversions.
2452
2453Note that MBCS (or DBCS) is a class of encodings, not just one. The
2454target encoding is defined by the user settings on the machine running
2455the codec.
2456
2457\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
2458 int size,
2459 const char *errors}
2460
2461Creates a Unicode object by decoding \var{size} bytes of the MBCS
2462encoded string \var{s}. Returns \NULL{} in case an exception was
2463raised by the codec.
2464\end{cfuncdesc}
2465
2466\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
2467 int size,
2468 const char *errors}
2469
2470Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
2471and returns a Python string object. Returns \NULL{} in case an
2472exception was raised by the codec.
2473\end{cfuncdesc}
2474
2475\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
2476
2477Encodes a Unicode objects using MBCS and returns the result as Python
2478string object. Error handling is ``strict''. Returns
2479\NULL{} in case an exception was raised by the codec.
2480\end{cfuncdesc}
2481
2482% --- Methods & Slots ----------------------------------------------------
2483
2484\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
2485
2486The following APIs are capable of handling Unicode objects and strings
2487on input (we refer to them as strings in the descriptions) and return
2488Unicode objects or integers as apporpriate.
2489
2490They all return \NULL{} or -1 in case an exception occurrs.
2491
2492\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
2493 PyObject *right}
2494
2495Concat two strings giving a new Unicode string.
2496\end{cfuncdesc}
2497
2498\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
2499 PyObject *sep,
2500 int maxsplit}
2501
2502Split a string giving a list of Unicode strings.
2503
2504If sep is NULL, splitting will be done at all whitespace
2505substrings. Otherwise, splits occur at the given separator.
2506
2507At most maxsplit splits will be done. If negative, no limit is set.
2508
2509Separators are not included in the resulting list.
2510\end{cfuncdesc}
2511
2512\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
2513 int maxsplit}
2514
2515Dito, but split at line breaks.
2516
2517CRLF is considered to be one line break. Line breaks are not
2518included in the resulting list.
2519\end{cfuncdesc}
2520
2521\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
2522 PyObject *table,
2523 const char *errors}
2524
2525Translate a string by applying a character mapping table to it and
2526return the resulting Unicode object.
2527
2528The mapping table must map Unicode ordinal integers to Unicode ordinal
2529integers or None (causing deletion of the character).
2530
2531Mapping tables must only provide the __getitem__ interface,
2532e.g. dictionaries or sequences. Unmapped character ordinals (ones
2533which cause a LookupError) are left untouched and are copied as-is.
2534
2535\var{errors} has the usual meaning for codecs. It may be \NULL{}
2536which indicates to use the default error handling.
2537
2538\end{cfuncdesc}
2539
2540\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
2541 PyObject *seq}
2542
2543Join a sequence of strings using the given separator and return
2544the resulting Unicode string.
2545\end{cfuncdesc}
2546
2547\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
2548 PyObject *substr,
2549 int start,
2550 int end,
2551 int direction}
2552
2553Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
2554the given tail end (\var{direction} == -1 means to do a prefix match,
2555\var{direction} == 1 a suffix match), 0 otherwise.
2556\end{cfuncdesc}
2557
2558\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
2559 PyObject *substr,
2560 int start,
2561 int end,
2562 int direction}
2563
2564Return the first position of \var{substr} in
2565\var{str}[\var{start}:\var{end}] using the given \var{direction}
2566(\var{direction} == 1 means to do a forward search,
2567\var{direction} == -1 a backward search), 0 otherwise.
2568\end{cfuncdesc}
2569
2570\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
2571 PyObject *substr,
2572 int start,
2573 int end}
2574
2575Count the number of occurrences of \var{substr} in
2576\var{str}[\var{start}:\var{end}]
2577\end{cfuncdesc}
2578
2579\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
2580 PyObject *substr,
2581 PyObject *replstr,
2582 int maxcount}
2583
2584Replace at most \var{maxcount} occurrences of \var{substr} in
2585\var{str} with \var{replstr} and return the resulting Unicode object.
2586\var{maxcount} == -1 means: replace all occurrences.
2587\end{cfuncdesc}
2588
2589\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left,
2590 PyObject *right}
2591
2592Compare two strings and return -1, 0, 1 for less than, equal,
2593greater than resp.
2594\end{cfuncdesc}
2595
2596\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
2597 PyObject *args}
2598Returns a new string object from \var{format} and \var{args}. Analogous
2599to \code{\var{format} \% \var{args}}. The \var{args} argument must be
2600a tuple.
2601\end{cfuncdesc}
2602
2603\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
2604 PyObject *element}
2605
2606Checks whether \var{element} is contained in \var{container} and
2607returns 1/0 accordingly.
2608
2609\var{element} has to coerce to an one element Unicode string. -1 is
2610returned in case of an error.
2611\end{cfuncdesc}
2612
2613
Fred Drake58c5a2a1999-08-04 13:13:24 +00002614\subsection{Buffer Objects \label{bufferObjects}}
Fred Drake659ebfa2000-04-03 15:42:13 +00002615\sectionauthor{Greg Stein}{gstein@lyra.org}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002616
Fred Drake659ebfa2000-04-03 15:42:13 +00002617\obindex{buffer}
2618Python objects implemented in C can export a group of functions called
2619the ``buffer\index{buffer interface} interface.'' These functions can
2620be used by an object to expose its data in a raw, byte-oriented
2621format. Clients of the object can use the buffer interface to access
2622the object data directly, without needing to copy it first.
2623
2624Two examples of objects that support
2625the buffer interface are strings and arrays. The string object exposes
2626the character contents in the buffer interface's byte-oriented
2627form. An array can also expose its contents, but it should be noted
2628that array elements may be multi-byte values.
2629
2630An example user of the buffer interface is the file object's
2631\method{write()} method. Any object that can export a series of bytes
2632through the buffer interface can be written to a file. There are a
2633number of format codes to \cfunction{PyArgs_ParseTuple()} that operate
2634against an object's buffer interface, returning data from the target
2635object.
2636
2637More information on the buffer interface is provided in the section
2638``Buffer Object Structures'' (section \ref{buffer-structs}), under
2639the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
2640
2641A ``buffer object'' is defined in the \file{bufferobject.h} header
2642(included by \file{Python.h}). These objects look very similar to
2643string objects at the Python programming level: they support slicing,
2644indexing, concatenation, and some other standard string
2645operations. However, their data can come from one of two sources: from
2646a block of memory, or from another object which exports the buffer
2647interface.
2648
2649Buffer objects are useful as a way to expose the data from another
2650object's buffer interface to the Python programmer. They can also be
2651used as a zero-copy slicing mechanism. Using their ability to
2652reference a block of memory, it is possible to expose any data to the
2653Python programmer quite easily. The memory could be a large, constant
2654array in a C extension, it could be a raw block of memory for
2655manipulation before passing to an operating system library, or it
2656could be used to pass around structured data in its native, in-memory
2657format.
2658
2659\begin{ctypedesc}{PyBufferObject}
2660This subtype of \ctype{PyObject} represents a buffer object.
2661\end{ctypedesc}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002662
2663\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
2664The instance of \ctype{PyTypeObject} which represents the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00002665buffer type; it is the same object as \code{types.BufferType} in the
2666Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002667\end{cvardesc}
2668
2669\begin{cvardesc}{int}{Py_END_OF_BUFFER}
Fred Drake659ebfa2000-04-03 15:42:13 +00002670This constant may be passed as the \var{size} parameter to
2671\cfunction{PyBuffer_FromObject()} or
2672\cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the new
2673\ctype{PyBufferObject} should refer to \var{base} object from the
2674specified \var{offset} to the end of its exported buffer. Using this
2675enables the caller to avoid querying the \var{base} object for its
2676length.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002677\end{cvardesc}
2678
2679\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
2680Return true if the argument has type \cdata{PyBuffer_Type}.
2681\end{cfuncdesc}
2682
2683\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
2684 int offset, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002685Return a new read-only buffer object. This raises
2686\exception{TypeError} if \var{base} doesn't support the read-only
2687buffer protocol or doesn't provide exactly one buffer segment, or it
2688raises \exception{ValueError} if \var{offset} is less than zero. The
2689buffer will hold a reference to the \var{base} object, and the
2690buffer's contents will refer to the \var{base} object's buffer
2691interface, starting as position \var{offset} and extending for
2692\var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
2693the new buffer's contents extend to the length of the
2694\var{base} object's exported buffer data.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002695\end{cfuncdesc}
2696
2697\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
2698 int offset,
2699 int size}
2700Return a new writable buffer object. Parameters and exceptions are
2701similar to those for \cfunction{PyBuffer_FromObject()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00002702If the \var{base} object does not export the writeable buffer
2703protocol, then \exception{TypeError} is raised.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002704\end{cfuncdesc}
2705
2706\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002707Return a new read-only buffer object that reads from a specified
2708location in memory, with a specified size.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002709The caller is responsible for ensuring that the memory buffer, passed
2710in as \var{ptr}, is not deallocated while the returned buffer object
2711exists. Raises \exception{ValueError} if \var{size} is less than
Fred Drake659ebfa2000-04-03 15:42:13 +00002712zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be passed
2713for the \var{size} parameter; \exception{ValueError} will be raised in
2714that case.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002715\end{cfuncdesc}
2716
2717\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002718Similar to \cfunction{PyBuffer_FromMemory()}, but the returned buffer
2719is writable.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002720\end{cfuncdesc}
2721
2722\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
2723Returns a new writable buffer object that maintains its own memory
Fred Drake659ebfa2000-04-03 15:42:13 +00002724buffer of \var{size} bytes. \exception{ValueError} is returned if
2725\var{size} is not zero or positive.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002726\end{cfuncdesc}
2727
Guido van Rossum44475131998-04-21 15:30:01 +00002728
Fred Drakeefd146c1999-02-15 15:30:45 +00002729\subsection{Tuple Objects \label{tupleObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002730
Fred Drake659ebfa2000-04-03 15:42:13 +00002731\obindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002732\begin{ctypedesc}{PyTupleObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002733This subtype of \ctype{PyObject} represents a Python tuple object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002734\end{ctypedesc}
2735
2736\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002737This instance of \ctype{PyTypeObject} represents the Python tuple
2738type; it is the same object as \code{types.TupleType} in the Python
2739layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002740\end{cvardesc}
2741
2742\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
2743Return true if the argument is a tuple object.
2744\end{cfuncdesc}
2745
Fred Drake659ebfa2000-04-03 15:42:13 +00002746\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
2747Return a new tuple object of size \var{len}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002748\end{cfuncdesc}
2749
2750\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
Fred Drakee058b4f1998-02-16 06:15:35 +00002751Takes a pointer to a tuple object, and returns the size
Fred Drakee5bf8b21998-02-12 21:22:28 +00002752of that tuple.
2753\end{cfuncdesc}
2754
Fred Drakec6fa34e1998-04-02 06:47:24 +00002755\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00002756Returns the object at position \var{pos} in the tuple pointed
2757to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00002758sets an \exception{IndexError} exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002759\end{cfuncdesc}
2760
Fred Drakec6fa34e1998-04-02 06:47:24 +00002761\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00002762Does the same, but does no checking of its arguments.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002763\end{cfuncdesc}
2764
Fred Drakec6fa34e1998-04-02 06:47:24 +00002765\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyTupleObject *p,
Fred Drakee5bf8b21998-02-12 21:22:28 +00002766 int low,
2767 int high}
Fred Drakee058b4f1998-02-16 06:15:35 +00002768Takes a slice of the tuple pointed to by \var{p} from
2769\var{low} to \var{high} and returns it as a new tuple.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002770\end{cfuncdesc}
2771
Fred Drake659ebfa2000-04-03 15:42:13 +00002772\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
2773 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002774Inserts a reference to object \var{o} at position \var{pos} of
2775the tuple pointed to by \var{p}. It returns \code{0} on success.
Fred Drake659ebfa2000-04-03 15:42:13 +00002776\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002777\end{cfuncdesc}
2778
Fred Drake659ebfa2000-04-03 15:42:13 +00002779\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
2780 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002781Does the same, but does no error checking, and
Fred Drakee5bf8b21998-02-12 21:22:28 +00002782should \emph{only} be used to fill in brand new tuples.
Fred Drake659ebfa2000-04-03 15:42:13 +00002783\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002784\end{cfuncdesc}
2785
Fred Drakec6fa34e1998-04-02 06:47:24 +00002786\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyTupleObject *p,
Fred Drake659ebfa2000-04-03 15:42:13 +00002787 int newsize, int last_is_sticky}
2788Can be used to resize a tuple. \var{newsize} will be the new length
2789of the tuple. Because tuples are \emph{supposed} to be immutable,
2790this should only be used if there is only one reference to the object.
2791Do \emph{not} use this if the tuple may already be known to some other
2792part of the code. \var{last_is_sticky} is a flag --- if true, the
2793tuple will grow or shrink at the front, otherwise it will grow or
2794shrink at the end. Think of this as destroying the old tuple and
2795creating a new one, only more efficiently. Returns \code{0} on
2796success and \code{-1} on failure (in which case a
2797\exception{MemoryError} or \exception{SystemError} will be raised).
Fred Drakee5bf8b21998-02-12 21:22:28 +00002798\end{cfuncdesc}
2799
2800
Fred Drakeefd146c1999-02-15 15:30:45 +00002801\subsection{List Objects \label{listObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002802
Fred Drake659ebfa2000-04-03 15:42:13 +00002803\obindex{list}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002804\begin{ctypedesc}{PyListObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002805This subtype of \ctype{PyObject} represents a Python list object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002806\end{ctypedesc}
2807
2808\begin{cvardesc}{PyTypeObject}{PyList_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002809This instance of \ctype{PyTypeObject} represents the Python list
2810type. This is the same object as \code{types.ListType}.
2811\withsubitem{(in module types)}{\ttindex{ListType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002812\end{cvardesc}
2813
2814\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00002815Returns true if its argument is a \ctype{PyListObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002816\end{cfuncdesc}
2817
Fred Drake659ebfa2000-04-03 15:42:13 +00002818\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
2819Returns a new list of length \var{len} on success, or \NULL{} on
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002820failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002821\end{cfuncdesc}
2822
Fred Drakec6fa34e1998-04-02 06:47:24 +00002823\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00002824Returns the length of the list object in \var{list}; this is
2825equivalent to \samp{len(\var{list})} on a list object.
2826\bifuncindex{len}
2827\end{cfuncdesc}
2828
2829\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
2830Macro form of \cfunction{PyList_GetSize()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002831\end{cfuncdesc}
2832
Fred Drakec6fa34e1998-04-02 06:47:24 +00002833\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
Guido van Rossum44475131998-04-21 15:30:01 +00002834Returns the object at position \var{pos} in the list pointed
2835to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00002836sets an \exception{IndexError} exception.
2837\end{cfuncdesc}
2838
2839\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
2840Macro form of \cfunction{PyList_GetItem()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002841\end{cfuncdesc}
2842
Fred Drakec6fa34e1998-04-02 06:47:24 +00002843\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
2844 PyObject *item}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002845Sets the item at index \var{index} in list to \var{item}.
Fred Drake659ebfa2000-04-03 15:42:13 +00002846\strong{Note:} This function ``steals'' a reference to \var{item}.
2847\end{cfuncdesc}
2848
2849\begin{cfuncdesc}{PyObject*}{PyList_SET_ITEM}{PyObject *list, int i,
2850 PyObject *o}
2851Macro form of \cfunction{PyList_SetItem()} without error checking.
2852\strong{Note:} This function ``steals'' a reference to \var{item}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002853\end{cfuncdesc}
2854
Fred Drakec6fa34e1998-04-02 06:47:24 +00002855\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
Guido van Rossum44475131998-04-21 15:30:01 +00002856 PyObject *item}
2857Inserts the item \var{item} into list \var{list} in front of index
Fred Drake659ebfa2000-04-03 15:42:13 +00002858\var{index}. Returns \code{0} if successful; returns \code{-1} and
2859raises an exception if unsuccessful. Analogous to
2860\code{\var{list}.insert(\var{index}, \var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002861\end{cfuncdesc}
2862
Fred Drakec6fa34e1998-04-02 06:47:24 +00002863\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
Guido van Rossum44475131998-04-21 15:30:01 +00002864Appends the object \var{item} at the end of list \var{list}. Returns
Fred Drake659ebfa2000-04-03 15:42:13 +00002865\code{0} if successful; returns \code{-1} and sets an exception if
2866unsuccessful. Analogous to \code{\var{list}.append(\var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002867\end{cfuncdesc}
2868
Fred Drakec6fa34e1998-04-02 06:47:24 +00002869\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
2870 int low, int high}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002871Returns a list of the objects in \var{list} containing the objects
Guido van Rossum44475131998-04-21 15:30:01 +00002872\emph{between} \var{low} and \var{high}. Returns NULL and sets an
2873exception if unsuccessful.
Fred Drake659ebfa2000-04-03 15:42:13 +00002874Analogous to \code{\var{list}[\var{low}:\var{high}]}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002875\end{cfuncdesc}
2876
Fred Drakec6fa34e1998-04-02 06:47:24 +00002877\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
2878 int low, int high,
2879 PyObject *itemlist}
Fred Drake659ebfa2000-04-03 15:42:13 +00002880Sets the slice of \var{list} between \var{low} and \var{high} to the
2881contents of \var{itemlist}. Analogous to
2882\code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
2883\code{0} on success, \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002884\end{cfuncdesc}
2885
Fred Drakec6fa34e1998-04-02 06:47:24 +00002886\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00002887Sorts the items of \var{list} in place. Returns \code{0} on success,
2888\code{-1} on failure. This is equivalent to
2889\samp{\var{list}.sort()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002890\end{cfuncdesc}
2891
Fred Drakec6fa34e1998-04-02 06:47:24 +00002892\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00002893Reverses the items of \var{list} in place. Returns \code{0} on
2894success, \code{-1} on failure. This is the equivalent of
2895\samp{\var{list}.reverse()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002896\end{cfuncdesc}
2897
Fred Drakec6fa34e1998-04-02 06:47:24 +00002898\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00002899Returns a new tuple object containing the contents of \var{list};
2900equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002901\end{cfuncdesc}
2902
2903
Fred Drakeefd146c1999-02-15 15:30:45 +00002904\section{Mapping Objects \label{mapObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002905
Fred Drake659ebfa2000-04-03 15:42:13 +00002906\obindex{mapping}
2907
2908
Fred Drakeefd146c1999-02-15 15:30:45 +00002909\subsection{Dictionary Objects \label{dictObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002910
Fred Drake659ebfa2000-04-03 15:42:13 +00002911\obindex{dictionary}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002912\begin{ctypedesc}{PyDictObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002913This subtype of \ctype{PyObject} represents a Python dictionary object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002914\end{ctypedesc}
2915
2916\begin{cvardesc}{PyTypeObject}{PyDict_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002917This instance of \ctype{PyTypeObject} represents the Python dictionary
2918type. This is exposed to Python programs as \code{types.DictType} and
2919\code{types.DictionaryType}.
2920\withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002921\end{cvardesc}
2922
2923\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00002924Returns true if its argument is a \ctype{PyDictObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002925\end{cfuncdesc}
2926
Fred Drakec6fa34e1998-04-02 06:47:24 +00002927\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00002928Returns a new empty dictionary, or \NULL{} on failure.
2929\end{cfuncdesc}
2930
2931\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
2932Empties an existing dictionary of all key-value pairs.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002933\end{cfuncdesc}
2934
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002935\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00002936Returns a new dictionary that contains the same key-value pairs as p.
2937Empties an existing dictionary of all key-value pairs.
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00002938\end{cfuncdesc}
2939
Fred Drake659ebfa2000-04-03 15:42:13 +00002940\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
2941 PyObject *val}
2942Inserts \var{value} into the dictionary with a key of \var{key}.
2943\var{key} must be hashable; if it isn't, \exception{TypeError} will be
2944raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002945\end{cfuncdesc}
2946
2947\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
2948 char *key,
2949 PyObject *val}
Fred Drakee058b4f1998-02-16 06:15:35 +00002950Inserts \var{value} into the dictionary using \var{key}
Fred Drakef8830d11998-04-23 14:06:01 +00002951as a key. \var{key} should be a \ctype{char *}. The key object is
Fred Drakee058b4f1998-02-16 06:15:35 +00002952created using \code{PyString_FromString(\var{key})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00002953\ttindex{PyString_FromString()}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002954\end{cfuncdesc}
2955
Fred Drake659ebfa2000-04-03 15:42:13 +00002956\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002957Removes the entry in dictionary \var{p} with key \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00002958\var{key} must be hashable; if it isn't, \exception{TypeError} is
2959raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002960\end{cfuncdesc}
2961
Fred Drake659ebfa2000-04-03 15:42:13 +00002962\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002963Removes the entry in dictionary \var{p} which has a key
Fred Drake659ebfa2000-04-03 15:42:13 +00002964specified by the string \var{key}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002965\end{cfuncdesc}
2966
Fred Drake659ebfa2000-04-03 15:42:13 +00002967\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00002968Returns the object from dictionary \var{p} which has a key
Guido van Rossum44475131998-04-21 15:30:01 +00002969\var{key}. Returns \NULL{} if the key \var{key} is not present, but
Fred Drake659ebfa2000-04-03 15:42:13 +00002970\emph{without} setting an exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002971\end{cfuncdesc}
2972
Fred Drake659ebfa2000-04-03 15:42:13 +00002973\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
Fred Drakef8830d11998-04-23 14:06:01 +00002974This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
Fred Drake659ebfa2000-04-03 15:42:13 +00002975specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002976\end{cfuncdesc}
2977
Fred Drake659ebfa2000-04-03 15:42:13 +00002978\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00002979Returns a \ctype{PyListObject} containing all the items
Guido van Rossum44475131998-04-21 15:30:01 +00002980from the dictionary, as in the dictinoary method \method{items()} (see
Fred Drakebe486461999-11-09 17:03:03 +00002981the \citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00002982\end{cfuncdesc}
2983
Fred Drake659ebfa2000-04-03 15:42:13 +00002984\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00002985Returns a \ctype{PyListObject} containing all the keys
Guido van Rossum44475131998-04-21 15:30:01 +00002986from the dictionary, as in the dictionary method \method{keys()} (see the
Fred Drakebe486461999-11-09 17:03:03 +00002987\citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00002988\end{cfuncdesc}
2989
Fred Drake659ebfa2000-04-03 15:42:13 +00002990\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00002991Returns a \ctype{PyListObject} containing all the values
Guido van Rossum44475131998-04-21 15:30:01 +00002992from the dictionary \var{p}, as in the dictionary method
Fred Drakebe486461999-11-09 17:03:03 +00002993\method{values()} (see the \citetitle[../lib/lib.html]{Python Library
2994Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00002995\end{cfuncdesc}
2996
Fred Drake659ebfa2000-04-03 15:42:13 +00002997\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
2998Returns the number of items in the dictionary. This is equivalent to
2999\samp{len(\var{p})} on a dictionary.\bifuncindex{len}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003000\end{cfuncdesc}
3001
3002\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p,
3003 int ppos,
3004 PyObject **pkey,
3005 PyObject **pvalue}
3006
3007\end{cfuncdesc}
3008
3009
Fred Drakeefd146c1999-02-15 15:30:45 +00003010\section{Numeric Objects \label{numericObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003011
Fred Drake659ebfa2000-04-03 15:42:13 +00003012\obindex{numeric}
3013
3014
Fred Drakeefd146c1999-02-15 15:30:45 +00003015\subsection{Plain Integer Objects \label{intObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003016
Fred Drake659ebfa2000-04-03 15:42:13 +00003017\obindex{integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003018\begin{ctypedesc}{PyIntObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003019This subtype of \ctype{PyObject} represents a Python integer object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003020\end{ctypedesc}
3021
3022\begin{cvardesc}{PyTypeObject}{PyInt_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003023This instance of \ctype{PyTypeObject} represents the Python plain
Fred Drake659ebfa2000-04-03 15:42:13 +00003024integer type. This is the same object as \code{types.IntType}.
3025\withsubitem{(in modules types)}{\ttindex{IntType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003026\end{cvardesc}
3027
Fred Drake659ebfa2000-04-03 15:42:13 +00003028\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
3029Returns true if \var{o} is of type \cdata{PyInt_Type}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003030\end{cfuncdesc}
3031
Fred Drakec6fa34e1998-04-02 06:47:24 +00003032\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
Fred Drakee058b4f1998-02-16 06:15:35 +00003033Creates a new integer object with a value of \var{ival}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003034
3035The current implementation keeps an array of integer objects for all
Fred Drakee058b4f1998-02-16 06:15:35 +00003036integers between \code{-1} and \code{100}, when you create an int in
3037that range you actually just get back a reference to the existing
3038object. So it should be possible to change the value of \code{1}. I
Fred Drake7e9d3141998-04-03 05:02:28 +00003039suspect the behaviour of Python in this case is undefined. :-)
Fred Drakee5bf8b21998-02-12 21:22:28 +00003040\end{cfuncdesc}
3041
Fred Drakee5bf8b21998-02-12 21:22:28 +00003042\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
Fred Drakef8830d11998-04-23 14:06:01 +00003043Will first attempt to cast the object to a \ctype{PyIntObject}, if
Fred Drakee058b4f1998-02-16 06:15:35 +00003044it is not already one, and then return its value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003045\end{cfuncdesc}
3046
Fred Drake659ebfa2000-04-03 15:42:13 +00003047\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
3048Returns the value of the object \var{io}. No error checking is
3049performed.
3050\end{cfuncdesc}
3051
Fred Drakee5bf8b21998-02-12 21:22:28 +00003052\begin{cfuncdesc}{long}{PyInt_GetMax}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003053Returns the system's idea of the largest integer it can handle
3054(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
3055header files).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003056\end{cfuncdesc}
3057
3058
Fred Drakeefd146c1999-02-15 15:30:45 +00003059\subsection{Long Integer Objects \label{longObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003060
Fred Drake659ebfa2000-04-03 15:42:13 +00003061\obindex{long integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003062\begin{ctypedesc}{PyLongObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003063This subtype of \ctype{PyObject} represents a Python long integer
Fred Drakee058b4f1998-02-16 06:15:35 +00003064object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003065\end{ctypedesc}
3066
3067\begin{cvardesc}{PyTypeObject}{PyLong_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003068This instance of \ctype{PyTypeObject} represents the Python long
Fred Drake659ebfa2000-04-03 15:42:13 +00003069integer type. This is the same object as \code{types.LongType}.
3070\withsubitem{(in modules types)}{\ttindex{LongType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003071\end{cvardesc}
3072
3073\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003074Returns true if its argument is a \ctype{PyLongObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003075\end{cfuncdesc}
3076
Fred Drakec6fa34e1998-04-02 06:47:24 +00003077\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003078Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on
3079failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003080\end{cfuncdesc}
3081
Fred Drakec6fa34e1998-04-02 06:47:24 +00003082\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003083Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
3084long}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003085\end{cfuncdesc}
3086
Fred Drakec6fa34e1998-04-02 06:47:24 +00003087\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003088Returns a new \ctype{PyLongObject} object from the integer part of
3089\var{v}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003090\end{cfuncdesc}
3091
Fred Drakec6fa34e1998-04-02 06:47:24 +00003092\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003093Returns a C \ctype{long} representation of the contents of
3094\var{pylong}. If \var{pylong} is greater than
3095\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is
3096raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003097\end{cfuncdesc}
3098
Fred Drakec6fa34e1998-04-02 06:47:24 +00003099\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003100Returns a C \ctype{unsigned long} representation of the contents of
3101\var{pylong}. If \var{pylong} is greater than
3102\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError}
3103is raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003104\end{cfuncdesc}
3105
Fred Drakec6fa34e1998-04-02 06:47:24 +00003106\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003107Returns a C \ctype{double} representation of the contents of \var{pylong}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003108\end{cfuncdesc}
3109
Fred Drakec6fa34e1998-04-02 06:47:24 +00003110\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
3111 int base}
Fred Drake659ebfa2000-04-03 15:42:13 +00003112Return a new \ctype{PyLongObject} based on the string value in
3113\var{str}, which is interpreted according to the radix in \var{base}.
3114If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first
3115character in \var{str} which follows the representation of the
3116number. If \var{base} is \code{0}, the radix will be determined base
3117on the leading characters of \var{str}: if \var{str} starts with
3118\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts
3119with \code{'0'}, radix 8 will be used; otherwise radix 10 will be
3120used. If \var{base} is not \code{0}, it must be between \code{2} and
3121\code{36}, inclusive. Leading spaces are ignored. If there are no
3122digits, \exception{ValueError} will be raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003123\end{cfuncdesc}
3124
3125
Fred Drakeefd146c1999-02-15 15:30:45 +00003126\subsection{Floating Point Objects \label{floatObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003127
Fred Drake659ebfa2000-04-03 15:42:13 +00003128\obindex{floating point}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003129\begin{ctypedesc}{PyFloatObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003130This subtype of \ctype{PyObject} represents a Python floating point
Fred Drakee058b4f1998-02-16 06:15:35 +00003131object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003132\end{ctypedesc}
3133
3134\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003135This instance of \ctype{PyTypeObject} represents the Python floating
Fred Drake659ebfa2000-04-03 15:42:13 +00003136point type. This is the same object as \code{types.FloatType}.
3137\withsubitem{(in modules types)}{\ttindex{FloatType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003138\end{cvardesc}
3139
3140\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003141Returns true if its argument is a \ctype{PyFloatObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003142\end{cfuncdesc}
3143
Fred Drakec6fa34e1998-04-02 06:47:24 +00003144\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003145Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
3146failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003147\end{cfuncdesc}
3148
Fred Drakec6fa34e1998-04-02 06:47:24 +00003149\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003150Returns a C \ctype{double} representation of the contents of \var{pyfloat}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003151\end{cfuncdesc}
3152
Fred Drakec6fa34e1998-04-02 06:47:24 +00003153\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003154Returns a C \ctype{double} representation of the contents of
Fred Drakef8830d11998-04-23 14:06:01 +00003155\var{pyfloat}, but without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003156\end{cfuncdesc}
3157
3158
Fred Drakeefd146c1999-02-15 15:30:45 +00003159\subsection{Complex Number Objects \label{complexObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003160
Fred Drake659ebfa2000-04-03 15:42:13 +00003161\obindex{complex number}
3162Python's complex number objects are implemented as two distinct types
3163when viewed from the C API: one is the Python object exposed to
3164Python programs, and the other is a C structure which represents the
3165actual complex number value. The API provides functions for working
3166with both.
3167
3168\subsubsection{Complex Numbers as C Structures}
3169
3170Note that the functions which accept these structures as parameters
3171and return them as results do so \emph{by value} rather than
3172dereferencing them through pointers. This is consistent throughout
3173the API.
3174
Fred Drakee5bf8b21998-02-12 21:22:28 +00003175\begin{ctypedesc}{Py_complex}
Fred Drake659ebfa2000-04-03 15:42:13 +00003176The C structure which corresponds to the value portion of a Python
Fred Drake4de05a91998-02-16 14:25:26 +00003177complex number object. Most of the functions for dealing with complex
3178number objects use structures of this type as input or output values,
3179as appropriate. It is defined as:
3180
Fred Drakee058b4f1998-02-16 06:15:35 +00003181\begin{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003182typedef struct {
3183 double real;
3184 double imag;
Fred Drake4de05a91998-02-16 14:25:26 +00003185} Py_complex;
Fred Drakee058b4f1998-02-16 06:15:35 +00003186\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003187\end{ctypedesc}
3188
Fred Drake659ebfa2000-04-03 15:42:13 +00003189\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
3190Return the sum of two complex numbers, using the C
3191\ctype{Py_complex} representation.
3192\end{cfuncdesc}
3193
3194\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
3195Return the difference between two complex numbers, using the C
3196\ctype{Py_complex} representation.
3197\end{cfuncdesc}
3198
3199\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
3200Return the negation of the complex number \var{complex}, using the C
3201\ctype{Py_complex} representation.
3202\end{cfuncdesc}
3203
3204\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
3205Return the product of two complex numbers, using the C
3206\ctype{Py_complex} representation.
3207\end{cfuncdesc}
3208
3209\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
3210 Py_complex divisor}
3211Return the quotient of two complex numbers, using the C
3212\ctype{Py_complex} representation.
3213\end{cfuncdesc}
3214
3215\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
3216Return the exponentiation of \var{num} by \var{exp}, using the C
3217\ctype{Py_complex} representation.
3218\end{cfuncdesc}
3219
3220
3221\subsubsection{Complex Numbers as Python Objects}
3222
Fred Drakee5bf8b21998-02-12 21:22:28 +00003223\begin{ctypedesc}{PyComplexObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003224This subtype of \ctype{PyObject} represents a Python complex number object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003225\end{ctypedesc}
3226
3227\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003228This instance of \ctype{PyTypeObject} represents the Python complex
Fred Drakee5bf8b21998-02-12 21:22:28 +00003229number type.
3230\end{cvardesc}
3231
3232\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003233Returns true if its argument is a \ctype{PyComplexObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003234\end{cfuncdesc}
3235
Fred Drakec6fa34e1998-04-02 06:47:24 +00003236\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003237Create a new Python complex number object from a C
3238\ctype{Py_complex} value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003239\end{cfuncdesc}
3240
Fred Drakec6fa34e1998-04-02 06:47:24 +00003241\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
Fred Drakef8830d11998-04-23 14:06:01 +00003242Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003243\end{cfuncdesc}
3244
3245\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003246Returns the real part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003247\end{cfuncdesc}
3248
3249\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003250Returns the imaginary part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003251\end{cfuncdesc}
3252
3253\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003254Returns the \ctype{Py_complex} value of the complex number \var{op}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003255\end{cfuncdesc}
3256
3257
3258
Fred Drakeefd146c1999-02-15 15:30:45 +00003259\section{Other Objects \label{otherObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003260
Fred Drakeefd146c1999-02-15 15:30:45 +00003261\subsection{File Objects \label{fileObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003262
Fred Drake659ebfa2000-04-03 15:42:13 +00003263\obindex{file}
3264Python's built-in file objects are implemented entirely on the
3265\ctype{FILE*} support from the C standard library. This is an
3266implementation detail and may change in future releases of Python.
3267
Fred Drakee5bf8b21998-02-12 21:22:28 +00003268\begin{ctypedesc}{PyFileObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003269This subtype of \ctype{PyObject} represents a Python file object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003270\end{ctypedesc}
3271
3272\begin{cvardesc}{PyTypeObject}{PyFile_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003273This instance of \ctype{PyTypeObject} represents the Python file
3274type. This is exposed to Python programs as \code{types.FileType}.
3275\withsubitem{(in module types)}{\ttindex{FileType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003276\end{cvardesc}
3277
3278\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003279Returns true if its argument is a \ctype{PyFileObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003280\end{cfuncdesc}
3281
Fred Drake659ebfa2000-04-03 15:42:13 +00003282\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
3283On success, returns a new file object that is opened on the
3284file given by \var{filename}, with a file mode given by \var{mode},
3285where \var{mode} has the same semantics as the standard C routine
3286\cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003287\end{cfuncdesc}
3288
Fred Drakec6fa34e1998-04-02 06:47:24 +00003289\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
Fred Drake659ebfa2000-04-03 15:42:13 +00003290 char *name, char *mode,
3291 int (*close)(FILE*)}
3292Creates a new \ctype{PyFileObject} from the already-open standard C
3293file pointer, \var{fp}. The function \var{close} will be called when
3294the file should be closed. Returns \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003295\end{cfuncdesc}
3296
Fred Drake659ebfa2000-04-03 15:42:13 +00003297\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
3298Returns the file object associated with \var{p} as a \ctype{FILE*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003299\end{cfuncdesc}
3300
Fred Drakec6fa34e1998-04-02 06:47:24 +00003301\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003302Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
3303function reads one line from the object \var{p}. \var{p} may be a
3304file object or any object with a \method{readline()} method. If
3305\var{n} is \code{0}, exactly one line is read, regardless of the
3306length of the line. If \var{n} is greater than \code{0}, no more than
3307\var{n} bytes will be read from the file; a partial line can be
3308returned. In both cases, an empty string is returned if the end of
3309the file is reached immediately. If \var{n} is less than \code{0},
3310however, one line is read regardless of length, but
3311\exception{EOFError} is raised if the end of the file is reached
3312immediately.
3313\withsubitem{(built-in exception)}{\ttindex{EOFError}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003314\end{cfuncdesc}
3315
Fred Drakec6fa34e1998-04-02 06:47:24 +00003316\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003317Returns the name of the file specified by \var{p} as a string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003318\end{cfuncdesc}
3319
3320\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003321Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
3322only. This should only be called immediately after file object
3323creation.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003324\end{cfuncdesc}
3325
Fred Drake659ebfa2000-04-03 15:42:13 +00003326\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
3327This function exists for internal use by the interpreter.
3328Sets the \member{softspace} attribute of \var{p} to \var{newflag} and
3329\withsubitem{(file attribute)}{\ttindex{softspace}}returns the
3330previous value. \var{p} does not have to be a file object
3331for this function to work properly; any object is supported (thought
3332its only interesting if the \member{softspace} attribute can be set).
3333This function clears any errors, and will return \code{0} as the
3334previous value if the attribute either does not exist or if there were
3335errors in retrieving it. There is no way to detect errors from this
3336function, but doing so should not be needed.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003337\end{cfuncdesc}
3338
Fred Drakec6fa34e1998-04-02 06:47:24 +00003339\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
3340 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003341Writes object \var{obj} to file object \var{p}. The only supported
3342flag for \var{flags} is \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW};
3343if given, the \function{str()} of the object is written instead of the
3344\function{repr()}. Returns \code{0} on success or \code{-1} on
3345failure; the appropriate exception will be set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003346\end{cfuncdesc}
3347
Fred Drakec6fa34e1998-04-02 06:47:24 +00003348\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p,
3349 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003350Writes string \var{s} to file object \var{p}. Returns \code{0} on
3351success or \code{-1} on failure; the appropriate exception will be
3352set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003353\end{cfuncdesc}
3354
3355
Fred Drakeefd146c1999-02-15 15:30:45 +00003356\subsection{Module Objects \label{moduleObjects}}
3357
3358\obindex{module}
3359There are only a few functions special to module objects.
3360
Fred Drake659ebfa2000-04-03 15:42:13 +00003361\begin{cvardesc}{PyTypeObject}{PyModule_Type}
3362This instance of \ctype{PyTypeObject} represents the Python module
3363type. This is exposed to Python programs as \code{types.ModuleType}.
3364\withsubitem{(in module types)}{\ttindex{ModuleType}}
3365\end{cvardesc}
3366
3367\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
3368Returns true if its argument is a module object.
Fred Drakeefd146c1999-02-15 15:30:45 +00003369\end{cfuncdesc}
3370
Fred Drake659ebfa2000-04-03 15:42:13 +00003371\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
3372Return a new module object with the \member{__name__} attribute set to
3373\var{name}. Only the module's \member{__doc__} and
3374\member{__name__} attributes are filled in; the caller is responsible
3375for providing a \member{__file__} attribute.
3376\withsubitem{(module attribute)}{
3377 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
3378\end{cfuncdesc}
3379
3380\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003381Return the dictionary object that implements \var{module}'s namespace;
3382this object is the same as the \member{__dict__} attribute of the
3383module object. This function never fails.
Fred Drake659ebfa2000-04-03 15:42:13 +00003384\withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003385\end{cfuncdesc}
3386
Fred Drake659ebfa2000-04-03 15:42:13 +00003387\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003388Return \var{module}'s \member{__name__} value. If the module does not
Fred Drake659ebfa2000-04-03 15:42:13 +00003389provide one, or if it is not a string, \exception{SystemError} is
3390raised and \NULL{} is returned.
3391\withsubitem{(module attribute)}{\ttindex{__name__}}
3392\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003393\end{cfuncdesc}
3394
Fred Drake659ebfa2000-04-03 15:42:13 +00003395\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003396Return the name of the file from which \var{module} was loaded using
3397\var{module}'s \member{__file__} attribute. If this is not defined,
Fred Drake659ebfa2000-04-03 15:42:13 +00003398or if it is not a string, raise \exception{SystemError} and return
3399\NULL.
3400\withsubitem{(module attribute)}{\ttindex{__file__}}
3401\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003402\end{cfuncdesc}
3403
3404
3405\subsection{CObjects \label{cObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003406
Fred Drake659ebfa2000-04-03 15:42:13 +00003407\obindex{CObject}
3408Refer to \emph{Extending and Embedding the Python Interpreter},
3409section 1.12 (``Providing a C API for an Extension Module''), for more
3410information on using these objects.
3411
3412
Guido van Rossum44475131998-04-21 15:30:01 +00003413\begin{ctypedesc}{PyCObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003414This subtype of \ctype{PyObject} represents an opaque value, useful for
Fred Drake659ebfa2000-04-03 15:42:13 +00003415C extension modules who need to pass an opaque value (as a
3416\ctype{void*} pointer) through Python code to other C code. It is
Guido van Rossum44475131998-04-21 15:30:01 +00003417often used to make a C function pointer defined in one module
3418available to other modules, so the regular import mechanism can be
3419used to access C APIs defined in dynamically loaded modules.
3420\end{ctypedesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003421
Fred Drake659ebfa2000-04-03 15:42:13 +00003422\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
3423Returns true if its argument is a \ctype{PyCObject}.
3424\end{cfuncdesc}
3425
3426\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003427 void (*destr)(void *)}
Fred Drakef8830d11998-04-23 14:06:01 +00003428Creates a \ctype{PyCObject} from the \code{void *} \var{cobj}. The
Fred Drakedab44681999-05-13 18:41:14 +00003429\var{destr} function will be called when the object is reclaimed, unless
3430it is \NULL.
Guido van Rossum44475131998-04-21 15:30:01 +00003431\end{cfuncdesc}
3432
Fred Drake659ebfa2000-04-03 15:42:13 +00003433\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003434 void* desc, void (*destr)(void *, void *) }
Fred Drakef8830d11998-04-23 14:06:01 +00003435Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
3436\var{destr} function will be called when the object is reclaimed. The
3437\var{desc} argument can be used to pass extra callback data for the
3438destructor function.
Guido van Rossum44475131998-04-21 15:30:01 +00003439\end{cfuncdesc}
3440
Fred Drake659ebfa2000-04-03 15:42:13 +00003441\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
3442Returns the object \ctype{void *} that the
3443\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003444\end{cfuncdesc}
3445
Fred Drake659ebfa2000-04-03 15:42:13 +00003446\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
3447Returns the description \ctype{void *} that the
3448\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003449\end{cfuncdesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003450
Fred Drake659ebfa2000-04-03 15:42:13 +00003451
Fred Drakeefd146c1999-02-15 15:30:45 +00003452\chapter{Initialization, Finalization, and Threads
3453 \label{initialization}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003454
Guido van Rossum4a944d71997-08-14 20:35:38 +00003455\begin{cfuncdesc}{void}{Py_Initialize}{}
3456Initialize the Python interpreter. In an application embedding
3457Python, this should be called before using any other Python/C API
Fred Drake659ebfa2000-04-03 15:42:13 +00003458functions; with the exception of
3459\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
3460\cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
3461\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
3462and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
3463This initializes the table of loaded modules (\code{sys.modules}), and
3464\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}creates the
3465fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake4de05a91998-02-16 14:25:26 +00003466\module{__main__}\refbimodindex{__main__} and
3467\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drake659ebfa2000-04-03 15:42:13 +00003468search\indexiii{module}{search}{path} path (\code{sys.path}).
3469It does not set \code{sys.argv}; use
3470\cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
3471is a no-op when called for a second time (without calling
3472\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is no
3473return value; it is a fatal error if the initialization fails.
Guido van Rossum42cefd01997-10-05 15:27:29 +00003474\end{cfuncdesc}
3475
3476\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00003477Return true (nonzero) when the Python interpreter has been
Fred Drakee058b4f1998-02-16 06:15:35 +00003478initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
3479called, this returns false until \cfunction{Py_Initialize()} is called
Guido van Rossum42cefd01997-10-05 15:27:29 +00003480again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003481\end{cfuncdesc}
3482
3483\begin{cfuncdesc}{void}{Py_Finalize}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003484Undo all initializations made by \cfunction{Py_Initialize()} and
3485subsequent use of Python/C API functions, and destroy all
3486sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
3487created and not yet destroyed since the last call to
3488\cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
3489by the Python interpreter. This is a no-op when called for a second
3490time (without calling \cfunction{Py_Initialize()} again first). There
3491is no return value; errors during finalization are ignored.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003492
3493This function is provided for a number of reasons. An embedding
3494application might want to restart Python without having to restart the
3495application itself. An application that has loaded the Python
3496interpreter from a dynamically loadable library (or DLL) might want to
3497free all memory allocated by Python before unloading the DLL. During a
3498hunt for memory leaks in an application a developer might want to free
3499all memory allocated by Python before exiting from the application.
3500
Fred Drakee058b4f1998-02-16 06:15:35 +00003501\strong{Bugs and caveats:} The destruction of modules and objects in
Guido van Rossum4a944d71997-08-14 20:35:38 +00003502modules is done in random order; this may cause destructors
Fred Drakee058b4f1998-02-16 06:15:35 +00003503(\method{__del__()} methods) to fail when they depend on other objects
Guido van Rossum4a944d71997-08-14 20:35:38 +00003504(even functions) or modules. Dynamically loaded extension modules
3505loaded by Python are not unloaded. Small amounts of memory allocated
3506by the Python interpreter may not be freed (if you find a leak, please
3507report it). Memory tied up in circular references between objects is
3508not freed. Some memory allocated by extension modules may not be
3509freed. Some extension may not work properly if their initialization
3510routine is called more than once; this can happen if an applcation
Fred Drakee058b4f1998-02-16 06:15:35 +00003511calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
3512than once.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003513\end{cfuncdesc}
3514
Fred Drakec6fa34e1998-04-02 06:47:24 +00003515\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003516Create a new sub-interpreter. This is an (almost) totally separate
3517environment for the execution of Python code. In particular, the new
3518interpreter has separate, independent versions of all imported
3519modules, including the fundamental modules
3520\module{__builtin__}\refbimodindex{__builtin__},
3521\module{__main__}\refbimodindex{__main__} and
3522\module{sys}\refbimodindex{sys}. The table of loaded modules
3523(\code{sys.modules}) and the module search path (\code{sys.path}) are
3524also separate. The new environment has no \code{sys.argv} variable.
3525It has new standard I/O stream file objects \code{sys.stdin},
3526\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drake659ebfa2000-04-03 15:42:13 +00003527same underlying \ctype{FILE} structures in the C library).
3528\withsubitem{(in module sys)}{
3529 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003530
3531The return value points to the first thread state created in the new
3532sub-interpreter. This thread state is made the current thread state.
3533Note that no actual thread is created; see the discussion of thread
3534states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003535\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00003536is stored in the current thread state and there may not be a current
3537thread state. (Like all other Python/C API functions, the global
3538interpreter lock must be held before calling this function and is
3539still held when it returns; however, unlike most other Python/C API
3540functions, there needn't be a current thread state on entry.)
3541
3542Extension modules are shared between (sub-)interpreters as follows:
3543the first time a particular extension is imported, it is initialized
3544normally, and a (shallow) copy of its module's dictionary is
3545squirreled away. When the same extension is imported by another
3546(sub-)interpreter, a new module is initialized and filled with the
Fred Drakee058b4f1998-02-16 06:15:35 +00003547contents of this copy; the extension's \code{init} function is not
3548called. Note that this is different from what happens when an
3549extension is imported after the interpreter has been completely
Fred Drake659ebfa2000-04-03 15:42:13 +00003550re-initialized by calling
3551\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
3552\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
3553the extension's \code{init\var{module}} function \emph{is} called
3554again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003555
Fred Drakee058b4f1998-02-16 06:15:35 +00003556\strong{Bugs and caveats:} Because sub-interpreters (and the main
Guido van Rossum4a944d71997-08-14 20:35:38 +00003557interpreter) are part of the same process, the insulation between them
Fred Drakee058b4f1998-02-16 06:15:35 +00003558isn't perfect --- for example, using low-level file operations like
Fred Drake659ebfa2000-04-03 15:42:13 +00003559\withsubitem{(in module os)}{\ttindex{close()}}
Fred Drakef8830d11998-04-23 14:06:01 +00003560\function{os.close()} they can (accidentally or maliciously) affect each
Guido van Rossum4a944d71997-08-14 20:35:38 +00003561other's open files. Because of the way extensions are shared between
3562(sub-)interpreters, some extensions may not work properly; this is
3563especially likely when the extension makes use of (static) global
3564variables, or when the extension manipulates its module's dictionary
3565after its initialization. It is possible to insert objects created in
3566one sub-interpreter into a namespace of another sub-interpreter; this
3567should be done with great care to avoid sharing user-defined
3568functions, methods, instances or classes between sub-interpreters,
3569since import operations executed by such objects may affect the
3570wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
3571a hard-to-fix bug that will be addressed in a future release.)
3572\end{cfuncdesc}
3573
3574\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
3575Destroy the (sub-)interpreter represented by the given thread state.
3576The given thread state must be the current thread state. See the
3577discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003578thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00003579interpreted are destroyed. (The global interpreter lock must be held
3580before calling this function and is still held when it returns.)
Fred Drake659ebfa2000-04-03 15:42:13 +00003581\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will destroy all
3582sub-interpreters that haven't been explicitly destroyed at that point.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003583\end{cfuncdesc}
3584
3585\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00003586This function should be called before
3587\cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
Guido van Rossum4a944d71997-08-14 20:35:38 +00003588for the first time, if it is called at all. It tells the interpreter
Fred Drake659ebfa2000-04-03 15:42:13 +00003589the value of the \code{argv[0]} argument to the
3590\cfunction{main()}\ttindex{main()} function of the program. This is
3591used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some other
Guido van Rossum4a944d71997-08-14 20:35:38 +00003592functions below to find the Python run-time libraries relative to the
3593interpreter executable. The default value is \code{"python"}. The
3594argument should point to a zero-terminated character string in static
3595storage whose contents will not change for the duration of the
3596program's execution. No code in the Python interpreter will change
3597the contents of this storage.
3598\end{cfuncdesc}
3599
Fred Drakec6fa34e1998-04-02 06:47:24 +00003600\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003601Return the program name set with
3602\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
Guido van Rossum4a944d71997-08-14 20:35:38 +00003603default. The returned string points into static storage; the caller
3604should not modify its value.
3605\end{cfuncdesc}
3606
Fred Drakec6fa34e1998-04-02 06:47:24 +00003607\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003608Return the \emph{prefix} for installed platform-independent files. This
Guido van Rossum4a944d71997-08-14 20:35:38 +00003609is derived through a number of complicated rules from the program name
Fred Drakee058b4f1998-02-16 06:15:35 +00003610set with \cfunction{Py_SetProgramName()} and some environment variables;
Guido van Rossum4a944d71997-08-14 20:35:38 +00003611for example, if the program name is \code{"/usr/local/bin/python"},
3612the prefix is \code{"/usr/local"}. The returned string points into
3613static storage; the caller should not modify its value. This
Fred Drakec94d9341998-04-12 02:39:13 +00003614corresponds to the \makevar{prefix} variable in the top-level
Fred Drake310ee611999-11-09 17:31:42 +00003615\file{Makefile} and the \programopt{-}\programopt{-prefix} argument to the
Fred Drakee058b4f1998-02-16 06:15:35 +00003616\program{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00003617Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00003618also the next function.
3619\end{cfuncdesc}
3620
Fred Drakec6fa34e1998-04-02 06:47:24 +00003621\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003622Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
Guido van Rossum4a944d71997-08-14 20:35:38 +00003623files. This is derived through a number of complicated rules from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003624program name set with \cfunction{Py_SetProgramName()} and some environment
Guido van Rossum4a944d71997-08-14 20:35:38 +00003625variables; for example, if the program name is
3626\code{"/usr/local/bin/python"}, the exec-prefix is
3627\code{"/usr/local"}. The returned string points into static storage;
3628the caller should not modify its value. This corresponds to the
Fred Drakec94d9341998-04-12 02:39:13 +00003629\makevar{exec_prefix} variable in the top-level \file{Makefile} and the
Fred Drake310ee611999-11-09 17:31:42 +00003630\programopt{-}\programopt{-exec_prefix} argument to the
3631\program{configure} script at build time. The value is available to
3632Python code as \code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003633
3634Background: The exec-prefix differs from the prefix when platform
3635dependent files (such as executables and shared libraries) are
3636installed in a different directory tree. In a typical installation,
3637platform dependent files may be installed in the
3638\code{"/usr/local/plat"} subtree while platform independent may be
3639installed in \code{"/usr/local"}.
3640
3641Generally speaking, a platform is a combination of hardware and
3642software families, e.g. Sparc machines running the Solaris 2.x
3643operating system are considered the same platform, but Intel machines
3644running Solaris 2.x are another platform, and Intel machines running
3645Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00003646operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003647operating systems are a different story; the installation strategies
3648on those systems are so different that the prefix and exec-prefix are
3649meaningless, and set to the empty string. Note that compiled Python
3650bytecode files are platform independent (but not independent from the
3651Python version by which they were compiled!).
3652
Fred Drakee058b4f1998-02-16 06:15:35 +00003653System administrators will know how to configure the \program{mount} or
3654\program{automount} programs to share \code{"/usr/local"} between platforms
Guido van Rossum4a944d71997-08-14 20:35:38 +00003655while having \code{"/usr/local/plat"} be a different filesystem for each
3656platform.
3657\end{cfuncdesc}
3658
Fred Drakec6fa34e1998-04-02 06:47:24 +00003659\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003660Return the full program name of the Python executable; this is
3661computed as a side-effect of deriving the default module search path
Fred Drake659ebfa2000-04-03 15:42:13 +00003662from the program name (set by
3663\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
3664The returned string points into static storage; the caller should not
Guido van Rossum4a944d71997-08-14 20:35:38 +00003665modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00003666\code{sys.executable}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003667\withsubitem{(in module sys)}{\ttindex{executable}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003668\end{cfuncdesc}
3669
Fred Drakec6fa34e1998-04-02 06:47:24 +00003670\begin{cfuncdesc}{char*}{Py_GetPath}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003671\indexiii{module}{search}{path}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003672Return the default module search path; this is computed from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003673program name (set by \cfunction{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00003674environment variables. The returned string consists of a series of
3675directory names separated by a platform dependent delimiter character.
Fred Drakef8830d11998-04-23 14:06:01 +00003676The delimiter character is \character{:} on \UNIX{}, \character{;} on
Fred Drake659ebfa2000-04-03 15:42:13 +00003677DOS/Windows, and \character{\e n} (the \ASCII{} newline character) on
Fred Drakee5bc4971998-02-12 23:36:49 +00003678Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00003679should not modify its value. The value is available to Python code
Fred Drake659ebfa2000-04-03 15:42:13 +00003680as the list \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}},
3681which may be modified to change the future search path for loaded
3682modules.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003683
3684% XXX should give the exact rules
3685\end{cfuncdesc}
3686
Fred Drakec6fa34e1998-04-02 06:47:24 +00003687\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003688Return the version of this Python interpreter. This is a string that
3689looks something like
3690
Guido van Rossum09270b51997-08-15 18:57:32 +00003691\begin{verbatim}
Fred Drakee058b4f1998-02-16 06:15:35 +00003692"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
Guido van Rossum09270b51997-08-15 18:57:32 +00003693\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003694
3695The first word (up to the first space character) is the current Python
3696version; the first three characters are the major and minor version
3697separated by a period. The returned string points into static storage;
3698the caller should not modify its value. The value is available to
3699Python code as the list \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003700\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003701\end{cfuncdesc}
3702
Fred Drakec6fa34e1998-04-02 06:47:24 +00003703\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00003704Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00003705this is formed from the ``official'' name of the operating system,
3706converted to lower case, followed by the major revision number; e.g.,
3707for Solaris 2.x, which is also known as SunOS 5.x, the value is
3708\code{"sunos5"}. On Macintosh, it is \code{"mac"}. On Windows, it
3709is \code{"win"}. The returned string points into static storage;
3710the caller should not modify its value. The value is available to
3711Python code as \code{sys.platform}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003712\withsubitem{(in module sys)}{\ttindex{platform}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003713\end{cfuncdesc}
3714
Fred Drakec6fa34e1998-04-02 06:47:24 +00003715\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003716Return the official copyright string for the current Python version,
3717for example
3718
3719\code{"Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam"}
3720
3721The returned string points into static storage; the caller should not
3722modify its value. The value is available to Python code as the list
3723\code{sys.copyright}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003724\withsubitem{(in module sys)}{\ttindex{copyright}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003725\end{cfuncdesc}
3726
Fred Drakec6fa34e1998-04-02 06:47:24 +00003727\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003728Return an indication of the compiler used to build the current Python
Fred Drakee058b4f1998-02-16 06:15:35 +00003729version, in square brackets, for example:
Guido van Rossum4a944d71997-08-14 20:35:38 +00003730
Fred Drakee058b4f1998-02-16 06:15:35 +00003731\begin{verbatim}
3732"[GCC 2.7.2.2]"
3733\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003734
3735The returned string points into static storage; the caller should not
3736modify its value. The value is available to Python code as part of
3737the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003738\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003739\end{cfuncdesc}
3740
Fred Drakec6fa34e1998-04-02 06:47:24 +00003741\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003742Return information about the sequence number and build date and time
3743of the current Python interpreter instance, for example
3744
Guido van Rossum09270b51997-08-15 18:57:32 +00003745\begin{verbatim}
3746"#67, Aug 1 1997, 22:34:28"
3747\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003748
3749The returned string points into static storage; the caller should not
3750modify its value. The value is available to Python code as part of
3751the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003752\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003753\end{cfuncdesc}
3754
3755\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
Fred Drake659ebfa2000-04-03 15:42:13 +00003756Set \code{sys.argv} based on \var{argc} and \var{argv}. These
3757parameters are similar to those passed to the program's
3758\cfunction{main()}\ttindex{main()} function with the difference that
3759the first entry should refer to the script file to be executed rather
3760than the executable hosting the Python interpreter. If there isn't a
3761script that will be run, the first entry in \var{argv} can be an empty
3762string. If this function fails to initialize \code{sys.argv}, a fatal
3763condition is signalled using
3764\cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
3765\withsubitem{(in module sys)}{\ttindex{argv}}
3766% XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
3767% check w/ Guido.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003768\end{cfuncdesc}
3769
3770% XXX Other PySys thingies (doesn't really belong in this chapter)
3771
Fred Drakeefd146c1999-02-15 15:30:45 +00003772\section{Thread State and the Global Interpreter Lock
3773 \label{threads}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003774
Fred Drake659ebfa2000-04-03 15:42:13 +00003775\index{global interpreter lock}
3776\index{interpreter lock}
3777\index{lock, interpreter}
3778
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003779The Python interpreter is not fully thread safe. In order to support
3780multi-threaded Python programs, there's a global lock that must be
3781held by the current thread before it can safely access Python objects.
3782Without the lock, even the simplest operations could cause problems in
Fred Drake7baf3d41998-02-20 00:45:52 +00003783a multi-threaded program: for example, when two threads simultaneously
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003784increment the reference count of the same object, the reference count
3785could end up being incremented only once instead of twice.
3786
3787Therefore, the rule exists that only the thread that has acquired the
3788global interpreter lock may operate on Python objects or call Python/C
3789API functions. In order to support multi-threaded Python programs,
Fred Drake659ebfa2000-04-03 15:42:13 +00003790the interpreter regularly releases and reacquires the lock --- by
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003791default, every ten bytecode instructions (this can be changed with
Fred Drake659ebfa2000-04-03 15:42:13 +00003792\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
Fred Drakee058b4f1998-02-16 06:15:35 +00003793\function{sys.setcheckinterval()}). The lock is also released and
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003794reacquired around potentially blocking I/O operations like reading or
3795writing a file, so that other threads can run while the thread that
3796requests the I/O is waiting for the I/O operation to complete.
3797
3798The Python interpreter needs to keep some bookkeeping information
Fred Drakee058b4f1998-02-16 06:15:35 +00003799separate per thread --- for this it uses a data structure called
Fred Drake659ebfa2000-04-03 15:42:13 +00003800\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
38011.5; in earlier versions, such state was stored in global variables,
3802and switching threads could cause problems. In particular, exception
3803handling is now thread safe, when the application uses
3804\withsubitem{(in module sys)}{\ttindex{exc_info()}}
3805\function{sys.exc_info()} to access the exception last raised in the
3806current thread.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003807
3808There's one global variable left, however: the pointer to the current
Fred Drake659ebfa2000-04-03 15:42:13 +00003809\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
3810thread packages have a way to store ``per-thread global data,''
3811Python's internal platform independent thread abstraction doesn't
3812support this yet. Therefore, the current thread state must be
3813manipulated explicitly.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003814
3815This is easy enough in most cases. Most code manipulating the global
3816interpreter lock has the following simple structure:
3817
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003818\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003819Save the thread state in a local variable.
3820Release the interpreter lock.
3821...Do some blocking I/O operation...
3822Reacquire the interpreter lock.
3823Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003824\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003825
3826This is so common that a pair of macros exists to simplify it:
3827
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003828\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003829Py_BEGIN_ALLOW_THREADS
3830...Do some blocking I/O operation...
3831Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003832\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003833
Fred Drake659ebfa2000-04-03 15:42:13 +00003834The \code{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS} macro
3835opens a new block and declares a hidden local variable; the
3836\code{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS} macro closes
Fred Drakee058b4f1998-02-16 06:15:35 +00003837the block. Another advantage of using these two macros is that when
3838Python is compiled without thread support, they are defined empty,
3839thus saving the thread state and lock manipulations.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003840
3841When thread support is enabled, the block above expands to the
3842following code:
3843
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003844\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003845 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00003846
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003847 _save = PyEval_SaveThread();
3848 ...Do some blocking I/O operation...
3849 PyEval_RestoreThread(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003850\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003851
3852Using even lower level primitives, we can get roughly the same effect
3853as follows:
3854
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003855\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003856 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00003857
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003858 _save = PyThreadState_Swap(NULL);
3859 PyEval_ReleaseLock();
3860 ...Do some blocking I/O operation...
3861 PyEval_AcquireLock();
3862 PyThreadState_Swap(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003863\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003864
3865There are some subtle differences; in particular,
Fred Drake659ebfa2000-04-03 15:42:13 +00003866\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
3867and restores the value of the global variable
3868\cdata{errno}\ttindex{errno}, since the lock manipulation does not
Fred Drakef8830d11998-04-23 14:06:01 +00003869guarantee that \cdata{errno} is left alone. Also, when thread support
Fred Drake659ebfa2000-04-03 15:42:13 +00003870is disabled,
3871\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
Fred Drakee058b4f1998-02-16 06:15:35 +00003872\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
Fred Drake659ebfa2000-04-03 15:42:13 +00003873case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
3874\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
3875available. This is done so that dynamically loaded extensions
3876compiled with thread support enabled can be loaded by an interpreter
3877that was compiled with disabled thread support.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003878
3879The global interpreter lock is used to protect the pointer to the
3880current thread state. When releasing the lock and saving the thread
3881state, the current thread state pointer must be retrieved before the
3882lock is released (since another thread could immediately acquire the
3883lock and store its own thread state in the global variable).
3884Reversely, when acquiring the lock and restoring the thread state, the
3885lock must be acquired before storing the thread state pointer.
3886
3887Why am I going on with so much detail about this? Because when
Fred Drake659ebfa2000-04-03 15:42:13 +00003888threads are created from C, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003889lock, nor is there a thread state data structure for them. Such
3890threads must bootstrap themselves into existence, by first creating a
3891thread state data structure, then acquiring the lock, and finally
3892storing their thread state pointer, before they can start using the
3893Python/C API. When they are done, they should reset the thread state
3894pointer, release the lock, and finally free their thread state data
3895structure.
3896
3897When creating a thread data structure, you need to provide an
3898interpreter state data structure. The interpreter state data
3899structure hold global data that is shared by all threads in an
3900interpreter, for example the module administration
3901(\code{sys.modules}). Depending on your needs, you can either create
3902a new interpreter state data structure, or share the interpreter state
3903data structure used by the Python main thread (to access the latter,
Fred Drakef8830d11998-04-23 14:06:01 +00003904you must obtain the thread state and access its \member{interp} member;
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003905this must be done by a thread that is created by Python or by the main
3906thread after Python is initialized).
3907
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003908
3909\begin{ctypedesc}{PyInterpreterState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003910This data structure represents the state shared by a number of
3911cooperating threads. Threads belonging to the same interpreter
3912share their module administration and a few other internal items.
3913There are no public members in this structure.
3914
3915Threads belonging to different interpreters initially share nothing,
3916except process state like available memory, open file descriptors and
3917such. The global interpreter lock is also shared by all threads,
3918regardless of to which interpreter they belong.
3919\end{ctypedesc}
3920
3921\begin{ctypedesc}{PyThreadState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003922This data structure represents the state of a single thread. The only
Fred Drakef8830d11998-04-23 14:06:01 +00003923public data member is \ctype{PyInterpreterState *}\member{interp},
3924which points to this thread's interpreter state.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003925\end{ctypedesc}
3926
3927\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
3928Initialize and acquire the global interpreter lock. It should be
3929called in the main thread before creating a second thread or engaging
Fred Drakee058b4f1998-02-16 06:15:35 +00003930in any other thread operations such as
Fred Drake659ebfa2000-04-03 15:42:13 +00003931\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
3932\code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
3933It is not needed before calling
3934\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
3935\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003936
3937This is a no-op when called for a second time. It is safe to call
Fred Drake659ebfa2000-04-03 15:42:13 +00003938this function before calling
3939\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003940
3941When only the main thread exists, no lock operations are needed. This
3942is a common situation (most Python programs do not use threads), and
3943the lock operations slow the interpreter down a bit. Therefore, the
3944lock is not created initially. This situation is equivalent to having
3945acquired the lock: when there is only a single thread, all object
3946accesses are safe. Therefore, when this function initializes the
Fred Drake4de05a91998-02-16 14:25:26 +00003947lock, it also acquires it. Before the Python
3948\module{thread}\refbimodindex{thread} module creates a new thread,
3949knowing that either it has the lock or the lock hasn't been created
3950yet, it calls \cfunction{PyEval_InitThreads()}. When this call
3951returns, it is guaranteed that the lock has been created and that it
3952has acquired it.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003953
3954It is \strong{not} safe to call this function when it is unknown which
3955thread (if any) currently has the global interpreter lock.
3956
3957This function is not available when thread support is disabled at
3958compile time.
3959\end{cfuncdesc}
3960
Guido van Rossum4a944d71997-08-14 20:35:38 +00003961\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003962Acquire the global interpreter lock. The lock must have been created
3963earlier. If this thread already has the lock, a deadlock ensues.
3964This function is not available when thread support is disabled at
3965compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003966\end{cfuncdesc}
3967
3968\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003969Release the global interpreter lock. The lock must have been created
3970earlier. This function is not available when thread support is
Fred Drakee058b4f1998-02-16 06:15:35 +00003971disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003972\end{cfuncdesc}
3973
3974\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003975Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003976state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003977have been created earlier. If this thread already has the lock,
3978deadlock ensues. This function is not available when thread support
Fred Drakee058b4f1998-02-16 06:15:35 +00003979is disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003980\end{cfuncdesc}
3981
3982\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003983Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003984interpreter lock. The lock must have been created earlier and must be
3985held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003986be \NULL{}, is only used to check that it represents the current
Fred Drakee058b4f1998-02-16 06:15:35 +00003987thread state --- if it isn't, a fatal error is reported. This
3988function is not available when thread support is disabled at compile
3989time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003990\end{cfuncdesc}
3991
Fred Drakec6fa34e1998-04-02 06:47:24 +00003992\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003993Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003994support is enabled) and reset the thread state to \NULL{},
3995returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003996the lock has been created, the current thread must have acquired it.
3997(This function is available even when thread support is disabled at
3998compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00003999\end{cfuncdesc}
4000
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004001\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004002Acquire the interpreter lock (if it has been created and thread
4003support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004004must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004005thread must not have acquired it, otherwise deadlock ensues. (This
4006function is available even when thread support is disabled at compile
4007time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004008\end{cfuncdesc}
4009
Fred Drake659ebfa2000-04-03 15:42:13 +00004010The following macros are normally used without a trailing semicolon;
4011look for example usage in the Python source distribution.
4012
4013\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004014This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004015\samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004016Note that it contains an opening brace; it must be matched with a
4017following \code{Py_END_ALLOW_THREADS} macro. See above for further
4018discussion of this macro. It is a no-op when thread support is
4019disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004020\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004021
Fred Drake659ebfa2000-04-03 15:42:13 +00004022\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004023This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004024\samp{PyEval_RestoreThread(_save); \}}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004025Note that it contains a closing brace; it must be matched with an
4026earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
4027discussion of this macro. It is a no-op when thread support is
4028disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004029\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004030
Fred Drake659ebfa2000-04-03 15:42:13 +00004031\begin{csimplemacrodesc}{Py_BEGIN_BLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004032This macro expands to \samp{PyEval_RestoreThread(_save);} i.e. it
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004033is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
4034brace. It is a no-op when thread support is disabled at compile
4035time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004036\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004037
Fred Drake659ebfa2000-04-03 15:42:13 +00004038\begin{csimplemacrodesc}{Py_BEGIN_UNBLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004039This macro expands to \samp{_save = PyEval_SaveThread();} i.e. it is
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004040equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
4041and variable declaration. It is a no-op when thread support is
4042disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004043\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004044
4045All of the following functions are only available when thread support
4046is enabled at compile time, and must be called only when the
Fred Drake9d20ac31998-02-16 15:27:08 +00004047interpreter lock has been created.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004048
Fred Drakec6fa34e1998-04-02 06:47:24 +00004049\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004050Create a new interpreter state object. The interpreter lock need not
4051be held, but may be held if it is necessary to serialize calls to this
4052function.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004053\end{cfuncdesc}
4054
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004055\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
4056Reset all information in an interpreter state object. The interpreter
4057lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004058\end{cfuncdesc}
4059
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004060\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
4061Destroy an interpreter state object. The interpreter lock need not be
4062held. The interpreter state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004063call to \cfunction{PyInterpreterState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004064\end{cfuncdesc}
4065
Fred Drakec6fa34e1998-04-02 06:47:24 +00004066\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004067Create a new thread state object belonging to the given interpreter
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004068object. The interpreter lock need not be held, but may be held if it
4069is necessary to serialize calls to this function.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004070\end{cfuncdesc}
4071
4072\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
4073Reset all information in a thread state object. The interpreter lock
4074must be held.
4075\end{cfuncdesc}
4076
4077\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
4078Destroy a thread state object. The interpreter lock need not be
4079held. The thread state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004080call to \cfunction{PyThreadState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004081\end{cfuncdesc}
4082
Fred Drakec6fa34e1998-04-02 06:47:24 +00004083\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004084Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004085When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004086error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004087\end{cfuncdesc}
4088
Fred Drakec6fa34e1998-04-02 06:47:24 +00004089\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004090Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004091argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004092must be held.
4093\end{cfuncdesc}
4094
4095
Fred Drake659ebfa2000-04-03 15:42:13 +00004096\chapter{Memory Management \label{memory}}
4097\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
4098
4099
4100\section{Overview \label{memoryOverview}}
4101
4102Memory management in Python involves a private heap containing all
4103Python objects and data structures. The management of this private
4104heap is ensured internally by the \emph{Python memory manager}. The
4105Python memory manager has different components which deal with various
4106dynamic storage management aspects, like sharing, segmentation,
4107preallocation or caching.
4108
4109At the lowest level, a raw memory allocator ensures that there is
4110enough room in the private heap for storing all Python-related data
4111by interacting with the memory manager of the operating system. On top
4112of the raw memory allocator, several object-specific allocators
4113operate on the same heap and implement distinct memory management
4114policies adapted to the peculiarities of every object type. For
4115example, integer objects are managed differently within the heap than
4116strings, tuples or dictionaries because integers imply different
4117storage requirements and speed/space tradeoffs. The Python memory
4118manager thus delegates some of the work to the object-specific
4119allocators, but ensures that the latter operate within the bounds of
4120the private heap.
4121
4122It is important to understand that the management of the Python heap
4123is performed by the interpreter itself and that the user has no
4124control on it, even if she regularly manipulates object pointers to
4125memory blocks inside that heap. The allocation of heap space for
4126Python objects and other internal buffers is performed on demand by
4127the Python memory manager through the Python/C API functions listed in
4128this document.
4129
4130To avoid memory corruption, extension writers should never try to
4131operate on Python objects with the functions exported by the C
4132library: \cfunction{malloc()}\ttindex{malloc()},
4133\cfunction{calloc()}\ttindex{calloc()},
4134\cfunction{realloc()}\ttindex{realloc()} and
4135\cfunction{free()}\ttindex{free()}. This will result in
4136mixed calls between the C allocator and the Python memory manager
4137with fatal consequences, because they implement different algorithms
4138and operate on different heaps. However, one may safely allocate and
4139release memory blocks with the C library allocator for individual
4140purposes, as shown in the following example:
4141
4142\begin{verbatim}
4143 PyObject *res;
4144 char *buf = (char *) malloc(BUFSIZ); /* for I/O */
4145
4146 if (buf == NULL)
4147 return PyErr_NoMemory();
4148 ...Do some I/O operation involving buf...
4149 res = PyString_FromString(buf);
4150 free(buf); /* malloc'ed */
4151 return res;
4152\end{verbatim}
4153
4154In this example, the memory request for the I/O buffer is handled by
4155the C library allocator. The Python memory manager is involved only
4156in the allocation of the string object returned as a result.
4157
4158In most situations, however, it is recommended to allocate memory from
4159the Python heap specifically because the latter is under control of
4160the Python memory manager. For example, this is required when the
4161interpreter is extended with new object types written in C. Another
4162reason for using the Python heap is the desire to \emph{inform} the
4163Python memory manager about the memory needs of the extension module.
4164Even when the requested memory is used exclusively for internal,
4165highly-specific purposes, delegating all memory requests to the Python
4166memory manager causes the interpreter to have a more accurate image of
4167its memory footprint as a whole. Consequently, under certain
4168circumstances, the Python memory manager may or may not trigger
4169appropriate actions, like garbage collection, memory compaction or
4170other preventive procedures. Note that by using the C library
4171allocator as shown in the previous example, the allocated memory for
4172the I/O buffer escapes completely the Python memory manager.
4173
4174
4175\section{Memory Interface \label{memoryInterface}}
4176
4177The following function sets, modeled after the ANSI C standard, are
4178available for allocating and releasing memory from the Python heap:
4179
4180
4181\begin{ctypedesc}{ANY*}
4182The type used to represent arbitrary blocks of memory. Values of this
4183type should be cast to the specific type that is needed.
4184\end{ctypedesc}
4185
4186\begin{cfuncdesc}{ANY*}{PyMem_Malloc}{size_t n}
4187Allocates \var{n} bytes and returns a pointer of type \ctype{ANY*} to
4188the allocated memory, or \NULL{} if the request fails. Requesting zero
4189bytes returns a non-\NULL{} pointer.
4190\end{cfuncdesc}
4191
4192\begin{cfuncdesc}{ANY*}{PyMem_Realloc}{ANY *p, size_t n}
4193Resizes the memory block pointed to by \var{p} to \var{n} bytes. The
4194contents will be unchanged to the minimum of the old and the new
4195sizes. If \var{p} is \NULL{}, the call is equivalent to
4196\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the memory block
4197is resized but is not freed, and the returned pointer is non-\NULL{}.
4198Unless \var{p} is \NULL{}, it must have been returned by a previous
4199call to \cfunction{PyMem_Malloc()} or \cfunction{PyMem_Realloc()}.
4200\end{cfuncdesc}
4201
4202\begin{cfuncdesc}{void}{PyMem_Free}{ANY *p}
4203Frees the memory block pointed to by \var{p}, which must have been
4204returned by a previous call to \cfunction{PyMem_Malloc()} or
4205\cfunction{PyMem_Realloc()}. Otherwise, or if
4206\cfunction{PyMem_Free(p)} has been called before, undefined behaviour
4207occurs. If \var{p} is \NULL{}, no operation is performed.
4208\end{cfuncdesc}
4209
4210\begin{cfuncdesc}{ANY*}{Py_Malloc}{size_t n}
4211Same as \cfunction{PyMem_Malloc()}, but calls
4212\cfunction{PyErr_NoMemory()} on failure.
4213\end{cfuncdesc}
4214
4215\begin{cfuncdesc}{ANY*}{Py_Realloc}{ANY *p, size_t n}
4216Same as \cfunction{PyMem_Realloc()}, but calls
4217\cfunction{PyErr_NoMemory()} on failure.
4218\end{cfuncdesc}
4219
4220\begin{cfuncdesc}{void}{Py_Free}{ANY *p}
4221Same as \cfunction{PyMem_Free()}.
4222\end{cfuncdesc}
4223
4224The following type-oriented macros are provided for convenience. Note
4225that \var{TYPE} refers to any C type.
4226
4227\begin{cfuncdesc}{\var{TYPE}*}{PyMem_NEW}{TYPE, size_t n}
4228Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
4229sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
4230\ctype{\var{TYPE}*}.
4231\end{cfuncdesc}
4232
4233\begin{cfuncdesc}{\var{TYPE}*}{PyMem_RESIZE}{ANY *p, TYPE, size_t n}
4234Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
4235to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
4236cast to \ctype{\var{TYPE}*}.
4237\end{cfuncdesc}
4238
4239\begin{cfuncdesc}{void}{PyMem_DEL}{ANY *p}
4240Same as \cfunction{PyMem_Free()}.
4241\end{cfuncdesc}
4242
4243
4244\section{Examples \label{memoryExamples}}
4245
4246Here is the example from section \ref{memoryOverview}, rewritten so
4247that the I/O buffer is allocated from the Python heap by using the
4248first function set:
4249
4250\begin{verbatim}
4251 PyObject *res;
4252 char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
4253
4254 if (buf == NULL)
4255 return PyErr_NoMemory();
4256 /* ...Do some I/O operation involving buf... */
4257 res = PyString_FromString(buf);
4258 PyMem_Free(buf); /* allocated with PyMem_Malloc */
4259 return res;
4260\end{verbatim}
4261
4262With the second function set, the need to call
4263\cfunction{PyErr_NoMemory()} is obviated:
4264
4265\begin{verbatim}
4266 PyObject *res;
4267 char *buf = (char *) Py_Malloc(BUFSIZ); /* for I/O */
4268
4269 if (buf == NULL)
4270 return NULL;
4271 /* ...Do some I/O operation involving buf... */
4272 res = PyString_FromString(buf);
4273 Py_Free(buf); /* allocated with Py_Malloc */
4274 return res;
4275\end{verbatim}
4276
4277The same code using the macro set:
4278
4279\begin{verbatim}
4280 PyObject *res;
4281 char *buf = PyMem_NEW(char, BUFSIZ); /* for I/O */
4282
4283 if (buf == NULL)
4284 return PyErr_NoMemory();
4285 /* ...Do some I/O operation involving buf... */
4286 res = PyString_FromString(buf);
4287 PyMem_DEL(buf); /* allocated with PyMem_NEW */
4288 return res;
4289\end{verbatim}
4290
4291Note that in the three examples above, the buffer is always
4292manipulated via functions/macros belonging to the same set. Indeed, it
4293is required to use the same memory API family for a given
4294memory block, so that the risk of mixing different allocators is
4295reduced to a minimum. The following code sequence contains two errors,
4296one of which is labeled as \emph{fatal} because it mixes two different
4297allocators operating on different heaps.
4298
4299\begin{verbatim}
4300char *buf1 = PyMem_NEW(char, BUFSIZ);
4301char *buf2 = (char *) malloc(BUFSIZ);
4302char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
4303...
4304PyMem_DEL(buf3); /* Wrong -- should be PyMem_Free() */
4305free(buf2); /* Right -- allocated via malloc() */
4306free(buf1); /* Fatal -- should be PyMem_DEL() */
4307\end{verbatim}
4308
4309In addition to the functions aimed at handling raw memory blocks from
4310the Python heap, objects in Python are allocated and released with
4311\cfunction{_PyObject_New()}\ttindex{_PyObject_New()} and
4312\cfunction{_PyObject_NewVar()}\ttindex{_PyObject_NewVar()}, or with
4313their corresponding macros
4314\cfunction{PyObject_NEW()}\ttindex{PyObject_NEW()} and
4315\cfunction{PyObject_NEW_VAR()}\ttindex{PyObject_NEW_VAR()}.
4316
4317% XXX use this for Python 1.6:
4318% \cfunction{_PyObject_New()}, \cfunction{_PyObject_NewVar()},
4319% \cfunction{_PyObject_Del()}, or with their corresponding macros
4320% \cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()},
4321% \cfunction{PyObject_DEL()}.
4322
4323% These will be explained in the next chapter on defining and
4324% implementing new object types in C.
4325
4326
Fred Drakeefd146c1999-02-15 15:30:45 +00004327\chapter{Defining New Object Types \label{newTypes}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004328
Fred Drakec6fa34e1998-04-02 06:47:24 +00004329\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00004330\end{cfuncdesc}
4331
Fred Drakec6fa34e1998-04-02 06:47:24 +00004332\begin{cfuncdesc}{PyObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00004333\end{cfuncdesc}
4334
Fred Drake659ebfa2000-04-03 15:42:13 +00004335\begin{cfuncdesc}{\var{TYPE}}{_PyObject_NEW}{TYPE, PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00004336\end{cfuncdesc}
4337
Fred Drake659ebfa2000-04-03 15:42:13 +00004338\begin{cfuncdesc}{\var{TYPE}}{_PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
4339 int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00004340\end{cfuncdesc}
4341
Guido van Rossum3c4378b1998-04-14 20:21:10 +00004342Py_InitModule (!!!)
4343
4344PyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse
4345
4346Py_BuildValue
Guido van Rossumae110af1997-05-22 20:11:52 +00004347
Fred Drake659ebfa2000-04-03 15:42:13 +00004348DL_IMPORT
4349
4350Py*_Check
4351
4352_Py_NoneStruct
4353
4354
4355\section{Common Object Structures \label{common-structs}}
4356
Guido van Rossumae110af1997-05-22 20:11:52 +00004357PyObject, PyVarObject
4358
4359PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
4360
4361Typedefs:
4362unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
4363intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
Guido van Rossumae110af1997-05-22 20:11:52 +00004364destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
4365setattrofunc, cmpfunc, reprfunc, hashfunc
4366
Fred Drake659ebfa2000-04-03 15:42:13 +00004367
4368\section{Mapping Object Structures \label{mapping-structs}}
4369
4370\begin{ctypedesc}{PyMappingMethods}
4371Structure used to hold pointers to the functions used to implement the
4372mapping protocol for an extension type.
4373\end{ctypedesc}
4374
4375
4376\section{Number Object Structures \label{number-structs}}
4377
4378\begin{ctypedesc}{PyNumberMethods}
4379Structure used to hold pointers to the functions an extension type
4380uses to implement the number protocol.
4381\end{ctypedesc}
4382
4383
4384\section{Sequence Object Structures \label{sequence-structs}}
4385
4386\begin{ctypedesc}{PySequenceMethods}
4387Structure used to hold pointers to the functions which an object uses
4388to implement the sequence protocol.
4389\end{ctypedesc}
4390
4391
4392\section{Buffer Object Structures \label{buffer-structs}}
4393\sectionauthor{Greg J. Stein}{greg@lyra.org}
4394
4395The buffer interface exports a model where an object can expose its
4396internal data as a set of chunks of data, where each chunk is
4397specified as a pointer/length pair. These chunks are called
4398\dfn{segments} and are presumed to be non-contiguous in memory.
4399
4400If an object does not export the buffer interface, then its
4401\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
4402should be \NULL{}. Otherwise, the \member{tp_as_buffer} will point to
4403a \ctype{PyBufferProcs} structure.
4404
4405\strong{Note:} It is very important that your
4406\ctype{PyTypeObject} structure uses \code{Py_TPFLAGS_DEFAULT} for the
4407value of the \member{tp_flags} member rather than \code{0}. This
4408tells the Python runtime that your \ctype{PyBufferProcs} structure
4409contains the \member{bf_getcharbuffer} slot. Older versions of Python
4410did not have this member, so a new Python interpreter using an old
4411extension needs to be able to test for its presence before using it.
4412
4413\begin{ctypedesc}{PyBufferProcs}
4414Structure used to hold the function pointers which define an
4415implementation of the buffer protocol.
4416
4417The first slot is \member{bf_getreadbuffer}, of type
4418\ctype{getreadbufferproc}. If this slot is \NULL{}, then the object
4419does not support reading from the internal data. This is
4420non-sensical, so implementors should fill this in, but callers should
4421test that the slot contains a non-\NULL{} value.
4422
4423The next slot is \member{bf_getwritebuffer} having type
4424\ctype{getwritebufferproc}. This slot may be \NULL{} if the object
4425does not allow writing into its returned buffers.
4426
4427The third slot is \member{bf_getsegcount}, with type
4428\ctype{getsegcountproc}. This slot must not be \NULL{} and is used to
4429inform the caller how many segments the object contains. Simple
4430objects such as \ctype{PyString_Type} and
4431\ctype{PyBuffer_Type} objects contain a single segment.
4432
4433The last slot is \member{bf_getcharbuffer}, of type
4434\ctype{getcharbufferproc}. This slot will only be present if the
4435\code{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
4436\member{tp_flags} field of the object's \ctype{PyTypeObject}. Before using
4437this slot, the caller should test whether it is present by using the
4438\cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()} function.
4439If present, it may be \NULL, indicating that the object's contents
4440cannot be used as \emph{8-bit characters}.
4441The slot function may also raise an error if the object's contents
4442cannot be interpreted as 8-bit characters. For example, if the object
4443is an array which is configured to hold floating point values, an
4444exception may be raised if a caller attempts to use
4445\member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
4446This notion of exporting the internal buffers as ``text'' is used to
4447distinguish between objects that are binary in nature, and those which
4448have character-based content.
4449
4450\strong{Note:} The current policy seems to state that these characters
4451may be multi-byte characters. This implies that a buffer size of
4452\var{N} does not mean there are \var{N} characters present.
4453\end{ctypedesc}
4454
4455\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
4456Flag bit set in the type structure to indicate that the
4457\member{bf_getcharbuffer} slot is known. This being set does not
4458indicate that the object supports the buffer interface or that the
4459\member{bf_getcharbuffer} slot is non-\NULL.
4460\end{datadesc}
4461
4462\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
4463 (PyObject *self, int segment, void **ptrptr)}
4464Return a pointer to a readable segment of the buffer. This function
4465is allowed to raise an exception, in which case it must return
4466\code{-1}. The \var{segment} which is passed must be zero or
4467positive, and strictly less than the number of segments returned by
4468the \member{bf_getsegcount} slot function. On success, returns
4469\code{0} and sets \code{*\var{ptrptr}} to a pointer to the buffer
4470memory.
4471\end{ctypedesc}
4472
4473\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
4474 (PyObject *self, int segment, void **ptrptr)}
Fred Drake58c5a2a1999-08-04 13:13:24 +00004475Return a pointer to a writable memory buffer in \code{*\var{ptrptr}};
4476the memory buffer must correspond to buffer segment \var{segment}.
4477Must return \code{-1} and set an exception on error.
4478\exception{TypeError} should be raised if the object only supports
4479read-only buffers, and \exception{SystemError} should be raised when
4480\var{segment} specifies a segment that doesn't exist.
4481% Why doesn't it raise ValueError for this one?
Fred Drake659ebfa2000-04-03 15:42:13 +00004482% GJS: because you shouldn't be calling it with an invalid
4483% segment. That indicates a blatant programming error in the C
4484% code.
Fred Drake58c5a2a1999-08-04 13:13:24 +00004485\end{ctypedesc}
4486
Fred Drake659ebfa2000-04-03 15:42:13 +00004487\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
4488 (PyObject *self, int *lenp)}
4489Return the number of memory segments which comprise the buffer. If
4490\var{lenp} is not \NULL, the implementation must report the sum of the
4491sizes (in bytes) of all segments in \code{*\var{lenp}}.
4492The function cannot fail.
4493\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004494
Fred Drake659ebfa2000-04-03 15:42:13 +00004495\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
4496 (PyObject *self, int segment, const char **ptrptr)}
4497\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004498
Guido van Rossumae110af1997-05-22 20:11:52 +00004499
Fred Drake659ebfa2000-04-03 15:42:13 +00004500% \chapter{Debugging \label{debugging}}
4501%
4502% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004503
4504
Fred Drakef3aa0e01998-03-17 06:23:13 +00004505\input{api.ind} % Index -- must be last
Guido van Rossum9231c8f1997-05-15 21:43:21 +00004506
4507\end{document}