blob: fe095500b83190fbbaf25fb5da42017af3be919a [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
Fred Drakea8455ab2000-06-16 19:58:42 +0000213Conversely, when a calling function passes it a reference to an
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000214object, there are two possibilities: the function \emph{steals} a
215reference to the object, or it does not. Few functions steal
Fred Drakee058b4f1998-02-16 06:15:35 +0000216references; the two notable exceptions are
Fred Drake659ebfa2000-04-03 15:42:13 +0000217\cfunction{PyList_SetItem()}\ttindex{PyList_SetItem()} and
218\cfunction{PyTuple_SetItem()}\ttindex{PyTuple_SetItem()}, which
Fred Drakee058b4f1998-02-16 06:15:35 +0000219steal a reference to the item (but not to the tuple or list into which
Fred Drake003d8da1998-04-13 00:53:42 +0000220the item is put!). These functions were designed to steal a reference
Fred Drakee058b4f1998-02-16 06:15:35 +0000221because of a common idiom for populating a tuple or list with newly
222created objects; for example, the code to create the tuple \code{(1,
2232, "three")} could look like this (forgetting about error handling for
Fred Drake659ebfa2000-04-03 15:42:13 +0000224the moment; a better way to code this is shown below):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000225
226\begin{verbatim}
227PyObject *t;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000228
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000229t = PyTuple_New(3);
230PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
231PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
232PyTuple_SetItem(t, 2, PyString_FromString("three"));
233\end{verbatim}
234
Fred Drakee058b4f1998-02-16 06:15:35 +0000235Incidentally, \cfunction{PyTuple_SetItem()} is the \emph{only} way to
236set tuple items; \cfunction{PySequence_SetItem()} and
237\cfunction{PyObject_SetItem()} refuse to do this since tuples are an
238immutable data type. You should only use
239\cfunction{PyTuple_SetItem()} for tuples that you are creating
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000240yourself.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000241
242Equivalent code for populating a list can be written using
Fred Drakee058b4f1998-02-16 06:15:35 +0000243\cfunction{PyList_New()} and \cfunction{PyList_SetItem()}. Such code
244can also use \cfunction{PySequence_SetItem()}; this illustrates the
245difference between the two (the extra \cfunction{Py_DECREF()} calls):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000246
247\begin{verbatim}
248PyObject *l, *x;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000249
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000250l = PyList_New(3);
251x = PyInt_FromLong(1L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000252PySequence_SetItem(l, 0, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000253x = PyInt_FromLong(2L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000254PySequence_SetItem(l, 1, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000255x = PyString_FromString("three");
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000256PySequence_SetItem(l, 2, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000257\end{verbatim}
258
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000259You might find it strange that the ``recommended'' approach takes more
260code. However, in practice, you will rarely use these ways of
261creating and populating a tuple or list. There's a generic function,
Fred Drakee058b4f1998-02-16 06:15:35 +0000262\cfunction{Py_BuildValue()}, that can create most common objects from
Fred Drake659ebfa2000-04-03 15:42:13 +0000263C values, directed by a \dfn{format string}. For example, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000264above two blocks of code could be replaced by the following (which
265also takes care of the error checking):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000266
267\begin{verbatim}
268PyObject *t, *l;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000269
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000270t = Py_BuildValue("(iis)", 1, 2, "three");
271l = Py_BuildValue("[iis]", 1, 2, "three");
272\end{verbatim}
273
Fred Drakee058b4f1998-02-16 06:15:35 +0000274It is much more common to use \cfunction{PyObject_SetItem()} and
275friends with items whose references you are only borrowing, like
276arguments that were passed in to the function you are writing. In
277that case, their behaviour regarding reference counts is much saner,
278since you don't have to increment a reference count so you can give a
279reference away (``have it be stolen''). For example, this function
280sets all items of a list (actually, any mutable sequence) to a given
281item:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000282
283\begin{verbatim}
284int set_all(PyObject *target, PyObject *item)
285{
286 int i, n;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000287
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000288 n = PyObject_Length(target);
289 if (n < 0)
290 return -1;
291 for (i = 0; i < n; i++) {
292 if (PyObject_SetItem(target, i, item) < 0)
293 return -1;
294 }
295 return 0;
296}
297\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000298\ttindex{set_all()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000299
300The situation is slightly different for function return values.
301While passing a reference to most functions does not change your
302ownership responsibilities for that reference, many functions that
303return a referece to an object give you ownership of the reference.
304The reason is simple: in many cases, the returned object is created
305on the fly, and the reference you get is the only reference to the
Fred Drakee058b4f1998-02-16 06:15:35 +0000306object. Therefore, the generic functions that return object
307references, like \cfunction{PyObject_GetItem()} and
308\cfunction{PySequence_GetItem()}, always return a new reference (i.e.,
309the caller becomes the owner of the reference).
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000310
311It is important to realize that whether you own a reference returned
Fred Drakee058b4f1998-02-16 06:15:35 +0000312by a function depends on which function you call only --- \emph{the
313plumage} (i.e., the type of the type of the object passed as an
314argument to the function) \emph{doesn't enter into it!} Thus, if you
315extract an item from a list using \cfunction{PyList_GetItem()}, you
316don't own the reference --- but if you obtain the same item from the
317same list using \cfunction{PySequence_GetItem()} (which happens to
318take exactly the same arguments), you do own a reference to the
319returned object.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000320
Fred Drakee058b4f1998-02-16 06:15:35 +0000321Here is an example of how you could write a function that computes the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000322sum of the items in a list of integers; once using
Fred Drake659ebfa2000-04-03 15:42:13 +0000323\cfunction{PyList_GetItem()}\ttindex{PyList_GetItem()}, and once using
324\cfunction{PySequence_GetItem()}\ttindex{PySequence_GetItem()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000325
326\begin{verbatim}
327long sum_list(PyObject *list)
328{
329 int i, n;
330 long total = 0;
331 PyObject *item;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000332
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000333 n = PyList_Size(list);
334 if (n < 0)
335 return -1; /* Not a list */
336 for (i = 0; i < n; i++) {
337 item = PyList_GetItem(list, i); /* Can't fail */
338 if (!PyInt_Check(item)) continue; /* Skip non-integers */
339 total += PyInt_AsLong(item);
340 }
341 return total;
342}
343\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000344\ttindex{sum_list()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000345
346\begin{verbatim}
347long sum_sequence(PyObject *sequence)
348{
349 int i, n;
350 long total = 0;
351 PyObject *item;
Fred Drake659ebfa2000-04-03 15:42:13 +0000352 n = PySequence_Length(sequence);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000353 if (n < 0)
354 return -1; /* Has no length */
355 for (i = 0; i < n; i++) {
Fred Drake659ebfa2000-04-03 15:42:13 +0000356 item = PySequence_GetItem(sequence, i);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000357 if (item == NULL)
358 return -1; /* Not a sequence, or other failure */
359 if (PyInt_Check(item))
360 total += PyInt_AsLong(item);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000361 Py_DECREF(item); /* Discard reference ownership */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000362 }
363 return total;
364}
365\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000366\ttindex{sum_sequence()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000367
Fred Drakeefd146c1999-02-15 15:30:45 +0000368
369\subsection{Types \label{types}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000370
371There are few other data types that play a significant role in
Fred Drake659ebfa2000-04-03 15:42:13 +0000372the Python/C API; most are simple C types such as \ctype{int},
373\ctype{long}, \ctype{double} and \ctype{char*}. A few structure types
Guido van Rossum4a944d71997-08-14 20:35:38 +0000374are used to describe static tables used to list the functions exported
Fred Drake659ebfa2000-04-03 15:42:13 +0000375by a module or the data attributes of a new object type, and another
376is used to describe the value of a complex number. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000377be discussed together with the functions that use them.
378
Fred Drakeefd146c1999-02-15 15:30:45 +0000379
380\section{Exceptions \label{exceptions}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000381
Guido van Rossum4a944d71997-08-14 20:35:38 +0000382The Python programmer only needs to deal with exceptions if specific
383error handling is required; unhandled exceptions are automatically
Fred Drake659ebfa2000-04-03 15:42:13 +0000384propagated to the caller, then to the caller's caller, and so on, until
Guido van Rossum4a944d71997-08-14 20:35:38 +0000385they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000386user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000387
Fred Drake659ebfa2000-04-03 15:42:13 +0000388For C programmers, however, error checking always has to be explicit.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000389All functions in the Python/C API can raise exceptions, unless an
390explicit claim is made otherwise in a function's documentation. In
391general, when a function encounters an error, it sets an exception,
392discards any object references that it owns, and returns an
Fred Drakee058b4f1998-02-16 06:15:35 +0000393error indicator --- usually \NULL{} or \code{-1}. A few functions
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000394return a Boolean true/false result, with false indicating an error.
395Very few functions return no explicit error indicator or have an
396ambiguous return value, and require explicit testing for errors with
Fred Drake659ebfa2000-04-03 15:42:13 +0000397\cfunction{PyErr_Occurred()}\ttindex{PyErr_Occurred()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000398
399Exception state is maintained in per-thread storage (this is
400equivalent to using global storage in an unthreaded application). A
Fred Drakec6fa34e1998-04-02 06:47:24 +0000401thread can be in one of two states: an exception has occurred, or not.
Fred Drakee058b4f1998-02-16 06:15:35 +0000402The function \cfunction{PyErr_Occurred()} can be used to check for
403this: it returns a borrowed reference to the exception type object
404when an exception has occurred, and \NULL{} otherwise. There are a
405number of functions to set the exception state:
Fred Drake659ebfa2000-04-03 15:42:13 +0000406\cfunction{PyErr_SetString()}\ttindex{PyErr_SetString()} is the most
407common (though not the most general) function to set the exception
408state, and \cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} clears the
409exception state.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000410
411The full exception state consists of three objects (all of which can
Fred Drakee058b4f1998-02-16 06:15:35 +0000412be \NULL{}): the exception type, the corresponding exception
Fred Drake659ebfa2000-04-03 15:42:13 +0000413value, and the traceback. These have the same meanings as the Python
414\withsubitem{(in module sys)}{
415 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
416objects \code{sys.exc_type}, \code{sys.exc_value}, and
417\code{sys.exc_traceback}; however, they are not the same: the Python
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000418objects represent the last exception being handled by a Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000419\keyword{try} \ldots\ \keyword{except} statement, while the C level
Fred Drakee058b4f1998-02-16 06:15:35 +0000420exception state only exists while an exception is being passed on
Fred Drake659ebfa2000-04-03 15:42:13 +0000421between C functions until it reaches the Python bytecode interpreter's
422main loop, which takes care of transferring it to \code{sys.exc_type}
423and friends.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000424
Fred Drakec6fa34e1998-04-02 06:47:24 +0000425Note that starting with Python 1.5, the preferred, thread-safe way to
Fred Drake659ebfa2000-04-03 15:42:13 +0000426access the exception state from Python code is to call the function
427\withsubitem{(in module sys)}{\ttindex{exc_info()}}
Fred Drakee058b4f1998-02-16 06:15:35 +0000428\function{sys.exc_info()}, which returns the per-thread exception state
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000429for Python code. Also, the semantics of both ways to access the
430exception state have changed so that a function which catches an
431exception will save and restore its thread's exception state so as to
432preserve the exception state of its caller. This prevents common bugs
433in exception handling code caused by an innocent-looking function
434overwriting the exception being handled; it also reduces the often
435unwanted lifetime extension for objects that are referenced by the
Fred Drakec6fa34e1998-04-02 06:47:24 +0000436stack frames in the traceback.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000437
438As a general principle, a function that calls another function to
439perform some task should check whether the called function raised an
440exception, and if so, pass the exception state on to its caller. It
Fred Drake659ebfa2000-04-03 15:42:13 +0000441should discard any object references that it owns, and return an
Fred Drakee058b4f1998-02-16 06:15:35 +0000442error indicator, but it should \emph{not} set another exception ---
443that would overwrite the exception that was just raised, and lose
444important information about the exact cause of the error.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000445
Fred Drake659ebfa2000-04-03 15:42:13 +0000446A simple example of detecting exceptions and passing them on is shown
447in the \cfunction{sum_sequence()}\ttindex{sum_sequence()} example
448above. It so happens that that example doesn't need to clean up any
449owned references when it detects an error. The following example
450function shows some error cleanup. First, to remind you why you like
451Python, we show the equivalent Python code:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000452
453\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000454def incr_item(dict, key):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000455 try:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000456 item = dict[key]
457 except KeyError:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000458 item = 0
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000459 return item + 1
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000460\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000461\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000462
Fred Drake659ebfa2000-04-03 15:42:13 +0000463Here is the corresponding C code, in all its glory:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000464
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000465\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000466int incr_item(PyObject *dict, PyObject *key)
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000467{
468 /* Objects all initialized to NULL for Py_XDECREF */
469 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000470 int rv = -1; /* Return value initialized to -1 (failure) */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000471
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000472 item = PyObject_GetItem(dict, key);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000473 if (item == NULL) {
Fred Drakec6fa34e1998-04-02 06:47:24 +0000474 /* Handle KeyError only: */
475 if (!PyErr_ExceptionMatches(PyExc_KeyError)) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000476
477 /* Clear the error and use zero: */
478 PyErr_Clear();
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000479 item = PyInt_FromLong(0L);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000480 if (item == NULL) goto error;
481 }
482
483 const_one = PyInt_FromLong(1L);
484 if (const_one == NULL) goto error;
485
486 incremented_item = PyNumber_Add(item, const_one);
487 if (incremented_item == NULL) goto error;
488
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000489 if (PyObject_SetItem(dict, key, incremented_item) < 0) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000490 rv = 0; /* Success */
491 /* Continue with cleanup code */
492
493 error:
494 /* Cleanup code, shared by success and failure path */
495
496 /* Use Py_XDECREF() to ignore NULL references */
497 Py_XDECREF(item);
498 Py_XDECREF(const_one);
499 Py_XDECREF(incremented_item);
500
501 return rv; /* -1 for error, 0 for success */
502}
503\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000504\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000505
Fred Drakef8830d11998-04-23 14:06:01 +0000506This example represents an endorsed use of the \keyword{goto} statement
Fred Drake659ebfa2000-04-03 15:42:13 +0000507in C! It illustrates the use of
508\cfunction{PyErr_ExceptionMatches()}\ttindex{PyErr_ExceptionMatches()} and
509\cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} to
510handle specific exceptions, and the use of
511\cfunction{Py_XDECREF()}\ttindex{Py_XDECREF()} to
512dispose of owned references that may be \NULL{} (note the
513\character{X} in the name; \cfunction{Py_DECREF()} would crash when
514confronted with a \NULL{} reference). It is important that the
515variables used to hold owned references are initialized to \NULL{} for
516this to work; likewise, the proposed return value is initialized to
517\code{-1} (failure) and only set to success after the final call made
518is successful.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000519
Guido van Rossum59a61351997-08-14 20:34:33 +0000520
Fred Drakeefd146c1999-02-15 15:30:45 +0000521\section{Embedding Python \label{embedding}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000522
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000523The one important task that only embedders (as opposed to extension
524writers) of the Python interpreter have to worry about is the
525initialization, and possibly the finalization, of the Python
526interpreter. Most functionality of the interpreter can only be used
527after the interpreter has been initialized.
Guido van Rossum59a61351997-08-14 20:34:33 +0000528
Fred Drake659ebfa2000-04-03 15:42:13 +0000529The basic initialization function is
530\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Fred Drakee058b4f1998-02-16 06:15:35 +0000531This initializes the table of loaded modules, and creates the
Fred Drake4de05a91998-02-16 14:25:26 +0000532fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
533\module{__main__}\refbimodindex{__main__} and
534\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drakec6fa34e1998-04-02 06:47:24 +0000535search path (\code{sys.path}).%
536\indexiii{module}{search}{path}
Fred Drake659ebfa2000-04-03 15:42:13 +0000537\withsubitem{(in module sys)}{\ttindex{path}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000538
Fred Drakee058b4f1998-02-16 06:15:35 +0000539\cfunction{Py_Initialize()} does not set the ``script argument list''
Guido van Rossum4a944d71997-08-14 20:35:38 +0000540(\code{sys.argv}). If this variable is needed by Python code that
541will be executed later, it must be set explicitly with a call to
Fred Drake659ebfa2000-04-03 15:42:13 +0000542\code{PySys_SetArgv(\var{argc},
543\var{argv})}\ttindex{PySys_SetArgv()} subsequent to the call to
544\cfunction{Py_Initialize()}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000545
Fred Drakeb0a78731998-01-13 18:51:10 +0000546On most systems (in particular, on \UNIX{} and Windows, although the
Fred Drake659ebfa2000-04-03 15:42:13 +0000547details are slightly different),
548\cfunction{Py_Initialize()} calculates the module search path based
549upon its best guess for the location of the standard Python
550interpreter executable, assuming that the Python library is found in a
551fixed location relative to the Python interpreter executable. In
552particular, it looks for a directory named
Fred 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 Drake510d08b2000-08-14 02:50:21 +0000600Note also that several of these functions take \ctype{FILE*}
601parameters. On particular issue which needs to be handled carefully
602is that the \ctype{FILE} structure for different C libraries can be
603different and incompatible. Under Windows (at least), it is possible
604for dynamically linked extensions to actually use different libraries,
605so care should be taken that \ctype{FILE*} parameters are only passed
606to these functions if it is certain that they were created by the same
607library that the Python runtime is using.
608
Fred Drakec6fa34e1998-04-02 06:47:24 +0000609\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000610 If \var{fp} refers to a file associated with an interactive device
611 (console or terminal input or \UNIX{} pseudo-terminal), return the
612 value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
613 result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
Fred Drakea8d73412000-08-11 20:39:29 +0000614 \NULL{}, this function uses \code{"???"} as the filename.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000615\end{cfuncdesc}
616
Fred Drakec6fa34e1998-04-02 06:47:24 +0000617\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
Fred Drake0041a941999-04-29 04:20:46 +0000618 Executes the Python source code from \var{command} in the
619 \module{__main__} module. If \module{__main__} does not already
620 exist, it is created. Returns \code{0} on success or \code{-1} if
621 an exception was raised. If there was an error, there is no way to
622 get the exception information.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000623\end{cfuncdesc}
624
Fred Drakec6fa34e1998-04-02 06:47:24 +0000625\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000626 Similar to \cfunction{PyRun_SimpleString()}, but the Python source
627 code is read from \var{fp} instead of an in-memory string.
628 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000629\end{cfuncdesc}
630
Fred Drakec6fa34e1998-04-02 06:47:24 +0000631\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000632 Read and execute a single statement from a file associated with an
633 interactive device. If \var{filename} is \NULL, \code{"???"} is
634 used instead. The user will be prompted using \code{sys.ps1} and
635 \code{sys.ps2}. Returns \code{0} when the input was executed
636 successfully, \code{-1} if there was an exception, or an error code
637 from the \file{errcode.h} include file distributed as part of Python
638 in case of a parse error. (Note that \file{errcode.h} is not
639 included by \file{Python.h}, so must be included specifically if
640 needed.)
Fred Drakee5bf8b21998-02-12 21:22:28 +0000641\end{cfuncdesc}
642
Fred Drakec6fa34e1998-04-02 06:47:24 +0000643\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000644 Read and execute statements from a file associated with an
645 interactive device until \EOF{} is reached. If \var{filename} is
646 \NULL, \code{"???"} is used instead. The user will be prompted
647 using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000648\end{cfuncdesc}
649
Fred Drakec6fa34e1998-04-02 06:47:24 +0000650\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
651 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000652 Parse Python source code from \var{str} using the start token
653 \var{start}. The result can be used to create a code object which
654 can be evaluated efficiently. This is useful if a code fragment
655 must be evaluated many times.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000656\end{cfuncdesc}
657
Fred Drakec6fa34e1998-04-02 06:47:24 +0000658\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
659 char *filename, int start}
Fred Drake0041a941999-04-29 04:20:46 +0000660 Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
661 source code is read from \var{fp} instead of an in-memory string.
662 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000663\end{cfuncdesc}
664
Fred Drakec6fa34e1998-04-02 06:47:24 +0000665\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
666 PyObject *globals,
667 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000668 Execute Python source code from \var{str} in the context specified
669 by the dictionaries \var{globals} and \var{locals}. The parameter
670 \var{start} specifies the start token that should be used to parse
671 the source code.
672
673 Returns the result of executing the code as a Python object, or
674 \NULL{} if an exception was raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000675\end{cfuncdesc}
676
Fred Drakec6fa34e1998-04-02 06:47:24 +0000677\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
678 int start, PyObject *globals,
679 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000680 Similar to \cfunction{PyRun_String()}, but the Python source code is
Fred Drake659ebfa2000-04-03 15:42:13 +0000681 read from \var{fp} instead of an in-memory string.
682 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000683\end{cfuncdesc}
684
Fred Drakec6fa34e1998-04-02 06:47:24 +0000685\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
686 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000687 Parse and compile the Python source code in \var{str}, returning the
688 resulting code object. The start token is given by \var{start};
Fred Drakec924b8d1999-08-23 18:57:25 +0000689 this can be used to constrain the code which can be compiled and should
690 be \constant{Py_eval_input}, \constant{Py_file_input}, or
691 \constant{Py_single_input}. The filename specified by
692 \var{filename} is used to construct the code object and may appear
693 in tracebacks or \exception{SyntaxError} exception messages. This
694 returns \NULL{} if the code cannot be parsed or compiled.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000695\end{cfuncdesc}
696
Fred Drakec924b8d1999-08-23 18:57:25 +0000697\begin{cvardesc}{int}{Py_eval_input}
698 The start symbol from the Python grammar for isolated expressions;
Fred Drake659ebfa2000-04-03 15:42:13 +0000699 for use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
Fred Drakec924b8d1999-08-23 18:57:25 +0000700\end{cvardesc}
701
702\begin{cvardesc}{int}{Py_file_input}
703 The start symbol from the Python grammar for sequences of statements
704 as read from a file or other source; for use with
Fred Drake659ebfa2000-04-03 15:42:13 +0000705 \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
706 the symbol to use when compiling arbitrarily long Python source code.
Fred Drakec924b8d1999-08-23 18:57:25 +0000707\end{cvardesc}
708
709\begin{cvardesc}{int}{Py_single_input}
710 The start symbol from the Python grammar for a single statement; for
Fred Drake659ebfa2000-04-03 15:42:13 +0000711 use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
712 This is the symbol used for the interactive interpreter loop.
Fred Drakec924b8d1999-08-23 18:57:25 +0000713\end{cvardesc}
714
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000715
Fred Drakeefd146c1999-02-15 15:30:45 +0000716\chapter{Reference Counting \label{countingRefs}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000717
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000718The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000719of Python objects.
720
721\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
Fred Drakec6fa34e1998-04-02 06:47:24 +0000722Increment the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000723not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000724\cfunction{Py_XINCREF()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000725\end{cfuncdesc}
726
727\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000728Increment the reference count for object \var{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000729\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000730\end{cfuncdesc}
731
732\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000733Decrement the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000734not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000735\cfunction{Py_XDECREF()}. If the reference count reaches zero, the
736object's type's deallocation function (which must not be \NULL{}) is
737invoked.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000738
739\strong{Warning:} The deallocation function can cause arbitrary Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000740code to be invoked (e.g. when a class instance with a
741\method{__del__()} method is deallocated). While exceptions in such
742code are not propagated, the executed code has free access to all
743Python global variables. This means that any object that is reachable
744from a global variable should be in a consistent state before
745\cfunction{Py_DECREF()} is invoked. For example, code to delete an
746object from a list should copy a reference to the deleted object in a
747temporary variable, update the list data structure, and then call
748\cfunction{Py_DECREF()} for the temporary variable.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000749\end{cfuncdesc}
750
751\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000752Decrement the reference count for object \var{o}. The object may be
753\NULL{}, in which case the macro has no effect; otherwise the effect
754is the same as for \cfunction{Py_DECREF()}, and the same warning
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000755applies.
756\end{cfuncdesc}
757
Fred Drake659ebfa2000-04-03 15:42:13 +0000758The following functions or macros are only for use within the
759interpreter core: \cfunction{_Py_Dealloc()},
760\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
761well as the global variable \cdata{_Py_RefTotal}.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000762
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000763
Fred Drakeefd146c1999-02-15 15:30:45 +0000764\chapter{Exception Handling \label{exceptionHandling}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000765
Fred Drake659ebfa2000-04-03 15:42:13 +0000766The functions described in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000767exceptions. It is important to understand some of the basics of
Fred Drake659ebfa2000-04-03 15:42:13 +0000768Python exception handling. It works somewhat like the
769\UNIX{} \cdata{errno} variable: there is a global indicator (per
770thread) of the last error that occurred. Most functions don't clear
771this on success, but will set it to indicate the cause of the error on
772failure. Most functions also return an error indicator, usually
773\NULL{} if they are supposed to return a pointer, or \code{-1} if they
774return an integer (exception: the \cfunction{PyArg_Parse*()} functions
775return \code{1} for success and \code{0} for failure). When a
776function must fail because some function it called failed, it
777generally doesn't set the error indicator; the function it called
778already set it.
Guido van Rossumae110af1997-05-22 20:11:52 +0000779
780The error indicator consists of three Python objects corresponding to
Fred Drake659ebfa2000-04-03 15:42:13 +0000781\withsubitem{(in module sys)}{
782 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000783the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
784\code{sys.exc_traceback}. API functions exist to interact with the
785error indicator in various ways. There is a separate error indicator
786for each thread.
787
788% XXX Order of these should be more thoughtful.
789% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000790
791\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000792Print a standard traceback to \code{sys.stderr} and clear the error
793indicator. Call this function only when the error indicator is set.
794(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000795\end{cfuncdesc}
796
Fred Drakec6fa34e1998-04-02 06:47:24 +0000797\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000798Test whether the error indicator is set. If set, return the exception
Fred Drakee058b4f1998-02-16 06:15:35 +0000799\emph{type} (the first argument to the last call to one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000800\cfunction{PyErr_Set*()} functions or to \cfunction{PyErr_Restore()}). If
Fred Drakee058b4f1998-02-16 06:15:35 +0000801not set, return \NULL{}. You do not own a reference to the return
802value, so you do not need to \cfunction{Py_DECREF()} it.
Fred Drake659ebfa2000-04-03 15:42:13 +0000803\strong{Note:} Do not compare the return value to a specific
Fred Drakee058b4f1998-02-16 06:15:35 +0000804exception; use \cfunction{PyErr_ExceptionMatches()} instead, shown
Fred Drake659ebfa2000-04-03 15:42:13 +0000805below. (The comparison could easily fail since the exception may be
806an instance instead of a class, in the case of a class exception, or
807it may the a subclass of the expected exception.)
Guido van Rossum42cefd01997-10-05 15:27:29 +0000808\end{cfuncdesc}
809
810\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000811Equivalent to
Fred Drakee058b4f1998-02-16 06:15:35 +0000812\samp{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
Fred Drake659ebfa2000-04-03 15:42:13 +0000813This should only be called when an exception is actually set; a memory
814access violation will occur if no exception has been raised.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000815\end{cfuncdesc}
816
817\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000818Return true if the \var{given} exception matches the exception in
819\var{exc}. If \var{exc} is a class object, this also returns true
Fred Drake659ebfa2000-04-03 15:42:13 +0000820when \var{given} is an instance of a subclass. If \var{exc} is a tuple, all
Guido van Rossum42cefd01997-10-05 15:27:29 +0000821exceptions in the tuple (and recursively in subtuples) are searched
Fred Drake659ebfa2000-04-03 15:42:13 +0000822for a match. If \var{given} is \NULL, a memory access violation will
823occur.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000824\end{cfuncdesc}
825
826\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000827Under certain circumstances, the values returned by
Fred Drakee058b4f1998-02-16 06:15:35 +0000828\cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning that
829\code{*\var{exc}} is a class object but \code{*\var{val}} is not an
830instance of the same class. This function can be used to instantiate
831the class in that case. If the values are already normalized, nothing
Fred Drake659ebfa2000-04-03 15:42:13 +0000832happens. The delayed normalization is implemented to improve
833performance.
Guido van Rossumae110af1997-05-22 20:11:52 +0000834\end{cfuncdesc}
835
836\begin{cfuncdesc}{void}{PyErr_Clear}{}
837Clear the error indicator. If the error indicator is not set, there
838is no effect.
839\end{cfuncdesc}
840
Fred Drake659ebfa2000-04-03 15:42:13 +0000841\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
842 PyObject **ptraceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000843Retrieve the error indicator into three variables whose addresses are
844passed. If the error indicator is not set, set all three variables to
845\NULL{}. If it is set, it will be cleared and you own a reference to
Fred Drake659ebfa2000-04-03 15:42:13 +0000846each object retrieved. The value and traceback object may be
847\NULL{} even when the type object is not. \strong{Note:} This
848function is normally only used by code that needs to handle exceptions
849or by code that needs to save and restore the error indicator
850temporarily.
Guido van Rossumae110af1997-05-22 20:11:52 +0000851\end{cfuncdesc}
852
853\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value, PyObject *traceback}
854Set the error indicator from the three objects. If the error
855indicator is already set, it is cleared first. If the objects are
856\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
857and non-\NULL{} value or traceback. The exception type should be a
858string or class; if it is a class, the value should be an instance of
859that class. Do not pass an invalid exception type or value.
860(Violating these rules will cause subtle problems later.) This call
861takes away a reference to each object, i.e. you must own a reference
862to each object before the call and after the call you no longer own
863these references. (If you don't understand this, don't use this
Fred Drake659ebfa2000-04-03 15:42:13 +0000864function. I warned you.) \strong{Note:} This function is normally
Guido van Rossumae110af1997-05-22 20:11:52 +0000865only used by code that needs to save and restore the error indicator
866temporarily.
867\end{cfuncdesc}
868
869\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
870This is the most common way to set the error indicator. The first
871argument specifies the exception type; it is normally one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000872standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
Guido van Rossumae110af1997-05-22 20:11:52 +0000873increment its reference count. The second argument is an error
874message; it is converted to a string object.
875\end{cfuncdesc}
876
877\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +0000878This function is similar to \cfunction{PyErr_SetString()} but lets you
Guido van Rossumae110af1997-05-22 20:11:52 +0000879specify an arbitrary Python object for the ``value'' of the exception.
880You need not increment its reference count.
881\end{cfuncdesc}
882
Fred Drake73577702000-04-10 18:50:14 +0000883\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
884 const char *format, ...}
Jeremy Hylton98605b52000-04-10 18:40:57 +0000885This function sets the error indicator using a printf-style format
886string. The first argument specifies the exception type and the
887second argument specifies the format string for the exception. Any
888subsequent arguments are converted to output by the C library's
889\cfunction{vsprintf()} function. The buffer used internally by
Fred Drake73577702000-04-10 18:50:14 +0000890\cfunction{PyErr_Format()} is 500 bytes long. The caller is
891responsible for guaranteeing that the formatted output does not
892overflow the buffer.
Jeremy Hylton98605b52000-04-10 18:40:57 +0000893\end{cfuncdesc}
894
Guido van Rossumae110af1997-05-22 20:11:52 +0000895\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +0000896This is a shorthand for \samp{PyErr_SetObject(\var{type}, Py_None)}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000897\end{cfuncdesc}
898
899\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000900This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000901\var{message})}, where \var{message} indicates that a built-in operation
902was invoked with an illegal argument. It is mostly for internal use.
903\end{cfuncdesc}
904
Fred Drakec6fa34e1998-04-02 06:47:24 +0000905\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000906This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
Guido van Rossumae110af1997-05-22 20:11:52 +0000907returns \NULL{} so an object allocation function can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000908\samp{return PyErr_NoMemory();} when it runs out of memory.
Guido van Rossumae110af1997-05-22 20:11:52 +0000909\end{cfuncdesc}
910
Fred Drakec6fa34e1998-04-02 06:47:24 +0000911\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
Fred Drake659ebfa2000-04-03 15:42:13 +0000912This is a convenience function to raise an exception when a C library
913function has returned an error and set the C variable \cdata{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000914It constructs a tuple object whose first item is the integer
Fred Drakef8830d11998-04-23 14:06:01 +0000915\cdata{errno} value and whose second item is the corresponding error
Fred Drake659ebfa2000-04-03 15:42:13 +0000916message (gotten from \cfunction{strerror()}\ttindex{strerror()}), and
917then calls
Fred Drakee058b4f1998-02-16 06:15:35 +0000918\samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
Fred Drakef8830d11998-04-23 14:06:01 +0000919the \cdata{errno} value is \constant{EINTR}, indicating an interrupted
Fred Drakee058b4f1998-02-16 06:15:35 +0000920system call, this calls \cfunction{PyErr_CheckSignals()}, and if that set
Guido van Rossumae110af1997-05-22 20:11:52 +0000921the error indicator, leaves it set to that. The function always
922returns \NULL{}, so a wrapper function around a system call can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000923\samp{return PyErr_SetFromErrno();} when the system call returns an
924error.
Guido van Rossumae110af1997-05-22 20:11:52 +0000925\end{cfuncdesc}
926
927\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000928This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000929\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000930operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000931argument. It is mostly for internal use.
932\end{cfuncdesc}
933
934\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
935This function interacts with Python's signal handling. It checks
936whether a signal has been sent to the processes and if so, invokes the
Fred Drake4de05a91998-02-16 14:25:26 +0000937corresponding signal handler. If the
938\module{signal}\refbimodindex{signal} module is supported, this can
939invoke a signal handler written in Python. In all cases, the default
Fred Drake659ebfa2000-04-03 15:42:13 +0000940effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
941\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
942\exception{KeyboardInterrupt} exception. If an exception is raised the
Fred Drakee058b4f1998-02-16 06:15:35 +0000943error indicator is set and the function returns \code{1}; otherwise
944the function returns \code{0}. The error indicator may or may not be
945cleared if it was previously set.
Guido van Rossumae110af1997-05-22 20:11:52 +0000946\end{cfuncdesc}
947
948\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
Fred Drake659ebfa2000-04-03 15:42:13 +0000949This function is obsolete. It simulates the effect of a
950\constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
Fred Drakee058b4f1998-02-16 06:15:35 +0000951\cfunction{PyErr_CheckSignals()} is called,
Fred Drake659ebfa2000-04-03 15:42:13 +0000952\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
953\exception{KeyboardInterrupt} will be raised.
954It may be called without holding the interpreter lock.
Guido van Rossumae110af1997-05-22 20:11:52 +0000955\end{cfuncdesc}
956
Fred Drakec6fa34e1998-04-02 06:47:24 +0000957\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
958 PyObject *base,
959 PyObject *dict}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000960This utility function creates and returns a new exception object. The
Fred Drake659ebfa2000-04-03 15:42:13 +0000961\var{name} argument must be the name of the new exception, a C string
962of the form \code{module.class}. The \var{base} and
Fred Draked04038d2000-06-29 20:15:14 +0000963\var{dict} arguments are normally \NULL{}. This creates a
Fred Drake659ebfa2000-04-03 15:42:13 +0000964class object derived from the root for all exceptions, the built-in
965name \exception{Exception} (accessible in C as
Fred Draked04038d2000-06-29 20:15:14 +0000966\cdata{PyExc_Exception}). The \member{__module__} attribute of the
967new class is set to the first part (up to the last dot) of the
968\var{name} argument, and the class name is set to the last part (after
969the last dot). The \var{base} argument can be used to specify an
970alternate base class. The \var{dict} argument can be used to specify
971a dictionary of class variables and methods.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000972\end{cfuncdesc}
973
974
Fred Drakeefd146c1999-02-15 15:30:45 +0000975\section{Standard Exceptions \label{standardExceptions}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000976
977All standard Python exceptions are available as global variables whose
Fred Drake659ebfa2000-04-03 15:42:13 +0000978names are \samp{PyExc_} followed by the Python exception name. These
979have the type \ctype{PyObject*}; they are all class objects. For
980completeness, here are all the variables:
981
982\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
983 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
984 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
985 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
986 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
987 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
988 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
989 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
990 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
991 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
992 \lineiii{PyExc_IOError}{\exception{IOError}}{}
993 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
994 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
995 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
996 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
997 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
998 \lineiii{PyExc_NameError}{\exception{NameError}}{}
999 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
1000 \lineiii{PyExc_OSError}{\exception{OSError}}{}
1001 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
1002 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
1003 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
1004 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
1005 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
1006 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
1007 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
Fred Drakea8d73412000-08-11 20:39:29 +00001008 \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(2)}
Fred Drake659ebfa2000-04-03 15:42:13 +00001009 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
1010\end{tableiii}
1011
1012\noindent
Fred Drakea8d73412000-08-11 20:39:29 +00001013Notes:
Fred Drake659ebfa2000-04-03 15:42:13 +00001014\begin{description}
1015\item[(1)]
Fred Draked04038d2000-06-29 20:15:14 +00001016 This is a base class for other standard exceptions.
Fred Drakea8d73412000-08-11 20:39:29 +00001017
1018\item[(2)]
1019 Only defined on Windows; protect code that uses this by testing that
1020 the preprocessor macro \code{MS_WINDOWS} is defined.
Fred Drake659ebfa2000-04-03 15:42:13 +00001021\end{description}
1022
1023
1024\section{Deprecation of String Exceptions}
1025
Fred Draked04038d2000-06-29 20:15:14 +00001026All exceptions built into Python or provided in the standard library
1027are derived from \exception{Exception}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001028\withsubitem{(built-in exception)}{\ttindex{Exception}}
Fred Drake659ebfa2000-04-03 15:42:13 +00001029
Fred Draked04038d2000-06-29 20:15:14 +00001030String exceptions are still supported in the interpreter to allow
Fred Drake659ebfa2000-04-03 15:42:13 +00001031existing code to run unmodified, but this will also change in a future
1032release.
Guido van Rossumae110af1997-05-22 20:11:52 +00001033
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001034
Fred Drakeefd146c1999-02-15 15:30:45 +00001035\chapter{Utilities \label{utilities}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001036
1037The functions in this chapter perform various utility tasks, such as
Fred Drake659ebfa2000-04-03 15:42:13 +00001038parsing function arguments and constructing Python values from C
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001039values.
1040
Fred Drakeefd146c1999-02-15 15:30:45 +00001041\section{OS Utilities \label{os}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001042
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001043\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001044Return true (nonzero) if the standard I/O file \var{fp} with name
1045\var{filename} is deemed interactive. This is the case for files for
1046which \samp{isatty(fileno(\var{fp}))} is true. If the global flag
Fred Drakef8830d11998-04-23 14:06:01 +00001047\cdata{Py_InteractiveFlag} is true, this function also returns true if
Fred Drakee058b4f1998-02-16 06:15:35 +00001048the \var{name} pointer is \NULL{} or if the name is equal to one of
Fred Drakea8455ab2000-06-16 19:58:42 +00001049the strings \code{'<stdin>'} or \code{'???'}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001050\end{cfuncdesc}
1051
1052\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001053Return the time of last modification of the file \var{filename}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001054The result is encoded in the same way as the timestamp returned by
Fred Drake659ebfa2000-04-03 15:42:13 +00001055the standard C library function \cfunction{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001056\end{cfuncdesc}
1057
Fred Drakecabbc3b2000-06-28 15:53:13 +00001058\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
1059Function to update some internal state after a process fork; this
1060should be called in the new process if the Python interpreter will
1061continue to be used. If a new executable is loaded into the new
1062process, this function does not need to be called.
1063\end{cfuncdesc}
1064
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001065
Fred Drakeefd146c1999-02-15 15:30:45 +00001066\section{Process Control \label{processControl}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001067
1068\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
1069Print a fatal error message and kill the process. No cleanup is
1070performed. This function should only be invoked when a condition is
1071detected that would make it dangerous to continue using the Python
1072interpreter; e.g., when the object administration appears to be
Fred Drake659ebfa2000-04-03 15:42:13 +00001073corrupted. On \UNIX{}, the standard C library function
1074\cfunction{abort()}\ttindex{abort()} is called which will attempt to
1075produce a \file{core} file.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001076\end{cfuncdesc}
1077
1078\begin{cfuncdesc}{void}{Py_Exit}{int status}
Fred Drake659ebfa2000-04-03 15:42:13 +00001079Exit the current process. This calls
1080\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
1081then calls the standard C library function
1082\code{exit(\var{status})}\ttindex{exit()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001083\end{cfuncdesc}
1084
1085\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drake659ebfa2000-04-03 15:42:13 +00001086Register a cleanup function to be called by
1087\cfunction{Py_Finalize()}\ttindex{Py_Finalize()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001088The cleanup function will be called with no arguments and should
Fred Drake659ebfa2000-04-03 15:42:13 +00001089return no value. At most 32 \index{cleanup functions}cleanup
1090functions can be registered.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001091When the registration is successful, \cfunction{Py_AtExit()} returns
1092\code{0}; on failure, it returns \code{-1}. The cleanup function
1093registered last is called first. Each cleanup function will be called
1094at most once. Since Python's internal finallization will have
1095completed before the cleanup function, no Python APIs should be called
1096by \var{func}.
1097\end{cfuncdesc}
1098
1099
Fred Drakeefd146c1999-02-15 15:30:45 +00001100\section{Importing Modules \label{importing}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001101
Fred Drakec6fa34e1998-04-02 06:47:24 +00001102\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00001103This is a simplified interface to
1104\cfunction{PyImport_ImportModuleEx()} below, leaving the
1105\var{globals} and \var{locals} arguments set to \NULL{}. When the
1106\var{name} argument contains a dot (i.e., when it specifies a
1107submodule of a package), the \var{fromlist} argument is set to the
1108list \code{['*']} so that the return value is the named module rather
1109than the top-level package containing it as would otherwise be the
1110case. (Unfortunately, this has an additional side effect when
1111\var{name} in fact specifies a subpackage instead of a submodule: the
1112submodules specified in the package's \code{__all__} variable are
1113\index{package variable!\code{__all__}}
1114\withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a
1115new reference to the imported module, or
1116\NULL{} with an exception set on failure (the module may still be
1117created in this case --- examine \code{sys.modules} to find out).
1118\withsubitem{(in module sys)}{\ttindex{modules}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001119\end{cfuncdesc}
1120
Fred Drakec6fa34e1998-04-02 06:47:24 +00001121\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001122Import a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001123Python function \function{__import__()}\bifuncindex{__import__}, as
1124the standard \function{__import__()} function calls this function
1125directly.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001126
Guido van Rossum42cefd01997-10-05 15:27:29 +00001127The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001128top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001129(the module may still be created in this case). Like for
Fred Drakee058b4f1998-02-16 06:15:35 +00001130\function{__import__()}, the return value when a submodule of a
1131package was requested is normally the top-level package, unless a
1132non-empty \var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001133\end{cfuncdesc}
1134
Fred Drakec6fa34e1998-04-02 06:47:24 +00001135\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001136This is a higher-level interface that calls the current ``import hook
Fred Drakee058b4f1998-02-16 06:15:35 +00001137function''. It invokes the \function{__import__()} function from the
Guido van Rossum42cefd01997-10-05 15:27:29 +00001138\code{__builtins__} of the current globals. This means that the
1139import is done using whatever import hooks are installed in the
Fred Drake4de05a91998-02-16 14:25:26 +00001140current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
1141\module{ihooks}\refstmodindex{ihooks}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001142\end{cfuncdesc}
1143
Fred Drakec6fa34e1998-04-02 06:47:24 +00001144\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001145Reload a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001146Python function \function{reload()}\bifuncindex{reload}, as the standard
Fred Drakee058b4f1998-02-16 06:15:35 +00001147\function{reload()} function calls this function directly. Return a
1148new reference to the reloaded module, or \NULL{} with an exception set
1149on failure (the module still exists in this case).
Guido van Rossum42cefd01997-10-05 15:27:29 +00001150\end{cfuncdesc}
1151
Fred Drakec6fa34e1998-04-02 06:47:24 +00001152\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001153Return the module object corresponding to a module name. The
1154\var{name} argument may be of the form \code{package.module}). First
1155check the modules dictionary if there's one there, and if not, create
Fred Drake659ebfa2000-04-03 15:42:13 +00001156a new one and insert in in the modules dictionary.
Guido van Rossuma096a2e1998-11-02 17:02:42 +00001157Warning: this function does not load or import the module; if the
1158module wasn't already loaded, you will get an empty module object.
1159Use \cfunction{PyImport_ImportModule()} or one of its variants to
1160import a module.
Fred Drake659ebfa2000-04-03 15:42:13 +00001161Return \NULL{} with an exception set on failure.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001162\end{cfuncdesc}
1163
Fred Drakec6fa34e1998-04-02 06:47:24 +00001164\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001165Given a module name (possibly of the form \code{package.module}) and a
1166code object read from a Python bytecode file or obtained from the
Fred Drake53fb7721998-02-16 06:23:20 +00001167built-in function \function{compile()}\bifuncindex{compile}, load the
1168module. Return a new reference to the module object, or \NULL{} with
1169an exception set if an error occurred (the module may still be created
1170in this case). (This function would reload the module if it was
1171already imported.)
Guido van Rossum42cefd01997-10-05 15:27:29 +00001172\end{cfuncdesc}
1173
1174\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001175Return the magic number for Python bytecode files (a.k.a.
1176\file{.pyc} and \file{.pyo} files). The magic number should be
1177present in the first four bytes of the bytecode file, in little-endian
1178byte order.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001179\end{cfuncdesc}
1180
Fred Drakec6fa34e1998-04-02 06:47:24 +00001181\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001182Return the dictionary used for the module administration
1183(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1184variable.
1185\end{cfuncdesc}
1186
1187\begin{cfuncdesc}{void}{_PyImport_Init}{}
1188Initialize the import mechanism. For internal use only.
1189\end{cfuncdesc}
1190
1191\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1192Empty the module table. For internal use only.
1193\end{cfuncdesc}
1194
1195\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1196Finalize the import mechanism. For internal use only.
1197\end{cfuncdesc}
1198
Fred Drakec6fa34e1998-04-02 06:47:24 +00001199\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001200For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001201\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001202
Fred Drakec6fa34e1998-04-02 06:47:24 +00001203\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001204For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001205\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001206
Fred Drake1d158692000-06-18 05:21:21 +00001207\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
1208Load a frozen module named \var{name}. Return \code{1} for success,
1209\code{0} if the module is not found, and \code{-1} with an exception
1210set if the initialization failed. To access the imported module on a
1211successful load, use \cfunction{PyImport_ImportModule()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00001212(Note the misnomer --- this function would reload the module if it was
Guido van Rossum42cefd01997-10-05 15:27:29 +00001213already imported.)
1214\end{cfuncdesc}
1215
Fred Drake659ebfa2000-04-03 15:42:13 +00001216\begin{ctypedesc}[_frozen]{struct _frozen}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001217This is the structure type definition for frozen module descriptors,
Fred Drakec6fa34e1998-04-02 06:47:24 +00001218as generated by the \program{freeze}\index{freeze utility} utility
1219(see \file{Tools/freeze/} in the Python source distribution). Its
1220definition is:
1221
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001222\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001223struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001224 char *name;
1225 unsigned char *code;
1226 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001227};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001228\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001229\end{ctypedesc}
1230
Fred Drakec6fa34e1998-04-02 06:47:24 +00001231\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
Fred Drakef8830d11998-04-23 14:06:01 +00001232This pointer is initialized to point to an array of \ctype{struct
Fred Drake659ebfa2000-04-03 15:42:13 +00001233_frozen} records, terminated by one whose members are all
1234\NULL{} or zero. When a frozen module is imported, it is searched in
1235this table. Third-party code could play tricks with this to provide a
Guido van Rossum42cefd01997-10-05 15:27:29 +00001236dynamically created collection of frozen modules.
1237\end{cvardesc}
1238
1239
Fred Drakeefd146c1999-02-15 15:30:45 +00001240\chapter{Abstract Objects Layer \label{abstract}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001241
1242The functions in this chapter interact with Python objects regardless
1243of their type, or with wide classes of object types (e.g. all
1244numerical types, or all sequence types). When used on object types
Fred Drake659ebfa2000-04-03 15:42:13 +00001245for which they do not apply, they will raise a Python exception.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001246
Fred Drakeefd146c1999-02-15 15:30:45 +00001247\section{Object Protocol \label{object}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001248
1249\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00001250Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error.
1251The flags argument is used to enable certain printing options. The
1252only option currently supported is \constant{Py_PRINT_RAW}; if given,
1253the \function{str()} of the object is written instead of the
1254\function{repr()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001255\end{cfuncdesc}
1256
1257\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001258Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1259\code{0} otherwise. This is equivalent to the Python expression
1260\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001261This function always succeeds.
1262\end{cfuncdesc}
1263
Fred Drake659ebfa2000-04-03 15:42:13 +00001264\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
1265 char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001266Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001267Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001268This is the equivalent of the Python expression
1269\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001270\end{cfuncdesc}
1271
1272
1273\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001274Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1275\code{0} otherwise. This is equivalent to the Python expression
1276\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001277This function always succeeds.
1278\end{cfuncdesc}
1279
1280
Fred Drake659ebfa2000-04-03 15:42:13 +00001281\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
1282 PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001283Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001284Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001285This is the equivalent of the Python expression
1286\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001287\end{cfuncdesc}
1288
1289
1290\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001291Set the value of the attribute named \var{attr_name}, for object
1292\var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1293the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1294\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001295\end{cfuncdesc}
1296
1297
1298\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001299Set the value of the attribute named \var{attr_name}, for
1300object \var{o},
1301to the value \var{v}. Returns \code{-1} on failure. This is
1302the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1303\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001304\end{cfuncdesc}
1305
1306
1307\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001308Delete attribute named \var{attr_name}, for object \var{o}. Returns
1309\code{-1} on failure. This is the equivalent of the Python
1310statement: \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001311\end{cfuncdesc}
1312
1313
1314\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001315Delete attribute named \var{attr_name}, for object \var{o}. Returns
1316\code{-1} on failure. This is the equivalent of the Python
1317statement \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001318\end{cfuncdesc}
1319
1320
1321\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
Fred Drakee058b4f1998-02-16 06:15:35 +00001322Compare the values of \var{o1} and \var{o2} using a routine provided
1323by \var{o1}, if one exists, otherwise with a routine provided by
1324\var{o2}. The result of the comparison is returned in \var{result}.
1325Returns \code{-1} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001326statement\bifuncindex{cmp} \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001327\end{cfuncdesc}
1328
1329
1330\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001331Compare the values of \var{o1} and \var{o2} using a routine provided
1332by \var{o1}, if one exists, otherwise with a routine provided by
1333\var{o2}. Returns the result of the comparison on success. On error,
1334the value returned is undefined; use \cfunction{PyErr_Occurred()} to
Fred Drake659ebfa2000-04-03 15:42:13 +00001335detect an error. This is equivalent to the Python
1336expression\bifuncindex{cmp} \samp{cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001337\end{cfuncdesc}
1338
1339
1340\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001341Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001342string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001343the equivalent of the Python expression \samp{repr(\var{o})}.
1344Called by the \function{repr()}\bifuncindex{repr} built-in function
1345and by reverse quotes.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001346\end{cfuncdesc}
1347
1348
1349\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001350Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001351string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001352the equivalent of the Python expression \samp{str(\var{o})}.
1353Called by the \function{str()}\bifuncindex{str} built-in function and
1354by the \keyword{print} statement.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001355\end{cfuncdesc}
1356
1357
1358\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001359Determine if the object \var{o} is callable. Return \code{1} if the
Fred Drakee058b4f1998-02-16 06:15:35 +00001360object is callable and \code{0} otherwise.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001361This function always succeeds.
1362\end{cfuncdesc}
1363
1364
Fred Drake659ebfa2000-04-03 15:42:13 +00001365\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
1366 PyObject *args}
Fred Drakee058b4f1998-02-16 06:15:35 +00001367Call a callable Python object \var{callable_object}, with
1368arguments given by the tuple \var{args}. If no arguments are
Fred Drake659ebfa2000-04-03 15:42:13 +00001369needed, then \var{args} may be \NULL{}. Returns the result of the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001370call on success, or \NULL{} on failure. This is the equivalent
Fred Drakee058b4f1998-02-16 06:15:35 +00001371of the Python expression \samp{apply(\var{o}, \var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001372\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001373\end{cfuncdesc}
1374
1375\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001376Call a callable Python object \var{callable_object}, with a
Fred Drake659ebfa2000-04-03 15:42:13 +00001377variable number of C arguments. The C arguments are described
Fred Drakee058b4f1998-02-16 06:15:35 +00001378using a \cfunction{Py_BuildValue()} style format string. The format may
1379be \NULL{}, indicating that no arguments are provided. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001380result of the call on success, or \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001381the equivalent of the Python expression \samp{apply(\var{o},
Fred Drake659ebfa2000-04-03 15:42:13 +00001382\var{args})}.\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001383\end{cfuncdesc}
1384
1385
1386\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001387Call the method named \var{m} of object \var{o} with a variable number
Fred Drake659ebfa2000-04-03 15:42:13 +00001388of C arguments. The C arguments are described by a
Fred Drakee058b4f1998-02-16 06:15:35 +00001389\cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1390indicating that no arguments are provided. Returns the result of the
1391call on success, or \NULL{} on failure. This is the equivalent of the
1392Python expression \samp{\var{o}.\var{method}(\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001393Note that special method names, such as \method{__add__()},
1394\method{__getitem__()}, and so on are not supported. The specific
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001395abstract-object routines for these must be used.
1396\end{cfuncdesc}
1397
1398
1399\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001400Compute and return the hash value of an object \var{o}. On
1401failure, return \code{-1}. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001402expression \samp{hash(\var{o})}.\bifuncindex{hash}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001403\end{cfuncdesc}
1404
1405
1406\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001407Returns \code{1} if the object \var{o} is considered to be true, and
1408\code{0} otherwise. This is equivalent to the Python expression
1409\samp{not not \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001410This function always succeeds.
1411\end{cfuncdesc}
1412
1413
1414\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1415On success, returns a type object corresponding to the object
Fred Drakee058b4f1998-02-16 06:15:35 +00001416type of object \var{o}. On failure, returns \NULL{}. This is
1417equivalent to the Python expression \samp{type(\var{o})}.
Fred Drake53fb7721998-02-16 06:23:20 +00001418\bifuncindex{type}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001419\end{cfuncdesc}
1420
1421\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001422Return the length of object \var{o}. If the object \var{o} provides
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001423both sequence and mapping protocols, the sequence length is
Fred Drake659ebfa2000-04-03 15:42:13 +00001424returned. On error, \code{-1} is returned. This is the equivalent
1425to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001426\end{cfuncdesc}
1427
1428
1429\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001430Return element of \var{o} corresponding to the object \var{key} or
1431\NULL{} on failure. This is the equivalent of the Python expression
1432\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001433\end{cfuncdesc}
1434
1435
1436\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001437Map the object \var{key} to the value \var{v}.
1438Returns \code{-1} on failure. This is the equivalent
1439of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001440\end{cfuncdesc}
1441
1442
Guido van Rossumd1dbf631999-01-22 20:10:49 +00001443\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001444Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1445failure. This is the equivalent of the Python statement \samp{del
1446\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001447\end{cfuncdesc}
1448
Andrew M. Kuchling8c46b302000-07-13 23:58:16 +00001449\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
1450Derives a file-descriptor from a Python object. If the object
1451is an integer or long integer, its value is returned. If not, the
1452object's \method{fileno()} method is called if it exists; the method
1453must return an integer or long integer, which is returned as the file
1454descriptor value. Returns \code{-1} on failure.
1455\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001456
Fred Drakeefd146c1999-02-15 15:30:45 +00001457\section{Number Protocol \label{number}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001458
1459\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001460Returns \code{1} if the object \var{o} provides numeric protocols, and
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001461false otherwise.
1462This function always succeeds.
1463\end{cfuncdesc}
1464
1465
1466\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001467Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1468failure. This is the equivalent of the Python expression
1469\samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001470\end{cfuncdesc}
1471
1472
1473\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
Fred Drake659ebfa2000-04-03 15:42:13 +00001474Returns the result of subtracting \var{o2} from \var{o1}, or
1475\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001476\samp{\var{o1} - \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001477\end{cfuncdesc}
1478
1479
1480\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001481Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1482failure. This is the equivalent of the Python expression
1483\samp{\var{o1} * \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001484\end{cfuncdesc}
1485
1486
1487\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001488Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1489failure.
1490This is the equivalent of the Python expression \samp{\var{o1} /
1491\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001492\end{cfuncdesc}
1493
1494
1495\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001496Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1497failure. This is the equivalent of the Python expression
Fred Drake659ebfa2000-04-03 15:42:13 +00001498\samp{\var{o1} \%\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001499\end{cfuncdesc}
1500
1501
1502\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
Fred Drake53fb7721998-02-16 06:23:20 +00001503See the built-in function \function{divmod()}\bifuncindex{divmod}.
1504Returns \NULL{} on failure. This is the equivalent of the Python
1505expression \samp{divmod(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001506\end{cfuncdesc}
1507
1508
1509\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
Fred Drake53fb7721998-02-16 06:23:20 +00001510See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1511\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001512\samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
Fred Drake659ebfa2000-04-03 15:42:13 +00001513If \var{o3} is to be ignored, pass \cdata{Py_None} in its place
1514(passing \NULL{} for \var{o3} would cause an illegal memory access).
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001515\end{cfuncdesc}
1516
1517
1518\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001519Returns the negation of \var{o} on success, or \NULL{} on failure.
1520This is the equivalent of the Python expression \samp{-\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001521\end{cfuncdesc}
1522
1523
1524\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001525Returns \var{o} on success, or \NULL{} on failure.
1526This is the equivalent of the Python expression \samp{+\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001527\end{cfuncdesc}
1528
1529
1530\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001531Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1532the equivalent of the Python expression \samp{abs(\var{o})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001533\bifuncindex{abs}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001534\end{cfuncdesc}
1535
1536
1537\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001538Returns the bitwise negation of \var{o} on success, or \NULL{} on
1539failure. This is the equivalent of the Python expression
1540\samp{\~\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001541\end{cfuncdesc}
1542
1543
1544\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001545Returns the result of left shifting \var{o1} by \var{o2} on success,
1546or \NULL{} on failure. This is the equivalent of the Python
1547expression \samp{\var{o1} << \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001548\end{cfuncdesc}
1549
1550
1551\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001552Returns the result of right shifting \var{o1} by \var{o2} on success,
1553or \NULL{} on failure. This is the equivalent of the Python
1554expression \samp{\var{o1} >> \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001555\end{cfuncdesc}
1556
1557
1558\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001559Returns the result of ``anding'' \var{o2} and \var{o2} on success and
1560\NULL{} on failure. This is the equivalent of the Python
1561expression \samp{\var{o1} and \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001562\end{cfuncdesc}
1563
1564
1565\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001566Returns the bitwise exclusive or of \var{o1} by \var{o2} on success,
1567or \NULL{} on failure. This is the equivalent of the Python
1568expression \samp{\var{o1} \^{ }\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001569\end{cfuncdesc}
1570
1571\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001572Returns the result of \var{o1} and \var{o2} on success, or \NULL{} on
1573failure. This is the equivalent of the Python expression
1574\samp{\var{o1} or \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001575\end{cfuncdesc}
1576
Fred Drakee058b4f1998-02-16 06:15:35 +00001577\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001578This function takes the addresses of two variables of type
Fred Drake659ebfa2000-04-03 15:42:13 +00001579\ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} and
1580\code{*\var{p2}} have the same type, increment their reference count
1581and return \code{0} (success). If the objects can be converted to a
1582common numeric type, replace \code{*p1} and \code{*p2} by their
1583converted value (with 'new' reference counts), and return \code{0}.
1584If no conversion is possible, or if some other error occurs, return
1585\code{-1} (failure) and don't increment the reference counts. The
1586call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1587statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
1588\bifuncindex{coerce}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001589\end{cfuncdesc}
1590
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001591\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001592Returns the \var{o} converted to an integer object on success, or
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001593\NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001594expression \samp{int(\var{o})}.\bifuncindex{int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001595\end{cfuncdesc}
1596
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001597\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001598Returns the \var{o} converted to a long integer object on success,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001599or \NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001600expression \samp{long(\var{o})}.\bifuncindex{long}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001601\end{cfuncdesc}
1602
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001603\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001604Returns the \var{o} converted to a float object on success, or
1605\NULL{} on failure. This is the equivalent of the Python expression
1606\samp{float(\var{o})}.\bifuncindex{float}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001607\end{cfuncdesc}
1608
1609
Fred Drakeefd146c1999-02-15 15:30:45 +00001610\section{Sequence Protocol \label{sequence}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001611
1612\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001613Return \code{1} if the object provides sequence protocol, and
1614\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001615\end{cfuncdesc}
1616
Fred Drake659ebfa2000-04-03 15:42:13 +00001617\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
1618Returns the number of objects in sequence \var{o} on success, and
1619\code{-1} on failure. For objects that do not provide sequence
1620protocol, this is equivalent to the Python expression
1621\samp{len(\var{o})}.\bifuncindex{len}
1622\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001623
1624\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001625Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001626failure. This is the equivalent of the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001627expression \samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001628\end{cfuncdesc}
1629
1630
1631\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Fred Drake659ebfa2000-04-03 15:42:13 +00001632Return the result of repeating sequence object
1633\var{o} \var{count} times, or \NULL{} on failure. This is the
1634equivalent of the Python expression \samp{\var{o} * \var{count}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001635\end{cfuncdesc}
1636
1637
1638\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001639Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
1640is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001641\end{cfuncdesc}
1642
1643
1644\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001645Return the slice of sequence object \var{o} between \var{i1} and
1646\var{i2}, or \NULL{} on failure. This is the equivalent of the Python
1647expression \samp{\var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001648\end{cfuncdesc}
1649
1650
1651\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001652Assign object \var{v} to the \var{i}th element of \var{o}.
1653Returns \code{-1} on failure. This is the equivalent of the Python
1654statement \samp{\var{o}[\var{i}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001655\end{cfuncdesc}
1656
1657\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001658Delete the \var{i}th element of object \var{v}. Returns
1659\code{-1} on failure. This is the equivalent of the Python
1660statement \samp{del \var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001661\end{cfuncdesc}
1662
Fred Drake659ebfa2000-04-03 15:42:13 +00001663\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
1664 int i2, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001665Assign the sequence object \var{v} to the slice in sequence
1666object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
1667the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001668\end{cfuncdesc}
1669
1670\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001671Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
1672Returns \code{-1} on failure. This is the equivalent of the Python
1673statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001674\end{cfuncdesc}
1675
1676\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001677Returns the \var{o} as a tuple on success, and \NULL{} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00001678This is equivalent to the Python expression \samp{tuple(\var{o})}.
1679\bifuncindex{tuple}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001680\end{cfuncdesc}
1681
1682\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001683Return the number of occurrences of \var{value} in \var{o}, that is,
1684return the number of keys for which \code{\var{o}[\var{key}] ==
1685\var{value}}. On failure, return \code{-1}. This is equivalent to
1686the Python expression \samp{\var{o}.count(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001687\end{cfuncdesc}
1688
Fred Drake659ebfa2000-04-03 15:42:13 +00001689\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001690Determine if \var{o} contains \var{value}. If an item in \var{o} is
1691equal to \var{value}, return \code{1}, otherwise return \code{0}. On
1692error, return \code{-1}. This is equivalent to the Python expression
1693\samp{\var{value} in \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001694\end{cfuncdesc}
1695
1696\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001697Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
1698\var{value}}. On error, return \code{-1}. This is equivalent to
1699the Python expression \samp{\var{o}.index(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001700\end{cfuncdesc}
1701
Fred Drakea8455ab2000-06-16 19:58:42 +00001702\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
1703Return a list object with the same contents as the arbitrary sequence
1704\var{o}. The returned list is guaranteed to be new.
1705\end{cfuncdesc}
1706
1707\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1708Return a tuple object with the same contents as the arbitrary sequence
1709\var{o}. If \var{o} is a tuple, a new reference will be returned,
1710otherwise a tuple will be constructed with the appropriate contents.
1711\end{cfuncdesc}
1712
Fred Drakef39ed671998-02-26 22:01:23 +00001713
Fred Drakeefd146c1999-02-15 15:30:45 +00001714\section{Mapping Protocol \label{mapping}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001715
1716\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001717Return \code{1} if the object provides mapping protocol, and
1718\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001719\end{cfuncdesc}
1720
1721
1722\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001723Returns the number of keys in object \var{o} on success, and
1724\code{-1} on failure. For objects that do not provide mapping
1725protocol, this is equivalent to the Python expression
1726\samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001727\end{cfuncdesc}
1728
1729
1730\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001731Remove the mapping for object \var{key} from the object \var{o}.
1732Return \code{-1} on failure. This is equivalent to
1733the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001734\end{cfuncdesc}
1735
1736
1737\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001738Remove the mapping for object \var{key} from the object \var{o}.
1739Return \code{-1} on failure. This is equivalent to
1740the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001741\end{cfuncdesc}
1742
1743
1744\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
Fred Drake659ebfa2000-04-03 15:42:13 +00001745On success, return \code{1} if the mapping object has the key
1746\var{key} and \code{0} otherwise. This is equivalent to the Python
1747expression \samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001748This function always succeeds.
1749\end{cfuncdesc}
1750
1751
1752\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001753Return \code{1} if the mapping object has the key \var{key} and
1754\code{0} otherwise. This is equivalent to the Python expression
1755\samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001756This function always succeeds.
1757\end{cfuncdesc}
1758
1759
1760\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001761On success, return a list of the keys in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001762failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001763expression \samp{\var{o}.keys()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001764\end{cfuncdesc}
1765
1766
1767\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001768On success, return a list of the values in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001769failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001770expression \samp{\var{o}.values()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001771\end{cfuncdesc}
1772
1773
1774\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001775On success, return a list of the items in object \var{o}, where
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001776each item is a tuple containing a key-value pair. On
1777failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001778expression \samp{\var{o}.items()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001779\end{cfuncdesc}
1780
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001781
1782\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001783Return element of \var{o} corresponding to the object \var{key} or
1784\NULL{} on failure. This is the equivalent of the Python expression
1785\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001786\end{cfuncdesc}
1787
Guido van Rossum0a0f11b1998-10-16 17:43:53 +00001788\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001789Map the object \var{key} to the value \var{v} in object \var{o}.
1790Returns \code{-1} on failure. This is the equivalent of the Python
1791statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001792\end{cfuncdesc}
1793
1794
Fred Drakeefd146c1999-02-15 15:30:45 +00001795\chapter{Concrete Objects Layer \label{concrete}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001796
1797The functions in this chapter are specific to certain Python object
1798types. Passing them an object of the wrong type is not a good idea;
1799if you receive an object from a Python program and you are not sure
1800that it has the right type, you must perform a type check first;
Fred Drake659ebfa2000-04-03 15:42:13 +00001801for example. to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00001802\cfunction{PyDict_Check()}. The chapter is structured like the
1803``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001804
1805
Fred Drakeefd146c1999-02-15 15:30:45 +00001806\section{Fundamental Objects \label{fundamental}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001807
Fred Drakee5bf8b21998-02-12 21:22:28 +00001808This section describes Python type objects and the singleton object
1809\code{None}.
1810
1811
Fred Drakeefd146c1999-02-15 15:30:45 +00001812\subsection{Type Objects \label{typeObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001813
Fred Drake659ebfa2000-04-03 15:42:13 +00001814\obindex{type}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001815\begin{ctypedesc}{PyTypeObject}
Fred Drake659ebfa2000-04-03 15:42:13 +00001816The C structure of the objects used to describe built-in types.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001817\end{ctypedesc}
1818
Fred Drake659ebfa2000-04-03 15:42:13 +00001819\begin{cvardesc}{PyObject*}{PyType_Type}
Fred Drakeefd146c1999-02-15 15:30:45 +00001820This is the type object for type objects; it is the same object as
1821\code{types.TypeType} in the Python layer.
Fred Drake659ebfa2000-04-03 15:42:13 +00001822\withsubitem{(in module types)}{\ttindex{TypeType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001823\end{cvardesc}
1824
Fred Drake659ebfa2000-04-03 15:42:13 +00001825\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
1826Returns true is the object \var{o} is a type object.
1827\end{cfuncdesc}
1828
1829\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
1830Returns true if the type object \var{o} sets the feature
1831\var{feature}. Type features are denoted by single bit flags. The
1832only defined feature flag is \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER},
1833described in section \ref{buffer-structs}.
1834\end{cfuncdesc}
1835
Fred Drakee5bf8b21998-02-12 21:22:28 +00001836
Fred Drakeefd146c1999-02-15 15:30:45 +00001837\subsection{The None Object \label{noneObject}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001838
Fred Drake659ebfa2000-04-03 15:42:13 +00001839\obindex{None@\texttt{None}}
1840Note that the \ctype{PyTypeObject} for \code{None} is not directly
1841exposed in the Python/C API. Since \code{None} is a singleton,
1842testing for object identity (using \samp{==} in C) is sufficient.
1843There is no \cfunction{PyNone_Check()} function for the same reason.
1844
1845\begin{cvardesc}{PyObject*}{Py_None}
Guido van Rossum44475131998-04-21 15:30:01 +00001846The Python \code{None} object, denoting lack of value. This object has
1847no methods.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001848\end{cvardesc}
1849
1850
Fred Drakeefd146c1999-02-15 15:30:45 +00001851\section{Sequence Objects \label{sequenceObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001852
Fred Drake659ebfa2000-04-03 15:42:13 +00001853\obindex{sequence}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001854Generic operations on sequence objects were discussed in the previous
1855chapter; this section deals with the specific kinds of sequence
1856objects that are intrinsic to the Python language.
1857
1858
Fred Drakeefd146c1999-02-15 15:30:45 +00001859\subsection{String Objects \label{stringObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001860
Fred Drake659ebfa2000-04-03 15:42:13 +00001861\obindex{string}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001862\begin{ctypedesc}{PyStringObject}
Fred Drakef8830d11998-04-23 14:06:01 +00001863This subtype of \ctype{PyObject} represents a Python string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001864\end{ctypedesc}
1865
1866\begin{cvardesc}{PyTypeObject}{PyString_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00001867This instance of \ctype{PyTypeObject} represents the Python string
1868type; it is the same object as \code{types.TypeType} in the Python
1869layer.\withsubitem{(in module types)}{\ttindex{StringType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001870\end{cvardesc}
1871
1872\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00001873Returns true if the object \var{o} is a string object.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001874\end{cfuncdesc}
1875
Fred Drakec6fa34e1998-04-02 06:47:24 +00001876\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00001877Returns a new string object with the value \var{v} on success, and
1878\NULL{} on failure.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001879\end{cfuncdesc}
1880
Fred Drake659ebfa2000-04-03 15:42:13 +00001881\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
1882 int len}
1883Returns a new string object with the value \var{v} and length
1884\var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
1885the contents of the string are uninitialized.
1886\end{cfuncdesc}
1887
Fred Drakec6fa34e1998-04-02 06:47:24 +00001888\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00001889Returns the length of the string in string object \var{string}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001890\end{cfuncdesc}
1891
Fred Drake659ebfa2000-04-03 15:42:13 +00001892\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
1893Macro form of \cfunction{PyString_GetSize()} but without error
1894checking.
1895\end{cfuncdesc}
1896
Fred Drakec6fa34e1998-04-02 06:47:24 +00001897\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
Fred Drake659ebfa2000-04-03 15:42:13 +00001898Returns a null-terminated representation of the contents of
1899\var{string}. The pointer refers to the internal buffer of
1900\var{string}, not a copy. The data must not be modified in any way.
1901It must not be de-allocated.
1902\end{cfuncdesc}
1903
1904\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
1905Macro form of \cfunction{PyString_AsString()} but without error
1906checking.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001907\end{cfuncdesc}
1908
1909\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
1910 PyObject *newpart}
Fred Drake66b989c1999-02-15 20:15:39 +00001911Creates a new string object in \var{*string} containing the
Fred Drakeddc6c272000-03-31 18:22:38 +00001912contents of \var{newpart} appended to \var{string}; the caller will
1913own the new reference. The reference to the old value of \var{string}
1914will be stolen. If the new string
Fred Drake66b989c1999-02-15 20:15:39 +00001915cannot be created, the old reference to \var{string} will still be
1916discarded and the value of \var{*string} will be set to
1917\NULL{}; the appropriate exception will be set.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001918\end{cfuncdesc}
1919
1920\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
1921 PyObject *newpart}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00001922Creates a new string object in \var{*string} containing the contents
Guido van Rossum44475131998-04-21 15:30:01 +00001923of \var{newpart} appended to \var{string}. This version decrements
1924the reference count of \var{newpart}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001925\end{cfuncdesc}
1926
1927\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
Guido van Rossum44475131998-04-21 15:30:01 +00001928A way to resize a string object even though it is ``immutable''.
1929Only use this to build up a brand new string object; don't use this if
1930the string may already be known in other parts of the code.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001931\end{cfuncdesc}
1932
1933\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
1934 PyObject *args}
Guido van Rossum44475131998-04-21 15:30:01 +00001935Returns a new string object from \var{format} and \var{args}. Analogous
Fred Drake659ebfa2000-04-03 15:42:13 +00001936to \code{\var{format} \%\ \var{args}}. The \var{args} argument must be
Guido van Rossum44475131998-04-21 15:30:01 +00001937a tuple.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001938\end{cfuncdesc}
1939
1940\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
Guido van Rossum44475131998-04-21 15:30:01 +00001941Intern the argument \var{*string} in place. The argument must be the
1942address of a pointer variable pointing to a Python string object.
1943If there is an existing interned string that is the same as
1944\var{*string}, it sets \var{*string} to it (decrementing the reference
1945count of the old string object and incrementing the reference count of
1946the interned string object), otherwise it leaves \var{*string} alone
1947and interns it (incrementing its reference count). (Clarification:
1948even though there is a lot of talk about reference counts, think of
Fred Drakef8830d11998-04-23 14:06:01 +00001949this function as reference-count-neutral; you own the object after
1950the call if and only if you owned it before the call.)
Fred Drakec6fa34e1998-04-02 06:47:24 +00001951\end{cfuncdesc}
1952
1953\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
Fred Drakef8830d11998-04-23 14:06:01 +00001954A combination of \cfunction{PyString_FromString()} and
1955\cfunction{PyString_InternInPlace()}, returning either a new string object
Guido van Rossum44475131998-04-21 15:30:01 +00001956that has been interned, or a new (``owned'') reference to an earlier
1957interned string object with the same value.
Fred Drakec6fa34e1998-04-02 06:47:24 +00001958\end{cfuncdesc}
1959
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00001960\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
1961 int size,
1962 const char *encoding,
1963 const char *errors}
1964Create a string object by decoding \var{size} bytes of the encoded
1965buffer \var{s}. \var{encoding} and \var{errors} have the same meaning
1966as the parameters of the same name in the unicode() builtin
1967function. The codec to be used is looked up using the Python codec
1968registry. Returns \NULL{} in case an exception was raised by the
1969codec.
1970\end{cfuncdesc}
1971
1972\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const Py_UNICODE *s,
1973 int size,
1974 const char *encoding,
1975 const char *errors}
1976Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
1977Python string object. \var{encoding} and \var{errors} have the same
1978meaning as the parameters of the same name in the string .encode()
1979method. The codec to be used is looked up using the Python codec
1980registry. Returns \NULL{} in case an exception was raised by the
1981codec.
1982\end{cfuncdesc}
1983
1984\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedString}{PyObject *unicode,
1985 const char *encoding,
1986 const char *errors}
1987Encodes a string object and returns the result as Python string
1988object. \var{encoding} and \var{errors} have the same meaning as the
1989parameters of the same name in the string .encode() method. The codec
1990to be used is looked up using the Python codec registry. Returns
1991\NULL{} in case an exception was raised by the codec.
1992\end{cfuncdesc}
1993
Fred Drakee5bf8b21998-02-12 21:22:28 +00001994
Fred Drakea4cd2612000-04-06 14:10:29 +00001995\subsection{Unicode Objects \label{unicodeObjects}}
1996\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
1997
1998%--- Unicode Type -------------------------------------------------------
1999
2000These are the basic Unicode object types used for the Unicode
2001implementation in Python:
2002
2003\begin{ctypedesc}{Py_UNICODE}
2004This type represents a 16-bit unsigned storage type which is used by
2005Python internally as basis for holding Unicode ordinals. On platforms
2006where \ctype{wchar_t} is available and also has 16-bits,
2007\ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
2008native platform compatibility. On all other platforms,
2009\ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
2010\end{ctypedesc}
2011
2012\begin{ctypedesc}{PyUnicodeObject}
2013This subtype of \ctype{PyObject} represents a Python Unicode object.
2014\end{ctypedesc}
2015
2016\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
2017This instance of \ctype{PyTypeObject} represents the Python Unicode type.
2018\end{cvardesc}
2019
2020%--- These are really C macros... is there a macrodesc TeX macro ?
2021
2022The following APIs are really C macros and can be used to do fast
2023checks and to access internal read-only data of Unicode objects:
2024
2025\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
2026Returns true if the object \var{o} is a Unicode object.
2027\end{cfuncdesc}
2028
2029\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
2030Returns the size of the object. o has to be a
2031PyUnicodeObject (not checked).
2032\end{cfuncdesc}
2033
2034\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
2035Returns the size of the object's internal buffer in bytes. o has to be
2036a PyUnicodeObject (not checked).
2037\end{cfuncdesc}
2038
Fred Drake992fe5a2000-06-16 21:04:15 +00002039\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002040Returns a pointer to the internal Py_UNICODE buffer of the object. o
2041has to be a PyUnicodeObject (not checked).
2042\end{cfuncdesc}
2043
Fred Drake992fe5a2000-06-16 21:04:15 +00002044\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002045Returns a (const char *) pointer to the internal buffer of the object.
2046o has to be a PyUnicodeObject (not checked).
2047\end{cfuncdesc}
2048
2049% --- Unicode character properties ---------------------------------------
2050
2051Unicode provides many different character properties. The most often
2052needed ones are available through these macros which are mapped to C
2053functions depending on the Python configuration.
2054
2055\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
2056Returns 1/0 depending on whether \var{ch} is a whitespace character.
2057\end{cfuncdesc}
2058
2059\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
2060Returns 1/0 depending on whether \var{ch} is a lowercase character.
2061\end{cfuncdesc}
2062
2063\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
Fred Drakeae96aab2000-07-03 13:38:10 +00002064Returns 1/0 depending on whether \var{ch} is an uppercase character.
Fred Drakea4cd2612000-04-06 14:10:29 +00002065\end{cfuncdesc}
2066
2067\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
2068Returns 1/0 depending on whether \var{ch} is a titlecase character.
2069\end{cfuncdesc}
2070
2071\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
2072Returns 1/0 depending on whether \var{ch} is a linebreak character.
2073\end{cfuncdesc}
2074
2075\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
2076Returns 1/0 depending on whether \var{ch} is a decimal character.
2077\end{cfuncdesc}
2078
2079\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
2080Returns 1/0 depending on whether \var{ch} is a digit character.
2081\end{cfuncdesc}
2082
2083\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
2084Returns 1/0 depending on whether \var{ch} is a numeric character.
2085\end{cfuncdesc}
2086
Fred Drakeae96aab2000-07-03 13:38:10 +00002087\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
2088Returns 1/0 depending on whether \var{ch} is an alphabetic character.
2089\end{cfuncdesc}
2090
2091\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
2092Returns 1/0 depending on whether \var{ch} is an alphanumeric character.
2093\end{cfuncdesc}
2094
Fred Drakea4cd2612000-04-06 14:10:29 +00002095These APIs can be used for fast direct character conversions:
2096
2097\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
2098Returns the character \var{ch} converted to lower case.
2099\end{cfuncdesc}
2100
2101\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
2102Returns the character \var{ch} converted to upper case.
2103\end{cfuncdesc}
2104
2105\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
2106Returns the character \var{ch} converted to title case.
2107\end{cfuncdesc}
2108
2109\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
2110Returns the character \var{ch} converted to a decimal positive integer.
2111Returns -1 in case this is not possible. Does not raise exceptions.
2112\end{cfuncdesc}
2113
2114\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
2115Returns the character \var{ch} converted to a single digit integer.
2116Returns -1 in case this is not possible. Does not raise exceptions.
2117\end{cfuncdesc}
2118
2119\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
2120Returns the character \var{ch} converted to a (positive) double.
2121Returns -1.0 in case this is not possible. Does not raise exceptions.
2122\end{cfuncdesc}
2123
2124% --- Plain Py_UNICODE ---------------------------------------------------
2125
2126To create Unicode objects and access their basic sequence properties,
2127use these APIs:
2128
2129\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
2130 int size}
2131
2132Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
2133given size. \var{u} may be \NULL{} which causes the contents to be
2134undefined. It is the user's responsibility to fill in the needed data.
2135The buffer is copied into the new object.
2136\end{cfuncdesc}
2137
Fred Drake1d158692000-06-18 05:21:21 +00002138\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002139Return a read-only pointer to the Unicode object's internal
2140\ctype{Py_UNICODE} buffer.
2141\end{cfuncdesc}
2142
2143\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
2144Return the length of the Unicode object.
2145\end{cfuncdesc}
2146
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002147\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
2148 const char *encoding,
2149 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002150
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002151Coerce an encoded object obj to an Unicode object and return a
2152reference with incremented refcount.
Fred Drakea4cd2612000-04-06 14:10:29 +00002153
2154Coercion is done in the following way:
2155\begin{enumerate}
2156\item Unicode objects are passed back as-is with incremented
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002157 refcount. Note: these cannot be decoded; passing a non-NULL
2158 value for encoding will result in a TypeError.
Fred Drakea4cd2612000-04-06 14:10:29 +00002159
2160\item String and other char buffer compatible objects are decoded
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002161 according to the given encoding and using the error handling
2162 defined by errors. Both can be NULL to have the interface use
2163 the default values (see the next section for details).
Fred Drakea4cd2612000-04-06 14:10:29 +00002164
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002165\item All other objects cause an exception.
Fred Drakea4cd2612000-04-06 14:10:29 +00002166\end{enumerate}
2167The API returns NULL in case of an error. The caller is responsible
2168for decref'ing the returned objects.
2169\end{cfuncdesc}
2170
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002171\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
2172
2173Shortcut for PyUnicode_FromEncodedObject(obj, NULL, ``strict'')
2174which is used throughout the interpreter whenever coercion to
2175Unicode is needed.
2176\end{cfuncdesc}
2177
Fred Drakea4cd2612000-04-06 14:10:29 +00002178% --- wchar_t support for platforms which support it ---------------------
2179
2180If the platform supports \ctype{wchar_t} and provides a header file
2181wchar.h, Python can interface directly to this type using the
2182following functions. Support is optimized if Python's own
2183\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
2184
2185\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
2186 int size}
2187Create a Unicode Object from the \ctype{whcar_t} buffer \var{w} of the
2188given size. Returns \NULL{} on failure.
2189\end{cfuncdesc}
2190
2191\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
2192 wchar_t *w,
2193 int size}
Fred Drakea4cd2612000-04-06 14:10:29 +00002194Copies the Unicode Object contents into the \ctype{whcar_t} buffer
2195\var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
2196Returns the number of \ctype{whcar_t} characters copied or -1 in case
2197of an error.
2198\end{cfuncdesc}
2199
2200
2201\subsubsection{Builtin Codecs \label{builtinCodecs}}
2202
2203Python provides a set of builtin codecs which are written in C
2204for speed. All of these codecs are directly usable via the
2205following functions.
2206
2207Many of the following APIs take two arguments encoding and
2208errors. These parameters encoding and errors have the same semantics
2209as the ones of the builtin unicode() Unicode object constructor.
2210
2211Setting encoding to NULL causes the default encoding to be used which
2212is UTF-8.
2213
2214Error handling is set by errors which may also be set to NULL meaning
2215to use the default handling defined for the codec. Default error
2216handling for all builtin codecs is ``strict'' (ValueErrors are raised).
2217
2218The codecs all use a similar interface. Only deviation from the
2219following generic ones are documented for simplicity.
2220
2221% --- Generic Codecs -----------------------------------------------------
2222
2223These are the generic codec APIs:
2224
2225\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
2226 int size,
2227 const char *encoding,
2228 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002229Create a Unicode object by decoding \var{size} bytes of the encoded
2230string \var{s}. \var{encoding} and \var{errors} have the same meaning
2231as the parameters of the same name in the unicode() builtin
2232function. The codec to be used is looked up using the Python codec
2233registry. Returns \NULL{} in case an exception was raised by the
2234codec.
2235\end{cfuncdesc}
2236
2237\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
2238 int size,
2239 const char *encoding,
2240 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002241Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2242Python string object. \var{encoding} and \var{errors} have the same
2243meaning as the parameters of the same name in the Unicode .encode()
2244method. The codec to be used is looked up using the Python codec
2245registry. Returns \NULL{} in case an exception was raised by the
2246codec.
2247\end{cfuncdesc}
2248
2249\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
2250 const char *encoding,
2251 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002252Encodes a Unicode object and returns the result as Python string
2253object. \var{encoding} and \var{errors} have the same meaning as the
2254parameters of the same name in the Unicode .encode() method. The codec
2255to be used is looked up using the Python codec registry. Returns
2256\NULL{} in case an exception was raised by the codec.
2257\end{cfuncdesc}
2258
2259% --- UTF-8 Codecs -------------------------------------------------------
2260
2261These are the UTF-8 codec APIs:
2262
2263\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
2264 int size,
2265 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002266Creates a Unicode object by decoding \var{size} bytes of the UTF-8
2267encoded string \var{s}. Returns \NULL{} in case an exception was
2268raised by the codec.
2269\end{cfuncdesc}
2270
2271\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
2272 int size,
2273 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002274Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
2275and returns a Python string object. Returns \NULL{} in case an
2276exception was raised by the codec.
2277\end{cfuncdesc}
2278
2279\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002280Encodes a Unicode objects using UTF-8 and returns the result as Python
2281string object. Error handling is ``strict''. Returns
2282\NULL{} in case an exception was raised by the codec.
2283\end{cfuncdesc}
2284
2285% --- UTF-16 Codecs ------------------------------------------------------ */
2286
2287These are the UTF-16 codec APIs:
2288
2289\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
2290 int size,
2291 const char *errors,
2292 int *byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002293Decodes \var{length} bytes from a UTF-16 encoded buffer string and
2294returns the corresponding Unicode object.
2295
2296\var{errors} (if non-NULL) defines the error handling. It defaults
2297to ``strict''.
2298
2299If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
2300the given byte order:
2301
2302\begin{verbatim}
2303 *byteorder == -1: little endian
2304 *byteorder == 0: native order
2305 *byteorder == 1: big endian
2306\end{verbatim}
2307
2308and then switches according to all byte order marks (BOM) it finds in
2309the input data. BOM marks are not copied into the resulting Unicode
2310string. After completion, \var{*byteorder} is set to the current byte
2311order at the end of input data.
2312
2313If \var{byteorder} is \NULL{}, the codec starts in native order mode.
2314
2315Returns \NULL{} in case an exception was raised by the codec.
2316\end{cfuncdesc}
2317
2318\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
2319 int size,
2320 const char *errors,
2321 int byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002322Returns a Python string object holding the UTF-16 encoded value of the
2323Unicode data in \var{s}.
2324
Fred Drakea8455ab2000-06-16 19:58:42 +00002325If \var{byteorder} is not \code{0}, output is written according to the
Fred Drakea4cd2612000-04-06 14:10:29 +00002326following byte order:
2327
2328\begin{verbatim}
2329 byteorder == -1: little endian
2330 byteorder == 0: native byte order (writes a BOM mark)
2331 byteorder == 1: big endian
2332\end{verbatim}
2333
Fred Drakea8455ab2000-06-16 19:58:42 +00002334If byteorder is \code{0}, the output string will always start with the
Fred Drakea4cd2612000-04-06 14:10:29 +00002335Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
2336prepended.
2337
2338Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
2339reduced to UCS-2. This trick makes it possible to add full UTF-16
2340capabilities at a later point without comprimising the APIs.
2341
2342Returns \NULL{} in case an exception was raised by the codec.
2343\end{cfuncdesc}
2344
2345\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002346Returns a Python string using the UTF-16 encoding in native byte
2347order. The string always starts with a BOM mark. Error handling is
2348``strict''. Returns \NULL{} in case an exception was raised by the
2349codec.
2350\end{cfuncdesc}
2351
2352% --- Unicode-Escape Codecs ----------------------------------------------
2353
2354These are the ``Unicode Esacpe'' codec APIs:
2355
2356\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
2357 int size,
2358 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002359Creates a Unicode object by decoding \var{size} bytes of the Unicode-Esacpe
2360encoded string \var{s}. Returns \NULL{} in case an exception was
2361raised by the codec.
2362\end{cfuncdesc}
2363
2364\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
2365 int size,
2366 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002367Encodes the \ctype{Py_UNICODE} buffer of the given size using Unicode-Escape
2368and returns a Python string object. Returns \NULL{} in case an
2369exception was raised by the codec.
2370\end{cfuncdesc}
2371
2372\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002373Encodes a Unicode objects using Unicode-Escape and returns the result
2374as Python string object. Error handling is ``strict''. Returns
2375\NULL{} in case an exception was raised by the codec.
2376\end{cfuncdesc}
2377
2378% --- Raw-Unicode-Escape Codecs ------------------------------------------
2379
2380These are the ``Raw Unicode Esacpe'' codec APIs:
2381
2382\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
2383 int size,
2384 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002385Creates a Unicode object by decoding \var{size} bytes of the Raw-Unicode-Esacpe
2386encoded string \var{s}. Returns \NULL{} in case an exception was
2387raised by the codec.
2388\end{cfuncdesc}
2389
2390\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
2391 int size,
2392 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002393Encodes the \ctype{Py_UNICODE} buffer of the given size using Raw-Unicode-Escape
2394and returns a Python string object. Returns \NULL{} in case an
2395exception was raised by the codec.
2396\end{cfuncdesc}
2397
2398\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002399Encodes a Unicode objects using Raw-Unicode-Escape and returns the result
2400as Python string object. Error handling is ``strict''. Returns
2401\NULL{} in case an exception was raised by the codec.
2402\end{cfuncdesc}
2403
2404% --- Latin-1 Codecs -----------------------------------------------------
2405
2406These are the Latin-1 codec APIs:
2407
2408Latin-1 corresponds to the first 256 Unicode ordinals and only these
2409are accepted by the codecs during encoding.
2410
2411\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002412 int size,
2413 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002414Creates a Unicode object by decoding \var{size} bytes of the Latin-1
2415encoded string \var{s}. Returns \NULL{} in case an exception was
2416raised by the codec.
2417\end{cfuncdesc}
2418
2419\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002420 int size,
2421 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002422Encodes the \ctype{Py_UNICODE} buffer of the given size using Latin-1
2423and returns a Python string object. Returns \NULL{} in case an
2424exception was raised by the codec.
2425\end{cfuncdesc}
2426
2427\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002428Encodes a Unicode objects using Latin-1 and returns the result as
2429Python string object. Error handling is ``strict''. Returns
2430\NULL{} in case an exception was raised by the codec.
2431\end{cfuncdesc}
2432
2433% --- ASCII Codecs -------------------------------------------------------
2434
Fred Drake1d158692000-06-18 05:21:21 +00002435These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
2436accepted. All other codes generate errors.
Fred Drakea4cd2612000-04-06 14:10:29 +00002437
2438\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002439 int size,
2440 const char *errors}
2441Creates a Unicode object by decoding \var{size} bytes of the
2442\ASCII{} encoded string \var{s}. Returns \NULL{} in case an exception
2443was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002444\end{cfuncdesc}
2445
2446\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002447 int size,
2448 const char *errors}
2449Encodes the \ctype{Py_UNICODE} buffer of the given size using
2450\ASCII{} and returns a Python string object. Returns \NULL{} in case
2451an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002452\end{cfuncdesc}
2453
2454\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
Fred Drake1d158692000-06-18 05:21:21 +00002455Encodes a Unicode objects using \ASCII{} and returns the result as Python
Fred Drakea4cd2612000-04-06 14:10:29 +00002456string object. Error handling is ``strict''. Returns
2457\NULL{} in case an exception was raised by the codec.
2458\end{cfuncdesc}
2459
2460% --- Character Map Codecs -----------------------------------------------
2461
2462These are the mapping codec APIs:
2463
2464This codec is special in that it can be used to implement many
2465different codecs (and this is in fact what was done to obtain most of
2466the standard codecs included in the \module{encodings} package). The
2467codec uses mapping to encode and decode characters.
2468
2469Decoding mappings must map single string characters to single Unicode
2470characters, integers (which are then interpreted as Unicode ordinals)
2471or None (meaning "undefined mapping" and causing an error).
2472
2473Encoding mappings must map single Unicode characters to single string
2474characters, integers (which are then interpreted as Latin-1 ordinals)
2475or None (meaning "undefined mapping" and causing an error).
2476
2477The mapping objects provided must only support the __getitem__ mapping
2478interface.
2479
2480If a character lookup fails with a LookupError, the character is
2481copied as-is meaning that its ordinal value will be interpreted as
2482Unicode or Latin-1 ordinal resp. Because of this, mappings only need
2483to contain those mappings which map characters to different code
2484points.
2485
2486\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
2487 int size,
2488 PyObject *mapping,
2489 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002490Creates a Unicode object by decoding \var{size} bytes of the encoded
2491string \var{s} using the given \var{mapping} object. Returns \NULL{}
2492in case an exception was raised by the codec.
2493\end{cfuncdesc}
2494
2495\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
2496 int size,
2497 PyObject *mapping,
2498 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002499Encodes the \ctype{Py_UNICODE} buffer of the given size using the
2500given \var{mapping} object and returns a Python string object.
2501Returns \NULL{} in case an exception was raised by the codec.
2502\end{cfuncdesc}
2503
2504\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
2505 PyObject *mapping}
Fred Drakea4cd2612000-04-06 14:10:29 +00002506Encodes a Unicode objects using the given \var{mapping} object and
2507returns the result as Python string object. Error handling is
2508``strict''. Returns \NULL{} in case an exception was raised by the
2509codec.
2510\end{cfuncdesc}
2511
2512The following codec API is special in that maps Unicode to Unicode.
2513
2514\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
2515 int size,
2516 PyObject *table,
2517 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002518Translates a \ctype{Py_UNICODE} buffer of the given length by applying
2519a character mapping \var{table} to it and returns the resulting
Fred Drake1d158692000-06-18 05:21:21 +00002520Unicode object. Returns \NULL{} when an exception was raised by the
2521codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002522
2523The \var{mapping} table must map Unicode ordinal integers to Unicode
2524ordinal integers or None (causing deletion of the character).
2525
2526Mapping tables must only provide the __getitem__ interface,
2527e.g. dictionaries or sequences. Unmapped character ordinals (ones
2528which cause a LookupError) are left untouched and are copied as-is.
Fred Drakea4cd2612000-04-06 14:10:29 +00002529\end{cfuncdesc}
2530
2531% --- MBCS codecs for Windows --------------------------------------------
2532
Fred Drake1d158692000-06-18 05:21:21 +00002533These are the MBCS codec APIs. They are currently only available on
Fred Drakea4cd2612000-04-06 14:10:29 +00002534Windows and use the Win32 MBCS converters to implement the
Fred Drake1d158692000-06-18 05:21:21 +00002535conversions. Note that MBCS (or DBCS) is a class of encodings, not
2536just one. The target encoding is defined by the user settings on the
2537machine running the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002538
2539\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
2540 int size,
2541 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002542Creates a Unicode object by decoding \var{size} bytes of the MBCS
Fred Drake1d158692000-06-18 05:21:21 +00002543encoded string \var{s}. Returns \NULL{} in case an exception was
Fred Drakea4cd2612000-04-06 14:10:29 +00002544raised by the codec.
2545\end{cfuncdesc}
2546
2547\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
2548 int size,
2549 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002550Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
2551and returns a Python string object. Returns \NULL{} in case an
2552exception was raised by the codec.
2553\end{cfuncdesc}
2554
2555\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002556Encodes a Unicode objects using MBCS and returns the result as Python
Fred Drake1d158692000-06-18 05:21:21 +00002557string object. Error handling is ``strict''. Returns \NULL{} in case
2558an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002559\end{cfuncdesc}
2560
2561% --- Methods & Slots ----------------------------------------------------
2562
2563\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
2564
2565The following APIs are capable of handling Unicode objects and strings
2566on input (we refer to them as strings in the descriptions) and return
2567Unicode objects or integers as apporpriate.
2568
2569They all return \NULL{} or -1 in case an exception occurrs.
2570
2571\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
2572 PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002573Concat two strings giving a new Unicode string.
2574\end{cfuncdesc}
2575
2576\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
2577 PyObject *sep,
2578 int maxsplit}
Fred Drakea4cd2612000-04-06 14:10:29 +00002579Split a string giving a list of Unicode strings.
2580
2581If sep is NULL, splitting will be done at all whitespace
2582substrings. Otherwise, splits occur at the given separator.
2583
2584At most maxsplit splits will be done. If negative, no limit is set.
2585
2586Separators are not included in the resulting list.
2587\end{cfuncdesc}
2588
2589\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
2590 int maxsplit}
Fred Drake1d158692000-06-18 05:21:21 +00002591Split a Unicode string at line breaks, returning a list of Unicode
2592strings. CRLF is considered to be one line break. The Line break
2593characters are not included in the resulting strings.
Fred Drakea4cd2612000-04-06 14:10:29 +00002594\end{cfuncdesc}
2595
2596\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
2597 PyObject *table,
2598 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002599Translate a string by applying a character mapping table to it and
2600return the resulting Unicode object.
2601
2602The mapping table must map Unicode ordinal integers to Unicode ordinal
2603integers or None (causing deletion of the character).
2604
2605Mapping tables must only provide the __getitem__ interface,
2606e.g. dictionaries or sequences. Unmapped character ordinals (ones
2607which cause a LookupError) are left untouched and are copied as-is.
2608
2609\var{errors} has the usual meaning for codecs. It may be \NULL{}
2610which indicates to use the default error handling.
Fred Drakea4cd2612000-04-06 14:10:29 +00002611\end{cfuncdesc}
2612
2613\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
2614 PyObject *seq}
Fred Drakea4cd2612000-04-06 14:10:29 +00002615Join a sequence of strings using the given separator and return
2616the resulting Unicode string.
2617\end{cfuncdesc}
2618
2619\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
2620 PyObject *substr,
2621 int start,
2622 int end,
2623 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002624Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
2625the given tail end (\var{direction} == -1 means to do a prefix match,
2626\var{direction} == 1 a suffix match), 0 otherwise.
2627\end{cfuncdesc}
2628
2629\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
2630 PyObject *substr,
2631 int start,
2632 int end,
2633 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002634Return the first position of \var{substr} in
2635\var{str}[\var{start}:\var{end}] using the given \var{direction}
2636(\var{direction} == 1 means to do a forward search,
2637\var{direction} == -1 a backward search), 0 otherwise.
2638\end{cfuncdesc}
2639
2640\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
2641 PyObject *substr,
2642 int start,
2643 int end}
Fred Drakea4cd2612000-04-06 14:10:29 +00002644Count the number of occurrences of \var{substr} in
2645\var{str}[\var{start}:\var{end}]
2646\end{cfuncdesc}
2647
2648\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
2649 PyObject *substr,
2650 PyObject *replstr,
2651 int maxcount}
Fred Drakea4cd2612000-04-06 14:10:29 +00002652Replace at most \var{maxcount} occurrences of \var{substr} in
2653\var{str} with \var{replstr} and return the resulting Unicode object.
2654\var{maxcount} == -1 means: replace all occurrences.
2655\end{cfuncdesc}
2656
Fred Drake1d158692000-06-18 05:21:21 +00002657\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002658Compare two strings and return -1, 0, 1 for less than, equal,
2659greater than resp.
2660\end{cfuncdesc}
2661
2662\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
2663 PyObject *args}
Fred Drake1d158692000-06-18 05:21:21 +00002664Returns a new string object from \var{format} and \var{args}; this is
2665analogous to \code{\var{format} \%\ \var{args}}. The
2666\var{args} argument must be a tuple.
Fred Drakea4cd2612000-04-06 14:10:29 +00002667\end{cfuncdesc}
2668
2669\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
2670 PyObject *element}
Fred Drakea4cd2612000-04-06 14:10:29 +00002671Checks whether \var{element} is contained in \var{container} and
Fred Drake1d158692000-06-18 05:21:21 +00002672returns true or false accordingly.
Fred Drakea4cd2612000-04-06 14:10:29 +00002673
Fred Drake1d158692000-06-18 05:21:21 +00002674\var{element} has to coerce to a one element Unicode string. \code{-1} is
Fred Drakea4cd2612000-04-06 14:10:29 +00002675returned in case of an error.
2676\end{cfuncdesc}
2677
2678
Fred Drake58c5a2a1999-08-04 13:13:24 +00002679\subsection{Buffer Objects \label{bufferObjects}}
Fred Drake659ebfa2000-04-03 15:42:13 +00002680\sectionauthor{Greg Stein}{gstein@lyra.org}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002681
Fred Drake659ebfa2000-04-03 15:42:13 +00002682\obindex{buffer}
2683Python objects implemented in C can export a group of functions called
2684the ``buffer\index{buffer interface} interface.'' These functions can
2685be used by an object to expose its data in a raw, byte-oriented
2686format. Clients of the object can use the buffer interface to access
2687the object data directly, without needing to copy it first.
2688
2689Two examples of objects that support
2690the buffer interface are strings and arrays. The string object exposes
2691the character contents in the buffer interface's byte-oriented
2692form. An array can also expose its contents, but it should be noted
2693that array elements may be multi-byte values.
2694
2695An example user of the buffer interface is the file object's
2696\method{write()} method. Any object that can export a series of bytes
2697through the buffer interface can be written to a file. There are a
2698number of format codes to \cfunction{PyArgs_ParseTuple()} that operate
2699against an object's buffer interface, returning data from the target
2700object.
2701
2702More information on the buffer interface is provided in the section
2703``Buffer Object Structures'' (section \ref{buffer-structs}), under
2704the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
2705
2706A ``buffer object'' is defined in the \file{bufferobject.h} header
2707(included by \file{Python.h}). These objects look very similar to
2708string objects at the Python programming level: they support slicing,
2709indexing, concatenation, and some other standard string
2710operations. However, their data can come from one of two sources: from
2711a block of memory, or from another object which exports the buffer
2712interface.
2713
2714Buffer objects are useful as a way to expose the data from another
2715object's buffer interface to the Python programmer. They can also be
2716used as a zero-copy slicing mechanism. Using their ability to
2717reference a block of memory, it is possible to expose any data to the
2718Python programmer quite easily. The memory could be a large, constant
2719array in a C extension, it could be a raw block of memory for
2720manipulation before passing to an operating system library, or it
2721could be used to pass around structured data in its native, in-memory
2722format.
2723
2724\begin{ctypedesc}{PyBufferObject}
2725This subtype of \ctype{PyObject} represents a buffer object.
2726\end{ctypedesc}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002727
2728\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
2729The instance of \ctype{PyTypeObject} which represents the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00002730buffer type; it is the same object as \code{types.BufferType} in the
2731Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002732\end{cvardesc}
2733
2734\begin{cvardesc}{int}{Py_END_OF_BUFFER}
Fred Drake659ebfa2000-04-03 15:42:13 +00002735This constant may be passed as the \var{size} parameter to
2736\cfunction{PyBuffer_FromObject()} or
2737\cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the new
2738\ctype{PyBufferObject} should refer to \var{base} object from the
2739specified \var{offset} to the end of its exported buffer. Using this
2740enables the caller to avoid querying the \var{base} object for its
2741length.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002742\end{cvardesc}
2743
2744\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
2745Return true if the argument has type \cdata{PyBuffer_Type}.
2746\end{cfuncdesc}
2747
2748\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
2749 int offset, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002750Return a new read-only buffer object. This raises
2751\exception{TypeError} if \var{base} doesn't support the read-only
2752buffer protocol or doesn't provide exactly one buffer segment, or it
2753raises \exception{ValueError} if \var{offset} is less than zero. The
2754buffer will hold a reference to the \var{base} object, and the
2755buffer's contents will refer to the \var{base} object's buffer
2756interface, starting as position \var{offset} and extending for
2757\var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
2758the new buffer's contents extend to the length of the
2759\var{base} object's exported buffer data.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002760\end{cfuncdesc}
2761
2762\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
2763 int offset,
2764 int size}
2765Return a new writable buffer object. Parameters and exceptions are
2766similar to those for \cfunction{PyBuffer_FromObject()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00002767If the \var{base} object does not export the writeable buffer
2768protocol, then \exception{TypeError} is raised.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002769\end{cfuncdesc}
2770
2771\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002772Return a new read-only buffer object that reads from a specified
2773location in memory, with a specified size.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002774The caller is responsible for ensuring that the memory buffer, passed
2775in as \var{ptr}, is not deallocated while the returned buffer object
2776exists. Raises \exception{ValueError} if \var{size} is less than
Fred Drake659ebfa2000-04-03 15:42:13 +00002777zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be passed
2778for the \var{size} parameter; \exception{ValueError} will be raised in
2779that case.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002780\end{cfuncdesc}
2781
2782\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002783Similar to \cfunction{PyBuffer_FromMemory()}, but the returned buffer
2784is writable.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002785\end{cfuncdesc}
2786
2787\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
2788Returns a new writable buffer object that maintains its own memory
Fred Drake659ebfa2000-04-03 15:42:13 +00002789buffer of \var{size} bytes. \exception{ValueError} is returned if
2790\var{size} is not zero or positive.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002791\end{cfuncdesc}
2792
Guido van Rossum44475131998-04-21 15:30:01 +00002793
Fred Drakeefd146c1999-02-15 15:30:45 +00002794\subsection{Tuple Objects \label{tupleObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002795
Fred Drake659ebfa2000-04-03 15:42:13 +00002796\obindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002797\begin{ctypedesc}{PyTupleObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002798This subtype of \ctype{PyObject} represents a Python tuple object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002799\end{ctypedesc}
2800
2801\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002802This instance of \ctype{PyTypeObject} represents the Python tuple
2803type; it is the same object as \code{types.TupleType} in the Python
2804layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002805\end{cvardesc}
2806
2807\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
2808Return true if the argument is a tuple object.
2809\end{cfuncdesc}
2810
Fred Drake659ebfa2000-04-03 15:42:13 +00002811\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
2812Return a new tuple object of size \var{len}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002813\end{cfuncdesc}
2814
2815\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
Fred Drakee058b4f1998-02-16 06:15:35 +00002816Takes a pointer to a tuple object, and returns the size
Fred Drakee5bf8b21998-02-12 21:22:28 +00002817of that tuple.
2818\end{cfuncdesc}
2819
Fred Drakec6fa34e1998-04-02 06:47:24 +00002820\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00002821Returns the object at position \var{pos} in the tuple pointed
2822to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00002823sets an \exception{IndexError} exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002824\end{cfuncdesc}
2825
Fred Drakec6fa34e1998-04-02 06:47:24 +00002826\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00002827Does the same, but does no checking of its arguments.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002828\end{cfuncdesc}
2829
Fred Drakec6fa34e1998-04-02 06:47:24 +00002830\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyTupleObject *p,
Fred Drakee5bf8b21998-02-12 21:22:28 +00002831 int low,
2832 int high}
Fred Drakee058b4f1998-02-16 06:15:35 +00002833Takes a slice of the tuple pointed to by \var{p} from
2834\var{low} to \var{high} and returns it as a new tuple.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002835\end{cfuncdesc}
2836
Fred Drake659ebfa2000-04-03 15:42:13 +00002837\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
2838 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002839Inserts a reference to object \var{o} at position \var{pos} of
2840the tuple pointed to by \var{p}. It returns \code{0} on success.
Fred Drake659ebfa2000-04-03 15:42:13 +00002841\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002842\end{cfuncdesc}
2843
Fred Drake659ebfa2000-04-03 15:42:13 +00002844\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
2845 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00002846Does the same, but does no error checking, and
Fred Drakee5bf8b21998-02-12 21:22:28 +00002847should \emph{only} be used to fill in brand new tuples.
Fred Drake659ebfa2000-04-03 15:42:13 +00002848\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002849\end{cfuncdesc}
2850
Fred Drakec6fa34e1998-04-02 06:47:24 +00002851\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyTupleObject *p,
Fred Drake659ebfa2000-04-03 15:42:13 +00002852 int newsize, int last_is_sticky}
2853Can be used to resize a tuple. \var{newsize} will be the new length
2854of the tuple. Because tuples are \emph{supposed} to be immutable,
2855this should only be used if there is only one reference to the object.
2856Do \emph{not} use this if the tuple may already be known to some other
2857part of the code. \var{last_is_sticky} is a flag --- if true, the
2858tuple will grow or shrink at the front, otherwise it will grow or
2859shrink at the end. Think of this as destroying the old tuple and
2860creating a new one, only more efficiently. Returns \code{0} on
2861success and \code{-1} on failure (in which case a
2862\exception{MemoryError} or \exception{SystemError} will be raised).
Fred Drakee5bf8b21998-02-12 21:22:28 +00002863\end{cfuncdesc}
2864
2865
Fred Drakeefd146c1999-02-15 15:30:45 +00002866\subsection{List Objects \label{listObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002867
Fred Drake659ebfa2000-04-03 15:42:13 +00002868\obindex{list}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002869\begin{ctypedesc}{PyListObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002870This subtype of \ctype{PyObject} represents a Python list object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002871\end{ctypedesc}
2872
2873\begin{cvardesc}{PyTypeObject}{PyList_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002874This instance of \ctype{PyTypeObject} represents the Python list
2875type. This is the same object as \code{types.ListType}.
2876\withsubitem{(in module types)}{\ttindex{ListType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002877\end{cvardesc}
2878
2879\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00002880Returns true if its argument is a \ctype{PyListObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002881\end{cfuncdesc}
2882
Fred Drake659ebfa2000-04-03 15:42:13 +00002883\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
2884Returns a new list of length \var{len} on success, or \NULL{} on
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002885failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002886\end{cfuncdesc}
2887
Fred Drakec6fa34e1998-04-02 06:47:24 +00002888\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00002889Returns the length of the list object in \var{list}; this is
2890equivalent to \samp{len(\var{list})} on a list object.
2891\bifuncindex{len}
2892\end{cfuncdesc}
2893
2894\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
2895Macro form of \cfunction{PyList_GetSize()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002896\end{cfuncdesc}
2897
Fred Drakec6fa34e1998-04-02 06:47:24 +00002898\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
Guido van Rossum44475131998-04-21 15:30:01 +00002899Returns the object at position \var{pos} in the list pointed
2900to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00002901sets an \exception{IndexError} exception.
2902\end{cfuncdesc}
2903
2904\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
2905Macro form of \cfunction{PyList_GetItem()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002906\end{cfuncdesc}
2907
Fred Drakec6fa34e1998-04-02 06:47:24 +00002908\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
2909 PyObject *item}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002910Sets the item at index \var{index} in list to \var{item}.
Fred Drake659ebfa2000-04-03 15:42:13 +00002911\strong{Note:} This function ``steals'' a reference to \var{item}.
2912\end{cfuncdesc}
2913
2914\begin{cfuncdesc}{PyObject*}{PyList_SET_ITEM}{PyObject *list, int i,
2915 PyObject *o}
2916Macro form of \cfunction{PyList_SetItem()} without error checking.
2917\strong{Note:} This function ``steals'' a reference to \var{item}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002918\end{cfuncdesc}
2919
Fred Drakec6fa34e1998-04-02 06:47:24 +00002920\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
Guido van Rossum44475131998-04-21 15:30:01 +00002921 PyObject *item}
2922Inserts the item \var{item} into list \var{list} in front of index
Fred Drake659ebfa2000-04-03 15:42:13 +00002923\var{index}. Returns \code{0} if successful; returns \code{-1} and
2924raises an exception if unsuccessful. Analogous to
2925\code{\var{list}.insert(\var{index}, \var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002926\end{cfuncdesc}
2927
Fred Drakec6fa34e1998-04-02 06:47:24 +00002928\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
Guido van Rossum44475131998-04-21 15:30:01 +00002929Appends the object \var{item} at the end of list \var{list}. Returns
Fred Drake659ebfa2000-04-03 15:42:13 +00002930\code{0} if successful; returns \code{-1} and sets an exception if
2931unsuccessful. Analogous to \code{\var{list}.append(\var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002932\end{cfuncdesc}
2933
Fred Drakec6fa34e1998-04-02 06:47:24 +00002934\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
2935 int low, int high}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002936Returns a list of the objects in \var{list} containing the objects
Guido van Rossum44475131998-04-21 15:30:01 +00002937\emph{between} \var{low} and \var{high}. Returns NULL and sets an
2938exception if unsuccessful.
Fred Drake659ebfa2000-04-03 15:42:13 +00002939Analogous to \code{\var{list}[\var{low}:\var{high}]}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002940\end{cfuncdesc}
2941
Fred Drakec6fa34e1998-04-02 06:47:24 +00002942\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
2943 int low, int high,
2944 PyObject *itemlist}
Fred Drake659ebfa2000-04-03 15:42:13 +00002945Sets the slice of \var{list} between \var{low} and \var{high} to the
2946contents of \var{itemlist}. Analogous to
2947\code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
2948\code{0} on success, \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002949\end{cfuncdesc}
2950
Fred Drakec6fa34e1998-04-02 06:47:24 +00002951\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00002952Sorts the items of \var{list} in place. Returns \code{0} on success,
2953\code{-1} on failure. This is equivalent to
2954\samp{\var{list}.sort()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002955\end{cfuncdesc}
2956
Fred Drakec6fa34e1998-04-02 06:47:24 +00002957\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00002958Reverses the items of \var{list} in place. Returns \code{0} on
2959success, \code{-1} on failure. This is the equivalent of
2960\samp{\var{list}.reverse()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002961\end{cfuncdesc}
2962
Fred Drakec6fa34e1998-04-02 06:47:24 +00002963\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00002964Returns a new tuple object containing the contents of \var{list};
2965equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002966\end{cfuncdesc}
2967
2968
Fred Drakeefd146c1999-02-15 15:30:45 +00002969\section{Mapping Objects \label{mapObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002970
Fred Drake659ebfa2000-04-03 15:42:13 +00002971\obindex{mapping}
2972
2973
Fred Drakeefd146c1999-02-15 15:30:45 +00002974\subsection{Dictionary Objects \label{dictObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002975
Fred Drake659ebfa2000-04-03 15:42:13 +00002976\obindex{dictionary}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002977\begin{ctypedesc}{PyDictObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002978This subtype of \ctype{PyObject} represents a Python dictionary object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002979\end{ctypedesc}
2980
2981\begin{cvardesc}{PyTypeObject}{PyDict_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002982This instance of \ctype{PyTypeObject} represents the Python dictionary
2983type. This is exposed to Python programs as \code{types.DictType} and
2984\code{types.DictionaryType}.
2985\withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002986\end{cvardesc}
2987
2988\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00002989Returns true if its argument is a \ctype{PyDictObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002990\end{cfuncdesc}
2991
Fred Drakec6fa34e1998-04-02 06:47:24 +00002992\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00002993Returns a new empty dictionary, or \NULL{} on failure.
2994\end{cfuncdesc}
2995
2996\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
2997Empties an existing dictionary of all key-value pairs.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002998\end{cfuncdesc}
2999
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003000\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003001Returns a new dictionary that contains the same key-value pairs as p.
3002Empties an existing dictionary of all key-value pairs.
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003003\end{cfuncdesc}
3004
Fred Drake659ebfa2000-04-03 15:42:13 +00003005\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
3006 PyObject *val}
3007Inserts \var{value} into the dictionary with a key of \var{key}.
3008\var{key} must be hashable; if it isn't, \exception{TypeError} will be
3009raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003010\end{cfuncdesc}
3011
3012\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
3013 char *key,
3014 PyObject *val}
Fred Drakee058b4f1998-02-16 06:15:35 +00003015Inserts \var{value} into the dictionary using \var{key}
Fred Drake1d158692000-06-18 05:21:21 +00003016as a key. \var{key} should be a \ctype{char*}. The key object is
Fred Drakee058b4f1998-02-16 06:15:35 +00003017created using \code{PyString_FromString(\var{key})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003018\ttindex{PyString_FromString()}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003019\end{cfuncdesc}
3020
Fred Drake659ebfa2000-04-03 15:42:13 +00003021\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003022Removes the entry in dictionary \var{p} with key \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003023\var{key} must be hashable; if it isn't, \exception{TypeError} is
3024raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003025\end{cfuncdesc}
3026
Fred Drake659ebfa2000-04-03 15:42:13 +00003027\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003028Removes the entry in dictionary \var{p} which has a key
Fred Drake659ebfa2000-04-03 15:42:13 +00003029specified by the string \var{key}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003030\end{cfuncdesc}
3031
Fred Drake659ebfa2000-04-03 15:42:13 +00003032\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003033Returns the object from dictionary \var{p} which has a key
Guido van Rossum44475131998-04-21 15:30:01 +00003034\var{key}. Returns \NULL{} if the key \var{key} is not present, but
Fred Drake659ebfa2000-04-03 15:42:13 +00003035\emph{without} setting an exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003036\end{cfuncdesc}
3037
Fred Drake659ebfa2000-04-03 15:42:13 +00003038\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
Fred Drakef8830d11998-04-23 14:06:01 +00003039This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
Fred Drake659ebfa2000-04-03 15:42:13 +00003040specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003041\end{cfuncdesc}
3042
Fred Drake659ebfa2000-04-03 15:42:13 +00003043\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003044Returns a \ctype{PyListObject} containing all the items
Guido van Rossum44475131998-04-21 15:30:01 +00003045from the dictionary, as in the dictinoary method \method{items()} (see
Fred Drakebe486461999-11-09 17:03:03 +00003046the \citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003047\end{cfuncdesc}
3048
Fred Drake659ebfa2000-04-03 15:42:13 +00003049\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003050Returns a \ctype{PyListObject} containing all the keys
Guido van Rossum44475131998-04-21 15:30:01 +00003051from the dictionary, as in the dictionary method \method{keys()} (see the
Fred Drakebe486461999-11-09 17:03:03 +00003052\citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003053\end{cfuncdesc}
3054
Fred Drake659ebfa2000-04-03 15:42:13 +00003055\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003056Returns a \ctype{PyListObject} containing all the values
Guido van Rossum44475131998-04-21 15:30:01 +00003057from the dictionary \var{p}, as in the dictionary method
Fred Drakebe486461999-11-09 17:03:03 +00003058\method{values()} (see the \citetitle[../lib/lib.html]{Python Library
3059Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003060\end{cfuncdesc}
3061
Fred Drake659ebfa2000-04-03 15:42:13 +00003062\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
3063Returns the number of items in the dictionary. This is equivalent to
3064\samp{len(\var{p})} on a dictionary.\bifuncindex{len}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003065\end{cfuncdesc}
3066
Fred Drake7d45d342000-08-11 17:07:32 +00003067\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p, int *ppos,
3068 PyObject **pkey, PyObject **pvalue}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003069
3070\end{cfuncdesc}
3071
3072
Fred Drakeefd146c1999-02-15 15:30:45 +00003073\section{Numeric Objects \label{numericObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003074
Fred Drake659ebfa2000-04-03 15:42:13 +00003075\obindex{numeric}
3076
3077
Fred Drakeefd146c1999-02-15 15:30:45 +00003078\subsection{Plain Integer Objects \label{intObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003079
Fred Drake659ebfa2000-04-03 15:42:13 +00003080\obindex{integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003081\begin{ctypedesc}{PyIntObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003082This subtype of \ctype{PyObject} represents a Python integer object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003083\end{ctypedesc}
3084
3085\begin{cvardesc}{PyTypeObject}{PyInt_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003086This instance of \ctype{PyTypeObject} represents the Python plain
Fred Drake659ebfa2000-04-03 15:42:13 +00003087integer type. This is the same object as \code{types.IntType}.
3088\withsubitem{(in modules types)}{\ttindex{IntType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003089\end{cvardesc}
3090
Fred Drake659ebfa2000-04-03 15:42:13 +00003091\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
3092Returns true if \var{o} is of type \cdata{PyInt_Type}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003093\end{cfuncdesc}
3094
Fred Drakec6fa34e1998-04-02 06:47:24 +00003095\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
Fred Drakee058b4f1998-02-16 06:15:35 +00003096Creates a new integer object with a value of \var{ival}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003097
3098The current implementation keeps an array of integer objects for all
Fred Drakee058b4f1998-02-16 06:15:35 +00003099integers between \code{-1} and \code{100}, when you create an int in
3100that range you actually just get back a reference to the existing
3101object. So it should be possible to change the value of \code{1}. I
Fred Drake7e9d3141998-04-03 05:02:28 +00003102suspect the behaviour of Python in this case is undefined. :-)
Fred Drakee5bf8b21998-02-12 21:22:28 +00003103\end{cfuncdesc}
3104
Fred Drakee5bf8b21998-02-12 21:22:28 +00003105\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
Fred Drakef8830d11998-04-23 14:06:01 +00003106Will first attempt to cast the object to a \ctype{PyIntObject}, if
Fred Drakee058b4f1998-02-16 06:15:35 +00003107it is not already one, and then return its value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003108\end{cfuncdesc}
3109
Fred Drake659ebfa2000-04-03 15:42:13 +00003110\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
3111Returns the value of the object \var{io}. No error checking is
3112performed.
3113\end{cfuncdesc}
3114
Fred Drakee5bf8b21998-02-12 21:22:28 +00003115\begin{cfuncdesc}{long}{PyInt_GetMax}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003116Returns the system's idea of the largest integer it can handle
3117(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
3118header files).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003119\end{cfuncdesc}
3120
3121
Fred Drakeefd146c1999-02-15 15:30:45 +00003122\subsection{Long Integer Objects \label{longObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003123
Fred Drake659ebfa2000-04-03 15:42:13 +00003124\obindex{long integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003125\begin{ctypedesc}{PyLongObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003126This subtype of \ctype{PyObject} represents a Python long integer
Fred Drakee058b4f1998-02-16 06:15:35 +00003127object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003128\end{ctypedesc}
3129
3130\begin{cvardesc}{PyTypeObject}{PyLong_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003131This instance of \ctype{PyTypeObject} represents the Python long
Fred Drake659ebfa2000-04-03 15:42:13 +00003132integer type. This is the same object as \code{types.LongType}.
3133\withsubitem{(in modules types)}{\ttindex{LongType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003134\end{cvardesc}
3135
3136\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003137Returns true if its argument is a \ctype{PyLongObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003138\end{cfuncdesc}
3139
Fred Drakec6fa34e1998-04-02 06:47:24 +00003140\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003141Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on
3142failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003143\end{cfuncdesc}
3144
Fred Drakec6fa34e1998-04-02 06:47:24 +00003145\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003146Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
3147long}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003148\end{cfuncdesc}
3149
Fred Drakec6fa34e1998-04-02 06:47:24 +00003150\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003151Returns a new \ctype{PyLongObject} object from the integer part of
3152\var{v}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003153\end{cfuncdesc}
3154
Fred Drakec6fa34e1998-04-02 06:47:24 +00003155\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003156Returns a C \ctype{long} representation of the contents of
3157\var{pylong}. If \var{pylong} is greater than
3158\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is
3159raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003160\end{cfuncdesc}
3161
Fred Drakec6fa34e1998-04-02 06:47:24 +00003162\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003163Returns a C \ctype{unsigned long} representation of the contents of
3164\var{pylong}. If \var{pylong} is greater than
3165\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError}
3166is raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003167\end{cfuncdesc}
3168
Fred Drakec6fa34e1998-04-02 06:47:24 +00003169\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003170Returns a C \ctype{double} representation of the contents of \var{pylong}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003171\end{cfuncdesc}
3172
Fred Drakec6fa34e1998-04-02 06:47:24 +00003173\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
3174 int base}
Fred Drake659ebfa2000-04-03 15:42:13 +00003175Return a new \ctype{PyLongObject} based on the string value in
3176\var{str}, which is interpreted according to the radix in \var{base}.
3177If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first
3178character in \var{str} which follows the representation of the
3179number. If \var{base} is \code{0}, the radix will be determined base
3180on the leading characters of \var{str}: if \var{str} starts with
3181\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts
3182with \code{'0'}, radix 8 will be used; otherwise radix 10 will be
3183used. If \var{base} is not \code{0}, it must be between \code{2} and
3184\code{36}, inclusive. Leading spaces are ignored. If there are no
3185digits, \exception{ValueError} will be raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003186\end{cfuncdesc}
3187
3188
Fred Drakeefd146c1999-02-15 15:30:45 +00003189\subsection{Floating Point Objects \label{floatObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003190
Fred Drake659ebfa2000-04-03 15:42:13 +00003191\obindex{floating point}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003192\begin{ctypedesc}{PyFloatObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003193This subtype of \ctype{PyObject} represents a Python floating point
Fred Drakee058b4f1998-02-16 06:15:35 +00003194object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003195\end{ctypedesc}
3196
3197\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003198This instance of \ctype{PyTypeObject} represents the Python floating
Fred Drake659ebfa2000-04-03 15:42:13 +00003199point type. This is the same object as \code{types.FloatType}.
3200\withsubitem{(in modules types)}{\ttindex{FloatType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003201\end{cvardesc}
3202
3203\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003204Returns true if its argument is a \ctype{PyFloatObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003205\end{cfuncdesc}
3206
Fred Drakec6fa34e1998-04-02 06:47:24 +00003207\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003208Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
3209failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003210\end{cfuncdesc}
3211
Fred Drakec6fa34e1998-04-02 06:47:24 +00003212\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003213Returns a C \ctype{double} representation of the contents of \var{pyfloat}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003214\end{cfuncdesc}
3215
Fred Drakec6fa34e1998-04-02 06:47:24 +00003216\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003217Returns a C \ctype{double} representation of the contents of
Fred Drakef8830d11998-04-23 14:06:01 +00003218\var{pyfloat}, but without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003219\end{cfuncdesc}
3220
3221
Fred Drakeefd146c1999-02-15 15:30:45 +00003222\subsection{Complex Number Objects \label{complexObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003223
Fred Drake659ebfa2000-04-03 15:42:13 +00003224\obindex{complex number}
3225Python's complex number objects are implemented as two distinct types
3226when viewed from the C API: one is the Python object exposed to
3227Python programs, and the other is a C structure which represents the
3228actual complex number value. The API provides functions for working
3229with both.
3230
3231\subsubsection{Complex Numbers as C Structures}
3232
3233Note that the functions which accept these structures as parameters
3234and return them as results do so \emph{by value} rather than
3235dereferencing them through pointers. This is consistent throughout
3236the API.
3237
Fred Drakee5bf8b21998-02-12 21:22:28 +00003238\begin{ctypedesc}{Py_complex}
Fred Drake659ebfa2000-04-03 15:42:13 +00003239The C structure which corresponds to the value portion of a Python
Fred Drake4de05a91998-02-16 14:25:26 +00003240complex number object. Most of the functions for dealing with complex
3241number objects use structures of this type as input or output values,
3242as appropriate. It is defined as:
3243
Fred Drakee058b4f1998-02-16 06:15:35 +00003244\begin{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003245typedef struct {
3246 double real;
3247 double imag;
Fred Drake4de05a91998-02-16 14:25:26 +00003248} Py_complex;
Fred Drakee058b4f1998-02-16 06:15:35 +00003249\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003250\end{ctypedesc}
3251
Fred Drake659ebfa2000-04-03 15:42:13 +00003252\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
3253Return the sum of two complex numbers, using the C
3254\ctype{Py_complex} representation.
3255\end{cfuncdesc}
3256
3257\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
3258Return the difference between two complex numbers, using the C
3259\ctype{Py_complex} representation.
3260\end{cfuncdesc}
3261
3262\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
3263Return the negation of the complex number \var{complex}, using the C
3264\ctype{Py_complex} representation.
3265\end{cfuncdesc}
3266
3267\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
3268Return the product of two complex numbers, using the C
3269\ctype{Py_complex} representation.
3270\end{cfuncdesc}
3271
3272\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
3273 Py_complex divisor}
3274Return the quotient of two complex numbers, using the C
3275\ctype{Py_complex} representation.
3276\end{cfuncdesc}
3277
3278\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
3279Return the exponentiation of \var{num} by \var{exp}, using the C
3280\ctype{Py_complex} representation.
3281\end{cfuncdesc}
3282
3283
3284\subsubsection{Complex Numbers as Python Objects}
3285
Fred Drakee5bf8b21998-02-12 21:22:28 +00003286\begin{ctypedesc}{PyComplexObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003287This subtype of \ctype{PyObject} represents a Python complex number object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003288\end{ctypedesc}
3289
3290\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003291This instance of \ctype{PyTypeObject} represents the Python complex
Fred Drakee5bf8b21998-02-12 21:22:28 +00003292number type.
3293\end{cvardesc}
3294
3295\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003296Returns true if its argument is a \ctype{PyComplexObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003297\end{cfuncdesc}
3298
Fred Drakec6fa34e1998-04-02 06:47:24 +00003299\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003300Create a new Python complex number object from a C
3301\ctype{Py_complex} value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003302\end{cfuncdesc}
3303
Fred Drakec6fa34e1998-04-02 06:47:24 +00003304\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
Fred Drakef8830d11998-04-23 14:06:01 +00003305Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003306\end{cfuncdesc}
3307
3308\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003309Returns the real part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003310\end{cfuncdesc}
3311
3312\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003313Returns the imaginary part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003314\end{cfuncdesc}
3315
3316\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003317Returns the \ctype{Py_complex} value of the complex number \var{op}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003318\end{cfuncdesc}
3319
3320
3321
Fred Drakeefd146c1999-02-15 15:30:45 +00003322\section{Other Objects \label{otherObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003323
Fred Drakeefd146c1999-02-15 15:30:45 +00003324\subsection{File Objects \label{fileObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003325
Fred Drake659ebfa2000-04-03 15:42:13 +00003326\obindex{file}
3327Python's built-in file objects are implemented entirely on the
3328\ctype{FILE*} support from the C standard library. This is an
3329implementation detail and may change in future releases of Python.
3330
Fred Drakee5bf8b21998-02-12 21:22:28 +00003331\begin{ctypedesc}{PyFileObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003332This subtype of \ctype{PyObject} represents a Python file object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003333\end{ctypedesc}
3334
3335\begin{cvardesc}{PyTypeObject}{PyFile_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003336This instance of \ctype{PyTypeObject} represents the Python file
3337type. This is exposed to Python programs as \code{types.FileType}.
3338\withsubitem{(in module types)}{\ttindex{FileType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003339\end{cvardesc}
3340
3341\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003342Returns true if its argument is a \ctype{PyFileObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003343\end{cfuncdesc}
3344
Fred Drake659ebfa2000-04-03 15:42:13 +00003345\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
3346On success, returns a new file object that is opened on the
3347file given by \var{filename}, with a file mode given by \var{mode},
3348where \var{mode} has the same semantics as the standard C routine
3349\cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003350\end{cfuncdesc}
3351
Fred Drakec6fa34e1998-04-02 06:47:24 +00003352\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
Fred Drake659ebfa2000-04-03 15:42:13 +00003353 char *name, char *mode,
3354 int (*close)(FILE*)}
3355Creates a new \ctype{PyFileObject} from the already-open standard C
3356file pointer, \var{fp}. The function \var{close} will be called when
3357the file should be closed. Returns \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003358\end{cfuncdesc}
3359
Fred Drake659ebfa2000-04-03 15:42:13 +00003360\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
3361Returns the file object associated with \var{p} as a \ctype{FILE*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003362\end{cfuncdesc}
3363
Fred Drakec6fa34e1998-04-02 06:47:24 +00003364\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003365Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
3366function reads one line from the object \var{p}. \var{p} may be a
3367file object or any object with a \method{readline()} method. If
3368\var{n} is \code{0}, exactly one line is read, regardless of the
3369length of the line. If \var{n} is greater than \code{0}, no more than
3370\var{n} bytes will be read from the file; a partial line can be
3371returned. In both cases, an empty string is returned if the end of
3372the file is reached immediately. If \var{n} is less than \code{0},
3373however, one line is read regardless of length, but
3374\exception{EOFError} is raised if the end of the file is reached
3375immediately.
3376\withsubitem{(built-in exception)}{\ttindex{EOFError}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003377\end{cfuncdesc}
3378
Fred Drakec6fa34e1998-04-02 06:47:24 +00003379\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003380Returns the name of the file specified by \var{p} as a string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003381\end{cfuncdesc}
3382
3383\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003384Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
3385only. This should only be called immediately after file object
3386creation.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003387\end{cfuncdesc}
3388
Fred Drake659ebfa2000-04-03 15:42:13 +00003389\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
3390This function exists for internal use by the interpreter.
3391Sets the \member{softspace} attribute of \var{p} to \var{newflag} and
3392\withsubitem{(file attribute)}{\ttindex{softspace}}returns the
3393previous value. \var{p} does not have to be a file object
3394for this function to work properly; any object is supported (thought
3395its only interesting if the \member{softspace} attribute can be set).
3396This function clears any errors, and will return \code{0} as the
3397previous value if the attribute either does not exist or if there were
3398errors in retrieving it. There is no way to detect errors from this
3399function, but doing so should not be needed.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003400\end{cfuncdesc}
3401
Fred Drakec6fa34e1998-04-02 06:47:24 +00003402\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
3403 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003404Writes object \var{obj} to file object \var{p}. The only supported
3405flag for \var{flags} is \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW};
3406if given, the \function{str()} of the object is written instead of the
3407\function{repr()}. Returns \code{0} on success or \code{-1} on
3408failure; the appropriate exception will be set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003409\end{cfuncdesc}
3410
Fred Drakec6fa34e1998-04-02 06:47:24 +00003411\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p,
3412 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003413Writes string \var{s} to file object \var{p}. Returns \code{0} on
3414success or \code{-1} on failure; the appropriate exception will be
3415set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003416\end{cfuncdesc}
3417
3418
Fred Drakeefd146c1999-02-15 15:30:45 +00003419\subsection{Module Objects \label{moduleObjects}}
3420
3421\obindex{module}
3422There are only a few functions special to module objects.
3423
Fred Drake659ebfa2000-04-03 15:42:13 +00003424\begin{cvardesc}{PyTypeObject}{PyModule_Type}
3425This instance of \ctype{PyTypeObject} represents the Python module
3426type. This is exposed to Python programs as \code{types.ModuleType}.
3427\withsubitem{(in module types)}{\ttindex{ModuleType}}
3428\end{cvardesc}
3429
3430\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
3431Returns true if its argument is a module object.
Fred Drakeefd146c1999-02-15 15:30:45 +00003432\end{cfuncdesc}
3433
Fred Drake659ebfa2000-04-03 15:42:13 +00003434\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
3435Return a new module object with the \member{__name__} attribute set to
3436\var{name}. Only the module's \member{__doc__} and
3437\member{__name__} attributes are filled in; the caller is responsible
3438for providing a \member{__file__} attribute.
3439\withsubitem{(module attribute)}{
3440 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
3441\end{cfuncdesc}
3442
3443\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003444Return the dictionary object that implements \var{module}'s namespace;
3445this object is the same as the \member{__dict__} attribute of the
3446module object. This function never fails.
Fred Drake659ebfa2000-04-03 15:42:13 +00003447\withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003448\end{cfuncdesc}
3449
Fred Drake659ebfa2000-04-03 15:42:13 +00003450\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003451Return \var{module}'s \member{__name__} value. If the module does not
Fred Drake659ebfa2000-04-03 15:42:13 +00003452provide one, or if it is not a string, \exception{SystemError} is
3453raised and \NULL{} is returned.
3454\withsubitem{(module attribute)}{\ttindex{__name__}}
3455\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003456\end{cfuncdesc}
3457
Fred Drake659ebfa2000-04-03 15:42:13 +00003458\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003459Return the name of the file from which \var{module} was loaded using
3460\var{module}'s \member{__file__} attribute. If this is not defined,
Fred Drake659ebfa2000-04-03 15:42:13 +00003461or if it is not a string, raise \exception{SystemError} and return
3462\NULL.
3463\withsubitem{(module attribute)}{\ttindex{__file__}}
3464\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003465\end{cfuncdesc}
3466
3467
3468\subsection{CObjects \label{cObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003469
Fred Drake659ebfa2000-04-03 15:42:13 +00003470\obindex{CObject}
3471Refer to \emph{Extending and Embedding the Python Interpreter},
3472section 1.12 (``Providing a C API for an Extension Module''), for more
3473information on using these objects.
3474
3475
Guido van Rossum44475131998-04-21 15:30:01 +00003476\begin{ctypedesc}{PyCObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003477This subtype of \ctype{PyObject} represents an opaque value, useful for
Fred Drake659ebfa2000-04-03 15:42:13 +00003478C extension modules who need to pass an opaque value (as a
3479\ctype{void*} pointer) through Python code to other C code. It is
Guido van Rossum44475131998-04-21 15:30:01 +00003480often used to make a C function pointer defined in one module
3481available to other modules, so the regular import mechanism can be
3482used to access C APIs defined in dynamically loaded modules.
3483\end{ctypedesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003484
Fred Drake659ebfa2000-04-03 15:42:13 +00003485\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
3486Returns true if its argument is a \ctype{PyCObject}.
3487\end{cfuncdesc}
3488
3489\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003490 void (*destr)(void *)}
Fred Drake1d158692000-06-18 05:21:21 +00003491Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drakedab44681999-05-13 18:41:14 +00003492\var{destr} function will be called when the object is reclaimed, unless
3493it is \NULL.
Guido van Rossum44475131998-04-21 15:30:01 +00003494\end{cfuncdesc}
3495
Fred Drake659ebfa2000-04-03 15:42:13 +00003496\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003497 void* desc, void (*destr)(void *, void *) }
Fred Drakef8830d11998-04-23 14:06:01 +00003498Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
3499\var{destr} function will be called when the object is reclaimed. The
3500\var{desc} argument can be used to pass extra callback data for the
3501destructor function.
Guido van Rossum44475131998-04-21 15:30:01 +00003502\end{cfuncdesc}
3503
Fred Drake659ebfa2000-04-03 15:42:13 +00003504\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
3505Returns the object \ctype{void *} that the
3506\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003507\end{cfuncdesc}
3508
Fred Drake659ebfa2000-04-03 15:42:13 +00003509\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
3510Returns the description \ctype{void *} that the
3511\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003512\end{cfuncdesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003513
Fred Drake659ebfa2000-04-03 15:42:13 +00003514
Fred Drakeefd146c1999-02-15 15:30:45 +00003515\chapter{Initialization, Finalization, and Threads
3516 \label{initialization}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003517
Guido van Rossum4a944d71997-08-14 20:35:38 +00003518\begin{cfuncdesc}{void}{Py_Initialize}{}
3519Initialize the Python interpreter. In an application embedding
3520Python, this should be called before using any other Python/C API
Fred Drake659ebfa2000-04-03 15:42:13 +00003521functions; with the exception of
3522\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
3523\cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
3524\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
3525and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
3526This initializes the table of loaded modules (\code{sys.modules}), and
3527\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}creates the
3528fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake4de05a91998-02-16 14:25:26 +00003529\module{__main__}\refbimodindex{__main__} and
3530\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drake659ebfa2000-04-03 15:42:13 +00003531search\indexiii{module}{search}{path} path (\code{sys.path}).
3532It does not set \code{sys.argv}; use
3533\cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
3534is a no-op when called for a second time (without calling
3535\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is no
3536return value; it is a fatal error if the initialization fails.
Guido van Rossum42cefd01997-10-05 15:27:29 +00003537\end{cfuncdesc}
3538
3539\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00003540Return true (nonzero) when the Python interpreter has been
Fred Drakee058b4f1998-02-16 06:15:35 +00003541initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
3542called, this returns false until \cfunction{Py_Initialize()} is called
Guido van Rossum42cefd01997-10-05 15:27:29 +00003543again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003544\end{cfuncdesc}
3545
3546\begin{cfuncdesc}{void}{Py_Finalize}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003547Undo all initializations made by \cfunction{Py_Initialize()} and
3548subsequent use of Python/C API functions, and destroy all
3549sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
3550created and not yet destroyed since the last call to
3551\cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
3552by the Python interpreter. This is a no-op when called for a second
3553time (without calling \cfunction{Py_Initialize()} again first). There
3554is no return value; errors during finalization are ignored.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003555
3556This function is provided for a number of reasons. An embedding
3557application might want to restart Python without having to restart the
3558application itself. An application that has loaded the Python
3559interpreter from a dynamically loadable library (or DLL) might want to
3560free all memory allocated by Python before unloading the DLL. During a
3561hunt for memory leaks in an application a developer might want to free
3562all memory allocated by Python before exiting from the application.
3563
Fred Drakee058b4f1998-02-16 06:15:35 +00003564\strong{Bugs and caveats:} The destruction of modules and objects in
Guido van Rossum4a944d71997-08-14 20:35:38 +00003565modules is done in random order; this may cause destructors
Fred Drakee058b4f1998-02-16 06:15:35 +00003566(\method{__del__()} methods) to fail when they depend on other objects
Guido van Rossum4a944d71997-08-14 20:35:38 +00003567(even functions) or modules. Dynamically loaded extension modules
3568loaded by Python are not unloaded. Small amounts of memory allocated
3569by the Python interpreter may not be freed (if you find a leak, please
3570report it). Memory tied up in circular references between objects is
3571not freed. Some memory allocated by extension modules may not be
3572freed. Some extension may not work properly if their initialization
3573routine is called more than once; this can happen if an applcation
Fred Drakee058b4f1998-02-16 06:15:35 +00003574calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
3575than once.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003576\end{cfuncdesc}
3577
Fred Drakec6fa34e1998-04-02 06:47:24 +00003578\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003579Create a new sub-interpreter. This is an (almost) totally separate
3580environment for the execution of Python code. In particular, the new
3581interpreter has separate, independent versions of all imported
3582modules, including the fundamental modules
3583\module{__builtin__}\refbimodindex{__builtin__},
3584\module{__main__}\refbimodindex{__main__} and
3585\module{sys}\refbimodindex{sys}. The table of loaded modules
3586(\code{sys.modules}) and the module search path (\code{sys.path}) are
3587also separate. The new environment has no \code{sys.argv} variable.
3588It has new standard I/O stream file objects \code{sys.stdin},
3589\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drake659ebfa2000-04-03 15:42:13 +00003590same underlying \ctype{FILE} structures in the C library).
3591\withsubitem{(in module sys)}{
3592 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003593
3594The return value points to the first thread state created in the new
3595sub-interpreter. This thread state is made the current thread state.
3596Note that no actual thread is created; see the discussion of thread
3597states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003598\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00003599is stored in the current thread state and there may not be a current
3600thread state. (Like all other Python/C API functions, the global
3601interpreter lock must be held before calling this function and is
3602still held when it returns; however, unlike most other Python/C API
3603functions, there needn't be a current thread state on entry.)
3604
3605Extension modules are shared between (sub-)interpreters as follows:
3606the first time a particular extension is imported, it is initialized
3607normally, and a (shallow) copy of its module's dictionary is
3608squirreled away. When the same extension is imported by another
3609(sub-)interpreter, a new module is initialized and filled with the
Fred Drakee058b4f1998-02-16 06:15:35 +00003610contents of this copy; the extension's \code{init} function is not
3611called. Note that this is different from what happens when an
3612extension is imported after the interpreter has been completely
Fred Drake659ebfa2000-04-03 15:42:13 +00003613re-initialized by calling
3614\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
3615\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
3616the extension's \code{init\var{module}} function \emph{is} called
3617again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003618
Fred Drakee058b4f1998-02-16 06:15:35 +00003619\strong{Bugs and caveats:} Because sub-interpreters (and the main
Guido van Rossum4a944d71997-08-14 20:35:38 +00003620interpreter) are part of the same process, the insulation between them
Fred Drakee058b4f1998-02-16 06:15:35 +00003621isn't perfect --- for example, using low-level file operations like
Fred Drake659ebfa2000-04-03 15:42:13 +00003622\withsubitem{(in module os)}{\ttindex{close()}}
Fred Drakef8830d11998-04-23 14:06:01 +00003623\function{os.close()} they can (accidentally or maliciously) affect each
Guido van Rossum4a944d71997-08-14 20:35:38 +00003624other's open files. Because of the way extensions are shared between
3625(sub-)interpreters, some extensions may not work properly; this is
3626especially likely when the extension makes use of (static) global
3627variables, or when the extension manipulates its module's dictionary
3628after its initialization. It is possible to insert objects created in
3629one sub-interpreter into a namespace of another sub-interpreter; this
3630should be done with great care to avoid sharing user-defined
3631functions, methods, instances or classes between sub-interpreters,
3632since import operations executed by such objects may affect the
3633wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
3634a hard-to-fix bug that will be addressed in a future release.)
3635\end{cfuncdesc}
3636
3637\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
3638Destroy the (sub-)interpreter represented by the given thread state.
3639The given thread state must be the current thread state. See the
3640discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003641thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00003642interpreted are destroyed. (The global interpreter lock must be held
3643before calling this function and is still held when it returns.)
Fred Drake659ebfa2000-04-03 15:42:13 +00003644\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will destroy all
3645sub-interpreters that haven't been explicitly destroyed at that point.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003646\end{cfuncdesc}
3647
3648\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00003649This function should be called before
3650\cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
Guido van Rossum4a944d71997-08-14 20:35:38 +00003651for the first time, if it is called at all. It tells the interpreter
Fred Drake659ebfa2000-04-03 15:42:13 +00003652the value of the \code{argv[0]} argument to the
3653\cfunction{main()}\ttindex{main()} function of the program. This is
3654used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some other
Guido van Rossum4a944d71997-08-14 20:35:38 +00003655functions below to find the Python run-time libraries relative to the
Fred Drakea8455ab2000-06-16 19:58:42 +00003656interpreter executable. The default value is \code{'python'}. The
Guido van Rossum4a944d71997-08-14 20:35:38 +00003657argument should point to a zero-terminated character string in static
3658storage whose contents will not change for the duration of the
3659program's execution. No code in the Python interpreter will change
3660the contents of this storage.
3661\end{cfuncdesc}
3662
Fred Drakec6fa34e1998-04-02 06:47:24 +00003663\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003664Return the program name set with
3665\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
Guido van Rossum4a944d71997-08-14 20:35:38 +00003666default. The returned string points into static storage; the caller
3667should not modify its value.
3668\end{cfuncdesc}
3669
Fred Drakec6fa34e1998-04-02 06:47:24 +00003670\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003671Return the \emph{prefix} for installed platform-independent files. This
Guido van Rossum4a944d71997-08-14 20:35:38 +00003672is derived through a number of complicated rules from the program name
Fred Drakee058b4f1998-02-16 06:15:35 +00003673set with \cfunction{Py_SetProgramName()} and some environment variables;
Fred Drakea8455ab2000-06-16 19:58:42 +00003674for example, if the program name is \code{'/usr/local/bin/python'},
3675the prefix is \code{'/usr/local'}. The returned string points into
Guido van Rossum4a944d71997-08-14 20:35:38 +00003676static storage; the caller should not modify its value. This
Fred Drakec94d9341998-04-12 02:39:13 +00003677corresponds to the \makevar{prefix} variable in the top-level
Fred Drakea8455ab2000-06-16 19:58:42 +00003678\file{Makefile} and the \longprogramopt{prefix} argument to the
Fred Drakee058b4f1998-02-16 06:15:35 +00003679\program{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00003680Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00003681also the next function.
3682\end{cfuncdesc}
3683
Fred Drakec6fa34e1998-04-02 06:47:24 +00003684\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003685Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
Guido van Rossum4a944d71997-08-14 20:35:38 +00003686files. This is derived through a number of complicated rules from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003687program name set with \cfunction{Py_SetProgramName()} and some environment
Guido van Rossum4a944d71997-08-14 20:35:38 +00003688variables; for example, if the program name is
Fred Drakea8455ab2000-06-16 19:58:42 +00003689\code{'/usr/local/bin/python'}, the exec-prefix is
3690\code{'/usr/local'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00003691the caller should not modify its value. This corresponds to the
Fred Drakec94d9341998-04-12 02:39:13 +00003692\makevar{exec_prefix} variable in the top-level \file{Makefile} and the
Fred Drakea8455ab2000-06-16 19:58:42 +00003693\longprogramopt{exec-prefix} argument to the
Fred Drake310ee611999-11-09 17:31:42 +00003694\program{configure} script at build time. The value is available to
3695Python code as \code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003696
3697Background: The exec-prefix differs from the prefix when platform
3698dependent files (such as executables and shared libraries) are
3699installed in a different directory tree. In a typical installation,
3700platform dependent files may be installed in the
Fred Drakea8455ab2000-06-16 19:58:42 +00003701\file{/usr/local/plat} subtree while platform independent may be
3702installed in \file{/usr/local}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003703
3704Generally speaking, a platform is a combination of hardware and
3705software families, e.g. Sparc machines running the Solaris 2.x
3706operating system are considered the same platform, but Intel machines
3707running Solaris 2.x are another platform, and Intel machines running
3708Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00003709operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003710operating systems are a different story; the installation strategies
3711on those systems are so different that the prefix and exec-prefix are
3712meaningless, and set to the empty string. Note that compiled Python
3713bytecode files are platform independent (but not independent from the
3714Python version by which they were compiled!).
3715
Fred Drakee058b4f1998-02-16 06:15:35 +00003716System administrators will know how to configure the \program{mount} or
Fred Drakea8455ab2000-06-16 19:58:42 +00003717\program{automount} programs to share \file{/usr/local} between platforms
3718while having \file{/usr/local/plat} be a different filesystem for each
Guido van Rossum4a944d71997-08-14 20:35:38 +00003719platform.
3720\end{cfuncdesc}
3721
Fred Drakec6fa34e1998-04-02 06:47:24 +00003722\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003723Return the full program name of the Python executable; this is
3724computed as a side-effect of deriving the default module search path
Fred Drake659ebfa2000-04-03 15:42:13 +00003725from the program name (set by
3726\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
3727The returned string points into static storage; the caller should not
Guido van Rossum4a944d71997-08-14 20:35:38 +00003728modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00003729\code{sys.executable}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003730\withsubitem{(in module sys)}{\ttindex{executable}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003731\end{cfuncdesc}
3732
Fred Drakec6fa34e1998-04-02 06:47:24 +00003733\begin{cfuncdesc}{char*}{Py_GetPath}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003734\indexiii{module}{search}{path}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003735Return the default module search path; this is computed from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003736program name (set by \cfunction{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00003737environment variables. The returned string consists of a series of
3738directory names separated by a platform dependent delimiter character.
Fred Drakef8830d11998-04-23 14:06:01 +00003739The delimiter character is \character{:} on \UNIX{}, \character{;} on
Fred Drake659ebfa2000-04-03 15:42:13 +00003740DOS/Windows, and \character{\e n} (the \ASCII{} newline character) on
Fred Drakee5bc4971998-02-12 23:36:49 +00003741Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00003742should not modify its value. The value is available to Python code
Fred Drake659ebfa2000-04-03 15:42:13 +00003743as the list \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}},
3744which may be modified to change the future search path for loaded
3745modules.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003746
3747% XXX should give the exact rules
3748\end{cfuncdesc}
3749
Fred Drakec6fa34e1998-04-02 06:47:24 +00003750\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003751Return the version of this Python interpreter. This is a string that
3752looks something like
3753
Guido van Rossum09270b51997-08-15 18:57:32 +00003754\begin{verbatim}
Fred Drakee058b4f1998-02-16 06:15:35 +00003755"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
Guido van Rossum09270b51997-08-15 18:57:32 +00003756\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003757
3758The first word (up to the first space character) is the current Python
3759version; the first three characters are the major and minor version
3760separated by a period. The returned string points into static storage;
3761the caller should not modify its value. The value is available to
3762Python code as the list \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003763\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003764\end{cfuncdesc}
3765
Fred Drakec6fa34e1998-04-02 06:47:24 +00003766\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00003767Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00003768this is formed from the ``official'' name of the operating system,
3769converted to lower case, followed by the major revision number; e.g.,
3770for Solaris 2.x, which is also known as SunOS 5.x, the value is
Fred Drakea8455ab2000-06-16 19:58:42 +00003771\code{'sunos5'}. On Macintosh, it is \code{'mac'}. On Windows, it
3772is \code{'win'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00003773the caller should not modify its value. The value is available to
3774Python code as \code{sys.platform}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003775\withsubitem{(in module sys)}{\ttindex{platform}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003776\end{cfuncdesc}
3777
Fred Drakec6fa34e1998-04-02 06:47:24 +00003778\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003779Return the official copyright string for the current Python version,
3780for example
3781
Fred Drakea8455ab2000-06-16 19:58:42 +00003782\code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003783
3784The returned string points into static storage; the caller should not
3785modify its value. The value is available to Python code as the list
3786\code{sys.copyright}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003787\withsubitem{(in module sys)}{\ttindex{copyright}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003788\end{cfuncdesc}
3789
Fred Drakec6fa34e1998-04-02 06:47:24 +00003790\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003791Return an indication of the compiler used to build the current Python
Fred Drakee058b4f1998-02-16 06:15:35 +00003792version, in square brackets, for example:
Guido van Rossum4a944d71997-08-14 20:35:38 +00003793
Fred Drakee058b4f1998-02-16 06:15:35 +00003794\begin{verbatim}
3795"[GCC 2.7.2.2]"
3796\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003797
3798The returned string points into static storage; the caller should not
3799modify its value. The value is available to Python code as part of
3800the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003801\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003802\end{cfuncdesc}
3803
Fred Drakec6fa34e1998-04-02 06:47:24 +00003804\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003805Return information about the sequence number and build date and time
3806of the current Python interpreter instance, for example
3807
Guido van Rossum09270b51997-08-15 18:57:32 +00003808\begin{verbatim}
3809"#67, Aug 1 1997, 22:34:28"
3810\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003811
3812The returned string points into static storage; the caller should not
3813modify its value. The value is available to Python code as part of
3814the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003815\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003816\end{cfuncdesc}
3817
3818\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
Fred Drake659ebfa2000-04-03 15:42:13 +00003819Set \code{sys.argv} based on \var{argc} and \var{argv}. These
3820parameters are similar to those passed to the program's
3821\cfunction{main()}\ttindex{main()} function with the difference that
3822the first entry should refer to the script file to be executed rather
3823than the executable hosting the Python interpreter. If there isn't a
3824script that will be run, the first entry in \var{argv} can be an empty
3825string. If this function fails to initialize \code{sys.argv}, a fatal
3826condition is signalled using
3827\cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
3828\withsubitem{(in module sys)}{\ttindex{argv}}
3829% XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
3830% check w/ Guido.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003831\end{cfuncdesc}
3832
3833% XXX Other PySys thingies (doesn't really belong in this chapter)
3834
Fred Drakeefd146c1999-02-15 15:30:45 +00003835\section{Thread State and the Global Interpreter Lock
3836 \label{threads}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003837
Fred Drake659ebfa2000-04-03 15:42:13 +00003838\index{global interpreter lock}
3839\index{interpreter lock}
3840\index{lock, interpreter}
3841
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003842The Python interpreter is not fully thread safe. In order to support
3843multi-threaded Python programs, there's a global lock that must be
3844held by the current thread before it can safely access Python objects.
3845Without the lock, even the simplest operations could cause problems in
Fred Drake7baf3d41998-02-20 00:45:52 +00003846a multi-threaded program: for example, when two threads simultaneously
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003847increment the reference count of the same object, the reference count
3848could end up being incremented only once instead of twice.
3849
3850Therefore, the rule exists that only the thread that has acquired the
3851global interpreter lock may operate on Python objects or call Python/C
3852API functions. In order to support multi-threaded Python programs,
Fred Drake659ebfa2000-04-03 15:42:13 +00003853the interpreter regularly releases and reacquires the lock --- by
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003854default, every ten bytecode instructions (this can be changed with
Fred Drake659ebfa2000-04-03 15:42:13 +00003855\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
Fred Drakee058b4f1998-02-16 06:15:35 +00003856\function{sys.setcheckinterval()}). The lock is also released and
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003857reacquired around potentially blocking I/O operations like reading or
3858writing a file, so that other threads can run while the thread that
3859requests the I/O is waiting for the I/O operation to complete.
3860
3861The Python interpreter needs to keep some bookkeeping information
Fred Drakee058b4f1998-02-16 06:15:35 +00003862separate per thread --- for this it uses a data structure called
Fred Drake659ebfa2000-04-03 15:42:13 +00003863\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
38641.5; in earlier versions, such state was stored in global variables,
3865and switching threads could cause problems. In particular, exception
3866handling is now thread safe, when the application uses
3867\withsubitem{(in module sys)}{\ttindex{exc_info()}}
3868\function{sys.exc_info()} to access the exception last raised in the
3869current thread.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003870
3871There's one global variable left, however: the pointer to the current
Fred Drake659ebfa2000-04-03 15:42:13 +00003872\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
3873thread packages have a way to store ``per-thread global data,''
3874Python's internal platform independent thread abstraction doesn't
3875support this yet. Therefore, the current thread state must be
3876manipulated explicitly.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003877
3878This is easy enough in most cases. Most code manipulating the global
3879interpreter lock has the following simple structure:
3880
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003881\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003882Save the thread state in a local variable.
3883Release the interpreter lock.
3884...Do some blocking I/O operation...
3885Reacquire the interpreter lock.
3886Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003887\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003888
3889This is so common that a pair of macros exists to simplify it:
3890
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003891\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003892Py_BEGIN_ALLOW_THREADS
3893...Do some blocking I/O operation...
3894Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003895\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003896
Fred Drake659ebfa2000-04-03 15:42:13 +00003897The \code{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS} macro
3898opens a new block and declares a hidden local variable; the
3899\code{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS} macro closes
Fred Drakee058b4f1998-02-16 06:15:35 +00003900the block. Another advantage of using these two macros is that when
3901Python is compiled without thread support, they are defined empty,
3902thus saving the thread state and lock manipulations.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003903
3904When thread support is enabled, the block above expands to the
3905following code:
3906
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003907\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003908 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00003909
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003910 _save = PyEval_SaveThread();
3911 ...Do some blocking I/O operation...
3912 PyEval_RestoreThread(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003913\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003914
3915Using even lower level primitives, we can get roughly the same effect
3916as follows:
3917
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003918\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003919 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00003920
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003921 _save = PyThreadState_Swap(NULL);
3922 PyEval_ReleaseLock();
3923 ...Do some blocking I/O operation...
3924 PyEval_AcquireLock();
3925 PyThreadState_Swap(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003926\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003927
3928There are some subtle differences; in particular,
Fred Drake659ebfa2000-04-03 15:42:13 +00003929\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
3930and restores the value of the global variable
3931\cdata{errno}\ttindex{errno}, since the lock manipulation does not
Fred Drakef8830d11998-04-23 14:06:01 +00003932guarantee that \cdata{errno} is left alone. Also, when thread support
Fred Drake659ebfa2000-04-03 15:42:13 +00003933is disabled,
3934\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
Fred Drakee058b4f1998-02-16 06:15:35 +00003935\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
Fred Drake659ebfa2000-04-03 15:42:13 +00003936case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
3937\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
3938available. This is done so that dynamically loaded extensions
3939compiled with thread support enabled can be loaded by an interpreter
3940that was compiled with disabled thread support.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003941
3942The global interpreter lock is used to protect the pointer to the
3943current thread state. When releasing the lock and saving the thread
3944state, the current thread state pointer must be retrieved before the
3945lock is released (since another thread could immediately acquire the
3946lock and store its own thread state in the global variable).
3947Reversely, when acquiring the lock and restoring the thread state, the
3948lock must be acquired before storing the thread state pointer.
3949
3950Why am I going on with so much detail about this? Because when
Fred Drake659ebfa2000-04-03 15:42:13 +00003951threads are created from C, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003952lock, nor is there a thread state data structure for them. Such
3953threads must bootstrap themselves into existence, by first creating a
3954thread state data structure, then acquiring the lock, and finally
3955storing their thread state pointer, before they can start using the
3956Python/C API. When they are done, they should reset the thread state
3957pointer, release the lock, and finally free their thread state data
3958structure.
3959
3960When creating a thread data structure, you need to provide an
3961interpreter state data structure. The interpreter state data
3962structure hold global data that is shared by all threads in an
3963interpreter, for example the module administration
3964(\code{sys.modules}). Depending on your needs, you can either create
3965a new interpreter state data structure, or share the interpreter state
3966data structure used by the Python main thread (to access the latter,
Fred Drakef8830d11998-04-23 14:06:01 +00003967you must obtain the thread state and access its \member{interp} member;
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003968this must be done by a thread that is created by Python or by the main
3969thread after Python is initialized).
3970
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003971
3972\begin{ctypedesc}{PyInterpreterState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003973This data structure represents the state shared by a number of
3974cooperating threads. Threads belonging to the same interpreter
3975share their module administration and a few other internal items.
3976There are no public members in this structure.
3977
3978Threads belonging to different interpreters initially share nothing,
3979except process state like available memory, open file descriptors and
3980such. The global interpreter lock is also shared by all threads,
3981regardless of to which interpreter they belong.
3982\end{ctypedesc}
3983
3984\begin{ctypedesc}{PyThreadState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003985This data structure represents the state of a single thread. The only
Fred Drakef8830d11998-04-23 14:06:01 +00003986public data member is \ctype{PyInterpreterState *}\member{interp},
3987which points to this thread's interpreter state.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003988\end{ctypedesc}
3989
3990\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
3991Initialize and acquire the global interpreter lock. It should be
3992called in the main thread before creating a second thread or engaging
Fred Drakee058b4f1998-02-16 06:15:35 +00003993in any other thread operations such as
Fred Drake659ebfa2000-04-03 15:42:13 +00003994\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
3995\code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
3996It is not needed before calling
3997\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
3998\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00003999
4000This is a no-op when called for a second time. It is safe to call
Fred Drake659ebfa2000-04-03 15:42:13 +00004001this function before calling
4002\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004003
4004When only the main thread exists, no lock operations are needed. This
4005is a common situation (most Python programs do not use threads), and
4006the lock operations slow the interpreter down a bit. Therefore, the
4007lock is not created initially. This situation is equivalent to having
4008acquired the lock: when there is only a single thread, all object
4009accesses are safe. Therefore, when this function initializes the
Fred Drake4de05a91998-02-16 14:25:26 +00004010lock, it also acquires it. Before the Python
4011\module{thread}\refbimodindex{thread} module creates a new thread,
4012knowing that either it has the lock or the lock hasn't been created
4013yet, it calls \cfunction{PyEval_InitThreads()}. When this call
4014returns, it is guaranteed that the lock has been created and that it
4015has acquired it.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004016
4017It is \strong{not} safe to call this function when it is unknown which
4018thread (if any) currently has the global interpreter lock.
4019
4020This function is not available when thread support is disabled at
4021compile time.
4022\end{cfuncdesc}
4023
Guido van Rossum4a944d71997-08-14 20:35:38 +00004024\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004025Acquire the global interpreter lock. The lock must have been created
4026earlier. If this thread already has the lock, a deadlock ensues.
4027This function is not available when thread support is disabled at
4028compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004029\end{cfuncdesc}
4030
4031\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004032Release the global interpreter lock. The lock must have been created
4033earlier. This function is not available when thread support is
Fred Drakee058b4f1998-02-16 06:15:35 +00004034disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004035\end{cfuncdesc}
4036
4037\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004038Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004039state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004040have been created earlier. If this thread already has the lock,
4041deadlock ensues. This function is not available when thread support
Fred Drakee058b4f1998-02-16 06:15:35 +00004042is disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004043\end{cfuncdesc}
4044
4045\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004046Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004047interpreter lock. The lock must have been created earlier and must be
4048held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004049be \NULL{}, is only used to check that it represents the current
Fred Drakee058b4f1998-02-16 06:15:35 +00004050thread state --- if it isn't, a fatal error is reported. This
4051function is not available when thread support is disabled at compile
4052time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004053\end{cfuncdesc}
4054
Fred Drakec6fa34e1998-04-02 06:47:24 +00004055\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004056Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004057support is enabled) and reset the thread state to \NULL{},
4058returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004059the lock has been created, the current thread must have acquired it.
4060(This function is available even when thread support is disabled at
4061compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004062\end{cfuncdesc}
4063
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004064\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004065Acquire the interpreter lock (if it has been created and thread
4066support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004067must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004068thread must not have acquired it, otherwise deadlock ensues. (This
4069function is available even when thread support is disabled at compile
4070time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004071\end{cfuncdesc}
4072
Fred Drake659ebfa2000-04-03 15:42:13 +00004073The following macros are normally used without a trailing semicolon;
4074look for example usage in the Python source distribution.
4075
4076\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004077This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004078\samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004079Note that it contains an opening brace; it must be matched with a
4080following \code{Py_END_ALLOW_THREADS} macro. See above for further
4081discussion of this macro. It is a no-op when thread support is
4082disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004083\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004084
Fred Drake659ebfa2000-04-03 15:42:13 +00004085\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004086This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004087\samp{PyEval_RestoreThread(_save); \}}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004088Note that it contains a closing brace; it must be matched with an
4089earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
4090discussion of this macro. It is a no-op when thread support is
4091disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004092\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004093
Fred Drake659ebfa2000-04-03 15:42:13 +00004094\begin{csimplemacrodesc}{Py_BEGIN_BLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004095This macro expands to \samp{PyEval_RestoreThread(_save);} i.e. it
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004096is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
4097brace. It is a no-op when thread support is disabled at compile
4098time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004099\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004100
Fred Drake659ebfa2000-04-03 15:42:13 +00004101\begin{csimplemacrodesc}{Py_BEGIN_UNBLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004102This macro expands to \samp{_save = PyEval_SaveThread();} i.e. it is
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004103equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
4104and variable declaration. It is a no-op when thread support is
4105disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004106\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004107
4108All of the following functions are only available when thread support
4109is enabled at compile time, and must be called only when the
Fred Drake9d20ac31998-02-16 15:27:08 +00004110interpreter lock has been created.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004111
Fred Drakec6fa34e1998-04-02 06:47:24 +00004112\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004113Create a new interpreter state object. The interpreter lock need not
4114be held, but may be held if it is necessary to serialize calls to this
4115function.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004116\end{cfuncdesc}
4117
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004118\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
4119Reset all information in an interpreter state object. The interpreter
4120lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004121\end{cfuncdesc}
4122
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004123\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
4124Destroy an interpreter state object. The interpreter lock need not be
4125held. The interpreter state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004126call to \cfunction{PyInterpreterState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004127\end{cfuncdesc}
4128
Fred Drakec6fa34e1998-04-02 06:47:24 +00004129\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004130Create a new thread state object belonging to the given interpreter
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004131object. The interpreter lock need not be held, but may be held if it
4132is necessary to serialize calls to this function.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004133\end{cfuncdesc}
4134
4135\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
4136Reset all information in a thread state object. The interpreter lock
4137must be held.
4138\end{cfuncdesc}
4139
4140\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
4141Destroy a thread state object. The interpreter lock need not be
4142held. The thread state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004143call to \cfunction{PyThreadState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004144\end{cfuncdesc}
4145
Fred Drakec6fa34e1998-04-02 06:47:24 +00004146\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004147Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004148When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004149error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004150\end{cfuncdesc}
4151
Fred Drakec6fa34e1998-04-02 06:47:24 +00004152\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004153Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004154argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004155must be held.
4156\end{cfuncdesc}
4157
4158
Fred Drake659ebfa2000-04-03 15:42:13 +00004159\chapter{Memory Management \label{memory}}
4160\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
4161
4162
4163\section{Overview \label{memoryOverview}}
4164
4165Memory management in Python involves a private heap containing all
4166Python objects and data structures. The management of this private
4167heap is ensured internally by the \emph{Python memory manager}. The
4168Python memory manager has different components which deal with various
4169dynamic storage management aspects, like sharing, segmentation,
4170preallocation or caching.
4171
4172At the lowest level, a raw memory allocator ensures that there is
4173enough room in the private heap for storing all Python-related data
4174by interacting with the memory manager of the operating system. On top
4175of the raw memory allocator, several object-specific allocators
4176operate on the same heap and implement distinct memory management
4177policies adapted to the peculiarities of every object type. For
4178example, integer objects are managed differently within the heap than
4179strings, tuples or dictionaries because integers imply different
4180storage requirements and speed/space tradeoffs. The Python memory
4181manager thus delegates some of the work to the object-specific
4182allocators, but ensures that the latter operate within the bounds of
4183the private heap.
4184
4185It is important to understand that the management of the Python heap
4186is performed by the interpreter itself and that the user has no
4187control on it, even if she regularly manipulates object pointers to
4188memory blocks inside that heap. The allocation of heap space for
4189Python objects and other internal buffers is performed on demand by
4190the Python memory manager through the Python/C API functions listed in
4191this document.
4192
4193To avoid memory corruption, extension writers should never try to
4194operate on Python objects with the functions exported by the C
4195library: \cfunction{malloc()}\ttindex{malloc()},
4196\cfunction{calloc()}\ttindex{calloc()},
4197\cfunction{realloc()}\ttindex{realloc()} and
4198\cfunction{free()}\ttindex{free()}. This will result in
4199mixed calls between the C allocator and the Python memory manager
4200with fatal consequences, because they implement different algorithms
4201and operate on different heaps. However, one may safely allocate and
4202release memory blocks with the C library allocator for individual
4203purposes, as shown in the following example:
4204
4205\begin{verbatim}
4206 PyObject *res;
4207 char *buf = (char *) malloc(BUFSIZ); /* for I/O */
4208
4209 if (buf == NULL)
4210 return PyErr_NoMemory();
4211 ...Do some I/O operation involving buf...
4212 res = PyString_FromString(buf);
4213 free(buf); /* malloc'ed */
4214 return res;
4215\end{verbatim}
4216
4217In this example, the memory request for the I/O buffer is handled by
4218the C library allocator. The Python memory manager is involved only
4219in the allocation of the string object returned as a result.
4220
4221In most situations, however, it is recommended to allocate memory from
4222the Python heap specifically because the latter is under control of
4223the Python memory manager. For example, this is required when the
4224interpreter is extended with new object types written in C. Another
4225reason for using the Python heap is the desire to \emph{inform} the
4226Python memory manager about the memory needs of the extension module.
4227Even when the requested memory is used exclusively for internal,
4228highly-specific purposes, delegating all memory requests to the Python
4229memory manager causes the interpreter to have a more accurate image of
4230its memory footprint as a whole. Consequently, under certain
4231circumstances, the Python memory manager may or may not trigger
4232appropriate actions, like garbage collection, memory compaction or
4233other preventive procedures. Note that by using the C library
4234allocator as shown in the previous example, the allocated memory for
4235the I/O buffer escapes completely the Python memory manager.
4236
4237
4238\section{Memory Interface \label{memoryInterface}}
4239
4240The following function sets, modeled after the ANSI C standard, are
4241available for allocating and releasing memory from the Python heap:
4242
4243
Fred Drake7d45d342000-08-11 17:07:32 +00004244\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
4245Allocates \var{n} bytes and returns a pointer of type \ctype{void*} to
Fred Drake659ebfa2000-04-03 15:42:13 +00004246the allocated memory, or \NULL{} if the request fails. Requesting zero
4247bytes returns a non-\NULL{} pointer.
4248\end{cfuncdesc}
4249
Fred Drake7d45d342000-08-11 17:07:32 +00004250\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004251Resizes the memory block pointed to by \var{p} to \var{n} bytes. The
4252contents will be unchanged to the minimum of the old and the new
4253sizes. If \var{p} is \NULL{}, the call is equivalent to
4254\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the memory block
4255is resized but is not freed, and the returned pointer is non-\NULL{}.
4256Unless \var{p} is \NULL{}, it must have been returned by a previous
4257call to \cfunction{PyMem_Malloc()} or \cfunction{PyMem_Realloc()}.
4258\end{cfuncdesc}
4259
Fred Drake7d45d342000-08-11 17:07:32 +00004260\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004261Frees the memory block pointed to by \var{p}, which must have been
4262returned by a previous call to \cfunction{PyMem_Malloc()} or
4263\cfunction{PyMem_Realloc()}. Otherwise, or if
4264\cfunction{PyMem_Free(p)} has been called before, undefined behaviour
4265occurs. If \var{p} is \NULL{}, no operation is performed.
4266\end{cfuncdesc}
4267
Fred Drake7d45d342000-08-11 17:07:32 +00004268\begin{cfuncdesc}{void*}{Py_Malloc}{size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004269Same as \cfunction{PyMem_Malloc()}, but calls
4270\cfunction{PyErr_NoMemory()} on failure.
4271\end{cfuncdesc}
4272
Fred Drake7d45d342000-08-11 17:07:32 +00004273\begin{cfuncdesc}{void*}{Py_Realloc}{void *p, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004274Same as \cfunction{PyMem_Realloc()}, but calls
4275\cfunction{PyErr_NoMemory()} on failure.
4276\end{cfuncdesc}
4277
Fred Drake7d45d342000-08-11 17:07:32 +00004278\begin{cfuncdesc}{void}{Py_Free}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004279Same as \cfunction{PyMem_Free()}.
4280\end{cfuncdesc}
4281
4282The following type-oriented macros are provided for convenience. Note
4283that \var{TYPE} refers to any C type.
4284
4285\begin{cfuncdesc}{\var{TYPE}*}{PyMem_NEW}{TYPE, size_t n}
4286Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
4287sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
4288\ctype{\var{TYPE}*}.
4289\end{cfuncdesc}
4290
Fred Drake7d45d342000-08-11 17:07:32 +00004291\begin{cfuncdesc}{\var{TYPE}*}{PyMem_RESIZE}{void *p, TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004292Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
4293to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
4294cast to \ctype{\var{TYPE}*}.
4295\end{cfuncdesc}
4296
Fred Drake7d45d342000-08-11 17:07:32 +00004297\begin{cfuncdesc}{void}{PyMem_DEL}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004298Same as \cfunction{PyMem_Free()}.
4299\end{cfuncdesc}
4300
4301
4302\section{Examples \label{memoryExamples}}
4303
4304Here is the example from section \ref{memoryOverview}, rewritten so
4305that the I/O buffer is allocated from the Python heap by using the
4306first function set:
4307
4308\begin{verbatim}
4309 PyObject *res;
4310 char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
4311
4312 if (buf == NULL)
4313 return PyErr_NoMemory();
4314 /* ...Do some I/O operation involving buf... */
4315 res = PyString_FromString(buf);
4316 PyMem_Free(buf); /* allocated with PyMem_Malloc */
4317 return res;
4318\end{verbatim}
4319
4320With the second function set, the need to call
4321\cfunction{PyErr_NoMemory()} is obviated:
4322
4323\begin{verbatim}
4324 PyObject *res;
4325 char *buf = (char *) Py_Malloc(BUFSIZ); /* for I/O */
4326
4327 if (buf == NULL)
4328 return NULL;
4329 /* ...Do some I/O operation involving buf... */
4330 res = PyString_FromString(buf);
4331 Py_Free(buf); /* allocated with Py_Malloc */
4332 return res;
4333\end{verbatim}
4334
4335The same code using the macro set:
4336
4337\begin{verbatim}
4338 PyObject *res;
4339 char *buf = PyMem_NEW(char, BUFSIZ); /* for I/O */
4340
4341 if (buf == NULL)
4342 return PyErr_NoMemory();
4343 /* ...Do some I/O operation involving buf... */
4344 res = PyString_FromString(buf);
4345 PyMem_DEL(buf); /* allocated with PyMem_NEW */
4346 return res;
4347\end{verbatim}
4348
4349Note that in the three examples above, the buffer is always
4350manipulated via functions/macros belonging to the same set. Indeed, it
4351is required to use the same memory API family for a given
4352memory block, so that the risk of mixing different allocators is
4353reduced to a minimum. The following code sequence contains two errors,
4354one of which is labeled as \emph{fatal} because it mixes two different
4355allocators operating on different heaps.
4356
4357\begin{verbatim}
4358char *buf1 = PyMem_NEW(char, BUFSIZ);
4359char *buf2 = (char *) malloc(BUFSIZ);
4360char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
4361...
4362PyMem_DEL(buf3); /* Wrong -- should be PyMem_Free() */
4363free(buf2); /* Right -- allocated via malloc() */
4364free(buf1); /* Fatal -- should be PyMem_DEL() */
4365\end{verbatim}
4366
4367In addition to the functions aimed at handling raw memory blocks from
4368the Python heap, objects in Python are allocated and released with
4369\cfunction{_PyObject_New()}\ttindex{_PyObject_New()} and
4370\cfunction{_PyObject_NewVar()}\ttindex{_PyObject_NewVar()}, or with
4371their corresponding macros
4372\cfunction{PyObject_NEW()}\ttindex{PyObject_NEW()} and
4373\cfunction{PyObject_NEW_VAR()}\ttindex{PyObject_NEW_VAR()}.
4374
Fred Drakee06f0f92000-06-30 15:52:39 +00004375\cfunction{_PyObject_New()}, \cfunction{_PyObject_NewVar()},
4376\cfunction{_PyObject_Del()}, or with their corresponding macros
4377\cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()},
4378\cfunction{PyObject_DEL()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004379
Fred Drakee06f0f92000-06-30 15:52:39 +00004380These will be explained in the next chapter on defining and
4381implementing new object types in C.
Fred Drake659ebfa2000-04-03 15:42:13 +00004382
4383
Fred Drakeefd146c1999-02-15 15:30:45 +00004384\chapter{Defining New Object Types \label{newTypes}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004385
Fred Drakec6fa34e1998-04-02 06:47:24 +00004386\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00004387\end{cfuncdesc}
4388
Fred Drakec6fa34e1998-04-02 06:47:24 +00004389\begin{cfuncdesc}{PyObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00004390\end{cfuncdesc}
4391
Fred Drake659ebfa2000-04-03 15:42:13 +00004392\begin{cfuncdesc}{\var{TYPE}}{_PyObject_NEW}{TYPE, PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00004393\end{cfuncdesc}
4394
Fred Drake659ebfa2000-04-03 15:42:13 +00004395\begin{cfuncdesc}{\var{TYPE}}{_PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
4396 int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00004397\end{cfuncdesc}
4398
Guido van Rossum3c4378b1998-04-14 20:21:10 +00004399Py_InitModule (!!!)
4400
4401PyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse
4402
4403Py_BuildValue
Guido van Rossumae110af1997-05-22 20:11:52 +00004404
Fred Drake659ebfa2000-04-03 15:42:13 +00004405DL_IMPORT
4406
4407Py*_Check
4408
4409_Py_NoneStruct
4410
4411
4412\section{Common Object Structures \label{common-structs}}
4413
Guido van Rossumae110af1997-05-22 20:11:52 +00004414PyObject, PyVarObject
4415
4416PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
4417
4418Typedefs:
4419unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
4420intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
Guido van Rossumae110af1997-05-22 20:11:52 +00004421destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
4422setattrofunc, cmpfunc, reprfunc, hashfunc
4423
Fred Drakea8455ab2000-06-16 19:58:42 +00004424\begin{ctypedesc}{PyCFunction}
4425Type of the functions used to implement most Python callables in C.
4426\end{ctypedesc}
4427
4428\begin{ctypedesc}{PyMethodDef}
4429Structure used to describe a method of an extension type. This
4430structure has four fields:
4431
4432\begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
4433 \lineiii{ml_name}{char *}{name of the method}
4434 \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
4435 \lineiii{ml_flags}{int}{flag bits indicating how the call should be
4436 constructed}
4437 \lineiii{ml_doc}{char *}{points to the contents of the docstring}
4438\end{tableiii}
4439\end{ctypedesc}
4440
4441\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef[] table,
4442 PyObject *ob, char *name}
4443Return a bound method object for an extension type implemented in C.
4444This function also handles the special attribute \member{__methods__},
4445returning a list of all the method names defined in \var{table}.
4446\end{cfuncdesc}
4447
Fred Drake659ebfa2000-04-03 15:42:13 +00004448
4449\section{Mapping Object Structures \label{mapping-structs}}
4450
4451\begin{ctypedesc}{PyMappingMethods}
4452Structure used to hold pointers to the functions used to implement the
4453mapping protocol for an extension type.
4454\end{ctypedesc}
4455
4456
4457\section{Number Object Structures \label{number-structs}}
4458
4459\begin{ctypedesc}{PyNumberMethods}
4460Structure used to hold pointers to the functions an extension type
4461uses to implement the number protocol.
4462\end{ctypedesc}
4463
4464
4465\section{Sequence Object Structures \label{sequence-structs}}
4466
4467\begin{ctypedesc}{PySequenceMethods}
4468Structure used to hold pointers to the functions which an object uses
4469to implement the sequence protocol.
4470\end{ctypedesc}
4471
4472
4473\section{Buffer Object Structures \label{buffer-structs}}
4474\sectionauthor{Greg J. Stein}{greg@lyra.org}
4475
4476The buffer interface exports a model where an object can expose its
4477internal data as a set of chunks of data, where each chunk is
4478specified as a pointer/length pair. These chunks are called
4479\dfn{segments} and are presumed to be non-contiguous in memory.
4480
4481If an object does not export the buffer interface, then its
4482\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
4483should be \NULL{}. Otherwise, the \member{tp_as_buffer} will point to
4484a \ctype{PyBufferProcs} structure.
4485
4486\strong{Note:} It is very important that your
4487\ctype{PyTypeObject} structure uses \code{Py_TPFLAGS_DEFAULT} for the
4488value of the \member{tp_flags} member rather than \code{0}. This
4489tells the Python runtime that your \ctype{PyBufferProcs} structure
4490contains the \member{bf_getcharbuffer} slot. Older versions of Python
4491did not have this member, so a new Python interpreter using an old
4492extension needs to be able to test for its presence before using it.
4493
4494\begin{ctypedesc}{PyBufferProcs}
4495Structure used to hold the function pointers which define an
4496implementation of the buffer protocol.
4497
4498The first slot is \member{bf_getreadbuffer}, of type
4499\ctype{getreadbufferproc}. If this slot is \NULL{}, then the object
4500does not support reading from the internal data. This is
4501non-sensical, so implementors should fill this in, but callers should
4502test that the slot contains a non-\NULL{} value.
4503
4504The next slot is \member{bf_getwritebuffer} having type
4505\ctype{getwritebufferproc}. This slot may be \NULL{} if the object
4506does not allow writing into its returned buffers.
4507
4508The third slot is \member{bf_getsegcount}, with type
4509\ctype{getsegcountproc}. This slot must not be \NULL{} and is used to
4510inform the caller how many segments the object contains. Simple
4511objects such as \ctype{PyString_Type} and
4512\ctype{PyBuffer_Type} objects contain a single segment.
4513
4514The last slot is \member{bf_getcharbuffer}, of type
4515\ctype{getcharbufferproc}. This slot will only be present if the
4516\code{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
4517\member{tp_flags} field of the object's \ctype{PyTypeObject}. Before using
4518this slot, the caller should test whether it is present by using the
4519\cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()} function.
4520If present, it may be \NULL, indicating that the object's contents
4521cannot be used as \emph{8-bit characters}.
4522The slot function may also raise an error if the object's contents
4523cannot be interpreted as 8-bit characters. For example, if the object
4524is an array which is configured to hold floating point values, an
4525exception may be raised if a caller attempts to use
4526\member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
4527This notion of exporting the internal buffers as ``text'' is used to
4528distinguish between objects that are binary in nature, and those which
4529have character-based content.
4530
4531\strong{Note:} The current policy seems to state that these characters
4532may be multi-byte characters. This implies that a buffer size of
4533\var{N} does not mean there are \var{N} characters present.
4534\end{ctypedesc}
4535
4536\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
4537Flag bit set in the type structure to indicate that the
4538\member{bf_getcharbuffer} slot is known. This being set does not
4539indicate that the object supports the buffer interface or that the
4540\member{bf_getcharbuffer} slot is non-\NULL.
4541\end{datadesc}
4542
4543\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
4544 (PyObject *self, int segment, void **ptrptr)}
4545Return a pointer to a readable segment of the buffer. This function
4546is allowed to raise an exception, in which case it must return
4547\code{-1}. The \var{segment} which is passed must be zero or
4548positive, and strictly less than the number of segments returned by
4549the \member{bf_getsegcount} slot function. On success, returns
4550\code{0} and sets \code{*\var{ptrptr}} to a pointer to the buffer
4551memory.
4552\end{ctypedesc}
4553
4554\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
4555 (PyObject *self, int segment, void **ptrptr)}
Fred Drake58c5a2a1999-08-04 13:13:24 +00004556Return a pointer to a writable memory buffer in \code{*\var{ptrptr}};
4557the memory buffer must correspond to buffer segment \var{segment}.
4558Must return \code{-1} and set an exception on error.
4559\exception{TypeError} should be raised if the object only supports
4560read-only buffers, and \exception{SystemError} should be raised when
4561\var{segment} specifies a segment that doesn't exist.
4562% Why doesn't it raise ValueError for this one?
Fred Drake659ebfa2000-04-03 15:42:13 +00004563% GJS: because you shouldn't be calling it with an invalid
4564% segment. That indicates a blatant programming error in the C
4565% code.
Fred Drake58c5a2a1999-08-04 13:13:24 +00004566\end{ctypedesc}
4567
Fred Drake659ebfa2000-04-03 15:42:13 +00004568\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
4569 (PyObject *self, int *lenp)}
4570Return the number of memory segments which comprise the buffer. If
4571\var{lenp} is not \NULL, the implementation must report the sum of the
4572sizes (in bytes) of all segments in \code{*\var{lenp}}.
4573The function cannot fail.
4574\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004575
Fred Drake659ebfa2000-04-03 15:42:13 +00004576\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
4577 (PyObject *self, int segment, const char **ptrptr)}
4578\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004579
Guido van Rossumae110af1997-05-22 20:11:52 +00004580
Fred Drake659ebfa2000-04-03 15:42:13 +00004581% \chapter{Debugging \label{debugging}}
4582%
4583% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004584
4585
Fred Drakef3aa0e01998-03-17 06:23:13 +00004586\input{api.ind} % Index -- must be last
Guido van Rossum9231c8f1997-05-15 21:43:21 +00004587
4588\end{document}