blob: 28fd9851ed6ce2b1f3b29831ff47553e3c172007 [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:
Fred Drake0b71cea2000-09-26 05:51:50 +000077\code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>},
78\code{<limits.h>}, and \code{<stdlib.h>} (if available).
Guido van Rossum580aa8d1997-11-25 15:34:51 +000079
80All user visible names defined by Python.h (except those defined by
Fred Drakee058b4f1998-02-16 06:15:35 +000081the included standard headers) have one of the prefixes \samp{Py} or
Fred Drake659ebfa2000-04-03 15:42:13 +000082\samp{_Py}. Names beginning with \samp{_Py} are for internal use by
83the Python implementation and should not be used by extension writers.
84Structure member names do not have a reserved prefix.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000085
Fred Drakee058b4f1998-02-16 06:15:35 +000086\strong{Important:} user code should never define names that begin
87with \samp{Py} or \samp{_Py}. This confuses the reader, and
88jeopardizes the portability of the user code to future Python
89versions, which may define additional names beginning with one of
90these prefixes.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000091
Fred Drake659ebfa2000-04-03 15:42:13 +000092The header files are typically installed with Python. On \UNIX, these
93are located in the directories
94\file{\envvar{prefix}/include/python\var{version}/} and
95\file{\envvar{exec_prefix}/include/python\var{version}/}, where
96\envvar{prefix} and \envvar{exec_prefix} are defined by the
97corresponding parameters to Python's \program{configure} script and
98\var{version} is \code{sys.version[:3]}. On Windows, the headers are
99installed in \file{\envvar{prefix}/include}, where \envvar{prefix} is
100the installation directory specified to the installer.
101
102To include the headers, place both directories (if different) on your
103compiler's search path for includes. Do \emph{not} place the parent
104directories on the search path and then use
Fred Draked5d04352000-09-14 20:24:17 +0000105\samp{\#include <python\shortversion/Python.h>}; this will break on
Fred Drake659ebfa2000-04-03 15:42:13 +0000106multi-platform builds since the platform independent headers under
107\envvar{prefix} include the platform specific headers from
108\envvar{exec_prefix}.
109
Fred Drakeefd146c1999-02-15 15:30:45 +0000110
111\section{Objects, Types and Reference Counts \label{objects}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000112
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000113Most Python/C API functions have one or more arguments as well as a
Fred Drake659ebfa2000-04-03 15:42:13 +0000114return value of type \ctype{PyObject*}. This type is a pointer
Fred Drakee058b4f1998-02-16 06:15:35 +0000115to an opaque data type representing an arbitrary Python
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000116object. Since all Python object types are treated the same way by the
117Python language in most situations (e.g., assignments, scope rules,
118and argument passing), it is only fitting that they should be
Fred Drake659ebfa2000-04-03 15:42:13 +0000119represented by a single C type. Almost all Python objects live on the
120heap: you never declare an automatic or static variable of type
121\ctype{PyObject}, only pointer variables of type \ctype{PyObject*} can
122be declared. The sole exception are the type objects\obindex{type};
123since these must never be deallocated, they are typically static
124\ctype{PyTypeObject} objects.
Guido van Rossum59a61351997-08-14 20:34:33 +0000125
Fred Drakee058b4f1998-02-16 06:15:35 +0000126All Python objects (even Python integers) have a \dfn{type} and a
127\dfn{reference count}. An object's type determines what kind of object
Guido van Rossum4a944d71997-08-14 20:35:38 +0000128it is (e.g., an integer, a list, or a user-defined function; there are
Fred Drakebe486461999-11-09 17:03:03 +0000129many more as explained in the \citetitle[../ref/ref.html]{Python
130Reference Manual}). For each of the well-known types there is a macro
131to check whether an object is of that type; for instance,
Fred Drake659ebfa2000-04-03 15:42:13 +0000132\samp{PyList_Check(\var{a})} is true if (and only if) the object
133pointed to by \var{a} is a Python list.
Guido van Rossum59a61351997-08-14 20:34:33 +0000134
Fred Drakeefd146c1999-02-15 15:30:45 +0000135
136\subsection{Reference Counts \label{refcounts}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000137
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000138The reference count is important because today's computers have a
Fred Drake003d8da1998-04-13 00:53:42 +0000139finite (and often severely limited) memory size; it counts how many
Guido van Rossum4a944d71997-08-14 20:35:38 +0000140different places there are that have a reference to an object. Such a
Fred Drake659ebfa2000-04-03 15:42:13 +0000141place could be another object, or a global (or static) C variable, or
142a local variable in some C function. When an object's reference count
Guido van Rossum4a944d71997-08-14 20:35:38 +0000143becomes zero, the object is deallocated. If it contains references to
144other objects, their reference count is decremented. Those other
145objects may be deallocated in turn, if this decrement makes their
146reference count become zero, and so on. (There's an obvious problem
147with objects that reference each other here; for now, the solution is
Fred Drake659ebfa2000-04-03 15:42:13 +0000148``don't do that.'')
Guido van Rossum59a61351997-08-14 20:34:33 +0000149
Guido van Rossum4a944d71997-08-14 20:35:38 +0000150Reference counts are always manipulated explicitly. The normal way is
Fred Drake659ebfa2000-04-03 15:42:13 +0000151to use the macro \cfunction{Py_INCREF()}\ttindex{Py_INCREF()} to
152increment an object's reference count by one, and
153\cfunction{Py_DECREF()}\ttindex{Py_DECREF()} to decrement it by
154one. The \cfunction{Py_DECREF()} macro is considerably more complex
155than the incref one, since it must check whether the reference count
156becomes zero and then cause the object's deallocator to be called.
157The deallocator is a function pointer contained in the object's type
158structure. The type-specific deallocator takes care of decrementing
159the reference counts for other objects contained in the object if this
160is a compound object type, such as a list, as well as performing any
161additional finalization that's needed. There's no chance that the
162reference count can overflow; at least as many bits are used to hold
163the reference count as there are distinct memory locations in virtual
164memory (assuming \code{sizeof(long) >= sizeof(char*)}). Thus, the
165reference count increment is a simple operation.
Guido van Rossum59a61351997-08-14 20:34:33 +0000166
Guido van Rossum4a944d71997-08-14 20:35:38 +0000167It is not necessary to increment an object's reference count for every
168local variable that contains a pointer to an object. In theory, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000169object's reference count goes up by one when the variable is made to
Guido van Rossum4a944d71997-08-14 20:35:38 +0000170point to it and it goes down by one when the variable goes out of
171scope. However, these two cancel each other out, so at the end the
172reference count hasn't changed. The only real reason to use the
173reference count is to prevent the object from being deallocated as
174long as our variable is pointing to it. If we know that there is at
175least one other reference to the object that lives at least as long as
176our variable, there is no need to increment the reference count
177temporarily. An important situation where this arises is in objects
Fred Drake659ebfa2000-04-03 15:42:13 +0000178that are passed as arguments to C functions in an extension module
Guido van Rossum4a944d71997-08-14 20:35:38 +0000179that are called from Python; the call mechanism guarantees to hold a
Guido van Rossum59a61351997-08-14 20:34:33 +0000180reference to every argument for the duration of the call.
181
Fred Drakee058b4f1998-02-16 06:15:35 +0000182However, a common pitfall is to extract an object from a list and
183hold on to it for a while without incrementing its reference count.
184Some other operation might conceivably remove the object from the
185list, decrementing its reference count and possible deallocating it.
186The real danger is that innocent-looking operations may invoke
187arbitrary Python code which could do this; there is a code path which
188allows control to flow back to the user from a \cfunction{Py_DECREF()},
189so almost any operation is potentially dangerous.
Guido van Rossum59a61351997-08-14 20:34:33 +0000190
Guido van Rossum4a944d71997-08-14 20:35:38 +0000191A safe approach is to always use the generic operations (functions
Fred Drake659ebfa2000-04-03 15:42:13 +0000192whose name begins with \samp{PyObject_}, \samp{PyNumber_},
193\samp{PySequence_} or \samp{PyMapping_}). These operations always
194increment the reference count of the object they return. This leaves
195the caller with the responsibility to call
196\cfunction{Py_DECREF()} when they are done with the result; this soon
197becomes second nature.
Guido van Rossum59a61351997-08-14 20:34:33 +0000198
Fred Drakeefd146c1999-02-15 15:30:45 +0000199
200\subsubsection{Reference Count Details \label{refcountDetails}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000201
202The reference count behavior of functions in the Python/C API is best
Fred Drake659ebfa2000-04-03 15:42:13 +0000203explained in terms of \emph{ownership of references}. Note that we
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000204talk of owning references, never of owning objects; objects are always
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000205shared! When a function owns a reference, it has to dispose of it
Fred Drakee058b4f1998-02-16 06:15:35 +0000206properly --- either by passing ownership on (usually to its caller) or
207by calling \cfunction{Py_DECREF()} or \cfunction{Py_XDECREF()}. When
208a function passes ownership of a reference on to its caller, the
209caller is said to receive a \emph{new} reference. When no ownership
210is transferred, the caller is said to \emph{borrow} the reference.
211Nothing needs to be done for a borrowed reference.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000212
Fred Drakea8455ab2000-06-16 19:58:42 +0000213Conversely, when a calling function passes it a reference to an
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000214object, there are two possibilities: the function \emph{steals} a
215reference to the object, or it does not. Few functions steal
Fred Drakee058b4f1998-02-16 06:15:35 +0000216references; the two notable exceptions are
Fred Drake659ebfa2000-04-03 15:42:13 +0000217\cfunction{PyList_SetItem()}\ttindex{PyList_SetItem()} and
218\cfunction{PyTuple_SetItem()}\ttindex{PyTuple_SetItem()}, which
Fred Drakee058b4f1998-02-16 06:15:35 +0000219steal a reference to the item (but not to the tuple or list into which
Fred Drake003d8da1998-04-13 00:53:42 +0000220the item is put!). These functions were designed to steal a reference
Fred Drakee058b4f1998-02-16 06:15:35 +0000221because of a common idiom for populating a tuple or list with newly
222created objects; for example, the code to create the tuple \code{(1,
2232, "three")} could look like this (forgetting about error handling for
Fred Drake659ebfa2000-04-03 15:42:13 +0000224the moment; a better way to code this is shown below):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000225
226\begin{verbatim}
227PyObject *t;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000228
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000229t = PyTuple_New(3);
230PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
231PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
232PyTuple_SetItem(t, 2, PyString_FromString("three"));
233\end{verbatim}
234
Fred Drakee058b4f1998-02-16 06:15:35 +0000235Incidentally, \cfunction{PyTuple_SetItem()} is the \emph{only} way to
236set tuple items; \cfunction{PySequence_SetItem()} and
237\cfunction{PyObject_SetItem()} refuse to do this since tuples are an
238immutable data type. You should only use
239\cfunction{PyTuple_SetItem()} for tuples that you are creating
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000240yourself.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000241
242Equivalent code for populating a list can be written using
Fred Drakee058b4f1998-02-16 06:15:35 +0000243\cfunction{PyList_New()} and \cfunction{PyList_SetItem()}. Such code
244can also use \cfunction{PySequence_SetItem()}; this illustrates the
245difference between the two (the extra \cfunction{Py_DECREF()} calls):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000246
247\begin{verbatim}
248PyObject *l, *x;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000249
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000250l = PyList_New(3);
251x = PyInt_FromLong(1L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000252PySequence_SetItem(l, 0, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000253x = PyInt_FromLong(2L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000254PySequence_SetItem(l, 1, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000255x = PyString_FromString("three");
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000256PySequence_SetItem(l, 2, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000257\end{verbatim}
258
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000259You might find it strange that the ``recommended'' approach takes more
260code. However, in practice, you will rarely use these ways of
261creating and populating a tuple or list. There's a generic function,
Fred Drakee058b4f1998-02-16 06:15:35 +0000262\cfunction{Py_BuildValue()}, that can create most common objects from
Fred Drake659ebfa2000-04-03 15:42:13 +0000263C values, directed by a \dfn{format string}. For example, the
Fred Drakee058b4f1998-02-16 06:15:35 +0000264above two blocks of code could be replaced by the following (which
265also takes care of the error checking):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000266
267\begin{verbatim}
268PyObject *t, *l;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000269
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000270t = Py_BuildValue("(iis)", 1, 2, "three");
271l = Py_BuildValue("[iis]", 1, 2, "three");
272\end{verbatim}
273
Fred Drakee058b4f1998-02-16 06:15:35 +0000274It is much more common to use \cfunction{PyObject_SetItem()} and
275friends with items whose references you are only borrowing, like
276arguments that were passed in to the function you are writing. In
277that case, their behaviour regarding reference counts is much saner,
278since you don't have to increment a reference count so you can give a
279reference away (``have it be stolen''). For example, this function
280sets all items of a list (actually, any mutable sequence) to a given
281item:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000282
283\begin{verbatim}
284int set_all(PyObject *target, PyObject *item)
285{
286 int i, n;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000287
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000288 n = PyObject_Length(target);
289 if (n < 0)
290 return -1;
291 for (i = 0; i < n; i++) {
292 if (PyObject_SetItem(target, i, item) < 0)
293 return -1;
294 }
295 return 0;
296}
297\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000298\ttindex{set_all()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000299
300The situation is slightly different for function return values.
301While passing a reference to most functions does not change your
302ownership responsibilities for that reference, many functions that
303return a referece to an object give you ownership of the reference.
304The reason is simple: in many cases, the returned object is created
305on the fly, and the reference you get is the only reference to the
Fred Drakee058b4f1998-02-16 06:15:35 +0000306object. Therefore, the generic functions that return object
307references, like \cfunction{PyObject_GetItem()} and
308\cfunction{PySequence_GetItem()}, always return a new reference (i.e.,
309the caller becomes the owner of the reference).
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000310
311It is important to realize that whether you own a reference returned
Fred Drakee058b4f1998-02-16 06:15:35 +0000312by a function depends on which function you call only --- \emph{the
313plumage} (i.e., the type of the type of the object passed as an
314argument to the function) \emph{doesn't enter into it!} Thus, if you
315extract an item from a list using \cfunction{PyList_GetItem()}, you
316don't own the reference --- but if you obtain the same item from the
317same list using \cfunction{PySequence_GetItem()} (which happens to
318take exactly the same arguments), you do own a reference to the
319returned object.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000320
Fred Drakee058b4f1998-02-16 06:15:35 +0000321Here is an example of how you could write a function that computes the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000322sum of the items in a list of integers; once using
Fred Drake659ebfa2000-04-03 15:42:13 +0000323\cfunction{PyList_GetItem()}\ttindex{PyList_GetItem()}, and once using
324\cfunction{PySequence_GetItem()}\ttindex{PySequence_GetItem()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000325
326\begin{verbatim}
327long sum_list(PyObject *list)
328{
329 int i, n;
330 long total = 0;
331 PyObject *item;
Fred Drakec6fa34e1998-04-02 06:47:24 +0000332
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000333 n = PyList_Size(list);
334 if (n < 0)
335 return -1; /* Not a list */
336 for (i = 0; i < n; i++) {
337 item = PyList_GetItem(list, i); /* Can't fail */
338 if (!PyInt_Check(item)) continue; /* Skip non-integers */
339 total += PyInt_AsLong(item);
340 }
341 return total;
342}
343\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000344\ttindex{sum_list()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000345
346\begin{verbatim}
347long sum_sequence(PyObject *sequence)
348{
349 int i, n;
350 long total = 0;
351 PyObject *item;
Fred Drake659ebfa2000-04-03 15:42:13 +0000352 n = PySequence_Length(sequence);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000353 if (n < 0)
354 return -1; /* Has no length */
355 for (i = 0; i < n; i++) {
Fred Drake659ebfa2000-04-03 15:42:13 +0000356 item = PySequence_GetItem(sequence, i);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000357 if (item == NULL)
358 return -1; /* Not a sequence, or other failure */
359 if (PyInt_Check(item))
360 total += PyInt_AsLong(item);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000361 Py_DECREF(item); /* Discard reference ownership */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000362 }
363 return total;
364}
365\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000366\ttindex{sum_sequence()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000367
Fred Drakeefd146c1999-02-15 15:30:45 +0000368
369\subsection{Types \label{types}}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000370
371There are few other data types that play a significant role in
Fred Drake659ebfa2000-04-03 15:42:13 +0000372the Python/C API; most are simple C types such as \ctype{int},
373\ctype{long}, \ctype{double} and \ctype{char*}. A few structure types
Guido van Rossum4a944d71997-08-14 20:35:38 +0000374are used to describe static tables used to list the functions exported
Fred Drake659ebfa2000-04-03 15:42:13 +0000375by a module or the data attributes of a new object type, and another
376is used to describe the value of a complex number. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000377be discussed together with the functions that use them.
378
Fred Drakeefd146c1999-02-15 15:30:45 +0000379
380\section{Exceptions \label{exceptions}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000381
Guido van Rossum4a944d71997-08-14 20:35:38 +0000382The Python programmer only needs to deal with exceptions if specific
383error handling is required; unhandled exceptions are automatically
Fred Drake659ebfa2000-04-03 15:42:13 +0000384propagated to the caller, then to the caller's caller, and so on, until
Guido van Rossum4a944d71997-08-14 20:35:38 +0000385they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000386user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000387
Fred Drake659ebfa2000-04-03 15:42:13 +0000388For C programmers, however, error checking always has to be explicit.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000389All functions in the Python/C API can raise exceptions, unless an
390explicit claim is made otherwise in a function's documentation. In
391general, when a function encounters an error, it sets an exception,
392discards any object references that it owns, and returns an
Fred Drakee058b4f1998-02-16 06:15:35 +0000393error indicator --- usually \NULL{} or \code{-1}. A few functions
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000394return a Boolean true/false result, with false indicating an error.
395Very few functions return no explicit error indicator or have an
396ambiguous return value, and require explicit testing for errors with
Fred Drake659ebfa2000-04-03 15:42:13 +0000397\cfunction{PyErr_Occurred()}\ttindex{PyErr_Occurred()}.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000398
399Exception state is maintained in per-thread storage (this is
400equivalent to using global storage in an unthreaded application). A
Fred Drakec6fa34e1998-04-02 06:47:24 +0000401thread can be in one of two states: an exception has occurred, or not.
Fred Drakee058b4f1998-02-16 06:15:35 +0000402The function \cfunction{PyErr_Occurred()} can be used to check for
403this: it returns a borrowed reference to the exception type object
404when an exception has occurred, and \NULL{} otherwise. There are a
405number of functions to set the exception state:
Fred Drake659ebfa2000-04-03 15:42:13 +0000406\cfunction{PyErr_SetString()}\ttindex{PyErr_SetString()} is the most
407common (though not the most general) function to set the exception
408state, and \cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} clears the
409exception state.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000410
411The full exception state consists of three objects (all of which can
Fred Drakee058b4f1998-02-16 06:15:35 +0000412be \NULL{}): the exception type, the corresponding exception
Fred Drake659ebfa2000-04-03 15:42:13 +0000413value, and the traceback. These have the same meanings as the Python
414\withsubitem{(in module sys)}{
415 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
416objects \code{sys.exc_type}, \code{sys.exc_value}, and
417\code{sys.exc_traceback}; however, they are not the same: the Python
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000418objects represent the last exception being handled by a Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000419\keyword{try} \ldots\ \keyword{except} statement, while the C level
Fred Drakee058b4f1998-02-16 06:15:35 +0000420exception state only exists while an exception is being passed on
Fred Drake659ebfa2000-04-03 15:42:13 +0000421between C functions until it reaches the Python bytecode interpreter's
422main loop, which takes care of transferring it to \code{sys.exc_type}
423and friends.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000424
Fred Drakec6fa34e1998-04-02 06:47:24 +0000425Note that starting with Python 1.5, the preferred, thread-safe way to
Fred Drake659ebfa2000-04-03 15:42:13 +0000426access the exception state from Python code is to call the function
427\withsubitem{(in module sys)}{\ttindex{exc_info()}}
Fred Drakee058b4f1998-02-16 06:15:35 +0000428\function{sys.exc_info()}, which returns the per-thread exception state
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000429for Python code. Also, the semantics of both ways to access the
430exception state have changed so that a function which catches an
431exception will save and restore its thread's exception state so as to
432preserve the exception state of its caller. This prevents common bugs
433in exception handling code caused by an innocent-looking function
434overwriting the exception being handled; it also reduces the often
435unwanted lifetime extension for objects that are referenced by the
Fred Drakec6fa34e1998-04-02 06:47:24 +0000436stack frames in the traceback.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000437
438As a general principle, a function that calls another function to
439perform some task should check whether the called function raised an
440exception, and if so, pass the exception state on to its caller. It
Fred Drake659ebfa2000-04-03 15:42:13 +0000441should discard any object references that it owns, and return an
Fred Drakee058b4f1998-02-16 06:15:35 +0000442error indicator, but it should \emph{not} set another exception ---
443that would overwrite the exception that was just raised, and lose
444important information about the exact cause of the error.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000445
Fred Drake659ebfa2000-04-03 15:42:13 +0000446A simple example of detecting exceptions and passing them on is shown
447in the \cfunction{sum_sequence()}\ttindex{sum_sequence()} example
448above. It so happens that that example doesn't need to clean up any
449owned references when it detects an error. The following example
450function shows some error cleanup. First, to remind you why you like
451Python, we show the equivalent Python code:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000452
453\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000454def incr_item(dict, key):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000455 try:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000456 item = dict[key]
457 except KeyError:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000458 item = 0
Fred Drake6b3f3f22000-11-29 15:48:22 +0000459 dict[key] = item + 1
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000460\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000461\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000462
Fred Drake659ebfa2000-04-03 15:42:13 +0000463Here is the corresponding C code, in all its glory:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000464
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000465\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000466int incr_item(PyObject *dict, PyObject *key)
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000467{
468 /* Objects all initialized to NULL for Py_XDECREF */
469 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000470 int rv = -1; /* Return value initialized to -1 (failure) */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000471
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000472 item = PyObject_GetItem(dict, key);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000473 if (item == NULL) {
Fred Drakec6fa34e1998-04-02 06:47:24 +0000474 /* Handle KeyError only: */
Fred Drake6b3f3f22000-11-29 15:48:22 +0000475 if (!PyErr_ExceptionMatches(PyExc_KeyError))
476 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000477
478 /* Clear the error and use zero: */
479 PyErr_Clear();
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000480 item = PyInt_FromLong(0L);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000481 if (item == NULL)
482 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000483 }
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000484 const_one = PyInt_FromLong(1L);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000485 if (const_one == NULL)
486 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000487
488 incremented_item = PyNumber_Add(item, const_one);
Fred Drake6b3f3f22000-11-29 15:48:22 +0000489 if (incremented_item == NULL)
490 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000491
Fred Drake6b3f3f22000-11-29 15:48:22 +0000492 if (PyObject_SetItem(dict, key, incremented_item) < 0)
493 goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000494 rv = 0; /* Success */
495 /* Continue with cleanup code */
496
497 error:
498 /* Cleanup code, shared by success and failure path */
499
500 /* Use Py_XDECREF() to ignore NULL references */
501 Py_XDECREF(item);
502 Py_XDECREF(const_one);
503 Py_XDECREF(incremented_item);
504
505 return rv; /* -1 for error, 0 for success */
506}
507\end{verbatim}
Fred Drake659ebfa2000-04-03 15:42:13 +0000508\ttindex{incr_item()}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000509
Fred Drakef8830d11998-04-23 14:06:01 +0000510This example represents an endorsed use of the \keyword{goto} statement
Fred Drake659ebfa2000-04-03 15:42:13 +0000511in C! It illustrates the use of
512\cfunction{PyErr_ExceptionMatches()}\ttindex{PyErr_ExceptionMatches()} and
513\cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} to
514handle specific exceptions, and the use of
515\cfunction{Py_XDECREF()}\ttindex{Py_XDECREF()} to
516dispose of owned references that may be \NULL{} (note the
517\character{X} in the name; \cfunction{Py_DECREF()} would crash when
518confronted with a \NULL{} reference). It is important that the
519variables used to hold owned references are initialized to \NULL{} for
520this to work; likewise, the proposed return value is initialized to
521\code{-1} (failure) and only set to success after the final call made
522is successful.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000523
Guido van Rossum59a61351997-08-14 20:34:33 +0000524
Fred Drakeefd146c1999-02-15 15:30:45 +0000525\section{Embedding Python \label{embedding}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000526
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000527The one important task that only embedders (as opposed to extension
528writers) of the Python interpreter have to worry about is the
529initialization, and possibly the finalization, of the Python
530interpreter. Most functionality of the interpreter can only be used
531after the interpreter has been initialized.
Guido van Rossum59a61351997-08-14 20:34:33 +0000532
Fred Drake659ebfa2000-04-03 15:42:13 +0000533The basic initialization function is
534\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Fred Drakee058b4f1998-02-16 06:15:35 +0000535This initializes the table of loaded modules, and creates the
Fred Drake4de05a91998-02-16 14:25:26 +0000536fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
537\module{__main__}\refbimodindex{__main__} and
538\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drakec6fa34e1998-04-02 06:47:24 +0000539search path (\code{sys.path}).%
540\indexiii{module}{search}{path}
Fred Drake659ebfa2000-04-03 15:42:13 +0000541\withsubitem{(in module sys)}{\ttindex{path}}
Guido van Rossum59a61351997-08-14 20:34:33 +0000542
Fred Drakee058b4f1998-02-16 06:15:35 +0000543\cfunction{Py_Initialize()} does not set the ``script argument list''
Guido van Rossum4a944d71997-08-14 20:35:38 +0000544(\code{sys.argv}). If this variable is needed by Python code that
545will be executed later, it must be set explicitly with a call to
Fred Drake659ebfa2000-04-03 15:42:13 +0000546\code{PySys_SetArgv(\var{argc},
547\var{argv})}\ttindex{PySys_SetArgv()} subsequent to the call to
548\cfunction{Py_Initialize()}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000549
Fred Drakeb0a78731998-01-13 18:51:10 +0000550On most systems (in particular, on \UNIX{} and Windows, although the
Fred Drake659ebfa2000-04-03 15:42:13 +0000551details are slightly different),
552\cfunction{Py_Initialize()} calculates the module search path based
553upon its best guess for the location of the standard Python
554interpreter executable, assuming that the Python library is found in a
555fixed location relative to the Python interpreter executable. In
556particular, it looks for a directory named
Fred Draked5d04352000-09-14 20:24:17 +0000557\file{lib/python\shortversion} relative to the parent directory where
558the executable named \file{python} is found on the shell command
559search path (the environment variable \envvar{PATH}).
Guido van Rossum42cefd01997-10-05 15:27:29 +0000560
561For instance, if the Python executable is found in
Fred Drakee058b4f1998-02-16 06:15:35 +0000562\file{/usr/local/bin/python}, it will assume that the libraries are in
Fred Draked5d04352000-09-14 20:24:17 +0000563\file{/usr/local/lib/python\shortversion}. (In fact, this particular path
Fred Drakee058b4f1998-02-16 06:15:35 +0000564is also the ``fallback'' location, used when no executable file named
Fred Drakec6fa34e1998-04-02 06:47:24 +0000565\file{python} is found along \envvar{PATH}.) The user can override
566this behavior by setting the environment variable \envvar{PYTHONHOME},
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000567or insert additional directories in front of the standard path by
Fred Drakec6fa34e1998-04-02 06:47:24 +0000568setting \envvar{PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000569
Guido van Rossum4a944d71997-08-14 20:35:38 +0000570The embedding application can steer the search by calling
Fred Drake659ebfa2000-04-03 15:42:13 +0000571\code{Py_SetProgramName(\var{file})}\ttindex{Py_SetProgramName()} \emph{before} calling
Fred Drakec6fa34e1998-04-02 06:47:24 +0000572\cfunction{Py_Initialize()}. Note that \envvar{PYTHONHOME} still
573overrides this and \envvar{PYTHONPATH} is still inserted in front of
Fred Drakee058b4f1998-02-16 06:15:35 +0000574the standard path. An application that requires total control has to
Fred Drake659ebfa2000-04-03 15:42:13 +0000575provide its own implementation of
576\cfunction{Py_GetPath()}\ttindex{Py_GetPath()},
577\cfunction{Py_GetPrefix()}\ttindex{Py_GetPrefix()},
578\cfunction{Py_GetExecPrefix()}\ttindex{Py_GetExecPrefix()}, and
579\cfunction{Py_GetProgramFullPath()}\ttindex{Py_GetProgramFullPath()} (all
580defined in \file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000581
Guido van Rossum4a944d71997-08-14 20:35:38 +0000582Sometimes, it is desirable to ``uninitialize'' Python. For instance,
583the application may want to start over (make another call to
Fred Drakee058b4f1998-02-16 06:15:35 +0000584\cfunction{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000585use of Python and wants to free all memory allocated by Python. This
Fred Drakee058b4f1998-02-16 06:15:35 +0000586can be accomplished by calling \cfunction{Py_Finalize()}. The function
Fred Drake659ebfa2000-04-03 15:42:13 +0000587\cfunction{Py_IsInitialized()}\ttindex{Py_IsInitialized()} returns
588true if Python is currently in the initialized state. More
589information about these functions is given in a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000590
Guido van Rossum4a944d71997-08-14 20:35:38 +0000591
Fred Drakeefd146c1999-02-15 15:30:45 +0000592\chapter{The Very High Level Layer \label{veryhigh}}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000593
Fred Drakee5bf8b21998-02-12 21:22:28 +0000594The functions in this chapter will let you execute Python source code
595given in a file or a buffer, but they will not let you interact in a
596more detailed way with the interpreter.
Guido van Rossum4a944d71997-08-14 20:35:38 +0000597
Fred Drake659ebfa2000-04-03 15:42:13 +0000598Several of these functions accept a start symbol from the grammar as a
599parameter. The available start symbols are \constant{Py_eval_input},
600\constant{Py_file_input}, and \constant{Py_single_input}. These are
601described following the functions which accept them as parameters.
602
Fred Drake510d08b2000-08-14 02:50:21 +0000603Note also that several of these functions take \ctype{FILE*}
604parameters. On particular issue which needs to be handled carefully
605is that the \ctype{FILE} structure for different C libraries can be
606different and incompatible. Under Windows (at least), it is possible
607for dynamically linked extensions to actually use different libraries,
608so care should be taken that \ctype{FILE*} parameters are only passed
609to these functions if it is certain that they were created by the same
610library that the Python runtime is using.
611
Fred Drakec6fa34e1998-04-02 06:47:24 +0000612\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000613 If \var{fp} refers to a file associated with an interactive device
614 (console or terminal input or \UNIX{} pseudo-terminal), return the
615 value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
616 result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
Fred Drakea8d73412000-08-11 20:39:29 +0000617 \NULL{}, this function uses \code{"???"} as the filename.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000618\end{cfuncdesc}
619
Fred Drakec6fa34e1998-04-02 06:47:24 +0000620\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
Fred Drake0041a941999-04-29 04:20:46 +0000621 Executes the Python source code from \var{command} in the
622 \module{__main__} module. If \module{__main__} does not already
623 exist, it is created. Returns \code{0} on success or \code{-1} if
624 an exception was raised. If there was an error, there is no way to
625 get the exception information.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000626\end{cfuncdesc}
627
Fred Drakec6fa34e1998-04-02 06:47:24 +0000628\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
Fred Drake0041a941999-04-29 04:20:46 +0000629 Similar to \cfunction{PyRun_SimpleString()}, but the Python source
630 code is read from \var{fp} instead of an in-memory string.
631 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000632\end{cfuncdesc}
633
Fred Drakec6fa34e1998-04-02 06:47:24 +0000634\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000635 Read and execute a single statement from a file associated with an
636 interactive device. If \var{filename} is \NULL, \code{"???"} is
637 used instead. The user will be prompted using \code{sys.ps1} and
638 \code{sys.ps2}. Returns \code{0} when the input was executed
639 successfully, \code{-1} if there was an exception, or an error code
640 from the \file{errcode.h} include file distributed as part of Python
641 in case of a parse error. (Note that \file{errcode.h} is not
642 included by \file{Python.h}, so must be included specifically if
643 needed.)
Fred Drakee5bf8b21998-02-12 21:22:28 +0000644\end{cfuncdesc}
645
Fred Drakec6fa34e1998-04-02 06:47:24 +0000646\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
Fred Drakea8d73412000-08-11 20:39:29 +0000647 Read and execute statements from a file associated with an
648 interactive device until \EOF{} is reached. If \var{filename} is
649 \NULL, \code{"???"} is used instead. The user will be prompted
650 using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000651\end{cfuncdesc}
652
Fred Drakec6fa34e1998-04-02 06:47:24 +0000653\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
654 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000655 Parse Python source code from \var{str} using the start token
656 \var{start}. The result can be used to create a code object which
657 can be evaluated efficiently. This is useful if a code fragment
658 must be evaluated many times.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000659\end{cfuncdesc}
660
Fred Drakec6fa34e1998-04-02 06:47:24 +0000661\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
662 char *filename, int start}
Fred Drake0041a941999-04-29 04:20:46 +0000663 Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
664 source code is read from \var{fp} instead of an in-memory string.
665 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000666\end{cfuncdesc}
667
Fred Drakec6fa34e1998-04-02 06:47:24 +0000668\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
669 PyObject *globals,
670 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000671 Execute Python source code from \var{str} in the context specified
672 by the dictionaries \var{globals} and \var{locals}. The parameter
673 \var{start} specifies the start token that should be used to parse
674 the source code.
675
676 Returns the result of executing the code as a Python object, or
677 \NULL{} if an exception was raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000678\end{cfuncdesc}
679
Fred Drakec6fa34e1998-04-02 06:47:24 +0000680\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
681 int start, PyObject *globals,
682 PyObject *locals}
Fred Drake0041a941999-04-29 04:20:46 +0000683 Similar to \cfunction{PyRun_String()}, but the Python source code is
Fred Drake659ebfa2000-04-03 15:42:13 +0000684 read from \var{fp} instead of an in-memory string.
685 \var{filename} should be the name of the file.
Fred Drakee5bf8b21998-02-12 21:22:28 +0000686\end{cfuncdesc}
687
Fred Drakec6fa34e1998-04-02 06:47:24 +0000688\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
689 int start}
Fred Drake0041a941999-04-29 04:20:46 +0000690 Parse and compile the Python source code in \var{str}, returning the
691 resulting code object. The start token is given by \var{start};
Fred Drakec924b8d1999-08-23 18:57:25 +0000692 this can be used to constrain the code which can be compiled and should
693 be \constant{Py_eval_input}, \constant{Py_file_input}, or
694 \constant{Py_single_input}. The filename specified by
695 \var{filename} is used to construct the code object and may appear
696 in tracebacks or \exception{SyntaxError} exception messages. This
697 returns \NULL{} if the code cannot be parsed or compiled.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000698\end{cfuncdesc}
699
Fred Drakec924b8d1999-08-23 18:57:25 +0000700\begin{cvardesc}{int}{Py_eval_input}
701 The start symbol from the Python grammar for isolated expressions;
Fred Drake659ebfa2000-04-03 15:42:13 +0000702 for use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
Fred Drakec924b8d1999-08-23 18:57:25 +0000703\end{cvardesc}
704
705\begin{cvardesc}{int}{Py_file_input}
706 The start symbol from the Python grammar for sequences of statements
707 as read from a file or other source; for use with
Fred Drake659ebfa2000-04-03 15:42:13 +0000708 \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
709 the symbol to use when compiling arbitrarily long Python source code.
Fred Drakec924b8d1999-08-23 18:57:25 +0000710\end{cvardesc}
711
712\begin{cvardesc}{int}{Py_single_input}
713 The start symbol from the Python grammar for a single statement; for
Fred Drake659ebfa2000-04-03 15:42:13 +0000714 use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
715 This is the symbol used for the interactive interpreter loop.
Fred Drakec924b8d1999-08-23 18:57:25 +0000716\end{cvardesc}
717
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000718
Fred Drakeefd146c1999-02-15 15:30:45 +0000719\chapter{Reference Counting \label{countingRefs}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000720
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000721The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000722of Python objects.
723
724\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
Fred Drakec6fa34e1998-04-02 06:47:24 +0000725Increment the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000726not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000727\cfunction{Py_XINCREF()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000728\end{cfuncdesc}
729
730\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000731Increment the reference count for object \var{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000732\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000733\end{cfuncdesc}
734
735\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000736Decrement the reference count for object \var{o}. The object must
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000737not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
Fred Drakee058b4f1998-02-16 06:15:35 +0000738\cfunction{Py_XDECREF()}. If the reference count reaches zero, the
739object's type's deallocation function (which must not be \NULL{}) is
740invoked.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000741
742\strong{Warning:} The deallocation function can cause arbitrary Python
Fred Drake659ebfa2000-04-03 15:42:13 +0000743code to be invoked (e.g. when a class instance with a
744\method{__del__()} method is deallocated). While exceptions in such
745code are not propagated, the executed code has free access to all
746Python global variables. This means that any object that is reachable
747from a global variable should be in a consistent state before
748\cfunction{Py_DECREF()} is invoked. For example, code to delete an
749object from a list should copy a reference to the deleted object in a
750temporary variable, update the list data structure, and then call
751\cfunction{Py_DECREF()} for the temporary variable.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000752\end{cfuncdesc}
753
754\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +0000755Decrement the reference count for object \var{o}. The object may be
756\NULL{}, in which case the macro has no effect; otherwise the effect
757is the same as for \cfunction{Py_DECREF()}, and the same warning
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000758applies.
759\end{cfuncdesc}
760
Fred Drake659ebfa2000-04-03 15:42:13 +0000761The following functions or macros are only for use within the
762interpreter core: \cfunction{_Py_Dealloc()},
763\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
764well as the global variable \cdata{_Py_RefTotal}.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000765
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000766
Fred Drakeefd146c1999-02-15 15:30:45 +0000767\chapter{Exception Handling \label{exceptionHandling}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000768
Fred Drake659ebfa2000-04-03 15:42:13 +0000769The functions described in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000770exceptions. It is important to understand some of the basics of
Fred Drake659ebfa2000-04-03 15:42:13 +0000771Python exception handling. It works somewhat like the
772\UNIX{} \cdata{errno} variable: there is a global indicator (per
773thread) of the last error that occurred. Most functions don't clear
774this on success, but will set it to indicate the cause of the error on
775failure. Most functions also return an error indicator, usually
776\NULL{} if they are supposed to return a pointer, or \code{-1} if they
777return an integer (exception: the \cfunction{PyArg_Parse*()} functions
778return \code{1} for success and \code{0} for failure). When a
779function must fail because some function it called failed, it
780generally doesn't set the error indicator; the function it called
781already set it.
Guido van Rossumae110af1997-05-22 20:11:52 +0000782
783The error indicator consists of three Python objects corresponding to
Fred Drake659ebfa2000-04-03 15:42:13 +0000784\withsubitem{(in module sys)}{
785 \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
Guido van Rossumae110af1997-05-22 20:11:52 +0000786the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
787\code{sys.exc_traceback}. API functions exist to interact with the
788error indicator in various ways. There is a separate error indicator
789for each thread.
790
791% XXX Order of these should be more thoughtful.
792% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000793
794\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000795Print a standard traceback to \code{sys.stderr} and clear the error
796indicator. Call this function only when the error indicator is set.
797(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000798\end{cfuncdesc}
799
Fred Drakec6fa34e1998-04-02 06:47:24 +0000800\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000801Test whether the error indicator is set. If set, return the exception
Fred Drakee058b4f1998-02-16 06:15:35 +0000802\emph{type} (the first argument to the last call to one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000803\cfunction{PyErr_Set*()} functions or to \cfunction{PyErr_Restore()}). If
Fred Drakee058b4f1998-02-16 06:15:35 +0000804not set, return \NULL{}. You do not own a reference to the return
805value, so you do not need to \cfunction{Py_DECREF()} it.
Fred Drake659ebfa2000-04-03 15:42:13 +0000806\strong{Note:} Do not compare the return value to a specific
Fred Drakee058b4f1998-02-16 06:15:35 +0000807exception; use \cfunction{PyErr_ExceptionMatches()} instead, shown
Fred Drake659ebfa2000-04-03 15:42:13 +0000808below. (The comparison could easily fail since the exception may be
809an instance instead of a class, in the case of a class exception, or
810it may the a subclass of the expected exception.)
Guido van Rossum42cefd01997-10-05 15:27:29 +0000811\end{cfuncdesc}
812
813\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000814Equivalent to
Fred Drakee058b4f1998-02-16 06:15:35 +0000815\samp{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
Fred Drake659ebfa2000-04-03 15:42:13 +0000816This should only be called when an exception is actually set; a memory
817access violation will occur if no exception has been raised.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000818\end{cfuncdesc}
819
820\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000821Return true if the \var{given} exception matches the exception in
822\var{exc}. If \var{exc} is a class object, this also returns true
Fred Drake659ebfa2000-04-03 15:42:13 +0000823when \var{given} is an instance of a subclass. If \var{exc} is a tuple, all
Guido van Rossum42cefd01997-10-05 15:27:29 +0000824exceptions in the tuple (and recursively in subtuples) are searched
Fred Drake659ebfa2000-04-03 15:42:13 +0000825for a match. If \var{given} is \NULL, a memory access violation will
826occur.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000827\end{cfuncdesc}
828
829\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000830Under certain circumstances, the values returned by
Fred Drakee058b4f1998-02-16 06:15:35 +0000831\cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning that
832\code{*\var{exc}} is a class object but \code{*\var{val}} is not an
833instance of the same class. This function can be used to instantiate
834the class in that case. If the values are already normalized, nothing
Fred Drake659ebfa2000-04-03 15:42:13 +0000835happens. The delayed normalization is implemented to improve
836performance.
Guido van Rossumae110af1997-05-22 20:11:52 +0000837\end{cfuncdesc}
838
839\begin{cfuncdesc}{void}{PyErr_Clear}{}
840Clear the error indicator. If the error indicator is not set, there
841is no effect.
842\end{cfuncdesc}
843
Fred Drake659ebfa2000-04-03 15:42:13 +0000844\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
845 PyObject **ptraceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000846Retrieve the error indicator into three variables whose addresses are
847passed. If the error indicator is not set, set all three variables to
848\NULL{}. If it is set, it will be cleared and you own a reference to
Fred Drake659ebfa2000-04-03 15:42:13 +0000849each object retrieved. The value and traceback object may be
850\NULL{} even when the type object is not. \strong{Note:} This
851function is normally only used by code that needs to handle exceptions
852or by code that needs to save and restore the error indicator
853temporarily.
Guido van Rossumae110af1997-05-22 20:11:52 +0000854\end{cfuncdesc}
855
Fred Drake17e63432000-08-31 05:50:40 +0000856\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
857 PyObject *traceback}
Guido van Rossumae110af1997-05-22 20:11:52 +0000858Set the error indicator from the three objects. If the error
859indicator is already set, it is cleared first. If the objects are
860\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
861and non-\NULL{} value or traceback. The exception type should be a
862string or class; if it is a class, the value should be an instance of
863that class. Do not pass an invalid exception type or value.
864(Violating these rules will cause subtle problems later.) This call
Fred Drake17e63432000-08-31 05:50:40 +0000865takes away a reference to each object, i.e.\ you must own a reference
Guido van Rossumae110af1997-05-22 20:11:52 +0000866to each object before the call and after the call you no longer own
867these references. (If you don't understand this, don't use this
Fred Drake659ebfa2000-04-03 15:42:13 +0000868function. I warned you.) \strong{Note:} This function is normally
Guido van Rossumae110af1997-05-22 20:11:52 +0000869only used by code that needs to save and restore the error indicator
870temporarily.
871\end{cfuncdesc}
872
873\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
874This is the most common way to set the error indicator. The first
875argument specifies the exception type; it is normally one of the
Fred Drakef8830d11998-04-23 14:06:01 +0000876standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
Guido van Rossumae110af1997-05-22 20:11:52 +0000877increment its reference count. The second argument is an error
878message; it is converted to a string object.
879\end{cfuncdesc}
880
881\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +0000882This function is similar to \cfunction{PyErr_SetString()} but lets you
Guido van Rossumae110af1997-05-22 20:11:52 +0000883specify an arbitrary Python object for the ``value'' of the exception.
884You need not increment its reference count.
885\end{cfuncdesc}
886
Fred Drake73577702000-04-10 18:50:14 +0000887\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
Moshe Zadka57a59322000-09-01 09:47:20 +0000888 const char *format, \moreargs}
Fred Drake89fb0352000-10-14 05:49:30 +0000889This function sets the error indicator. \var{exception} should be a
890Python exception (string or class, not an instance).
Moshe Zadka57a59322000-09-01 09:47:20 +0000891\var{fmt} should be a string, containing format codes, similar to
892\cfunction{printf}. The \code{width.precision} before a format code
893is parsed, but the width part is ignored.
894
895\begin{tableii}{c|l}{character}{Character}{Meaning}
896 \lineii{c}{Character, as an \ctype{int} parameter}
897 \lineii{d}{Number in decimal, as an \ctype{int} parameter}
898 \lineii{x}{Number in hexadecimal, as an \ctype{int} parameter}
899 \lineii{x}{A string, as a \ctype{char *} parameter}
900\end{tableii}
901
902An unrecognized format character causes all the rest of
903the format string to be copied as-is to the result string,
904and any extra arguments discarded.
905
906A new reference is returned, which is owned by the caller.
Jeremy Hylton98605b52000-04-10 18:40:57 +0000907\end{cfuncdesc}
908
Guido van Rossumae110af1997-05-22 20:11:52 +0000909\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +0000910This is a shorthand for \samp{PyErr_SetObject(\var{type}, Py_None)}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000911\end{cfuncdesc}
912
913\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000914This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000915\var{message})}, where \var{message} indicates that a built-in operation
916was invoked with an illegal argument. It is mostly for internal use.
917\end{cfuncdesc}
918
Fred Drakec6fa34e1998-04-02 06:47:24 +0000919\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000920This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
Guido van Rossumae110af1997-05-22 20:11:52 +0000921returns \NULL{} so an object allocation function can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000922\samp{return PyErr_NoMemory();} when it runs out of memory.
Guido van Rossumae110af1997-05-22 20:11:52 +0000923\end{cfuncdesc}
924
Fred Drakec6fa34e1998-04-02 06:47:24 +0000925\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
Fred Drake659ebfa2000-04-03 15:42:13 +0000926This is a convenience function to raise an exception when a C library
927function has returned an error and set the C variable \cdata{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000928It constructs a tuple object whose first item is the integer
Fred Drakef8830d11998-04-23 14:06:01 +0000929\cdata{errno} value and whose second item is the corresponding error
Fred Drake659ebfa2000-04-03 15:42:13 +0000930message (gotten from \cfunction{strerror()}\ttindex{strerror()}), and
931then calls
Fred Drakee058b4f1998-02-16 06:15:35 +0000932\samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
Fred Drakef8830d11998-04-23 14:06:01 +0000933the \cdata{errno} value is \constant{EINTR}, indicating an interrupted
Fred Drakee058b4f1998-02-16 06:15:35 +0000934system call, this calls \cfunction{PyErr_CheckSignals()}, and if that set
Guido van Rossumae110af1997-05-22 20:11:52 +0000935the error indicator, leaves it set to that. The function always
936returns \NULL{}, so a wrapper function around a system call can write
Fred Drakee058b4f1998-02-16 06:15:35 +0000937\samp{return PyErr_SetFromErrno();} when the system call returns an
938error.
Guido van Rossumae110af1997-05-22 20:11:52 +0000939\end{cfuncdesc}
940
941\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
Fred Drakee058b4f1998-02-16 06:15:35 +0000942This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
Guido van Rossumae110af1997-05-22 20:11:52 +0000943\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000944operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000945argument. It is mostly for internal use.
946\end{cfuncdesc}
947
948\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
949This function interacts with Python's signal handling. It checks
950whether a signal has been sent to the processes and if so, invokes the
Fred Drake4de05a91998-02-16 14:25:26 +0000951corresponding signal handler. If the
952\module{signal}\refbimodindex{signal} module is supported, this can
953invoke a signal handler written in Python. In all cases, the default
Fred Drake659ebfa2000-04-03 15:42:13 +0000954effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
955\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
956\exception{KeyboardInterrupt} exception. If an exception is raised the
Fred Drakee058b4f1998-02-16 06:15:35 +0000957error indicator is set and the function returns \code{1}; otherwise
958the function returns \code{0}. The error indicator may or may not be
959cleared if it was previously set.
Guido van Rossumae110af1997-05-22 20:11:52 +0000960\end{cfuncdesc}
961
962\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
Fred Drake659ebfa2000-04-03 15:42:13 +0000963This function is obsolete. It simulates the effect of a
964\constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
Fred Drakee058b4f1998-02-16 06:15:35 +0000965\cfunction{PyErr_CheckSignals()} is called,
Fred Drake659ebfa2000-04-03 15:42:13 +0000966\withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
967\exception{KeyboardInterrupt} will be raised.
968It may be called without holding the interpreter lock.
Guido van Rossumae110af1997-05-22 20:11:52 +0000969\end{cfuncdesc}
970
Fred Drakec6fa34e1998-04-02 06:47:24 +0000971\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
972 PyObject *base,
973 PyObject *dict}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000974This utility function creates and returns a new exception object. The
Fred Drake659ebfa2000-04-03 15:42:13 +0000975\var{name} argument must be the name of the new exception, a C string
976of the form \code{module.class}. The \var{base} and
Fred Draked04038d2000-06-29 20:15:14 +0000977\var{dict} arguments are normally \NULL{}. This creates a
Fred Drake659ebfa2000-04-03 15:42:13 +0000978class object derived from the root for all exceptions, the built-in
979name \exception{Exception} (accessible in C as
Fred Draked04038d2000-06-29 20:15:14 +0000980\cdata{PyExc_Exception}). The \member{__module__} attribute of the
981new class is set to the first part (up to the last dot) of the
982\var{name} argument, and the class name is set to the last part (after
983the last dot). The \var{base} argument can be used to specify an
984alternate base class. The \var{dict} argument can be used to specify
985a dictionary of class variables and methods.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000986\end{cfuncdesc}
987
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000988\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
989This utility function prints a warning message to \var{sys.stderr}
990when an exception has been set but it is impossible for the
991interpreter to actually raise the exception. It is used, for example,
992when an exception occurs in an \member{__del__} method.
993
994The function is called with a single argument \var{obj} that
995identifies where the context in which the unraisable exception
996occurred. The repr of \var{obj} will be printed in the warning
997message.
998\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000999
Fred Drakeefd146c1999-02-15 15:30:45 +00001000\section{Standard Exceptions \label{standardExceptions}}
Guido van Rossumae110af1997-05-22 20:11:52 +00001001
1002All standard Python exceptions are available as global variables whose
Fred Drake659ebfa2000-04-03 15:42:13 +00001003names are \samp{PyExc_} followed by the Python exception name. These
1004have the type \ctype{PyObject*}; they are all class objects. For
1005completeness, here are all the variables:
1006
1007\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
1008 \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
1009 \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
1010 \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
1011 \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
1012 \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
1013 \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
1014 \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
1015 \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
1016 \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
1017 \lineiii{PyExc_IOError}{\exception{IOError}}{}
1018 \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
1019 \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
1020 \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
1021 \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
1022 \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
1023 \lineiii{PyExc_NameError}{\exception{NameError}}{}
1024 \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
1025 \lineiii{PyExc_OSError}{\exception{OSError}}{}
1026 \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
1027 \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
1028 \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
1029 \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
1030 \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
1031 \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
1032 \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
Fred Drakea8d73412000-08-11 20:39:29 +00001033 \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(2)}
Fred Drake659ebfa2000-04-03 15:42:13 +00001034 \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
1035\end{tableiii}
1036
1037\noindent
Fred Drakea8d73412000-08-11 20:39:29 +00001038Notes:
Fred Drake659ebfa2000-04-03 15:42:13 +00001039\begin{description}
1040\item[(1)]
Fred Draked04038d2000-06-29 20:15:14 +00001041 This is a base class for other standard exceptions.
Fred Drakea8d73412000-08-11 20:39:29 +00001042
1043\item[(2)]
1044 Only defined on Windows; protect code that uses this by testing that
1045 the preprocessor macro \code{MS_WINDOWS} is defined.
Fred Drake659ebfa2000-04-03 15:42:13 +00001046\end{description}
1047
1048
1049\section{Deprecation of String Exceptions}
1050
Fred Draked04038d2000-06-29 20:15:14 +00001051All exceptions built into Python or provided in the standard library
1052are derived from \exception{Exception}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001053\withsubitem{(built-in exception)}{\ttindex{Exception}}
Fred Drake659ebfa2000-04-03 15:42:13 +00001054
Fred Draked04038d2000-06-29 20:15:14 +00001055String exceptions are still supported in the interpreter to allow
Fred Drake659ebfa2000-04-03 15:42:13 +00001056existing code to run unmodified, but this will also change in a future
1057release.
Guido van Rossumae110af1997-05-22 20:11:52 +00001058
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001059
Fred Drakeefd146c1999-02-15 15:30:45 +00001060\chapter{Utilities \label{utilities}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001061
1062The functions in this chapter perform various utility tasks, such as
Fred Drake659ebfa2000-04-03 15:42:13 +00001063parsing function arguments and constructing Python values from C
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001064values.
1065
Fred Drakeefd146c1999-02-15 15:30:45 +00001066\section{OS Utilities \label{os}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001067
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001068\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001069Return true (nonzero) if the standard I/O file \var{fp} with name
1070\var{filename} is deemed interactive. This is the case for files for
1071which \samp{isatty(fileno(\var{fp}))} is true. If the global flag
Fred Drakef8830d11998-04-23 14:06:01 +00001072\cdata{Py_InteractiveFlag} is true, this function also returns true if
Fred Drakee058b4f1998-02-16 06:15:35 +00001073the \var{name} pointer is \NULL{} or if the name is equal to one of
Fred Drakea8455ab2000-06-16 19:58:42 +00001074the strings \code{'<stdin>'} or \code{'???'}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001075\end{cfuncdesc}
1076
1077\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
Fred Drakee058b4f1998-02-16 06:15:35 +00001078Return the time of last modification of the file \var{filename}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001079The result is encoded in the same way as the timestamp returned by
Fred Drake659ebfa2000-04-03 15:42:13 +00001080the standard C library function \cfunction{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001081\end{cfuncdesc}
1082
Fred Drakecabbc3b2000-06-28 15:53:13 +00001083\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
1084Function to update some internal state after a process fork; this
1085should be called in the new process if the Python interpreter will
1086continue to be used. If a new executable is loaded into the new
1087process, this function does not need to be called.
1088\end{cfuncdesc}
1089
Fred Drake17e63432000-08-31 05:50:40 +00001090\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
1091Return true when the interpreter runs out of stack space. This is a
1092reliable check, but is only available when \code{USE_STACKCHECK} is
1093defined (currently on Windows using the Microsoft Visual C++ compiler
1094and on the Macintosh). \code{USE_CHECKSTACK} will be defined
1095automatically; you should never change the definition in your own
1096code.
1097\end{cfuncdesc}
1098
Guido van Rossumc96ec6e2000-09-16 16:30:48 +00001099\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i}
1100Return the current signal handler for signal \var{i}.
1101This is a thin wrapper around either \cfunction{sigaction} or
1102\cfunction{signal}. Do not call those functions directly!
1103\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1104\end{cfuncdesc}
1105
1106\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h}
1107Set the signal handler for signal \var{i} to be \var{h};
1108return the old signal handler.
1109This is a thin wrapper around either \cfunction{sigaction} or
1110\cfunction{signal}. Do not call those functions directly!
1111\ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void (*)(int)}.
1112\end{cfuncdesc}
1113
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001114
Fred Drakeefd146c1999-02-15 15:30:45 +00001115\section{Process Control \label{processControl}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00001116
1117\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
1118Print a fatal error message and kill the process. No cleanup is
1119performed. This function should only be invoked when a condition is
1120detected that would make it dangerous to continue using the Python
1121interpreter; e.g., when the object administration appears to be
Fred Drake659ebfa2000-04-03 15:42:13 +00001122corrupted. On \UNIX{}, the standard C library function
1123\cfunction{abort()}\ttindex{abort()} is called which will attempt to
1124produce a \file{core} file.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001125\end{cfuncdesc}
1126
1127\begin{cfuncdesc}{void}{Py_Exit}{int status}
Fred Drake659ebfa2000-04-03 15:42:13 +00001128Exit the current process. This calls
1129\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
1130then calls the standard C library function
1131\code{exit(\var{status})}\ttindex{exit()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001132\end{cfuncdesc}
1133
1134\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drake659ebfa2000-04-03 15:42:13 +00001135Register a cleanup function to be called by
1136\cfunction{Py_Finalize()}\ttindex{Py_Finalize()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001137The cleanup function will be called with no arguments and should
Fred Drake659ebfa2000-04-03 15:42:13 +00001138return no value. At most 32 \index{cleanup functions}cleanup
1139functions can be registered.
Fred Drakee5bf8b21998-02-12 21:22:28 +00001140When the registration is successful, \cfunction{Py_AtExit()} returns
1141\code{0}; on failure, it returns \code{-1}. The cleanup function
1142registered last is called first. Each cleanup function will be called
1143at most once. Since Python's internal finallization will have
1144completed before the cleanup function, no Python APIs should be called
1145by \var{func}.
1146\end{cfuncdesc}
1147
1148
Fred Drakeefd146c1999-02-15 15:30:45 +00001149\section{Importing Modules \label{importing}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001150
Fred Drakec6fa34e1998-04-02 06:47:24 +00001151\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00001152This is a simplified interface to
1153\cfunction{PyImport_ImportModuleEx()} below, leaving the
1154\var{globals} and \var{locals} arguments set to \NULL{}. When the
1155\var{name} argument contains a dot (i.e., when it specifies a
1156submodule of a package), the \var{fromlist} argument is set to the
1157list \code{['*']} so that the return value is the named module rather
1158than the top-level package containing it as would otherwise be the
1159case. (Unfortunately, this has an additional side effect when
1160\var{name} in fact specifies a subpackage instead of a submodule: the
1161submodules specified in the package's \code{__all__} variable are
1162\index{package variable!\code{__all__}}
1163\withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return a
1164new reference to the imported module, or
1165\NULL{} with an exception set on failure (the module may still be
1166created in this case --- examine \code{sys.modules} to find out).
1167\withsubitem{(in module sys)}{\ttindex{modules}}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001168\end{cfuncdesc}
1169
Fred Drakec6fa34e1998-04-02 06:47:24 +00001170\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001171Import a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001172Python function \function{__import__()}\bifuncindex{__import__}, as
1173the standard \function{__import__()} function calls this function
1174directly.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001175
Guido van Rossum42cefd01997-10-05 15:27:29 +00001176The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001177top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001178(the module may still be created in this case). Like for
Fred Drakee058b4f1998-02-16 06:15:35 +00001179\function{__import__()}, the return value when a submodule of a
1180package was requested is normally the top-level package, unless a
1181non-empty \var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001182\end{cfuncdesc}
1183
Fred Drakec6fa34e1998-04-02 06:47:24 +00001184\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001185This is a higher-level interface that calls the current ``import hook
Fred Drakee058b4f1998-02-16 06:15:35 +00001186function''. It invokes the \function{__import__()} function from the
Guido van Rossum42cefd01997-10-05 15:27:29 +00001187\code{__builtins__} of the current globals. This means that the
1188import is done using whatever import hooks are installed in the
Fred Drake4de05a91998-02-16 14:25:26 +00001189current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
1190\module{ihooks}\refstmodindex{ihooks}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001191\end{cfuncdesc}
1192
Fred Drakec6fa34e1998-04-02 06:47:24 +00001193\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001194Reload a module. This is best described by referring to the built-in
Fred Drake53fb7721998-02-16 06:23:20 +00001195Python function \function{reload()}\bifuncindex{reload}, as the standard
Fred Drakee058b4f1998-02-16 06:15:35 +00001196\function{reload()} function calls this function directly. Return a
1197new reference to the reloaded module, or \NULL{} with an exception set
1198on failure (the module still exists in this case).
Guido van Rossum42cefd01997-10-05 15:27:29 +00001199\end{cfuncdesc}
1200
Fred Drakec6fa34e1998-04-02 06:47:24 +00001201\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001202Return the module object corresponding to a module name. The
1203\var{name} argument may be of the form \code{package.module}). First
1204check the modules dictionary if there's one there, and if not, create
Fred Drake659ebfa2000-04-03 15:42:13 +00001205a new one and insert in in the modules dictionary.
Guido van Rossuma096a2e1998-11-02 17:02:42 +00001206Warning: this function does not load or import the module; if the
1207module wasn't already loaded, you will get an empty module object.
1208Use \cfunction{PyImport_ImportModule()} or one of its variants to
1209import a module.
Fred Drake659ebfa2000-04-03 15:42:13 +00001210Return \NULL{} with an exception set on failure.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001211\end{cfuncdesc}
1212
Fred Drakec6fa34e1998-04-02 06:47:24 +00001213\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001214Given a module name (possibly of the form \code{package.module}) and a
1215code object read from a Python bytecode file or obtained from the
Fred Drake53fb7721998-02-16 06:23:20 +00001216built-in function \function{compile()}\bifuncindex{compile}, load the
1217module. Return a new reference to the module object, or \NULL{} with
1218an exception set if an error occurred (the module may still be created
1219in this case). (This function would reload the module if it was
1220already imported.)
Guido van Rossum42cefd01997-10-05 15:27:29 +00001221\end{cfuncdesc}
1222
1223\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00001224Return the magic number for Python bytecode files (a.k.a.
1225\file{.pyc} and \file{.pyo} files). The magic number should be
1226present in the first four bytes of the bytecode file, in little-endian
1227byte order.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001228\end{cfuncdesc}
1229
Fred Drakec6fa34e1998-04-02 06:47:24 +00001230\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001231Return the dictionary used for the module administration
1232(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1233variable.
1234\end{cfuncdesc}
1235
1236\begin{cfuncdesc}{void}{_PyImport_Init}{}
1237Initialize the import mechanism. For internal use only.
1238\end{cfuncdesc}
1239
1240\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1241Empty the module table. For internal use only.
1242\end{cfuncdesc}
1243
1244\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1245Finalize the import mechanism. For internal use only.
1246\end{cfuncdesc}
1247
Fred Drakec6fa34e1998-04-02 06:47:24 +00001248\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001249For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001250\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001251
Fred Drakec6fa34e1998-04-02 06:47:24 +00001252\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001253For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001254\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001255
Fred Drake1d158692000-06-18 05:21:21 +00001256\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
1257Load a frozen module named \var{name}. Return \code{1} for success,
1258\code{0} if the module is not found, and \code{-1} with an exception
1259set if the initialization failed. To access the imported module on a
1260successful load, use \cfunction{PyImport_ImportModule()}.
Fred Drakee058b4f1998-02-16 06:15:35 +00001261(Note the misnomer --- this function would reload the module if it was
Guido van Rossum42cefd01997-10-05 15:27:29 +00001262already imported.)
1263\end{cfuncdesc}
1264
Fred Drake659ebfa2000-04-03 15:42:13 +00001265\begin{ctypedesc}[_frozen]{struct _frozen}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001266This is the structure type definition for frozen module descriptors,
Fred Drakec6fa34e1998-04-02 06:47:24 +00001267as generated by the \program{freeze}\index{freeze utility} utility
1268(see \file{Tools/freeze/} in the Python source distribution). Its
Fred Drakee0d9a832000-09-01 05:30:00 +00001269definition, found in \file{Include/import.h}, is:
Fred Drakec6fa34e1998-04-02 06:47:24 +00001270
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001271\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001272struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001273 char *name;
1274 unsigned char *code;
1275 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001276};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001277\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001278\end{ctypedesc}
1279
Fred Drakec6fa34e1998-04-02 06:47:24 +00001280\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
Fred Drakef8830d11998-04-23 14:06:01 +00001281This pointer is initialized to point to an array of \ctype{struct
Fred Drake659ebfa2000-04-03 15:42:13 +00001282_frozen} records, terminated by one whose members are all
1283\NULL{} or zero. When a frozen module is imported, it is searched in
1284this table. Third-party code could play tricks with this to provide a
Guido van Rossum42cefd01997-10-05 15:27:29 +00001285dynamically created collection of frozen modules.
1286\end{cvardesc}
1287
Fred Drakee0d9a832000-09-01 05:30:00 +00001288\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
1289 void (*initfunc)(void)}
1290Add a single module to the existing table of built-in modules. This
1291is a convenience wrapper around \cfunction{PyImport_ExtendInittab()},
1292returning \code{-1} if the table could not be extended. The new
1293module can be imported by the name \var{name}, and uses the function
1294\var{initfunc} as the initialization function called on the first
1295attempted import. This should be called before
1296\cfunction{Py_Initialize()}.
1297\end{cfuncdesc}
1298
1299\begin{ctypedesc}[_inittab]{struct _inittab}
1300Structure describing a single entry in the list of built-in modules.
1301Each of these structures gives the name and initialization function
1302for a module built into the interpreter. Programs which embed Python
1303may use an array of these structures in conjunction with
1304\cfunction{PyImport_ExtendInittab()} to provide additional built-in
1305modules. The structure is defined in \file{Include/import.h} as:
1306
1307\begin{verbatim}
1308struct _inittab {
1309 char *name;
1310 void (*initfunc)(void);
1311};
1312\end{verbatim}
1313\end{ctypedesc}
1314
1315\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
1316Add a collection of modules to the table of built-in modules. The
1317\var{newtab} array must end with a sentinel entry which contains
1318\NULL{} for the \member{name} field; failure to provide the sentinel
1319value can result in a memory fault. Returns \code{0} on success or
1320\code{-1} if insufficient memory could be allocated to extend the
1321internal table. In the event of failure, no modules are added to the
1322internal table. This should be called before
1323\cfunction{Py_Initialize()}.
1324\end{cfuncdesc}
1325
Guido van Rossum42cefd01997-10-05 15:27:29 +00001326
Fred Drakeefd146c1999-02-15 15:30:45 +00001327\chapter{Abstract Objects Layer \label{abstract}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001328
1329The functions in this chapter interact with Python objects regardless
1330of their type, or with wide classes of object types (e.g. all
1331numerical types, or all sequence types). When used on object types
Fred Drake659ebfa2000-04-03 15:42:13 +00001332for which they do not apply, they will raise a Python exception.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001333
Fred Drakeefd146c1999-02-15 15:30:45 +00001334\section{Object Protocol \label{object}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001335
1336\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00001337Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error.
1338The flags argument is used to enable certain printing options. The
1339only option currently supported is \constant{Py_PRINT_RAW}; if given,
1340the \function{str()} of the object is written instead of the
1341\function{repr()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001342\end{cfuncdesc}
1343
1344\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001345Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1346\code{0} otherwise. This is equivalent to the Python expression
1347\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001348This function always succeeds.
1349\end{cfuncdesc}
1350
Fred Drake659ebfa2000-04-03 15:42:13 +00001351\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
1352 char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001353Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001354Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001355This is the equivalent of the Python expression
1356\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001357\end{cfuncdesc}
1358
1359
1360\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001361Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1362\code{0} otherwise. This is equivalent to the Python expression
1363\samp{hasattr(\var{o}, \var{attr_name})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001364This function always succeeds.
1365\end{cfuncdesc}
1366
1367
Fred Drake659ebfa2000-04-03 15:42:13 +00001368\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
1369 PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001370Retrieve an attribute named \var{attr_name} from object \var{o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001371Returns the attribute value on success, or \NULL{} on failure.
Fred Drakee058b4f1998-02-16 06:15:35 +00001372This is the equivalent of the Python expression
1373\samp{\var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001374\end{cfuncdesc}
1375
1376
1377\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001378Set the value of the attribute named \var{attr_name}, for object
1379\var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1380the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1381\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001382\end{cfuncdesc}
1383
1384
1385\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001386Set the value of the attribute named \var{attr_name}, for
1387object \var{o},
1388to the value \var{v}. Returns \code{-1} on failure. This is
1389the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1390\var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001391\end{cfuncdesc}
1392
1393
1394\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001395Delete attribute named \var{attr_name}, for object \var{o}. Returns
1396\code{-1} on failure. This is the equivalent of the Python
1397statement: \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001398\end{cfuncdesc}
1399
1400
1401\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
Fred Drakee058b4f1998-02-16 06:15:35 +00001402Delete attribute named \var{attr_name}, for object \var{o}. Returns
1403\code{-1} on failure. This is the equivalent of the Python
1404statement \samp{del \var{o}.\var{attr_name}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001405\end{cfuncdesc}
1406
1407
1408\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
Fred Drakee058b4f1998-02-16 06:15:35 +00001409Compare the values of \var{o1} and \var{o2} using a routine provided
1410by \var{o1}, if one exists, otherwise with a routine provided by
1411\var{o2}. The result of the comparison is returned in \var{result}.
1412Returns \code{-1} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001413statement\bifuncindex{cmp} \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001414\end{cfuncdesc}
1415
1416
1417\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001418Compare the values of \var{o1} and \var{o2} using a routine provided
1419by \var{o1}, if one exists, otherwise with a routine provided by
1420\var{o2}. Returns the result of the comparison on success. On error,
1421the value returned is undefined; use \cfunction{PyErr_Occurred()} to
Fred Drake659ebfa2000-04-03 15:42:13 +00001422detect an error. This is equivalent to the Python
1423expression\bifuncindex{cmp} \samp{cmp(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001424\end{cfuncdesc}
1425
1426
1427\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001428Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001429string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001430the equivalent of the Python expression \samp{repr(\var{o})}.
1431Called by the \function{repr()}\bifuncindex{repr} built-in function
1432and by reverse quotes.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001433\end{cfuncdesc}
1434
1435
1436\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001437Compute a string representation of object \var{o}. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001438string representation on success, \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001439the equivalent of the Python expression \samp{str(\var{o})}.
1440Called by the \function{str()}\bifuncindex{str} built-in function and
1441by the \keyword{print} statement.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001442\end{cfuncdesc}
1443
1444
1445\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001446Determine if the object \var{o} is callable. Return \code{1} if the
Fred Drakee058b4f1998-02-16 06:15:35 +00001447object is callable and \code{0} otherwise.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001448This function always succeeds.
1449\end{cfuncdesc}
1450
1451
Fred Drake659ebfa2000-04-03 15:42:13 +00001452\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
1453 PyObject *args}
Fred Drakee058b4f1998-02-16 06:15:35 +00001454Call a callable Python object \var{callable_object}, with
1455arguments given by the tuple \var{args}. If no arguments are
Fred Drake659ebfa2000-04-03 15:42:13 +00001456needed, then \var{args} may be \NULL{}. Returns the result of the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001457call on success, or \NULL{} on failure. This is the equivalent
Fred Drakee058b4f1998-02-16 06:15:35 +00001458of the Python expression \samp{apply(\var{o}, \var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001459\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001460\end{cfuncdesc}
1461
1462\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001463Call a callable Python object \var{callable_object}, with a
Fred Drake659ebfa2000-04-03 15:42:13 +00001464variable number of C arguments. The C arguments are described
Fred Drakee058b4f1998-02-16 06:15:35 +00001465using a \cfunction{Py_BuildValue()} style format string. The format may
1466be \NULL{}, indicating that no arguments are provided. Returns the
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001467result of the call on success, or \NULL{} on failure. This is
Fred Drakee058b4f1998-02-16 06:15:35 +00001468the equivalent of the Python expression \samp{apply(\var{o},
Fred Drake659ebfa2000-04-03 15:42:13 +00001469\var{args})}.\bifuncindex{apply}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001470\end{cfuncdesc}
1471
1472
1473\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
Fred Drakee058b4f1998-02-16 06:15:35 +00001474Call the method named \var{m} of object \var{o} with a variable number
Fred Drake659ebfa2000-04-03 15:42:13 +00001475of C arguments. The C arguments are described by a
Fred Drakee058b4f1998-02-16 06:15:35 +00001476\cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1477indicating that no arguments are provided. Returns the result of the
1478call on success, or \NULL{} on failure. This is the equivalent of the
1479Python expression \samp{\var{o}.\var{method}(\var{args})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001480Note that special method names, such as \method{__add__()},
1481\method{__getitem__()}, and so on are not supported. The specific
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001482abstract-object routines for these must be used.
1483\end{cfuncdesc}
1484
1485
1486\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001487Compute and return the hash value of an object \var{o}. On
1488failure, return \code{-1}. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001489expression \samp{hash(\var{o})}.\bifuncindex{hash}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001490\end{cfuncdesc}
1491
1492
1493\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001494Returns \code{1} if the object \var{o} is considered to be true, and
1495\code{0} otherwise. This is equivalent to the Python expression
1496\samp{not not \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001497This function always succeeds.
1498\end{cfuncdesc}
1499
1500
1501\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1502On success, returns a type object corresponding to the object
Fred Drakee058b4f1998-02-16 06:15:35 +00001503type of object \var{o}. On failure, returns \NULL{}. This is
1504equivalent to the Python expression \samp{type(\var{o})}.
Fred Drake53fb7721998-02-16 06:23:20 +00001505\bifuncindex{type}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001506\end{cfuncdesc}
1507
1508\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001509Return the length of object \var{o}. If the object \var{o} provides
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001510both sequence and mapping protocols, the sequence length is
Fred Drake659ebfa2000-04-03 15:42:13 +00001511returned. On error, \code{-1} is returned. This is the equivalent
1512to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001513\end{cfuncdesc}
1514
1515
1516\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001517Return element of \var{o} corresponding to the object \var{key} or
1518\NULL{} on failure. This is the equivalent of the Python expression
1519\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001520\end{cfuncdesc}
1521
1522
1523\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001524Map the object \var{key} to the value \var{v}.
1525Returns \code{-1} on failure. This is the equivalent
1526of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001527\end{cfuncdesc}
1528
1529
Guido van Rossumd1dbf631999-01-22 20:10:49 +00001530\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001531Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1532failure. This is the equivalent of the Python statement \samp{del
1533\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001534\end{cfuncdesc}
1535
Andrew M. Kuchling8c46b302000-07-13 23:58:16 +00001536\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
1537Derives a file-descriptor from a Python object. If the object
1538is an integer or long integer, its value is returned. If not, the
1539object's \method{fileno()} method is called if it exists; the method
1540must return an integer or long integer, which is returned as the file
1541descriptor value. Returns \code{-1} on failure.
1542\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001543
Fred Drakeefd146c1999-02-15 15:30:45 +00001544\section{Number Protocol \label{number}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001545
1546\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001547Returns \code{1} if the object \var{o} provides numeric protocols, and
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001548false otherwise.
1549This function always succeeds.
1550\end{cfuncdesc}
1551
1552
1553\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001554Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1555failure. This is the equivalent of the Python expression
1556\samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001557\end{cfuncdesc}
1558
1559
1560\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
Fred Drake659ebfa2000-04-03 15:42:13 +00001561Returns the result of subtracting \var{o2} from \var{o1}, or
1562\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001563\samp{\var{o1} - \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001564\end{cfuncdesc}
1565
1566
1567\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001568Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1569failure. This is the equivalent of the Python expression
1570\samp{\var{o1} * \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001571\end{cfuncdesc}
1572
1573
1574\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001575Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1576failure.
1577This is the equivalent of the Python expression \samp{\var{o1} /
1578\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001579\end{cfuncdesc}
1580
1581
1582\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001583Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1584failure. This is the equivalent of the Python expression
Fred Drake659ebfa2000-04-03 15:42:13 +00001585\samp{\var{o1} \%\ \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001586\end{cfuncdesc}
1587
1588
1589\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
Fred Drake53fb7721998-02-16 06:23:20 +00001590See the built-in function \function{divmod()}\bifuncindex{divmod}.
1591Returns \NULL{} on failure. This is the equivalent of the Python
1592expression \samp{divmod(\var{o1}, \var{o2})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001593\end{cfuncdesc}
1594
1595
1596\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
Fred Drake53fb7721998-02-16 06:23:20 +00001597See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1598\NULL{} on failure. This is the equivalent of the Python expression
Fred Drakee058b4f1998-02-16 06:15:35 +00001599\samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
Fred Drake659ebfa2000-04-03 15:42:13 +00001600If \var{o3} is to be ignored, pass \cdata{Py_None} in its place
1601(passing \NULL{} for \var{o3} would cause an illegal memory access).
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001602\end{cfuncdesc}
1603
1604
1605\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001606Returns the negation of \var{o} on success, or \NULL{} on failure.
1607This is the equivalent of the Python expression \samp{-\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001608\end{cfuncdesc}
1609
1610
1611\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001612Returns \var{o} on success, or \NULL{} on failure.
1613This is the equivalent of the Python expression \samp{+\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001614\end{cfuncdesc}
1615
1616
1617\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001618Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1619the equivalent of the Python expression \samp{abs(\var{o})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00001620\bifuncindex{abs}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001621\end{cfuncdesc}
1622
1623
1624\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001625Returns the bitwise negation of \var{o} on success, or \NULL{} on
1626failure. This is the equivalent of the Python expression
1627\samp{\~\var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001628\end{cfuncdesc}
1629
1630
1631\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001632Returns the result of left shifting \var{o1} by \var{o2} on success,
1633or \NULL{} on failure. This is the equivalent of the Python
1634expression \samp{\var{o1} << \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001635\end{cfuncdesc}
1636
1637
1638\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001639Returns the result of right shifting \var{o1} by \var{o2} on success,
1640or \NULL{} on failure. This is the equivalent of the Python
1641expression \samp{\var{o1} >> \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001642\end{cfuncdesc}
1643
1644
1645\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001646Returns the ``bitwise and'' of \var{o2} and \var{o2} on success and
1647\NULL{} on failure. This is the equivalent of the Python expression
1648\samp{\var{o1} \& \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001649\end{cfuncdesc}
1650
1651
1652\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001653Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success,
Fred Drakee058b4f1998-02-16 06:15:35 +00001654or \NULL{} on failure. This is the equivalent of the Python
1655expression \samp{\var{o1} \^{ }\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001656\end{cfuncdesc}
1657
1658\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Fred Drake7740a012000-09-12 20:27:05 +00001659Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
1660\NULL{} on failure. This is the equivalent of the Python expression
1661\samp{\var{o1} | \var{o2}}.
1662\end{cfuncdesc}
1663
1664
1665\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAdd}{PyObject *o1, PyObject *o2}
1666Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on failure.
1667The operation is done \emph{in-place} when \var{o1} supports it. This is the
1668equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1669\end{cfuncdesc}
1670
1671
1672\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceSubtract}{PyObject *o1, PyObject *o2}
1673Returns the result of subtracting \var{o2} from \var{o1}, or
1674\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1675supports it. This is the equivalent of the Python expression \samp{\var{o1}
1676-= \var{o2}}.
1677\end{cfuncdesc}
1678
1679
1680\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceMultiply}{PyObject *o1, PyObject *o2}
1681Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1682failure. The operation is done \emph{in-place} when \var{o1} supports it.
1683This is the equivalent of the Python expression \samp{\var{o1} *= \var{o2}}.
1684\end{cfuncdesc}
1685
1686
1687\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceDivide}{PyObject *o1, PyObject *o2}
1688Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on failure.
1689The operation is done \emph{in-place} when \var{o1} supports it. This is the
1690equivalent of the Python expression \samp{\var{o1} /= \var{o2}}.
1691\end{cfuncdesc}
1692
1693
1694\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRemainder}{PyObject *o1, PyObject *o2}
1695Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1696failure. The operation is done \emph{in-place} when \var{o1} supports it.
1697This is the equivalent of the Python expression \samp{\var{o1} \%= \var{o2}}.
1698\end{cfuncdesc}
1699
1700
1701\begin{cfuncdesc}{PyObject*}{PyNumber_InPlacePower}{PyObject *o1, PyObject *o2, PyObject *o3}
1702See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1703\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1704supports it. This is the equivalent of the Python expression \samp{\var{o1}
1705**= \var{o2}} when o3 is \cdata{Py_None}, or an in-place variant of
1706\samp{pow(\var{o1}, \var{o2}, var{o3})} otherwise. If \var{o3} is to be
1707ignored, pass \cdata{Py_None} in its place (passing \NULL{} for \var{o3}
1708would cause an illegal memory access).
1709\end{cfuncdesc}
1710
1711\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceLshift}{PyObject *o1, PyObject *o2}
1712Returns the result of left shifting \var{o1} by \var{o2} on success, or
1713\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1714supports it. This is the equivalent of the Python expression \samp{\var{o1}
1715<<= \var{o2}}.
1716\end{cfuncdesc}
1717
1718
1719\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRshift}{PyObject *o1, PyObject *o2}
1720Returns the result of right shifting \var{o1} by \var{o2} on success, or
1721\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1722supports it. This is the equivalent of the Python expression \samp{\var{o1}
1723>>= \var{o2}}.
1724\end{cfuncdesc}
1725
1726
1727\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAnd}{PyObject *o1, PyObject *o2}
1728Returns the ``bitwise and'' of \var{o2} and \var{o2} on success
1729and \NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1730supports it. This is the equivalent of the Python expression \samp{\var{o1}
1731\&= \var{o2}}.
1732\end{cfuncdesc}
1733
1734
1735\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceXor}{PyObject *o1, PyObject *o2}
1736Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success, or
1737\NULL{} on failure. The operation is done \emph{in-place} when \var{o1}
1738supports it. This is the equivalent of the Python expression \samp{\var{o1}
1739\^= \var{o2}}.
1740\end{cfuncdesc}
1741
1742\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2}
1743Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or \NULL{}
1744on failure. The operation is done \emph{in-place} when \var{o1} supports
1745it. This is the equivalent of the Python expression \samp{\var{o1} |=
1746\var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001747\end{cfuncdesc}
1748
Fred Drakec0e6c5b2000-09-22 18:17:49 +00001749\begin{cfuncdesc}{int}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001750This function takes the addresses of two variables of type
Fred Drake659ebfa2000-04-03 15:42:13 +00001751\ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} and
1752\code{*\var{p2}} have the same type, increment their reference count
1753and return \code{0} (success). If the objects can be converted to a
1754common numeric type, replace \code{*p1} and \code{*p2} by their
1755converted value (with 'new' reference counts), and return \code{0}.
1756If no conversion is possible, or if some other error occurs, return
1757\code{-1} (failure) and don't increment the reference counts. The
1758call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1759statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
1760\bifuncindex{coerce}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001761\end{cfuncdesc}
1762
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001763\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001764Returns the \var{o} converted to an integer object on success, or
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001765\NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001766expression \samp{int(\var{o})}.\bifuncindex{int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001767\end{cfuncdesc}
1768
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001769\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001770Returns the \var{o} converted to a long integer object on success,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001771or \NULL{} on failure. This is the equivalent of the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00001772expression \samp{long(\var{o})}.\bifuncindex{long}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001773\end{cfuncdesc}
1774
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001775\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001776Returns the \var{o} converted to a float object on success, or
1777\NULL{} on failure. This is the equivalent of the Python expression
1778\samp{float(\var{o})}.\bifuncindex{float}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001779\end{cfuncdesc}
1780
1781
Fred Drakeefd146c1999-02-15 15:30:45 +00001782\section{Sequence Protocol \label{sequence}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001783
1784\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001785Return \code{1} if the object provides sequence protocol, and
1786\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001787\end{cfuncdesc}
1788
Fred Drake659ebfa2000-04-03 15:42:13 +00001789\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
1790Returns the number of objects in sequence \var{o} on success, and
1791\code{-1} on failure. For objects that do not provide sequence
1792protocol, this is equivalent to the Python expression
1793\samp{len(\var{o})}.\bifuncindex{len}
1794\end{cfuncdesc}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001795
1796\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001797Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001798failure. This is the equivalent of the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001799expression \samp{\var{o1} + \var{o2}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001800\end{cfuncdesc}
1801
1802
1803\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Fred Drake659ebfa2000-04-03 15:42:13 +00001804Return the result of repeating sequence object
1805\var{o} \var{count} times, or \NULL{} on failure. This is the
1806equivalent of the Python expression \samp{\var{o} * \var{count}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001807\end{cfuncdesc}
1808
Fred Drake7740a012000-09-12 20:27:05 +00001809\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceConcat}{PyObject *o1, PyObject *o2}
1810Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
1811failure. The operation is done \emph{in-place} when \var{o1} supports it.
1812This is the equivalent of the Python expression \samp{\var{o1} += \var{o2}}.
1813\end{cfuncdesc}
1814
1815
1816\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceRepeat}{PyObject *o, int count}
1817Return the result of repeating sequence object \var{o} \var{count} times, or
1818\NULL{} on failure. The operation is done \emph{in-place} when \var{o}
1819supports it. This is the equivalent of the Python expression \samp{\var{o}
1820*= \var{count}}.
1821\end{cfuncdesc}
1822
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001823
1824\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001825Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
1826is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001827\end{cfuncdesc}
1828
1829
1830\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001831Return the slice of sequence object \var{o} between \var{i1} and
1832\var{i2}, or \NULL{} on failure. This is the equivalent of the Python
1833expression \samp{\var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001834\end{cfuncdesc}
1835
1836
1837\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001838Assign object \var{v} to the \var{i}th element of \var{o}.
1839Returns \code{-1} on failure. This is the equivalent of the Python
1840statement \samp{\var{o}[\var{i}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001841\end{cfuncdesc}
1842
1843\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
Fred Drakee058b4f1998-02-16 06:15:35 +00001844Delete the \var{i}th element of object \var{v}. Returns
1845\code{-1} on failure. This is the equivalent of the Python
1846statement \samp{del \var{o}[\var{i}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001847\end{cfuncdesc}
1848
Fred Drake659ebfa2000-04-03 15:42:13 +00001849\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
1850 int i2, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001851Assign the sequence object \var{v} to the slice in sequence
1852object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
1853the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001854\end{cfuncdesc}
1855
1856\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
Fred Drakee058b4f1998-02-16 06:15:35 +00001857Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
1858Returns \code{-1} on failure. This is the equivalent of the Python
1859statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001860\end{cfuncdesc}
1861
1862\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001863Returns the \var{o} as a tuple on success, and \NULL{} on failure.
Fred Drake659ebfa2000-04-03 15:42:13 +00001864This is equivalent to the Python expression \samp{tuple(\var{o})}.
1865\bifuncindex{tuple}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001866\end{cfuncdesc}
1867
1868\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001869Return the number of occurrences of \var{value} in \var{o}, that is,
1870return the number of keys for which \code{\var{o}[\var{key}] ==
1871\var{value}}. On failure, return \code{-1}. This is equivalent to
1872the Python expression \samp{\var{o}.count(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001873\end{cfuncdesc}
1874
Fred Drake659ebfa2000-04-03 15:42:13 +00001875\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001876Determine if \var{o} contains \var{value}. If an item in \var{o} is
1877equal to \var{value}, return \code{1}, otherwise return \code{0}. On
1878error, return \code{-1}. This is equivalent to the Python expression
1879\samp{\var{value} in \var{o}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001880\end{cfuncdesc}
1881
1882\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Fred Drakee058b4f1998-02-16 06:15:35 +00001883Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
1884\var{value}}. On error, return \code{-1}. This is equivalent to
1885the Python expression \samp{\var{o}.index(\var{value})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001886\end{cfuncdesc}
1887
Fred Drakea8455ab2000-06-16 19:58:42 +00001888\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
1889Return a list object with the same contents as the arbitrary sequence
1890\var{o}. The returned list is guaranteed to be new.
1891\end{cfuncdesc}
1892
1893\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1894Return a tuple object with the same contents as the arbitrary sequence
1895\var{o}. If \var{o} is a tuple, a new reference will be returned,
1896otherwise a tuple will be constructed with the appropriate contents.
1897\end{cfuncdesc}
1898
Fred Drakef39ed671998-02-26 22:01:23 +00001899
Fred Drake81cccb72000-09-12 15:22:05 +00001900\begin{cfuncdesc}{PyObject*}{PySequence_Fast}{PyObject *o, const char *m}
1901Returns the sequence \var{o} as a tuple, unless it is already a
1902tuple or list, in which case \var{o} is returned. Use
1903\cfunction{PySequence_Fast_GET_ITEM()} to access the members of the
1904result. Returns \NULL{} on failure. If the object is not a sequence,
1905raises \exception{TypeError} with \var{m} as the message text.
1906\end{cfuncdesc}
1907
1908\begin{cfuncdesc}{PyObject*}{PySequence_Fast_GET_ITEM}{PyObject *o, int i}
1909Return the \var{i}th element of \var{o}, assuming that \var{o} was
1910returned by \cfunction{PySequence_Fast()}, and that \var{i} is within
1911bounds. The caller is expected to get the length of the sequence by
1912calling \cfunction{PyObject_Size()} on \var{o}, since lists and tuples
1913are guaranteed to always return their true length.
1914\end{cfuncdesc}
1915
1916
Fred Drakeefd146c1999-02-15 15:30:45 +00001917\section{Mapping Protocol \label{mapping}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001918
1919\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001920Return \code{1} if the object provides mapping protocol, and
1921\code{0} otherwise. This function always succeeds.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001922\end{cfuncdesc}
1923
1924
1925\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
Fred Drake659ebfa2000-04-03 15:42:13 +00001926Returns the number of keys in object \var{o} on success, and
1927\code{-1} on failure. For objects that do not provide mapping
1928protocol, this is equivalent to the Python expression
1929\samp{len(\var{o})}.\bifuncindex{len}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001930\end{cfuncdesc}
1931
1932
1933\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001934Remove the mapping for object \var{key} from the object \var{o}.
1935Return \code{-1} on failure. This is equivalent to
1936the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001937\end{cfuncdesc}
1938
1939
1940\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001941Remove the mapping for object \var{key} from the object \var{o}.
1942Return \code{-1} on failure. This is equivalent to
1943the Python statement \samp{del \var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001944\end{cfuncdesc}
1945
1946
1947\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
Fred Drake659ebfa2000-04-03 15:42:13 +00001948On success, return \code{1} if the mapping object has the key
1949\var{key} and \code{0} otherwise. This is equivalent to the Python
1950expression \samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001951This function always succeeds.
1952\end{cfuncdesc}
1953
1954
1955\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001956Return \code{1} if the mapping object has the key \var{key} and
1957\code{0} otherwise. This is equivalent to the Python expression
1958\samp{\var{o}.has_key(\var{key})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001959This function always succeeds.
1960\end{cfuncdesc}
1961
1962
1963\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001964On success, return a list of the keys in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001965failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001966expression \samp{\var{o}.keys()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001967\end{cfuncdesc}
1968
1969
1970\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001971On success, return a list of the values in object \var{o}. On
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001972failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001973expression \samp{\var{o}.values()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001974\end{cfuncdesc}
1975
1976
1977\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00001978On success, return a list of the items in object \var{o}, where
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001979each item is a tuple containing a key-value pair. On
1980failure, return \NULL{}. This is equivalent to the Python
Fred Drakee058b4f1998-02-16 06:15:35 +00001981expression \samp{\var{o}.items()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001982\end{cfuncdesc}
1983
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001984
1985\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00001986Return element of \var{o} corresponding to the object \var{key} or
1987\NULL{} on failure. This is the equivalent of the Python expression
1988\samp{\var{o}[\var{key}]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001989\end{cfuncdesc}
1990
Guido van Rossum0a0f11b1998-10-16 17:43:53 +00001991\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
Fred Drakee058b4f1998-02-16 06:15:35 +00001992Map the object \var{key} to the value \var{v} in object \var{o}.
1993Returns \code{-1} on failure. This is the equivalent of the Python
1994statement \samp{\var{o}[\var{key}] = \var{v}}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001995\end{cfuncdesc}
1996
1997
Fred Drakeefd146c1999-02-15 15:30:45 +00001998\chapter{Concrete Objects Layer \label{concrete}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001999
2000The functions in this chapter are specific to certain Python object
2001types. Passing them an object of the wrong type is not a good idea;
2002if you receive an object from a Python program and you are not sure
2003that it has the right type, you must perform a type check first;
Fred Drake659ebfa2000-04-03 15:42:13 +00002004for example. to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00002005\cfunction{PyDict_Check()}. The chapter is structured like the
2006``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002007
Fred Drake89024422000-10-23 16:00:54 +00002008\strong{Warning:}
2009While the functions described in this chapter carefully check the type
2010of the objects which are passed in, many of them do not check for
2011\NULL{} being passed instead of a valid object. Allowing \NULL{} to
2012be passed in can cause memory access violations and immediate
2013termination of the interpreter.
2014
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002015
Fred Drakeefd146c1999-02-15 15:30:45 +00002016\section{Fundamental Objects \label{fundamental}}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002017
Fred Drakee5bf8b21998-02-12 21:22:28 +00002018This section describes Python type objects and the singleton object
2019\code{None}.
2020
2021
Fred Drakeefd146c1999-02-15 15:30:45 +00002022\subsection{Type Objects \label{typeObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002023
Fred Drake659ebfa2000-04-03 15:42:13 +00002024\obindex{type}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002025\begin{ctypedesc}{PyTypeObject}
Fred Drake659ebfa2000-04-03 15:42:13 +00002026The C structure of the objects used to describe built-in types.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002027\end{ctypedesc}
2028
Fred Drake659ebfa2000-04-03 15:42:13 +00002029\begin{cvardesc}{PyObject*}{PyType_Type}
Fred Drakeefd146c1999-02-15 15:30:45 +00002030This is the type object for type objects; it is the same object as
2031\code{types.TypeType} in the Python layer.
Fred Drake659ebfa2000-04-03 15:42:13 +00002032\withsubitem{(in module types)}{\ttindex{TypeType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002033\end{cvardesc}
2034
Fred Drake659ebfa2000-04-03 15:42:13 +00002035\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
2036Returns true is the object \var{o} is a type object.
2037\end{cfuncdesc}
2038
2039\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
2040Returns true if the type object \var{o} sets the feature
2041\var{feature}. Type features are denoted by single bit flags. The
2042only defined feature flag is \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER},
2043described in section \ref{buffer-structs}.
2044\end{cfuncdesc}
2045
Fred Drakee5bf8b21998-02-12 21:22:28 +00002046
Fred Drakeefd146c1999-02-15 15:30:45 +00002047\subsection{The None Object \label{noneObject}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002048
Fred Drake659ebfa2000-04-03 15:42:13 +00002049\obindex{None@\texttt{None}}
2050Note that the \ctype{PyTypeObject} for \code{None} is not directly
2051exposed in the Python/C API. Since \code{None} is a singleton,
2052testing for object identity (using \samp{==} in C) is sufficient.
2053There is no \cfunction{PyNone_Check()} function for the same reason.
2054
2055\begin{cvardesc}{PyObject*}{Py_None}
Guido van Rossum44475131998-04-21 15:30:01 +00002056The Python \code{None} object, denoting lack of value. This object has
2057no methods.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002058\end{cvardesc}
2059
2060
Fred Drakeefd146c1999-02-15 15:30:45 +00002061\section{Sequence Objects \label{sequenceObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002062
Fred Drake659ebfa2000-04-03 15:42:13 +00002063\obindex{sequence}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002064Generic operations on sequence objects were discussed in the previous
2065chapter; this section deals with the specific kinds of sequence
2066objects that are intrinsic to the Python language.
2067
2068
Fred Drakeefd146c1999-02-15 15:30:45 +00002069\subsection{String Objects \label{stringObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002070
Fred Drake89024422000-10-23 16:00:54 +00002071These functions raise \exception{TypeError} when expecting a string
2072parameter and are called with a non-string parameter.
2073
Fred Drake659ebfa2000-04-03 15:42:13 +00002074\obindex{string}
Fred Drakee5bf8b21998-02-12 21:22:28 +00002075\begin{ctypedesc}{PyStringObject}
Fred Drakef8830d11998-04-23 14:06:01 +00002076This subtype of \ctype{PyObject} represents a Python string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002077\end{ctypedesc}
2078
2079\begin{cvardesc}{PyTypeObject}{PyString_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00002080This instance of \ctype{PyTypeObject} represents the Python string
2081type; it is the same object as \code{types.TypeType} in the Python
2082layer.\withsubitem{(in module types)}{\ttindex{StringType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00002083\end{cvardesc}
2084
2085\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002086Returns true if the object \var{o} is a string object.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002087\end{cfuncdesc}
2088
Fred Drakec6fa34e1998-04-02 06:47:24 +00002089\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002090Returns a new string object with the value \var{v} on success, and
2091\NULL{} on failure.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002092\end{cfuncdesc}
2093
Fred Drake659ebfa2000-04-03 15:42:13 +00002094\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
2095 int len}
2096Returns a new string object with the value \var{v} and length
2097\var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
2098the contents of the string are uninitialized.
2099\end{cfuncdesc}
2100
Fred Drakec6fa34e1998-04-02 06:47:24 +00002101\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002102Returns the length of the string in string object \var{string}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002103\end{cfuncdesc}
2104
Fred Drake659ebfa2000-04-03 15:42:13 +00002105\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
Fred Drake5d644212000-10-07 12:31:50 +00002106Macro form of \cfunction{PyString_Size()} but without error
Fred Drake659ebfa2000-04-03 15:42:13 +00002107checking.
2108\end{cfuncdesc}
2109
Fred Drakec6fa34e1998-04-02 06:47:24 +00002110\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
Fred Drake659ebfa2000-04-03 15:42:13 +00002111Returns a null-terminated representation of the contents of
2112\var{string}. The pointer refers to the internal buffer of
Fred Drake89024422000-10-23 16:00:54 +00002113\var{string}, not a copy. The data must not be modified in any way,
2114unless the string was just created using
2115\code{PyString_FromStringAndSize(NULL, \var{size})}.
2116It must not be deallocated.
Fred Drake659ebfa2000-04-03 15:42:13 +00002117\end{cfuncdesc}
2118
2119\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
2120Macro form of \cfunction{PyString_AsString()} but without error
2121checking.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002122\end{cfuncdesc}
2123
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002124\begin{cfuncdesc}{int}{PyString_AsStringAndSize}{PyObject *obj,
2125 char **buffer,
2126 int *length}
2127Returns a null-terminated representation of the contents of the object
2128\var{obj} through the output variables \var{buffer} and \var{length}.
2129
2130The function accepts both string and Unicode objects as input. For
2131Unicode objects it returns the default encoded version of the object.
2132If \var{length} is set to \NULL{}, the resulting buffer may not contain
2133null characters; if it does, the function returns -1 and a
2134TypeError is raised.
2135
2136The buffer refers to an internal string buffer of \var{obj}, not a
Fred Drake89024422000-10-23 16:00:54 +00002137copy. The data must not be modified in any way, unless the string was
2138just created using \code{PyString_FromStringAndSize(NULL,
2139\var{size})}. It must not be deallocated.
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +00002140\end{cfuncdesc}
2141
Fred Drakec6fa34e1998-04-02 06:47:24 +00002142\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
2143 PyObject *newpart}
Fred Drake66b989c1999-02-15 20:15:39 +00002144Creates a new string object in \var{*string} containing the
Fred Drakeddc6c272000-03-31 18:22:38 +00002145contents of \var{newpart} appended to \var{string}; the caller will
2146own the new reference. The reference to the old value of \var{string}
2147will be stolen. If the new string
Fred Drake66b989c1999-02-15 20:15:39 +00002148cannot be created, the old reference to \var{string} will still be
2149discarded and the value of \var{*string} will be set to
2150\NULL{}; the appropriate exception will be set.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002151\end{cfuncdesc}
2152
2153\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
2154 PyObject *newpart}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00002155Creates a new string object in \var{*string} containing the contents
Guido van Rossum44475131998-04-21 15:30:01 +00002156of \var{newpart} appended to \var{string}. This version decrements
2157the reference count of \var{newpart}.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002158\end{cfuncdesc}
2159
2160\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
Guido van Rossum44475131998-04-21 15:30:01 +00002161A way to resize a string object even though it is ``immutable''.
2162Only use this to build up a brand new string object; don't use this if
2163the string may already be known in other parts of the code.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002164\end{cfuncdesc}
2165
2166\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
2167 PyObject *args}
Guido van Rossum44475131998-04-21 15:30:01 +00002168Returns a new string object from \var{format} and \var{args}. Analogous
Fred Drake659ebfa2000-04-03 15:42:13 +00002169to \code{\var{format} \%\ \var{args}}. The \var{args} argument must be
Guido van Rossum44475131998-04-21 15:30:01 +00002170a tuple.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002171\end{cfuncdesc}
2172
2173\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
Guido van Rossum44475131998-04-21 15:30:01 +00002174Intern the argument \var{*string} in place. The argument must be the
2175address of a pointer variable pointing to a Python string object.
2176If there is an existing interned string that is the same as
2177\var{*string}, it sets \var{*string} to it (decrementing the reference
2178count of the old string object and incrementing the reference count of
2179the interned string object), otherwise it leaves \var{*string} alone
2180and interns it (incrementing its reference count). (Clarification:
2181even though there is a lot of talk about reference counts, think of
Fred Drakef8830d11998-04-23 14:06:01 +00002182this function as reference-count-neutral; you own the object after
2183the call if and only if you owned it before the call.)
Fred Drakec6fa34e1998-04-02 06:47:24 +00002184\end{cfuncdesc}
2185
2186\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
Fred Drakef8830d11998-04-23 14:06:01 +00002187A combination of \cfunction{PyString_FromString()} and
2188\cfunction{PyString_InternInPlace()}, returning either a new string object
Guido van Rossum44475131998-04-21 15:30:01 +00002189that has been interned, or a new (``owned'') reference to an earlier
2190interned string object with the same value.
Fred Drakec6fa34e1998-04-02 06:47:24 +00002191\end{cfuncdesc}
2192
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002193\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
2194 int size,
2195 const char *encoding,
2196 const char *errors}
2197Create a string object by decoding \var{size} bytes of the encoded
2198buffer \var{s}. \var{encoding} and \var{errors} have the same meaning
2199as the parameters of the same name in the unicode() builtin
2200function. The codec to be used is looked up using the Python codec
2201registry. Returns \NULL{} in case an exception was raised by the
2202codec.
2203\end{cfuncdesc}
2204
2205\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const Py_UNICODE *s,
2206 int size,
2207 const char *encoding,
2208 const char *errors}
2209Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2210Python string object. \var{encoding} and \var{errors} have the same
2211meaning as the parameters of the same name in the string .encode()
2212method. The codec to be used is looked up using the Python codec
2213registry. Returns \NULL{} in case an exception was raised by the
2214codec.
2215\end{cfuncdesc}
2216
2217\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedString}{PyObject *unicode,
2218 const char *encoding,
2219 const char *errors}
2220Encodes a string object and returns the result as Python string
2221object. \var{encoding} and \var{errors} have the same meaning as the
2222parameters of the same name in the string .encode() method. The codec
2223to be used is looked up using the Python codec registry. Returns
2224\NULL{} in case an exception was raised by the codec.
2225\end{cfuncdesc}
2226
Fred Drakee5bf8b21998-02-12 21:22:28 +00002227
Fred Drakea4cd2612000-04-06 14:10:29 +00002228\subsection{Unicode Objects \label{unicodeObjects}}
2229\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
2230
2231%--- Unicode Type -------------------------------------------------------
2232
2233These are the basic Unicode object types used for the Unicode
2234implementation in Python:
2235
2236\begin{ctypedesc}{Py_UNICODE}
2237This type represents a 16-bit unsigned storage type which is used by
2238Python internally as basis for holding Unicode ordinals. On platforms
2239where \ctype{wchar_t} is available and also has 16-bits,
2240\ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
2241native platform compatibility. On all other platforms,
2242\ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
2243\end{ctypedesc}
2244
2245\begin{ctypedesc}{PyUnicodeObject}
2246This subtype of \ctype{PyObject} represents a Python Unicode object.
2247\end{ctypedesc}
2248
2249\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
2250This instance of \ctype{PyTypeObject} represents the Python Unicode type.
2251\end{cvardesc}
2252
2253%--- These are really C macros... is there a macrodesc TeX macro ?
2254
2255The following APIs are really C macros and can be used to do fast
2256checks and to access internal read-only data of Unicode objects:
2257
2258\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
2259Returns true if the object \var{o} is a Unicode object.
2260\end{cfuncdesc}
2261
2262\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
2263Returns the size of the object. o has to be a
2264PyUnicodeObject (not checked).
2265\end{cfuncdesc}
2266
2267\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
2268Returns the size of the object's internal buffer in bytes. o has to be
2269a PyUnicodeObject (not checked).
2270\end{cfuncdesc}
2271
Fred Drake992fe5a2000-06-16 21:04:15 +00002272\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002273Returns a pointer to the internal Py_UNICODE buffer of the object. o
2274has to be a PyUnicodeObject (not checked).
2275\end{cfuncdesc}
2276
Fred Drake992fe5a2000-06-16 21:04:15 +00002277\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
Fred Drakea4cd2612000-04-06 14:10:29 +00002278Returns a (const char *) pointer to the internal buffer of the object.
2279o has to be a PyUnicodeObject (not checked).
2280\end{cfuncdesc}
2281
2282% --- Unicode character properties ---------------------------------------
2283
2284Unicode provides many different character properties. The most often
2285needed ones are available through these macros which are mapped to C
2286functions depending on the Python configuration.
2287
2288\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
2289Returns 1/0 depending on whether \var{ch} is a whitespace character.
2290\end{cfuncdesc}
2291
2292\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
2293Returns 1/0 depending on whether \var{ch} is a lowercase character.
2294\end{cfuncdesc}
2295
2296\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
Fred Drakeae96aab2000-07-03 13:38:10 +00002297Returns 1/0 depending on whether \var{ch} is an uppercase character.
Fred Drakea4cd2612000-04-06 14:10:29 +00002298\end{cfuncdesc}
2299
2300\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
2301Returns 1/0 depending on whether \var{ch} is a titlecase character.
2302\end{cfuncdesc}
2303
2304\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
2305Returns 1/0 depending on whether \var{ch} is a linebreak character.
2306\end{cfuncdesc}
2307
2308\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
2309Returns 1/0 depending on whether \var{ch} is a decimal character.
2310\end{cfuncdesc}
2311
2312\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
2313Returns 1/0 depending on whether \var{ch} is a digit character.
2314\end{cfuncdesc}
2315
2316\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
2317Returns 1/0 depending on whether \var{ch} is a numeric character.
2318\end{cfuncdesc}
2319
Fred Drakeae96aab2000-07-03 13:38:10 +00002320\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
2321Returns 1/0 depending on whether \var{ch} is an alphabetic character.
2322\end{cfuncdesc}
2323
2324\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
2325Returns 1/0 depending on whether \var{ch} is an alphanumeric character.
2326\end{cfuncdesc}
2327
Fred Drakea4cd2612000-04-06 14:10:29 +00002328These APIs can be used for fast direct character conversions:
2329
2330\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
2331Returns the character \var{ch} converted to lower case.
2332\end{cfuncdesc}
2333
2334\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
2335Returns the character \var{ch} converted to upper case.
2336\end{cfuncdesc}
2337
2338\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
2339Returns the character \var{ch} converted to title case.
2340\end{cfuncdesc}
2341
2342\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
2343Returns the character \var{ch} converted to a decimal positive integer.
2344Returns -1 in case this is not possible. Does not raise exceptions.
2345\end{cfuncdesc}
2346
2347\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
2348Returns the character \var{ch} converted to a single digit integer.
2349Returns -1 in case this is not possible. Does not raise exceptions.
2350\end{cfuncdesc}
2351
2352\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
2353Returns the character \var{ch} converted to a (positive) double.
2354Returns -1.0 in case this is not possible. Does not raise exceptions.
2355\end{cfuncdesc}
2356
2357% --- Plain Py_UNICODE ---------------------------------------------------
2358
2359To create Unicode objects and access their basic sequence properties,
2360use these APIs:
2361
2362\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
2363 int size}
2364
2365Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
2366given size. \var{u} may be \NULL{} which causes the contents to be
2367undefined. It is the user's responsibility to fill in the needed data.
2368The buffer is copied into the new object.
2369\end{cfuncdesc}
2370
Fred Drake1d158692000-06-18 05:21:21 +00002371\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002372Return a read-only pointer to the Unicode object's internal
2373\ctype{Py_UNICODE} buffer.
2374\end{cfuncdesc}
2375
2376\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
2377Return the length of the Unicode object.
2378\end{cfuncdesc}
2379
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002380\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
2381 const char *encoding,
2382 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002383
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002384Coerce an encoded object obj to an Unicode object and return a
2385reference with incremented refcount.
Fred Drakea4cd2612000-04-06 14:10:29 +00002386
2387Coercion is done in the following way:
2388\begin{enumerate}
2389\item Unicode objects are passed back as-is with incremented
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002390 refcount. Note: these cannot be decoded; passing a non-NULL
2391 value for encoding will result in a TypeError.
Fred Drakea4cd2612000-04-06 14:10:29 +00002392
2393\item String and other char buffer compatible objects are decoded
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002394 according to the given encoding and using the error handling
2395 defined by errors. Both can be NULL to have the interface use
2396 the default values (see the next section for details).
Fred Drakea4cd2612000-04-06 14:10:29 +00002397
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002398\item All other objects cause an exception.
Fred Drakea4cd2612000-04-06 14:10:29 +00002399\end{enumerate}
2400The API returns NULL in case of an error. The caller is responsible
2401for decref'ing the returned objects.
2402\end{cfuncdesc}
2403
Marc-André Lemburg5a20b212000-07-07 15:47:06 +00002404\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
2405
2406Shortcut for PyUnicode_FromEncodedObject(obj, NULL, ``strict'')
2407which is used throughout the interpreter whenever coercion to
2408Unicode is needed.
2409\end{cfuncdesc}
2410
Fred Drakea4cd2612000-04-06 14:10:29 +00002411% --- wchar_t support for platforms which support it ---------------------
2412
2413If the platform supports \ctype{wchar_t} and provides a header file
2414wchar.h, Python can interface directly to this type using the
2415following functions. Support is optimized if Python's own
2416\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
2417
2418\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
2419 int size}
2420Create a Unicode Object from the \ctype{whcar_t} buffer \var{w} of the
2421given size. Returns \NULL{} on failure.
2422\end{cfuncdesc}
2423
2424\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
2425 wchar_t *w,
2426 int size}
Fred Drakea4cd2612000-04-06 14:10:29 +00002427Copies the Unicode Object contents into the \ctype{whcar_t} buffer
2428\var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
2429Returns the number of \ctype{whcar_t} characters copied or -1 in case
2430of an error.
2431\end{cfuncdesc}
2432
2433
2434\subsubsection{Builtin Codecs \label{builtinCodecs}}
2435
2436Python provides a set of builtin codecs which are written in C
2437for speed. All of these codecs are directly usable via the
2438following functions.
2439
2440Many of the following APIs take two arguments encoding and
2441errors. These parameters encoding and errors have the same semantics
2442as the ones of the builtin unicode() Unicode object constructor.
2443
2444Setting encoding to NULL causes the default encoding to be used which
2445is UTF-8.
2446
2447Error handling is set by errors which may also be set to NULL meaning
2448to use the default handling defined for the codec. Default error
2449handling for all builtin codecs is ``strict'' (ValueErrors are raised).
2450
2451The codecs all use a similar interface. Only deviation from the
2452following generic ones are documented for simplicity.
2453
2454% --- Generic Codecs -----------------------------------------------------
2455
2456These are the generic codec APIs:
2457
2458\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
2459 int size,
2460 const char *encoding,
2461 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002462Create a Unicode object by decoding \var{size} bytes of the encoded
2463string \var{s}. \var{encoding} and \var{errors} have the same meaning
2464as the parameters of the same name in the unicode() builtin
2465function. The codec to be used is looked up using the Python codec
2466registry. Returns \NULL{} in case an exception was raised by the
2467codec.
2468\end{cfuncdesc}
2469
2470\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
2471 int size,
2472 const char *encoding,
2473 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002474Encodes the \ctype{Py_UNICODE} buffer of the given size and returns a
2475Python string object. \var{encoding} and \var{errors} have the same
2476meaning as the parameters of the same name in the Unicode .encode()
2477method. The codec to be used is looked up using the Python codec
2478registry. Returns \NULL{} in case an exception was raised by the
2479codec.
2480\end{cfuncdesc}
2481
2482\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
2483 const char *encoding,
2484 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002485Encodes a Unicode object and returns the result as Python string
2486object. \var{encoding} and \var{errors} have the same meaning as the
2487parameters of the same name in the Unicode .encode() method. The codec
2488to be used is looked up using the Python codec registry. Returns
2489\NULL{} in case an exception was raised by the codec.
2490\end{cfuncdesc}
2491
2492% --- UTF-8 Codecs -------------------------------------------------------
2493
2494These are the UTF-8 codec APIs:
2495
2496\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
2497 int size,
2498 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002499Creates a Unicode object by decoding \var{size} bytes of the UTF-8
2500encoded string \var{s}. Returns \NULL{} in case an exception was
2501raised by the codec.
2502\end{cfuncdesc}
2503
2504\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
2505 int size,
2506 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002507Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
2508and returns a Python string object. Returns \NULL{} in case an
2509exception was raised by the codec.
2510\end{cfuncdesc}
2511
2512\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002513Encodes a Unicode objects using UTF-8 and returns the result as Python
2514string object. Error handling is ``strict''. Returns
2515\NULL{} in case an exception was raised by the codec.
2516\end{cfuncdesc}
2517
2518% --- UTF-16 Codecs ------------------------------------------------------ */
2519
2520These are the UTF-16 codec APIs:
2521
2522\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
2523 int size,
2524 const char *errors,
2525 int *byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002526Decodes \var{length} bytes from a UTF-16 encoded buffer string and
2527returns the corresponding Unicode object.
2528
2529\var{errors} (if non-NULL) defines the error handling. It defaults
2530to ``strict''.
2531
2532If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
2533the given byte order:
2534
2535\begin{verbatim}
2536 *byteorder == -1: little endian
2537 *byteorder == 0: native order
2538 *byteorder == 1: big endian
2539\end{verbatim}
2540
2541and then switches according to all byte order marks (BOM) it finds in
2542the input data. BOM marks are not copied into the resulting Unicode
2543string. After completion, \var{*byteorder} is set to the current byte
2544order at the end of input data.
2545
2546If \var{byteorder} is \NULL{}, the codec starts in native order mode.
2547
2548Returns \NULL{} in case an exception was raised by the codec.
2549\end{cfuncdesc}
2550
2551\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
2552 int size,
2553 const char *errors,
2554 int byteorder}
Fred Drakea4cd2612000-04-06 14:10:29 +00002555Returns a Python string object holding the UTF-16 encoded value of the
2556Unicode data in \var{s}.
2557
Fred Drakea8455ab2000-06-16 19:58:42 +00002558If \var{byteorder} is not \code{0}, output is written according to the
Fred Drakea4cd2612000-04-06 14:10:29 +00002559following byte order:
2560
2561\begin{verbatim}
2562 byteorder == -1: little endian
2563 byteorder == 0: native byte order (writes a BOM mark)
2564 byteorder == 1: big endian
2565\end{verbatim}
2566
Fred Drakea8455ab2000-06-16 19:58:42 +00002567If byteorder is \code{0}, the output string will always start with the
Fred Drakea4cd2612000-04-06 14:10:29 +00002568Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is
2569prepended.
2570
2571Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
2572reduced to UCS-2. This trick makes it possible to add full UTF-16
2573capabilities at a later point without comprimising the APIs.
2574
2575Returns \NULL{} in case an exception was raised by the codec.
2576\end{cfuncdesc}
2577
2578\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002579Returns a Python string using the UTF-16 encoding in native byte
2580order. The string always starts with a BOM mark. Error handling is
2581``strict''. Returns \NULL{} in case an exception was raised by the
2582codec.
2583\end{cfuncdesc}
2584
2585% --- Unicode-Escape Codecs ----------------------------------------------
2586
2587These are the ``Unicode Esacpe'' codec APIs:
2588
2589\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
2590 int size,
2591 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002592Creates a Unicode object by decoding \var{size} bytes of the Unicode-Esacpe
2593encoded string \var{s}. Returns \NULL{} in case an exception was
2594raised by the codec.
2595\end{cfuncdesc}
2596
2597\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
2598 int size,
2599 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002600Encodes the \ctype{Py_UNICODE} buffer of the given size using Unicode-Escape
2601and returns a Python string object. Returns \NULL{} in case an
2602exception was raised by the codec.
2603\end{cfuncdesc}
2604
2605\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002606Encodes a Unicode objects using Unicode-Escape and returns the result
2607as Python string object. Error handling is ``strict''. Returns
2608\NULL{} in case an exception was raised by the codec.
2609\end{cfuncdesc}
2610
2611% --- Raw-Unicode-Escape Codecs ------------------------------------------
2612
2613These are the ``Raw Unicode Esacpe'' codec APIs:
2614
2615\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
2616 int size,
2617 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002618Creates a Unicode object by decoding \var{size} bytes of the Raw-Unicode-Esacpe
2619encoded string \var{s}. Returns \NULL{} in case an exception was
2620raised by the codec.
2621\end{cfuncdesc}
2622
2623\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
2624 int size,
2625 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002626Encodes the \ctype{Py_UNICODE} buffer of the given size using Raw-Unicode-Escape
2627and returns a Python string object. Returns \NULL{} in case an
2628exception was raised by the codec.
2629\end{cfuncdesc}
2630
2631\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002632Encodes a Unicode objects using Raw-Unicode-Escape and returns the result
2633as Python string object. Error handling is ``strict''. Returns
2634\NULL{} in case an exception was raised by the codec.
2635\end{cfuncdesc}
2636
2637% --- Latin-1 Codecs -----------------------------------------------------
2638
2639These are the Latin-1 codec APIs:
2640
2641Latin-1 corresponds to the first 256 Unicode ordinals and only these
2642are accepted by the codecs during encoding.
2643
2644\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002645 int size,
2646 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002647Creates a Unicode object by decoding \var{size} bytes of the Latin-1
2648encoded string \var{s}. Returns \NULL{} in case an exception was
2649raised by the codec.
2650\end{cfuncdesc}
2651
2652\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002653 int size,
2654 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002655Encodes the \ctype{Py_UNICODE} buffer of the given size using Latin-1
2656and returns a Python string object. Returns \NULL{} in case an
2657exception was raised by the codec.
2658\end{cfuncdesc}
2659
2660\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002661Encodes a Unicode objects using Latin-1 and returns the result as
2662Python string object. Error handling is ``strict''. Returns
2663\NULL{} in case an exception was raised by the codec.
2664\end{cfuncdesc}
2665
2666% --- ASCII Codecs -------------------------------------------------------
2667
Fred Drake1d158692000-06-18 05:21:21 +00002668These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
2669accepted. All other codes generate errors.
Fred Drakea4cd2612000-04-06 14:10:29 +00002670
2671\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
Fred Drake1d158692000-06-18 05:21:21 +00002672 int size,
2673 const char *errors}
2674Creates a Unicode object by decoding \var{size} bytes of the
2675\ASCII{} encoded string \var{s}. Returns \NULL{} in case an exception
2676was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002677\end{cfuncdesc}
2678
2679\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
Fred Drake1d158692000-06-18 05:21:21 +00002680 int size,
2681 const char *errors}
2682Encodes the \ctype{Py_UNICODE} buffer of the given size using
2683\ASCII{} and returns a Python string object. Returns \NULL{} in case
2684an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002685\end{cfuncdesc}
2686
2687\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
Fred Drake1d158692000-06-18 05:21:21 +00002688Encodes a Unicode objects using \ASCII{} and returns the result as Python
Fred Drakea4cd2612000-04-06 14:10:29 +00002689string object. Error handling is ``strict''. Returns
2690\NULL{} in case an exception was raised by the codec.
2691\end{cfuncdesc}
2692
2693% --- Character Map Codecs -----------------------------------------------
2694
2695These are the mapping codec APIs:
2696
2697This codec is special in that it can be used to implement many
2698different codecs (and this is in fact what was done to obtain most of
2699the standard codecs included in the \module{encodings} package). The
2700codec uses mapping to encode and decode characters.
2701
2702Decoding mappings must map single string characters to single Unicode
2703characters, integers (which are then interpreted as Unicode ordinals)
2704or None (meaning "undefined mapping" and causing an error).
2705
2706Encoding mappings must map single Unicode characters to single string
2707characters, integers (which are then interpreted as Latin-1 ordinals)
2708or None (meaning "undefined mapping" and causing an error).
2709
2710The mapping objects provided must only support the __getitem__ mapping
2711interface.
2712
2713If a character lookup fails with a LookupError, the character is
2714copied as-is meaning that its ordinal value will be interpreted as
2715Unicode or Latin-1 ordinal resp. Because of this, mappings only need
2716to contain those mappings which map characters to different code
2717points.
2718
2719\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
2720 int size,
2721 PyObject *mapping,
2722 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002723Creates a Unicode object by decoding \var{size} bytes of the encoded
2724string \var{s} using the given \var{mapping} object. Returns \NULL{}
2725in case an exception was raised by the codec.
2726\end{cfuncdesc}
2727
2728\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
2729 int size,
2730 PyObject *mapping,
2731 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002732Encodes the \ctype{Py_UNICODE} buffer of the given size using the
2733given \var{mapping} object and returns a Python string object.
2734Returns \NULL{} in case an exception was raised by the codec.
2735\end{cfuncdesc}
2736
2737\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
2738 PyObject *mapping}
Fred Drakea4cd2612000-04-06 14:10:29 +00002739Encodes a Unicode objects using the given \var{mapping} object and
2740returns the result as Python string object. Error handling is
2741``strict''. Returns \NULL{} in case an exception was raised by the
2742codec.
2743\end{cfuncdesc}
2744
2745The following codec API is special in that maps Unicode to Unicode.
2746
2747\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
2748 int size,
2749 PyObject *table,
2750 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002751Translates a \ctype{Py_UNICODE} buffer of the given length by applying
2752a character mapping \var{table} to it and returns the resulting
Fred Drake1d158692000-06-18 05:21:21 +00002753Unicode object. Returns \NULL{} when an exception was raised by the
2754codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002755
2756The \var{mapping} table must map Unicode ordinal integers to Unicode
2757ordinal integers or None (causing deletion of the character).
2758
2759Mapping tables must only provide the __getitem__ interface,
2760e.g. dictionaries or sequences. Unmapped character ordinals (ones
2761which cause a LookupError) are left untouched and are copied as-is.
Fred Drakea4cd2612000-04-06 14:10:29 +00002762\end{cfuncdesc}
2763
2764% --- MBCS codecs for Windows --------------------------------------------
2765
Fred Drake1d158692000-06-18 05:21:21 +00002766These are the MBCS codec APIs. They are currently only available on
Fred Drakea4cd2612000-04-06 14:10:29 +00002767Windows and use the Win32 MBCS converters to implement the
Fred Drake1d158692000-06-18 05:21:21 +00002768conversions. Note that MBCS (or DBCS) is a class of encodings, not
2769just one. The target encoding is defined by the user settings on the
2770machine running the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002771
2772\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
2773 int size,
2774 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002775Creates a Unicode object by decoding \var{size} bytes of the MBCS
Fred Drake1d158692000-06-18 05:21:21 +00002776encoded string \var{s}. Returns \NULL{} in case an exception was
Fred Drakea4cd2612000-04-06 14:10:29 +00002777raised by the codec.
2778\end{cfuncdesc}
2779
2780\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
2781 int size,
2782 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002783Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
2784and returns a Python string object. Returns \NULL{} in case an
2785exception was raised by the codec.
2786\end{cfuncdesc}
2787
2788\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
Fred Drakea4cd2612000-04-06 14:10:29 +00002789Encodes a Unicode objects using MBCS and returns the result as Python
Fred Drake1d158692000-06-18 05:21:21 +00002790string object. Error handling is ``strict''. Returns \NULL{} in case
2791an exception was raised by the codec.
Fred Drakea4cd2612000-04-06 14:10:29 +00002792\end{cfuncdesc}
2793
2794% --- Methods & Slots ----------------------------------------------------
2795
2796\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
2797
2798The following APIs are capable of handling Unicode objects and strings
2799on input (we refer to them as strings in the descriptions) and return
2800Unicode objects or integers as apporpriate.
2801
2802They all return \NULL{} or -1 in case an exception occurrs.
2803
2804\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
2805 PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002806Concat two strings giving a new Unicode string.
2807\end{cfuncdesc}
2808
2809\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
2810 PyObject *sep,
2811 int maxsplit}
Fred Drakea4cd2612000-04-06 14:10:29 +00002812Split a string giving a list of Unicode strings.
2813
2814If sep is NULL, splitting will be done at all whitespace
2815substrings. Otherwise, splits occur at the given separator.
2816
2817At most maxsplit splits will be done. If negative, no limit is set.
2818
2819Separators are not included in the resulting list.
2820\end{cfuncdesc}
2821
2822\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
2823 int maxsplit}
Fred Drake1d158692000-06-18 05:21:21 +00002824Split a Unicode string at line breaks, returning a list of Unicode
2825strings. CRLF is considered to be one line break. The Line break
2826characters are not included in the resulting strings.
Fred Drakea4cd2612000-04-06 14:10:29 +00002827\end{cfuncdesc}
2828
2829\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
2830 PyObject *table,
2831 const char *errors}
Fred Drakea4cd2612000-04-06 14:10:29 +00002832Translate a string by applying a character mapping table to it and
2833return the resulting Unicode object.
2834
2835The mapping table must map Unicode ordinal integers to Unicode ordinal
2836integers or None (causing deletion of the character).
2837
2838Mapping tables must only provide the __getitem__ interface,
2839e.g. dictionaries or sequences. Unmapped character ordinals (ones
2840which cause a LookupError) are left untouched and are copied as-is.
2841
2842\var{errors} has the usual meaning for codecs. It may be \NULL{}
2843which indicates to use the default error handling.
Fred Drakea4cd2612000-04-06 14:10:29 +00002844\end{cfuncdesc}
2845
2846\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
2847 PyObject *seq}
Fred Drakea4cd2612000-04-06 14:10:29 +00002848Join a sequence of strings using the given separator and return
2849the resulting Unicode string.
2850\end{cfuncdesc}
2851
2852\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
2853 PyObject *substr,
2854 int start,
2855 int end,
2856 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002857Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
2858the given tail end (\var{direction} == -1 means to do a prefix match,
2859\var{direction} == 1 a suffix match), 0 otherwise.
2860\end{cfuncdesc}
2861
2862\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
2863 PyObject *substr,
2864 int start,
2865 int end,
2866 int direction}
Fred Drakea4cd2612000-04-06 14:10:29 +00002867Return the first position of \var{substr} in
2868\var{str}[\var{start}:\var{end}] using the given \var{direction}
2869(\var{direction} == 1 means to do a forward search,
2870\var{direction} == -1 a backward search), 0 otherwise.
2871\end{cfuncdesc}
2872
2873\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
2874 PyObject *substr,
2875 int start,
2876 int end}
Fred Drakea4cd2612000-04-06 14:10:29 +00002877Count the number of occurrences of \var{substr} in
2878\var{str}[\var{start}:\var{end}]
2879\end{cfuncdesc}
2880
2881\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
2882 PyObject *substr,
2883 PyObject *replstr,
2884 int maxcount}
Fred Drakea4cd2612000-04-06 14:10:29 +00002885Replace at most \var{maxcount} occurrences of \var{substr} in
2886\var{str} with \var{replstr} and return the resulting Unicode object.
2887\var{maxcount} == -1 means: replace all occurrences.
2888\end{cfuncdesc}
2889
Fred Drake1d158692000-06-18 05:21:21 +00002890\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
Fred Drakea4cd2612000-04-06 14:10:29 +00002891Compare two strings and return -1, 0, 1 for less than, equal,
2892greater than resp.
2893\end{cfuncdesc}
2894
2895\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
2896 PyObject *args}
Fred Drake1d158692000-06-18 05:21:21 +00002897Returns a new string object from \var{format} and \var{args}; this is
2898analogous to \code{\var{format} \%\ \var{args}}. The
2899\var{args} argument must be a tuple.
Fred Drakea4cd2612000-04-06 14:10:29 +00002900\end{cfuncdesc}
2901
2902\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
2903 PyObject *element}
Fred Drakea4cd2612000-04-06 14:10:29 +00002904Checks whether \var{element} is contained in \var{container} and
Fred Drake1d158692000-06-18 05:21:21 +00002905returns true or false accordingly.
Fred Drakea4cd2612000-04-06 14:10:29 +00002906
Fred Drake1d158692000-06-18 05:21:21 +00002907\var{element} has to coerce to a one element Unicode string. \code{-1} is
Fred Drakea4cd2612000-04-06 14:10:29 +00002908returned in case of an error.
2909\end{cfuncdesc}
2910
2911
Fred Drake58c5a2a1999-08-04 13:13:24 +00002912\subsection{Buffer Objects \label{bufferObjects}}
Fred Drake659ebfa2000-04-03 15:42:13 +00002913\sectionauthor{Greg Stein}{gstein@lyra.org}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002914
Fred Drake659ebfa2000-04-03 15:42:13 +00002915\obindex{buffer}
2916Python objects implemented in C can export a group of functions called
2917the ``buffer\index{buffer interface} interface.'' These functions can
2918be used by an object to expose its data in a raw, byte-oriented
2919format. Clients of the object can use the buffer interface to access
2920the object data directly, without needing to copy it first.
2921
2922Two examples of objects that support
2923the buffer interface are strings and arrays. The string object exposes
2924the character contents in the buffer interface's byte-oriented
2925form. An array can also expose its contents, but it should be noted
2926that array elements may be multi-byte values.
2927
2928An example user of the buffer interface is the file object's
2929\method{write()} method. Any object that can export a series of bytes
2930through the buffer interface can be written to a file. There are a
2931number of format codes to \cfunction{PyArgs_ParseTuple()} that operate
2932against an object's buffer interface, returning data from the target
2933object.
2934
2935More information on the buffer interface is provided in the section
2936``Buffer Object Structures'' (section \ref{buffer-structs}), under
2937the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
2938
2939A ``buffer object'' is defined in the \file{bufferobject.h} header
2940(included by \file{Python.h}). These objects look very similar to
2941string objects at the Python programming level: they support slicing,
2942indexing, concatenation, and some other standard string
2943operations. However, their data can come from one of two sources: from
2944a block of memory, or from another object which exports the buffer
2945interface.
2946
2947Buffer objects are useful as a way to expose the data from another
2948object's buffer interface to the Python programmer. They can also be
2949used as a zero-copy slicing mechanism. Using their ability to
2950reference a block of memory, it is possible to expose any data to the
2951Python programmer quite easily. The memory could be a large, constant
2952array in a C extension, it could be a raw block of memory for
2953manipulation before passing to an operating system library, or it
2954could be used to pass around structured data in its native, in-memory
2955format.
2956
2957\begin{ctypedesc}{PyBufferObject}
2958This subtype of \ctype{PyObject} represents a buffer object.
2959\end{ctypedesc}
Fred Drake58c5a2a1999-08-04 13:13:24 +00002960
2961\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
2962The instance of \ctype{PyTypeObject} which represents the Python
Fred Drake659ebfa2000-04-03 15:42:13 +00002963buffer type; it is the same object as \code{types.BufferType} in the
2964Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002965\end{cvardesc}
2966
2967\begin{cvardesc}{int}{Py_END_OF_BUFFER}
Fred Drake659ebfa2000-04-03 15:42:13 +00002968This constant may be passed as the \var{size} parameter to
2969\cfunction{PyBuffer_FromObject()} or
2970\cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the new
2971\ctype{PyBufferObject} should refer to \var{base} object from the
2972specified \var{offset} to the end of its exported buffer. Using this
2973enables the caller to avoid querying the \var{base} object for its
2974length.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002975\end{cvardesc}
2976
2977\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
2978Return true if the argument has type \cdata{PyBuffer_Type}.
2979\end{cfuncdesc}
2980
2981\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
2982 int offset, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00002983Return a new read-only buffer object. This raises
2984\exception{TypeError} if \var{base} doesn't support the read-only
2985buffer protocol or doesn't provide exactly one buffer segment, or it
2986raises \exception{ValueError} if \var{offset} is less than zero. The
2987buffer will hold a reference to the \var{base} object, and the
2988buffer's contents will refer to the \var{base} object's buffer
2989interface, starting as position \var{offset} and extending for
2990\var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
2991the new buffer's contents extend to the length of the
2992\var{base} object's exported buffer data.
Fred Drake58c5a2a1999-08-04 13:13:24 +00002993\end{cfuncdesc}
2994
2995\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
2996 int offset,
2997 int size}
2998Return a new writable buffer object. Parameters and exceptions are
2999similar to those for \cfunction{PyBuffer_FromObject()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003000If the \var{base} object does not export the writeable buffer
3001protocol, then \exception{TypeError} is raised.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003002\end{cfuncdesc}
3003
3004\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003005Return a new read-only buffer object that reads from a specified
3006location in memory, with a specified size.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003007The caller is responsible for ensuring that the memory buffer, passed
3008in as \var{ptr}, is not deallocated while the returned buffer object
3009exists. Raises \exception{ValueError} if \var{size} is less than
Fred Drake659ebfa2000-04-03 15:42:13 +00003010zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be passed
3011for the \var{size} parameter; \exception{ValueError} will be raised in
3012that case.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003013\end{cfuncdesc}
3014
3015\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
Fred Drake659ebfa2000-04-03 15:42:13 +00003016Similar to \cfunction{PyBuffer_FromMemory()}, but the returned buffer
3017is writable.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003018\end{cfuncdesc}
3019
3020\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
3021Returns a new writable buffer object that maintains its own memory
Fred Drake659ebfa2000-04-03 15:42:13 +00003022buffer of \var{size} bytes. \exception{ValueError} is returned if
3023\var{size} is not zero or positive.
Fred Drake58c5a2a1999-08-04 13:13:24 +00003024\end{cfuncdesc}
3025
Guido van Rossum44475131998-04-21 15:30:01 +00003026
Fred Drakeefd146c1999-02-15 15:30:45 +00003027\subsection{Tuple Objects \label{tupleObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003028
Fred Drake659ebfa2000-04-03 15:42:13 +00003029\obindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003030\begin{ctypedesc}{PyTupleObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003031This subtype of \ctype{PyObject} represents a Python tuple object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003032\end{ctypedesc}
3033
3034\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003035This instance of \ctype{PyTypeObject} represents the Python tuple
3036type; it is the same object as \code{types.TupleType} in the Python
3037layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003038\end{cvardesc}
3039
3040\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
3041Return true if the argument is a tuple object.
3042\end{cfuncdesc}
3043
Fred Drake659ebfa2000-04-03 15:42:13 +00003044\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
3045Return a new tuple object of size \var{len}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003046\end{cfuncdesc}
3047
3048\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
Fred Drakee058b4f1998-02-16 06:15:35 +00003049Takes a pointer to a tuple object, and returns the size
Fred Drakee5bf8b21998-02-12 21:22:28 +00003050of that tuple.
3051\end{cfuncdesc}
3052
Fred Drakec6fa34e1998-04-02 06:47:24 +00003053\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003054Returns the object at position \var{pos} in the tuple pointed
3055to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003056sets an \exception{IndexError} exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003057\end{cfuncdesc}
3058
Fred Drakec6fa34e1998-04-02 06:47:24 +00003059\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
Fred Drakee058b4f1998-02-16 06:15:35 +00003060Does the same, but does no checking of its arguments.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003061\end{cfuncdesc}
3062
Fred Drakec6fa34e1998-04-02 06:47:24 +00003063\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyTupleObject *p,
Fred Drakee5bf8b21998-02-12 21:22:28 +00003064 int low,
3065 int high}
Fred Drakee058b4f1998-02-16 06:15:35 +00003066Takes a slice of the tuple pointed to by \var{p} from
3067\var{low} to \var{high} and returns it as a new tuple.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003068\end{cfuncdesc}
3069
Fred Drake659ebfa2000-04-03 15:42:13 +00003070\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
3071 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003072Inserts a reference to object \var{o} at position \var{pos} of
3073the tuple pointed to by \var{p}. It returns \code{0} on success.
Fred Drake659ebfa2000-04-03 15:42:13 +00003074\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003075\end{cfuncdesc}
3076
Fred Drake659ebfa2000-04-03 15:42:13 +00003077\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
3078 int pos, PyObject *o}
Fred Drakee058b4f1998-02-16 06:15:35 +00003079Does the same, but does no error checking, and
Fred Drakee5bf8b21998-02-12 21:22:28 +00003080should \emph{only} be used to fill in brand new tuples.
Fred Drake659ebfa2000-04-03 15:42:13 +00003081\strong{Note:} This function ``steals'' a reference to \var{o}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003082\end{cfuncdesc}
3083
Fred Drakec6fa34e1998-04-02 06:47:24 +00003084\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyTupleObject *p,
Fred Drake659ebfa2000-04-03 15:42:13 +00003085 int newsize, int last_is_sticky}
3086Can be used to resize a tuple. \var{newsize} will be the new length
3087of the tuple. Because tuples are \emph{supposed} to be immutable,
3088this should only be used if there is only one reference to the object.
3089Do \emph{not} use this if the tuple may already be known to some other
Neil Schemenauer410cb6b2000-10-05 19:38:24 +00003090part of the code. The tuple will always grow or shrink at the end. The
3091\var{last_is_sticky} flag is not used and should always be false. Think
3092of this as destroying the old tuple and creating a new one, only more
3093efficiently. Returns \code{0} on success and \code{-1} on failure (in
3094which case a \exception{MemoryError} or \exception{SystemError} will be
3095raised).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003096\end{cfuncdesc}
3097
3098
Fred Drakeefd146c1999-02-15 15:30:45 +00003099\subsection{List Objects \label{listObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003100
Fred Drake659ebfa2000-04-03 15:42:13 +00003101\obindex{list}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003102\begin{ctypedesc}{PyListObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003103This subtype of \ctype{PyObject} represents a Python list object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003104\end{ctypedesc}
3105
3106\begin{cvardesc}{PyTypeObject}{PyList_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003107This instance of \ctype{PyTypeObject} represents the Python list
3108type. This is the same object as \code{types.ListType}.
3109\withsubitem{(in module types)}{\ttindex{ListType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003110\end{cvardesc}
3111
3112\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003113Returns true if its argument is a \ctype{PyListObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003114\end{cfuncdesc}
3115
Fred Drake659ebfa2000-04-03 15:42:13 +00003116\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
3117Returns a new list of length \var{len} on success, or \NULL{} on
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003118failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003119\end{cfuncdesc}
3120
Fred Drakec6fa34e1998-04-02 06:47:24 +00003121\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003122Returns the length of the list object in \var{list}; this is
3123equivalent to \samp{len(\var{list})} on a list object.
3124\bifuncindex{len}
3125\end{cfuncdesc}
3126
3127\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
Fred Drake5d644212000-10-07 12:31:50 +00003128Macro form of \cfunction{PyList_Size()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003129\end{cfuncdesc}
3130
Fred Drakec6fa34e1998-04-02 06:47:24 +00003131\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
Guido van Rossum44475131998-04-21 15:30:01 +00003132Returns the object at position \var{pos} in the list pointed
3133to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
Fred Drake659ebfa2000-04-03 15:42:13 +00003134sets an \exception{IndexError} exception.
3135\end{cfuncdesc}
3136
3137\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
3138Macro form of \cfunction{PyList_GetItem()} without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003139\end{cfuncdesc}
3140
Fred Drakec6fa34e1998-04-02 06:47:24 +00003141\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
3142 PyObject *item}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003143Sets the item at index \var{index} in list to \var{item}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003144\strong{Note:} This function ``steals'' a reference to \var{item}.
3145\end{cfuncdesc}
3146
3147\begin{cfuncdesc}{PyObject*}{PyList_SET_ITEM}{PyObject *list, int i,
3148 PyObject *o}
3149Macro form of \cfunction{PyList_SetItem()} without error checking.
3150\strong{Note:} This function ``steals'' a reference to \var{item}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003151\end{cfuncdesc}
3152
Fred Drakec6fa34e1998-04-02 06:47:24 +00003153\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
Guido van Rossum44475131998-04-21 15:30:01 +00003154 PyObject *item}
3155Inserts the item \var{item} into list \var{list} in front of index
Fred Drake659ebfa2000-04-03 15:42:13 +00003156\var{index}. Returns \code{0} if successful; returns \code{-1} and
3157raises an exception if unsuccessful. Analogous to
3158\code{\var{list}.insert(\var{index}, \var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003159\end{cfuncdesc}
3160
Fred Drakec6fa34e1998-04-02 06:47:24 +00003161\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
Guido van Rossum44475131998-04-21 15:30:01 +00003162Appends the object \var{item} at the end of list \var{list}. Returns
Fred Drake659ebfa2000-04-03 15:42:13 +00003163\code{0} if successful; returns \code{-1} and sets an exception if
3164unsuccessful. Analogous to \code{\var{list}.append(\var{item})}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003165\end{cfuncdesc}
3166
Fred Drakec6fa34e1998-04-02 06:47:24 +00003167\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
3168 int low, int high}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00003169Returns a list of the objects in \var{list} containing the objects
Guido van Rossum44475131998-04-21 15:30:01 +00003170\emph{between} \var{low} and \var{high}. Returns NULL and sets an
3171exception if unsuccessful.
Fred Drake659ebfa2000-04-03 15:42:13 +00003172Analogous to \code{\var{list}[\var{low}:\var{high}]}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003173\end{cfuncdesc}
3174
Fred Drakec6fa34e1998-04-02 06:47:24 +00003175\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
3176 int low, int high,
3177 PyObject *itemlist}
Fred Drake659ebfa2000-04-03 15:42:13 +00003178Sets the slice of \var{list} between \var{low} and \var{high} to the
3179contents of \var{itemlist}. Analogous to
3180\code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
3181\code{0} on success, \code{-1} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003182\end{cfuncdesc}
3183
Fred Drakec6fa34e1998-04-02 06:47:24 +00003184\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003185Sorts the items of \var{list} in place. Returns \code{0} on success,
3186\code{-1} on failure. This is equivalent to
3187\samp{\var{list}.sort()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003188\end{cfuncdesc}
3189
Fred Drakec6fa34e1998-04-02 06:47:24 +00003190\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003191Reverses the items of \var{list} in place. Returns \code{0} on
3192success, \code{-1} on failure. This is the equivalent of
3193\samp{\var{list}.reverse()}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003194\end{cfuncdesc}
3195
Fred Drakec6fa34e1998-04-02 06:47:24 +00003196\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
Fred Drake659ebfa2000-04-03 15:42:13 +00003197Returns a new tuple object containing the contents of \var{list};
3198equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003199\end{cfuncdesc}
3200
3201
Fred Drakeefd146c1999-02-15 15:30:45 +00003202\section{Mapping Objects \label{mapObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003203
Fred Drake659ebfa2000-04-03 15:42:13 +00003204\obindex{mapping}
3205
3206
Fred Drakeefd146c1999-02-15 15:30:45 +00003207\subsection{Dictionary Objects \label{dictObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003208
Fred Drake659ebfa2000-04-03 15:42:13 +00003209\obindex{dictionary}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003210\begin{ctypedesc}{PyDictObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003211This subtype of \ctype{PyObject} represents a Python dictionary object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003212\end{ctypedesc}
3213
3214\begin{cvardesc}{PyTypeObject}{PyDict_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003215This instance of \ctype{PyTypeObject} represents the Python dictionary
3216type. This is exposed to Python programs as \code{types.DictType} and
3217\code{types.DictionaryType}.
3218\withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003219\end{cvardesc}
3220
3221\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003222Returns true if its argument is a \ctype{PyDictObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003223\end{cfuncdesc}
3224
Fred Drakec6fa34e1998-04-02 06:47:24 +00003225\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003226Returns a new empty dictionary, or \NULL{} on failure.
3227\end{cfuncdesc}
3228
3229\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
3230Empties an existing dictionary of all key-value pairs.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003231\end{cfuncdesc}
3232
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003233\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003234Returns a new dictionary that contains the same key-value pairs as p.
3235Empties an existing dictionary of all key-value pairs.
Jeremy Hyltona12c7a72000-03-30 22:27:31 +00003236\end{cfuncdesc}
3237
Fred Drake659ebfa2000-04-03 15:42:13 +00003238\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
3239 PyObject *val}
3240Inserts \var{value} into the dictionary with a key of \var{key}.
3241\var{key} must be hashable; if it isn't, \exception{TypeError} will be
3242raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003243\end{cfuncdesc}
3244
3245\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
3246 char *key,
3247 PyObject *val}
Fred Drakee058b4f1998-02-16 06:15:35 +00003248Inserts \var{value} into the dictionary using \var{key}
Fred Drake1d158692000-06-18 05:21:21 +00003249as a key. \var{key} should be a \ctype{char*}. The key object is
Fred Drakee058b4f1998-02-16 06:15:35 +00003250created using \code{PyString_FromString(\var{key})}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003251\ttindex{PyString_FromString()}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003252\end{cfuncdesc}
3253
Fred Drake659ebfa2000-04-03 15:42:13 +00003254\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003255Removes the entry in dictionary \var{p} with key \var{key}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003256\var{key} must be hashable; if it isn't, \exception{TypeError} is
3257raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003258\end{cfuncdesc}
3259
Fred Drake659ebfa2000-04-03 15:42:13 +00003260\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003261Removes the entry in dictionary \var{p} which has a key
Fred Drake659ebfa2000-04-03 15:42:13 +00003262specified by the string \var{key}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003263\end{cfuncdesc}
3264
Fred Drake659ebfa2000-04-03 15:42:13 +00003265\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
Fred Drakee058b4f1998-02-16 06:15:35 +00003266Returns the object from dictionary \var{p} which has a key
Guido van Rossum44475131998-04-21 15:30:01 +00003267\var{key}. Returns \NULL{} if the key \var{key} is not present, but
Fred Drake659ebfa2000-04-03 15:42:13 +00003268\emph{without} setting an exception.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003269\end{cfuncdesc}
3270
Fred Drake659ebfa2000-04-03 15:42:13 +00003271\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
Fred Drakef8830d11998-04-23 14:06:01 +00003272This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
Fred Drake659ebfa2000-04-03 15:42:13 +00003273specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003274\end{cfuncdesc}
3275
Fred Drake659ebfa2000-04-03 15:42:13 +00003276\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003277Returns a \ctype{PyListObject} containing all the items
Guido van Rossum44475131998-04-21 15:30:01 +00003278from the dictionary, as in the dictinoary method \method{items()} (see
Fred Drakebe486461999-11-09 17:03:03 +00003279the \citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003280\end{cfuncdesc}
3281
Fred Drake659ebfa2000-04-03 15:42:13 +00003282\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003283Returns a \ctype{PyListObject} containing all the keys
Guido van Rossum44475131998-04-21 15:30:01 +00003284from the dictionary, as in the dictionary method \method{keys()} (see the
Fred Drakebe486461999-11-09 17:03:03 +00003285\citetitle[../lib/lib.html]{Python Library Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003286\end{cfuncdesc}
3287
Fred Drake659ebfa2000-04-03 15:42:13 +00003288\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003289Returns a \ctype{PyListObject} containing all the values
Guido van Rossum44475131998-04-21 15:30:01 +00003290from the dictionary \var{p}, as in the dictionary method
Fred Drakebe486461999-11-09 17:03:03 +00003291\method{values()} (see the \citetitle[../lib/lib.html]{Python Library
3292Reference}).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003293\end{cfuncdesc}
3294
Fred Drake659ebfa2000-04-03 15:42:13 +00003295\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
3296Returns the number of items in the dictionary. This is equivalent to
3297\samp{len(\var{p})} on a dictionary.\bifuncindex{len}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003298\end{cfuncdesc}
3299
Fred Drake7d45d342000-08-11 17:07:32 +00003300\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p, int *ppos,
3301 PyObject **pkey, PyObject **pvalue}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003302
3303\end{cfuncdesc}
3304
3305
Fred Drakeefd146c1999-02-15 15:30:45 +00003306\section{Numeric Objects \label{numericObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003307
Fred Drake659ebfa2000-04-03 15:42:13 +00003308\obindex{numeric}
3309
3310
Fred Drakeefd146c1999-02-15 15:30:45 +00003311\subsection{Plain Integer Objects \label{intObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003312
Fred Drake659ebfa2000-04-03 15:42:13 +00003313\obindex{integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003314\begin{ctypedesc}{PyIntObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003315This subtype of \ctype{PyObject} represents a Python integer object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003316\end{ctypedesc}
3317
3318\begin{cvardesc}{PyTypeObject}{PyInt_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003319This instance of \ctype{PyTypeObject} represents the Python plain
Fred Drake659ebfa2000-04-03 15:42:13 +00003320integer type. This is the same object as \code{types.IntType}.
3321\withsubitem{(in modules types)}{\ttindex{IntType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003322\end{cvardesc}
3323
Fred Drake659ebfa2000-04-03 15:42:13 +00003324\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
3325Returns true if \var{o} is of type \cdata{PyInt_Type}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003326\end{cfuncdesc}
3327
Fred Drakec6fa34e1998-04-02 06:47:24 +00003328\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
Fred Drakee058b4f1998-02-16 06:15:35 +00003329Creates a new integer object with a value of \var{ival}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003330
3331The current implementation keeps an array of integer objects for all
Fred Drakee058b4f1998-02-16 06:15:35 +00003332integers between \code{-1} and \code{100}, when you create an int in
3333that range you actually just get back a reference to the existing
3334object. So it should be possible to change the value of \code{1}. I
Fred Drake7e9d3141998-04-03 05:02:28 +00003335suspect the behaviour of Python in this case is undefined. :-)
Fred Drakee5bf8b21998-02-12 21:22:28 +00003336\end{cfuncdesc}
3337
Fred Drakee5bf8b21998-02-12 21:22:28 +00003338\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
Fred Drakef8830d11998-04-23 14:06:01 +00003339Will first attempt to cast the object to a \ctype{PyIntObject}, if
Fred Drakee058b4f1998-02-16 06:15:35 +00003340it is not already one, and then return its value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003341\end{cfuncdesc}
3342
Fred Drake659ebfa2000-04-03 15:42:13 +00003343\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
3344Returns the value of the object \var{io}. No error checking is
3345performed.
3346\end{cfuncdesc}
3347
Fred Drakee5bf8b21998-02-12 21:22:28 +00003348\begin{cfuncdesc}{long}{PyInt_GetMax}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003349Returns the system's idea of the largest integer it can handle
3350(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
3351header files).
Fred Drakee5bf8b21998-02-12 21:22:28 +00003352\end{cfuncdesc}
3353
3354
Fred Drakeefd146c1999-02-15 15:30:45 +00003355\subsection{Long Integer Objects \label{longObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003356
Fred Drake659ebfa2000-04-03 15:42:13 +00003357\obindex{long integer}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003358\begin{ctypedesc}{PyLongObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003359This subtype of \ctype{PyObject} represents a Python long integer
Fred Drakee058b4f1998-02-16 06:15:35 +00003360object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003361\end{ctypedesc}
3362
3363\begin{cvardesc}{PyTypeObject}{PyLong_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003364This instance of \ctype{PyTypeObject} represents the Python long
Fred Drake659ebfa2000-04-03 15:42:13 +00003365integer type. This is the same object as \code{types.LongType}.
3366\withsubitem{(in modules types)}{\ttindex{LongType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003367\end{cvardesc}
3368
3369\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003370Returns true if its argument is a \ctype{PyLongObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003371\end{cfuncdesc}
3372
Fred Drakec6fa34e1998-04-02 06:47:24 +00003373\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003374Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on
3375failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003376\end{cfuncdesc}
3377
Fred Drakec6fa34e1998-04-02 06:47:24 +00003378\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003379Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
3380long}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003381\end{cfuncdesc}
3382
Fred Drakec6fa34e1998-04-02 06:47:24 +00003383\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003384Returns a new \ctype{PyLongObject} object from the integer part of
3385\var{v}, or \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003386\end{cfuncdesc}
3387
Fred Drakec6fa34e1998-04-02 06:47:24 +00003388\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003389Returns a C \ctype{long} representation of the contents of
3390\var{pylong}. If \var{pylong} is greater than
3391\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is
3392raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003393\end{cfuncdesc}
3394
Fred Drakec6fa34e1998-04-02 06:47:24 +00003395\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003396Returns a C \ctype{unsigned long} representation of the contents of
3397\var{pylong}. If \var{pylong} is greater than
3398\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError}
3399is raised.\withsubitem{(built-in exception)}{OverflowError}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003400\end{cfuncdesc}
3401
Fred Drakec6fa34e1998-04-02 06:47:24 +00003402\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
Fred Drake659ebfa2000-04-03 15:42:13 +00003403Returns a C \ctype{double} representation of the contents of \var{pylong}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003404\end{cfuncdesc}
3405
Fred Drakec6fa34e1998-04-02 06:47:24 +00003406\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
3407 int base}
Fred Drake659ebfa2000-04-03 15:42:13 +00003408Return a new \ctype{PyLongObject} based on the string value in
3409\var{str}, which is interpreted according to the radix in \var{base}.
3410If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first
3411character in \var{str} which follows the representation of the
3412number. If \var{base} is \code{0}, the radix will be determined base
3413on the leading characters of \var{str}: if \var{str} starts with
3414\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts
3415with \code{'0'}, radix 8 will be used; otherwise radix 10 will be
3416used. If \var{base} is not \code{0}, it must be between \code{2} and
3417\code{36}, inclusive. Leading spaces are ignored. If there are no
3418digits, \exception{ValueError} will be raised.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003419\end{cfuncdesc}
3420
3421
Fred Drakeefd146c1999-02-15 15:30:45 +00003422\subsection{Floating Point Objects \label{floatObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003423
Fred Drake659ebfa2000-04-03 15:42:13 +00003424\obindex{floating point}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003425\begin{ctypedesc}{PyFloatObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003426This subtype of \ctype{PyObject} represents a Python floating point
Fred Drakee058b4f1998-02-16 06:15:35 +00003427object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003428\end{ctypedesc}
3429
3430\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003431This instance of \ctype{PyTypeObject} represents the Python floating
Fred Drake659ebfa2000-04-03 15:42:13 +00003432point type. This is the same object as \code{types.FloatType}.
3433\withsubitem{(in modules types)}{\ttindex{FloatType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003434\end{cvardesc}
3435
3436\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003437Returns true if its argument is a \ctype{PyFloatObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003438\end{cfuncdesc}
3439
Fred Drakec6fa34e1998-04-02 06:47:24 +00003440\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003441Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
3442failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003443\end{cfuncdesc}
3444
Fred Drakec6fa34e1998-04-02 06:47:24 +00003445\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003446Returns a C \ctype{double} representation of the contents of \var{pyfloat}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003447\end{cfuncdesc}
3448
Fred Drakec6fa34e1998-04-02 06:47:24 +00003449\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
Fred Drake659ebfa2000-04-03 15:42:13 +00003450Returns a C \ctype{double} representation of the contents of
Fred Drakef8830d11998-04-23 14:06:01 +00003451\var{pyfloat}, but without error checking.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003452\end{cfuncdesc}
3453
3454
Fred Drakeefd146c1999-02-15 15:30:45 +00003455\subsection{Complex Number Objects \label{complexObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003456
Fred Drake659ebfa2000-04-03 15:42:13 +00003457\obindex{complex number}
3458Python's complex number objects are implemented as two distinct types
3459when viewed from the C API: one is the Python object exposed to
3460Python programs, and the other is a C structure which represents the
3461actual complex number value. The API provides functions for working
3462with both.
3463
3464\subsubsection{Complex Numbers as C Structures}
3465
3466Note that the functions which accept these structures as parameters
3467and return them as results do so \emph{by value} rather than
3468dereferencing them through pointers. This is consistent throughout
3469the API.
3470
Fred Drakee5bf8b21998-02-12 21:22:28 +00003471\begin{ctypedesc}{Py_complex}
Fred Drake659ebfa2000-04-03 15:42:13 +00003472The C structure which corresponds to the value portion of a Python
Fred Drake4de05a91998-02-16 14:25:26 +00003473complex number object. Most of the functions for dealing with complex
3474number objects use structures of this type as input or output values,
3475as appropriate. It is defined as:
3476
Fred Drakee058b4f1998-02-16 06:15:35 +00003477\begin{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003478typedef struct {
3479 double real;
3480 double imag;
Fred Drake4de05a91998-02-16 14:25:26 +00003481} Py_complex;
Fred Drakee058b4f1998-02-16 06:15:35 +00003482\end{verbatim}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003483\end{ctypedesc}
3484
Fred Drake659ebfa2000-04-03 15:42:13 +00003485\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
3486Return the sum of two complex numbers, using the C
3487\ctype{Py_complex} representation.
3488\end{cfuncdesc}
3489
3490\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
3491Return the difference between two complex numbers, using the C
3492\ctype{Py_complex} representation.
3493\end{cfuncdesc}
3494
3495\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
3496Return the negation of the complex number \var{complex}, using the C
3497\ctype{Py_complex} representation.
3498\end{cfuncdesc}
3499
3500\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
3501Return the product of two complex numbers, using the C
3502\ctype{Py_complex} representation.
3503\end{cfuncdesc}
3504
3505\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
3506 Py_complex divisor}
3507Return the quotient of two complex numbers, using the C
3508\ctype{Py_complex} representation.
3509\end{cfuncdesc}
3510
3511\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
3512Return the exponentiation of \var{num} by \var{exp}, using the C
3513\ctype{Py_complex} representation.
3514\end{cfuncdesc}
3515
3516
3517\subsubsection{Complex Numbers as Python Objects}
3518
Fred Drakee5bf8b21998-02-12 21:22:28 +00003519\begin{ctypedesc}{PyComplexObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003520This subtype of \ctype{PyObject} represents a Python complex number object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003521\end{ctypedesc}
3522
3523\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
Fred Drakef8830d11998-04-23 14:06:01 +00003524This instance of \ctype{PyTypeObject} represents the Python complex
Fred Drakee5bf8b21998-02-12 21:22:28 +00003525number type.
3526\end{cvardesc}
3527
3528\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003529Returns true if its argument is a \ctype{PyComplexObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003530\end{cfuncdesc}
3531
Fred Drakec6fa34e1998-04-02 06:47:24 +00003532\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
Fred Drake659ebfa2000-04-03 15:42:13 +00003533Create a new Python complex number object from a C
3534\ctype{Py_complex} value.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003535\end{cfuncdesc}
3536
Fred Drakec6fa34e1998-04-02 06:47:24 +00003537\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
Fred Drakef8830d11998-04-23 14:06:01 +00003538Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003539\end{cfuncdesc}
3540
3541\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003542Returns the real part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003543\end{cfuncdesc}
3544
3545\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003546Returns the imaginary part of \var{op} as a C \ctype{double}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003547\end{cfuncdesc}
3548
3549\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
Fred Drake659ebfa2000-04-03 15:42:13 +00003550Returns the \ctype{Py_complex} value of the complex number \var{op}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003551\end{cfuncdesc}
3552
3553
3554
Fred Drakeefd146c1999-02-15 15:30:45 +00003555\section{Other Objects \label{otherObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003556
Fred Drakeefd146c1999-02-15 15:30:45 +00003557\subsection{File Objects \label{fileObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003558
Fred Drake659ebfa2000-04-03 15:42:13 +00003559\obindex{file}
3560Python's built-in file objects are implemented entirely on the
3561\ctype{FILE*} support from the C standard library. This is an
3562implementation detail and may change in future releases of Python.
3563
Fred Drakee5bf8b21998-02-12 21:22:28 +00003564\begin{ctypedesc}{PyFileObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003565This subtype of \ctype{PyObject} represents a Python file object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003566\end{ctypedesc}
3567
3568\begin{cvardesc}{PyTypeObject}{PyFile_Type}
Fred Drake659ebfa2000-04-03 15:42:13 +00003569This instance of \ctype{PyTypeObject} represents the Python file
3570type. This is exposed to Python programs as \code{types.FileType}.
3571\withsubitem{(in module types)}{\ttindex{FileType}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003572\end{cvardesc}
3573
3574\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
Fred Drakef8830d11998-04-23 14:06:01 +00003575Returns true if its argument is a \ctype{PyFileObject}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003576\end{cfuncdesc}
3577
Fred Drake659ebfa2000-04-03 15:42:13 +00003578\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
3579On success, returns a new file object that is opened on the
3580file given by \var{filename}, with a file mode given by \var{mode},
3581where \var{mode} has the same semantics as the standard C routine
3582\cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003583\end{cfuncdesc}
3584
Fred Drakec6fa34e1998-04-02 06:47:24 +00003585\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
Fred Drake659ebfa2000-04-03 15:42:13 +00003586 char *name, char *mode,
3587 int (*close)(FILE*)}
3588Creates a new \ctype{PyFileObject} from the already-open standard C
3589file pointer, \var{fp}. The function \var{close} will be called when
3590the file should be closed. Returns \NULL{} on failure.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003591\end{cfuncdesc}
3592
Fred Drake659ebfa2000-04-03 15:42:13 +00003593\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
3594Returns the file object associated with \var{p} as a \ctype{FILE*}.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003595\end{cfuncdesc}
3596
Fred Drakec6fa34e1998-04-02 06:47:24 +00003597\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003598Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
3599function reads one line from the object \var{p}. \var{p} may be a
3600file object or any object with a \method{readline()} method. If
3601\var{n} is \code{0}, exactly one line is read, regardless of the
3602length of the line. If \var{n} is greater than \code{0}, no more than
3603\var{n} bytes will be read from the file; a partial line can be
3604returned. In both cases, an empty string is returned if the end of
3605the file is reached immediately. If \var{n} is less than \code{0},
3606however, one line is read regardless of length, but
3607\exception{EOFError} is raised if the end of the file is reached
3608immediately.
3609\withsubitem{(built-in exception)}{\ttindex{EOFError}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003610\end{cfuncdesc}
3611
Fred Drakec6fa34e1998-04-02 06:47:24 +00003612\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00003613Returns the name of the file specified by \var{p} as a string object.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003614\end{cfuncdesc}
3615
3616\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
Fred Drake659ebfa2000-04-03 15:42:13 +00003617Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
3618only. This should only be called immediately after file object
3619creation.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003620\end{cfuncdesc}
3621
Fred Drake659ebfa2000-04-03 15:42:13 +00003622\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
3623This function exists for internal use by the interpreter.
3624Sets the \member{softspace} attribute of \var{p} to \var{newflag} and
3625\withsubitem{(file attribute)}{\ttindex{softspace}}returns the
3626previous value. \var{p} does not have to be a file object
3627for this function to work properly; any object is supported (thought
3628its only interesting if the \member{softspace} attribute can be set).
3629This function clears any errors, and will return \code{0} as the
3630previous value if the attribute either does not exist or if there were
3631errors in retrieving it. There is no way to detect errors from this
3632function, but doing so should not be needed.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003633\end{cfuncdesc}
3634
Fred Drakec6fa34e1998-04-02 06:47:24 +00003635\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
3636 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003637Writes object \var{obj} to file object \var{p}. The only supported
3638flag for \var{flags} is \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW};
3639if given, the \function{str()} of the object is written instead of the
3640\function{repr()}. Returns \code{0} on success or \code{-1} on
3641failure; the appropriate exception will be set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003642\end{cfuncdesc}
3643
Fred Drakec6fa34e1998-04-02 06:47:24 +00003644\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p,
3645 int flags}
Fred Drake659ebfa2000-04-03 15:42:13 +00003646Writes string \var{s} to file object \var{p}. Returns \code{0} on
3647success or \code{-1} on failure; the appropriate exception will be
3648set.
Fred Drakee5bf8b21998-02-12 21:22:28 +00003649\end{cfuncdesc}
3650
3651
Fred Drakeefd146c1999-02-15 15:30:45 +00003652\subsection{Module Objects \label{moduleObjects}}
3653
3654\obindex{module}
3655There are only a few functions special to module objects.
3656
Fred Drake659ebfa2000-04-03 15:42:13 +00003657\begin{cvardesc}{PyTypeObject}{PyModule_Type}
3658This instance of \ctype{PyTypeObject} represents the Python module
3659type. This is exposed to Python programs as \code{types.ModuleType}.
3660\withsubitem{(in module types)}{\ttindex{ModuleType}}
3661\end{cvardesc}
3662
3663\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
3664Returns true if its argument is a module object.
Fred Drakeefd146c1999-02-15 15:30:45 +00003665\end{cfuncdesc}
3666
Fred Drake659ebfa2000-04-03 15:42:13 +00003667\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
3668Return a new module object with the \member{__name__} attribute set to
3669\var{name}. Only the module's \member{__doc__} and
3670\member{__name__} attributes are filled in; the caller is responsible
3671for providing a \member{__file__} attribute.
3672\withsubitem{(module attribute)}{
3673 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
3674\end{cfuncdesc}
3675
3676\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003677Return the dictionary object that implements \var{module}'s namespace;
3678this object is the same as the \member{__dict__} attribute of the
3679module object. This function never fails.
Fred Drake659ebfa2000-04-03 15:42:13 +00003680\withsubitem{(module attribute)}{\ttindex{__dict__}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003681\end{cfuncdesc}
3682
Fred Drake659ebfa2000-04-03 15:42:13 +00003683\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003684Return \var{module}'s \member{__name__} value. If the module does not
Fred Drake659ebfa2000-04-03 15:42:13 +00003685provide one, or if it is not a string, \exception{SystemError} is
3686raised and \NULL{} is returned.
3687\withsubitem{(module attribute)}{\ttindex{__name__}}
3688\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003689\end{cfuncdesc}
3690
Fred Drake659ebfa2000-04-03 15:42:13 +00003691\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
Fred Drakeefd146c1999-02-15 15:30:45 +00003692Return the name of the file from which \var{module} was loaded using
3693\var{module}'s \member{__file__} attribute. If this is not defined,
Fred Drake659ebfa2000-04-03 15:42:13 +00003694or if it is not a string, raise \exception{SystemError} and return
3695\NULL.
3696\withsubitem{(module attribute)}{\ttindex{__file__}}
3697\withsubitem{(built-in exception)}{\ttindex{SystemError}}
Fred Drakeefd146c1999-02-15 15:30:45 +00003698\end{cfuncdesc}
3699
Fred Drake891150b2000-09-23 03:25:42 +00003700\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
3701 char *name, PyObject *value}
3702Add an object to \var{module} as \var{name}. This is a convenience
3703function which can be used from the module's initialization function.
3704This steals a reference to \var{value}. Returns \code{-1} on error,
3705\code{0} on success.
3706\versionadded{2.0}
3707\end{cfuncdesc}
3708
3709\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
3710 char *name, int value}
3711Add an integer constant to \var{module} as \var{name}. This convenience
3712function can be used from the module's initialization function.
3713Returns \code{-1} on error, \code{0} on success.
3714\versionadded{2.0}
3715\end{cfuncdesc}
3716
3717\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
3718 char *name, char *value}
3719Add a string constant to \var{module} as \var{name}. This convenience
3720function can be used from the module's initialization function. The
3721string \var{value} must be null-terminated. Returns \code{-1} on
3722error, \code{0} on success.
3723\versionadded{2.0}
3724\end{cfuncdesc}
3725
Fred Drakeefd146c1999-02-15 15:30:45 +00003726
3727\subsection{CObjects \label{cObjects}}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003728
Fred Drake659ebfa2000-04-03 15:42:13 +00003729\obindex{CObject}
3730Refer to \emph{Extending and Embedding the Python Interpreter},
3731section 1.12 (``Providing a C API for an Extension Module''), for more
3732information on using these objects.
3733
3734
Guido van Rossum44475131998-04-21 15:30:01 +00003735\begin{ctypedesc}{PyCObject}
Fred Drakef8830d11998-04-23 14:06:01 +00003736This subtype of \ctype{PyObject} represents an opaque value, useful for
Fred Drake659ebfa2000-04-03 15:42:13 +00003737C extension modules who need to pass an opaque value (as a
3738\ctype{void*} pointer) through Python code to other C code. It is
Guido van Rossum44475131998-04-21 15:30:01 +00003739often used to make a C function pointer defined in one module
3740available to other modules, so the regular import mechanism can be
3741used to access C APIs defined in dynamically loaded modules.
3742\end{ctypedesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003743
Fred Drake659ebfa2000-04-03 15:42:13 +00003744\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
3745Returns true if its argument is a \ctype{PyCObject}.
3746\end{cfuncdesc}
3747
3748\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003749 void (*destr)(void *)}
Fred Drake1d158692000-06-18 05:21:21 +00003750Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
Fred Drakedab44681999-05-13 18:41:14 +00003751\var{destr} function will be called when the object is reclaimed, unless
3752it is \NULL.
Guido van Rossum44475131998-04-21 15:30:01 +00003753\end{cfuncdesc}
3754
Fred Drake659ebfa2000-04-03 15:42:13 +00003755\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
Guido van Rossum44475131998-04-21 15:30:01 +00003756 void* desc, void (*destr)(void *, void *) }
Fred Drakef8830d11998-04-23 14:06:01 +00003757Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
3758\var{destr} function will be called when the object is reclaimed. The
3759\var{desc} argument can be used to pass extra callback data for the
3760destructor function.
Guido van Rossum44475131998-04-21 15:30:01 +00003761\end{cfuncdesc}
3762
Fred Drake659ebfa2000-04-03 15:42:13 +00003763\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
3764Returns the object \ctype{void *} that the
3765\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003766\end{cfuncdesc}
3767
Fred Drake659ebfa2000-04-03 15:42:13 +00003768\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
3769Returns the description \ctype{void *} that the
3770\ctype{PyCObject} \var{self} was created with.
Guido van Rossum44475131998-04-21 15:30:01 +00003771\end{cfuncdesc}
Fred Drakee5bf8b21998-02-12 21:22:28 +00003772
Fred Drake659ebfa2000-04-03 15:42:13 +00003773
Fred Drakeefd146c1999-02-15 15:30:45 +00003774\chapter{Initialization, Finalization, and Threads
3775 \label{initialization}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003776
Guido van Rossum4a944d71997-08-14 20:35:38 +00003777\begin{cfuncdesc}{void}{Py_Initialize}{}
3778Initialize the Python interpreter. In an application embedding
3779Python, this should be called before using any other Python/C API
Fred Drake659ebfa2000-04-03 15:42:13 +00003780functions; with the exception of
3781\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
3782\cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
3783\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
3784and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
3785This initializes the table of loaded modules (\code{sys.modules}), and
3786\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}creates the
3787fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
Fred Drake4de05a91998-02-16 14:25:26 +00003788\module{__main__}\refbimodindex{__main__} and
3789\module{sys}\refbimodindex{sys}. It also initializes the module
Fred Drake659ebfa2000-04-03 15:42:13 +00003790search\indexiii{module}{search}{path} path (\code{sys.path}).
3791It does not set \code{sys.argv}; use
3792\cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
3793is a no-op when called for a second time (without calling
3794\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is no
3795return value; it is a fatal error if the initialization fails.
Guido van Rossum42cefd01997-10-05 15:27:29 +00003796\end{cfuncdesc}
3797
3798\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00003799Return true (nonzero) when the Python interpreter has been
Fred Drakee058b4f1998-02-16 06:15:35 +00003800initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
3801called, this returns false until \cfunction{Py_Initialize()} is called
Guido van Rossum42cefd01997-10-05 15:27:29 +00003802again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003803\end{cfuncdesc}
3804
3805\begin{cfuncdesc}{void}{Py_Finalize}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003806Undo all initializations made by \cfunction{Py_Initialize()} and
3807subsequent use of Python/C API functions, and destroy all
3808sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
3809created and not yet destroyed since the last call to
3810\cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
3811by the Python interpreter. This is a no-op when called for a second
3812time (without calling \cfunction{Py_Initialize()} again first). There
3813is no return value; errors during finalization are ignored.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003814
3815This function is provided for a number of reasons. An embedding
3816application might want to restart Python without having to restart the
3817application itself. An application that has loaded the Python
3818interpreter from a dynamically loadable library (or DLL) might want to
3819free all memory allocated by Python before unloading the DLL. During a
3820hunt for memory leaks in an application a developer might want to free
3821all memory allocated by Python before exiting from the application.
3822
Fred Drakee058b4f1998-02-16 06:15:35 +00003823\strong{Bugs and caveats:} The destruction of modules and objects in
Guido van Rossum4a944d71997-08-14 20:35:38 +00003824modules is done in random order; this may cause destructors
Fred Drakee058b4f1998-02-16 06:15:35 +00003825(\method{__del__()} methods) to fail when they depend on other objects
Guido van Rossum4a944d71997-08-14 20:35:38 +00003826(even functions) or modules. Dynamically loaded extension modules
3827loaded by Python are not unloaded. Small amounts of memory allocated
3828by the Python interpreter may not be freed (if you find a leak, please
3829report it). Memory tied up in circular references between objects is
3830not freed. Some memory allocated by extension modules may not be
3831freed. Some extension may not work properly if their initialization
3832routine is called more than once; this can happen if an applcation
Fred Drakee058b4f1998-02-16 06:15:35 +00003833calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
3834than once.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003835\end{cfuncdesc}
3836
Fred Drakec6fa34e1998-04-02 06:47:24 +00003837\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003838Create a new sub-interpreter. This is an (almost) totally separate
3839environment for the execution of Python code. In particular, the new
3840interpreter has separate, independent versions of all imported
3841modules, including the fundamental modules
3842\module{__builtin__}\refbimodindex{__builtin__},
3843\module{__main__}\refbimodindex{__main__} and
3844\module{sys}\refbimodindex{sys}. The table of loaded modules
3845(\code{sys.modules}) and the module search path (\code{sys.path}) are
3846also separate. The new environment has no \code{sys.argv} variable.
3847It has new standard I/O stream file objects \code{sys.stdin},
3848\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drake659ebfa2000-04-03 15:42:13 +00003849same underlying \ctype{FILE} structures in the C library).
3850\withsubitem{(in module sys)}{
3851 \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003852
3853The return value points to the first thread state created in the new
3854sub-interpreter. This thread state is made the current thread state.
3855Note that no actual thread is created; see the discussion of thread
3856states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003857\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00003858is stored in the current thread state and there may not be a current
3859thread state. (Like all other Python/C API functions, the global
3860interpreter lock must be held before calling this function and is
3861still held when it returns; however, unlike most other Python/C API
3862functions, there needn't be a current thread state on entry.)
3863
3864Extension modules are shared between (sub-)interpreters as follows:
3865the first time a particular extension is imported, it is initialized
3866normally, and a (shallow) copy of its module's dictionary is
3867squirreled away. When the same extension is imported by another
3868(sub-)interpreter, a new module is initialized and filled with the
Fred Drakee058b4f1998-02-16 06:15:35 +00003869contents of this copy; the extension's \code{init} function is not
3870called. Note that this is different from what happens when an
3871extension is imported after the interpreter has been completely
Fred Drake659ebfa2000-04-03 15:42:13 +00003872re-initialized by calling
3873\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
3874\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
3875the extension's \code{init\var{module}} function \emph{is} called
3876again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003877
Fred Drakee058b4f1998-02-16 06:15:35 +00003878\strong{Bugs and caveats:} Because sub-interpreters (and the main
Guido van Rossum4a944d71997-08-14 20:35:38 +00003879interpreter) are part of the same process, the insulation between them
Fred Drakee058b4f1998-02-16 06:15:35 +00003880isn't perfect --- for example, using low-level file operations like
Fred Drake659ebfa2000-04-03 15:42:13 +00003881\withsubitem{(in module os)}{\ttindex{close()}}
Fred Drakef8830d11998-04-23 14:06:01 +00003882\function{os.close()} they can (accidentally or maliciously) affect each
Guido van Rossum4a944d71997-08-14 20:35:38 +00003883other's open files. Because of the way extensions are shared between
3884(sub-)interpreters, some extensions may not work properly; this is
3885especially likely when the extension makes use of (static) global
3886variables, or when the extension manipulates its module's dictionary
3887after its initialization. It is possible to insert objects created in
3888one sub-interpreter into a namespace of another sub-interpreter; this
3889should be done with great care to avoid sharing user-defined
3890functions, methods, instances or classes between sub-interpreters,
3891since import operations executed by such objects may affect the
3892wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
3893a hard-to-fix bug that will be addressed in a future release.)
3894\end{cfuncdesc}
3895
3896\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
3897Destroy the (sub-)interpreter represented by the given thread state.
3898The given thread state must be the current thread state. See the
3899discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00003900thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00003901interpreted are destroyed. (The global interpreter lock must be held
3902before calling this function and is still held when it returns.)
Fred Drake659ebfa2000-04-03 15:42:13 +00003903\cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will destroy all
3904sub-interpreters that haven't been explicitly destroyed at that point.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003905\end{cfuncdesc}
3906
3907\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Fred Drake659ebfa2000-04-03 15:42:13 +00003908This function should be called before
3909\cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
Guido van Rossum4a944d71997-08-14 20:35:38 +00003910for the first time, if it is called at all. It tells the interpreter
Fred Drake659ebfa2000-04-03 15:42:13 +00003911the value of the \code{argv[0]} argument to the
3912\cfunction{main()}\ttindex{main()} function of the program. This is
3913used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some other
Guido van Rossum4a944d71997-08-14 20:35:38 +00003914functions below to find the Python run-time libraries relative to the
Fred Drakea8455ab2000-06-16 19:58:42 +00003915interpreter executable. The default value is \code{'python'}. The
Guido van Rossum4a944d71997-08-14 20:35:38 +00003916argument should point to a zero-terminated character string in static
3917storage whose contents will not change for the duration of the
3918program's execution. No code in the Python interpreter will change
3919the contents of this storage.
3920\end{cfuncdesc}
3921
Fred Drakec6fa34e1998-04-02 06:47:24 +00003922\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
Fred Drake659ebfa2000-04-03 15:42:13 +00003923Return the program name set with
3924\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
Guido van Rossum4a944d71997-08-14 20:35:38 +00003925default. The returned string points into static storage; the caller
3926should not modify its value.
3927\end{cfuncdesc}
3928
Fred Drakec6fa34e1998-04-02 06:47:24 +00003929\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003930Return the \emph{prefix} for installed platform-independent files. This
Guido van Rossum4a944d71997-08-14 20:35:38 +00003931is derived through a number of complicated rules from the program name
Fred Drakee058b4f1998-02-16 06:15:35 +00003932set with \cfunction{Py_SetProgramName()} and some environment variables;
Fred Drakea8455ab2000-06-16 19:58:42 +00003933for example, if the program name is \code{'/usr/local/bin/python'},
3934the prefix is \code{'/usr/local'}. The returned string points into
Guido van Rossum4a944d71997-08-14 20:35:38 +00003935static storage; the caller should not modify its value. This
Fred Drakec94d9341998-04-12 02:39:13 +00003936corresponds to the \makevar{prefix} variable in the top-level
Fred Drakea8455ab2000-06-16 19:58:42 +00003937\file{Makefile} and the \longprogramopt{prefix} argument to the
Fred Drakee058b4f1998-02-16 06:15:35 +00003938\program{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00003939Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00003940also the next function.
3941\end{cfuncdesc}
3942
Fred Drakec6fa34e1998-04-02 06:47:24 +00003943\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
Fred Drakee058b4f1998-02-16 06:15:35 +00003944Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
Guido van Rossum4a944d71997-08-14 20:35:38 +00003945files. This is derived through a number of complicated rules from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003946program name set with \cfunction{Py_SetProgramName()} and some environment
Guido van Rossum4a944d71997-08-14 20:35:38 +00003947variables; for example, if the program name is
Fred Drakea8455ab2000-06-16 19:58:42 +00003948\code{'/usr/local/bin/python'}, the exec-prefix is
3949\code{'/usr/local'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00003950the caller should not modify its value. This corresponds to the
Fred Drakec94d9341998-04-12 02:39:13 +00003951\makevar{exec_prefix} variable in the top-level \file{Makefile} and the
Fred Drakea8455ab2000-06-16 19:58:42 +00003952\longprogramopt{exec-prefix} argument to the
Fred Drake310ee611999-11-09 17:31:42 +00003953\program{configure} script at build time. The value is available to
3954Python code as \code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003955
3956Background: The exec-prefix differs from the prefix when platform
3957dependent files (such as executables and shared libraries) are
3958installed in a different directory tree. In a typical installation,
3959platform dependent files may be installed in the
Fred Drakea8455ab2000-06-16 19:58:42 +00003960\file{/usr/local/plat} subtree while platform independent may be
3961installed in \file{/usr/local}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00003962
3963Generally speaking, a platform is a combination of hardware and
3964software families, e.g. Sparc machines running the Solaris 2.x
3965operating system are considered the same platform, but Intel machines
3966running Solaris 2.x are another platform, and Intel machines running
3967Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00003968operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003969operating systems are a different story; the installation strategies
3970on those systems are so different that the prefix and exec-prefix are
3971meaningless, and set to the empty string. Note that compiled Python
3972bytecode files are platform independent (but not independent from the
3973Python version by which they were compiled!).
3974
Fred Drakee058b4f1998-02-16 06:15:35 +00003975System administrators will know how to configure the \program{mount} or
Fred Drakea8455ab2000-06-16 19:58:42 +00003976\program{automount} programs to share \file{/usr/local} between platforms
3977while having \file{/usr/local/plat} be a different filesystem for each
Guido van Rossum4a944d71997-08-14 20:35:38 +00003978platform.
3979\end{cfuncdesc}
3980
Fred Drakec6fa34e1998-04-02 06:47:24 +00003981\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003982Return the full program name of the Python executable; this is
3983computed as a side-effect of deriving the default module search path
Fred Drake659ebfa2000-04-03 15:42:13 +00003984from the program name (set by
3985\cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
3986The returned string points into static storage; the caller should not
Guido van Rossum4a944d71997-08-14 20:35:38 +00003987modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00003988\code{sys.executable}.
Fred Drake659ebfa2000-04-03 15:42:13 +00003989\withsubitem{(in module sys)}{\ttindex{executable}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003990\end{cfuncdesc}
3991
Fred Drakec6fa34e1998-04-02 06:47:24 +00003992\begin{cfuncdesc}{char*}{Py_GetPath}{}
Fred Drake4de05a91998-02-16 14:25:26 +00003993\indexiii{module}{search}{path}
Guido van Rossum4a944d71997-08-14 20:35:38 +00003994Return the default module search path; this is computed from the
Fred Drakee058b4f1998-02-16 06:15:35 +00003995program name (set by \cfunction{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00003996environment variables. The returned string consists of a series of
3997directory names separated by a platform dependent delimiter character.
Fred Drakef8830d11998-04-23 14:06:01 +00003998The delimiter character is \character{:} on \UNIX{}, \character{;} on
Fred Drake659ebfa2000-04-03 15:42:13 +00003999DOS/Windows, and \character{\e n} (the \ASCII{} newline character) on
Fred Drakee5bc4971998-02-12 23:36:49 +00004000Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00004001should not modify its value. The value is available to Python code
Fred Drake659ebfa2000-04-03 15:42:13 +00004002as the list \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}},
4003which may be modified to change the future search path for loaded
4004modules.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004005
4006% XXX should give the exact rules
4007\end{cfuncdesc}
4008
Fred Drakec6fa34e1998-04-02 06:47:24 +00004009\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004010Return the version of this Python interpreter. This is a string that
4011looks something like
4012
Guido van Rossum09270b51997-08-15 18:57:32 +00004013\begin{verbatim}
Fred Drakee058b4f1998-02-16 06:15:35 +00004014"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
Guido van Rossum09270b51997-08-15 18:57:32 +00004015\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004016
4017The first word (up to the first space character) is the current Python
4018version; the first three characters are the major and minor version
4019separated by a period. The returned string points into static storage;
4020the caller should not modify its value. The value is available to
4021Python code as the list \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004022\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004023\end{cfuncdesc}
4024
Fred Drakec6fa34e1998-04-02 06:47:24 +00004025\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00004026Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00004027this is formed from the ``official'' name of the operating system,
4028converted to lower case, followed by the major revision number; e.g.,
4029for Solaris 2.x, which is also known as SunOS 5.x, the value is
Fred Drakea8455ab2000-06-16 19:58:42 +00004030\code{'sunos5'}. On Macintosh, it is \code{'mac'}. On Windows, it
4031is \code{'win'}. The returned string points into static storage;
Guido van Rossum4a944d71997-08-14 20:35:38 +00004032the caller should not modify its value. The value is available to
4033Python code as \code{sys.platform}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004034\withsubitem{(in module sys)}{\ttindex{platform}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004035\end{cfuncdesc}
4036
Fred Drakec6fa34e1998-04-02 06:47:24 +00004037\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004038Return the official copyright string for the current Python version,
4039for example
4040
Fred Drakea8455ab2000-06-16 19:58:42 +00004041\code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004042
4043The returned string points into static storage; the caller should not
4044modify its value. The value is available to Python code as the list
4045\code{sys.copyright}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004046\withsubitem{(in module sys)}{\ttindex{copyright}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004047\end{cfuncdesc}
4048
Fred Drakec6fa34e1998-04-02 06:47:24 +00004049\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004050Return an indication of the compiler used to build the current Python
Fred Drakee058b4f1998-02-16 06:15:35 +00004051version, in square brackets, for example:
Guido van Rossum4a944d71997-08-14 20:35:38 +00004052
Fred Drakee058b4f1998-02-16 06:15:35 +00004053\begin{verbatim}
4054"[GCC 2.7.2.2]"
4055\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004056
4057The returned string points into static storage; the caller should not
4058modify its value. The value is available to Python code as part of
4059the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004060\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004061\end{cfuncdesc}
4062
Fred Drakec6fa34e1998-04-02 06:47:24 +00004063\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004064Return information about the sequence number and build date and time
4065of the current Python interpreter instance, for example
4066
Guido van Rossum09270b51997-08-15 18:57:32 +00004067\begin{verbatim}
4068"#67, Aug 1 1997, 22:34:28"
4069\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004070
4071The returned string points into static storage; the caller should not
4072modify its value. The value is available to Python code as part of
4073the variable \code{sys.version}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004074\withsubitem{(in module sys)}{\ttindex{version}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004075\end{cfuncdesc}
4076
4077\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
Fred Drake659ebfa2000-04-03 15:42:13 +00004078Set \code{sys.argv} based on \var{argc} and \var{argv}. These
4079parameters are similar to those passed to the program's
4080\cfunction{main()}\ttindex{main()} function with the difference that
4081the first entry should refer to the script file to be executed rather
4082than the executable hosting the Python interpreter. If there isn't a
4083script that will be run, the first entry in \var{argv} can be an empty
4084string. If this function fails to initialize \code{sys.argv}, a fatal
4085condition is signalled using
4086\cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
4087\withsubitem{(in module sys)}{\ttindex{argv}}
4088% XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
4089% check w/ Guido.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004090\end{cfuncdesc}
4091
4092% XXX Other PySys thingies (doesn't really belong in this chapter)
4093
Fred Drakeefd146c1999-02-15 15:30:45 +00004094\section{Thread State and the Global Interpreter Lock
4095 \label{threads}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004096
Fred Drake659ebfa2000-04-03 15:42:13 +00004097\index{global interpreter lock}
4098\index{interpreter lock}
4099\index{lock, interpreter}
4100
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004101The Python interpreter is not fully thread safe. In order to support
4102multi-threaded Python programs, there's a global lock that must be
4103held by the current thread before it can safely access Python objects.
4104Without the lock, even the simplest operations could cause problems in
Fred Drake7baf3d41998-02-20 00:45:52 +00004105a multi-threaded program: for example, when two threads simultaneously
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004106increment the reference count of the same object, the reference count
4107could end up being incremented only once instead of twice.
4108
4109Therefore, the rule exists that only the thread that has acquired the
4110global interpreter lock may operate on Python objects or call Python/C
4111API functions. In order to support multi-threaded Python programs,
Fred Drake659ebfa2000-04-03 15:42:13 +00004112the interpreter regularly releases and reacquires the lock --- by
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004113default, every ten bytecode instructions (this can be changed with
Fred Drake659ebfa2000-04-03 15:42:13 +00004114\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
Fred Drakee058b4f1998-02-16 06:15:35 +00004115\function{sys.setcheckinterval()}). The lock is also released and
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004116reacquired around potentially blocking I/O operations like reading or
4117writing a file, so that other threads can run while the thread that
4118requests the I/O is waiting for the I/O operation to complete.
4119
4120The Python interpreter needs to keep some bookkeeping information
Fred Drakee058b4f1998-02-16 06:15:35 +00004121separate per thread --- for this it uses a data structure called
Fred Drake659ebfa2000-04-03 15:42:13 +00004122\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
41231.5; in earlier versions, such state was stored in global variables,
4124and switching threads could cause problems. In particular, exception
4125handling is now thread safe, when the application uses
4126\withsubitem{(in module sys)}{\ttindex{exc_info()}}
4127\function{sys.exc_info()} to access the exception last raised in the
4128current thread.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004129
4130There's one global variable left, however: the pointer to the current
Fred Drake659ebfa2000-04-03 15:42:13 +00004131\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
4132thread packages have a way to store ``per-thread global data,''
4133Python's internal platform independent thread abstraction doesn't
4134support this yet. Therefore, the current thread state must be
4135manipulated explicitly.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004136
4137This is easy enough in most cases. Most code manipulating the global
4138interpreter lock has the following simple structure:
4139
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004140\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004141Save the thread state in a local variable.
4142Release the interpreter lock.
4143...Do some blocking I/O operation...
4144Reacquire the interpreter lock.
4145Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004146\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004147
4148This is so common that a pair of macros exists to simplify it:
4149
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004150\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004151Py_BEGIN_ALLOW_THREADS
4152...Do some blocking I/O operation...
4153Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004154\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004155
Fred Drake659ebfa2000-04-03 15:42:13 +00004156The \code{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS} macro
4157opens a new block and declares a hidden local variable; the
4158\code{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS} macro closes
Fred Drakee058b4f1998-02-16 06:15:35 +00004159the block. Another advantage of using these two macros is that when
4160Python is compiled without thread support, they are defined empty,
4161thus saving the thread state and lock manipulations.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004162
4163When thread support is enabled, the block above expands to the
4164following code:
4165
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004166\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004167 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004168
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004169 _save = PyEval_SaveThread();
4170 ...Do some blocking I/O operation...
4171 PyEval_RestoreThread(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004172\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004173
4174Using even lower level primitives, we can get roughly the same effect
4175as follows:
4176
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004177\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004178 PyThreadState *_save;
Fred Drake659ebfa2000-04-03 15:42:13 +00004179
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004180 _save = PyThreadState_Swap(NULL);
4181 PyEval_ReleaseLock();
4182 ...Do some blocking I/O operation...
4183 PyEval_AcquireLock();
4184 PyThreadState_Swap(_save);
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004185\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004186
4187There are some subtle differences; in particular,
Fred Drake659ebfa2000-04-03 15:42:13 +00004188\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
4189and restores the value of the global variable
4190\cdata{errno}\ttindex{errno}, since the lock manipulation does not
Fred Drakef8830d11998-04-23 14:06:01 +00004191guarantee that \cdata{errno} is left alone. Also, when thread support
Fred Drake659ebfa2000-04-03 15:42:13 +00004192is disabled,
4193\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
Fred Drakee058b4f1998-02-16 06:15:35 +00004194\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
Fred Drake659ebfa2000-04-03 15:42:13 +00004195case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
4196\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
4197available. This is done so that dynamically loaded extensions
4198compiled with thread support enabled can be loaded by an interpreter
4199that was compiled with disabled thread support.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004200
4201The global interpreter lock is used to protect the pointer to the
4202current thread state. When releasing the lock and saving the thread
4203state, the current thread state pointer must be retrieved before the
4204lock is released (since another thread could immediately acquire the
4205lock and store its own thread state in the global variable).
Fred Drakeffe58ca2000-09-29 17:31:54 +00004206Conversely, when acquiring the lock and restoring the thread state,
4207the lock must be acquired before storing the thread state pointer.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004208
4209Why am I going on with so much detail about this? Because when
Fred Drake659ebfa2000-04-03 15:42:13 +00004210threads are created from C, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004211lock, nor is there a thread state data structure for them. Such
4212threads must bootstrap themselves into existence, by first creating a
4213thread state data structure, then acquiring the lock, and finally
4214storing their thread state pointer, before they can start using the
4215Python/C API. When they are done, they should reset the thread state
4216pointer, release the lock, and finally free their thread state data
4217structure.
4218
4219When creating a thread data structure, you need to provide an
4220interpreter state data structure. The interpreter state data
4221structure hold global data that is shared by all threads in an
4222interpreter, for example the module administration
4223(\code{sys.modules}). Depending on your needs, you can either create
4224a new interpreter state data structure, or share the interpreter state
4225data structure used by the Python main thread (to access the latter,
Fred Drakef8830d11998-04-23 14:06:01 +00004226you must obtain the thread state and access its \member{interp} member;
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004227this must be done by a thread that is created by Python or by the main
4228thread after Python is initialized).
4229
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004230
4231\begin{ctypedesc}{PyInterpreterState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004232This data structure represents the state shared by a number of
4233cooperating threads. Threads belonging to the same interpreter
4234share their module administration and a few other internal items.
4235There are no public members in this structure.
4236
4237Threads belonging to different interpreters initially share nothing,
4238except process state like available memory, open file descriptors and
4239such. The global interpreter lock is also shared by all threads,
4240regardless of to which interpreter they belong.
4241\end{ctypedesc}
4242
4243\begin{ctypedesc}{PyThreadState}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004244This data structure represents the state of a single thread. The only
Fred Drakef8830d11998-04-23 14:06:01 +00004245public data member is \ctype{PyInterpreterState *}\member{interp},
4246which points to this thread's interpreter state.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004247\end{ctypedesc}
4248
4249\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
4250Initialize and acquire the global interpreter lock. It should be
4251called in the main thread before creating a second thread or engaging
Fred Drakee058b4f1998-02-16 06:15:35 +00004252in any other thread operations such as
Fred Drake659ebfa2000-04-03 15:42:13 +00004253\cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
4254\code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
4255It is not needed before calling
4256\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
4257\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004258
4259This is a no-op when called for a second time. It is safe to call
Fred Drake659ebfa2000-04-03 15:42:13 +00004260this function before calling
4261\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004262
4263When only the main thread exists, no lock operations are needed. This
4264is a common situation (most Python programs do not use threads), and
4265the lock operations slow the interpreter down a bit. Therefore, the
4266lock is not created initially. This situation is equivalent to having
4267acquired the lock: when there is only a single thread, all object
4268accesses are safe. Therefore, when this function initializes the
Fred Drake4de05a91998-02-16 14:25:26 +00004269lock, it also acquires it. Before the Python
4270\module{thread}\refbimodindex{thread} module creates a new thread,
4271knowing that either it has the lock or the lock hasn't been created
4272yet, it calls \cfunction{PyEval_InitThreads()}. When this call
4273returns, it is guaranteed that the lock has been created and that it
4274has acquired it.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004275
4276It is \strong{not} safe to call this function when it is unknown which
4277thread (if any) currently has the global interpreter lock.
4278
4279This function is not available when thread support is disabled at
4280compile time.
4281\end{cfuncdesc}
4282
Guido van Rossum4a944d71997-08-14 20:35:38 +00004283\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004284Acquire the global interpreter lock. The lock must have been created
4285earlier. If this thread already has the lock, a deadlock ensues.
4286This function is not available when thread support is disabled at
4287compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004288\end{cfuncdesc}
4289
4290\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004291Release the global interpreter lock. The lock must have been created
4292earlier. This function is not available when thread support is
Fred Drakee058b4f1998-02-16 06:15:35 +00004293disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004294\end{cfuncdesc}
4295
4296\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004297Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004298state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004299have been created earlier. If this thread already has the lock,
4300deadlock ensues. This function is not available when thread support
Fred Drakee058b4f1998-02-16 06:15:35 +00004301is disabled at compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004302\end{cfuncdesc}
4303
4304\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004305Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004306interpreter lock. The lock must have been created earlier and must be
4307held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004308be \NULL{}, is only used to check that it represents the current
Fred Drakee058b4f1998-02-16 06:15:35 +00004309thread state --- if it isn't, a fatal error is reported. This
4310function is not available when thread support is disabled at compile
4311time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004312\end{cfuncdesc}
4313
Fred Drakec6fa34e1998-04-02 06:47:24 +00004314\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004315Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004316support is enabled) and reset the thread state to \NULL{},
4317returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004318the lock has been created, the current thread must have acquired it.
4319(This function is available even when thread support is disabled at
4320compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004321\end{cfuncdesc}
4322
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004323\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004324Acquire the interpreter lock (if it has been created and thread
4325support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004326must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004327thread must not have acquired it, otherwise deadlock ensues. (This
4328function is available even when thread support is disabled at compile
4329time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00004330\end{cfuncdesc}
4331
Fred Drake659ebfa2000-04-03 15:42:13 +00004332The following macros are normally used without a trailing semicolon;
4333look for example usage in the Python source distribution.
4334
4335\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004336This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004337\samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004338Note that it contains an opening brace; it must be matched with a
4339following \code{Py_END_ALLOW_THREADS} macro. See above for further
4340discussion of this macro. It is a no-op when thread support is
4341disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004342\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004343
Fred Drake659ebfa2000-04-03 15:42:13 +00004344\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004345This macro expands to
Fred Drakee058b4f1998-02-16 06:15:35 +00004346\samp{PyEval_RestoreThread(_save); \}}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004347Note that it contains a closing brace; it must be matched with an
4348earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
4349discussion of this macro. It is a no-op when thread support is
4350disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004351\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004352
Fred Drake659ebfa2000-04-03 15:42:13 +00004353\begin{csimplemacrodesc}{Py_BEGIN_BLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004354This macro expands to \samp{PyEval_RestoreThread(_save);} i.e. it
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004355is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
4356brace. It is a no-op when thread support is disabled at compile
4357time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004358\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004359
Fred Drake659ebfa2000-04-03 15:42:13 +00004360\begin{csimplemacrodesc}{Py_BEGIN_UNBLOCK_THREADS}
Fred Drakee058b4f1998-02-16 06:15:35 +00004361This macro expands to \samp{_save = PyEval_SaveThread();} i.e. it is
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004362equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
4363and variable declaration. It is a no-op when thread support is
4364disabled at compile time.
Fred Drake659ebfa2000-04-03 15:42:13 +00004365\end{csimplemacrodesc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004366
4367All of the following functions are only available when thread support
4368is enabled at compile time, and must be called only when the
Fred Drake9d20ac31998-02-16 15:27:08 +00004369interpreter lock has been created.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004370
Fred Drakec6fa34e1998-04-02 06:47:24 +00004371\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004372Create a new interpreter state object. The interpreter lock need not
4373be held, but may be held if it is necessary to serialize calls to this
4374function.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004375\end{cfuncdesc}
4376
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004377\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
4378Reset all information in an interpreter state object. The interpreter
4379lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00004380\end{cfuncdesc}
4381
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004382\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
4383Destroy an interpreter state object. The interpreter lock need not be
4384held. The interpreter state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004385call to \cfunction{PyInterpreterState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004386\end{cfuncdesc}
4387
Fred Drakec6fa34e1998-04-02 06:47:24 +00004388\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004389Create a new thread state object belonging to the given interpreter
Guido van Rossumed9dcc11998-08-07 18:28:03 +00004390object. The interpreter lock need not be held, but may be held if it
4391is necessary to serialize calls to this function.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004392\end{cfuncdesc}
4393
4394\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
4395Reset all information in a thread state object. The interpreter lock
4396must be held.
4397\end{cfuncdesc}
4398
4399\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
4400Destroy a thread state object. The interpreter lock need not be
4401held. The thread state must have been reset with a previous
Fred Drakee058b4f1998-02-16 06:15:35 +00004402call to \cfunction{PyThreadState_Clear()}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004403\end{cfuncdesc}
4404
Fred Drakec6fa34e1998-04-02 06:47:24 +00004405\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004406Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004407When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004408error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004409\end{cfuncdesc}
4410
Fred Drakec6fa34e1998-04-02 06:47:24 +00004411\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004412Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00004413argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00004414must be held.
4415\end{cfuncdesc}
4416
4417
Fred Drake659ebfa2000-04-03 15:42:13 +00004418\chapter{Memory Management \label{memory}}
4419\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
4420
4421
4422\section{Overview \label{memoryOverview}}
4423
4424Memory management in Python involves a private heap containing all
4425Python objects and data structures. The management of this private
4426heap is ensured internally by the \emph{Python memory manager}. The
4427Python memory manager has different components which deal with various
4428dynamic storage management aspects, like sharing, segmentation,
4429preallocation or caching.
4430
4431At the lowest level, a raw memory allocator ensures that there is
4432enough room in the private heap for storing all Python-related data
4433by interacting with the memory manager of the operating system. On top
4434of the raw memory allocator, several object-specific allocators
4435operate on the same heap and implement distinct memory management
4436policies adapted to the peculiarities of every object type. For
4437example, integer objects are managed differently within the heap than
4438strings, tuples or dictionaries because integers imply different
4439storage requirements and speed/space tradeoffs. The Python memory
4440manager thus delegates some of the work to the object-specific
4441allocators, but ensures that the latter operate within the bounds of
4442the private heap.
4443
4444It is important to understand that the management of the Python heap
4445is performed by the interpreter itself and that the user has no
4446control on it, even if she regularly manipulates object pointers to
4447memory blocks inside that heap. The allocation of heap space for
4448Python objects and other internal buffers is performed on demand by
4449the Python memory manager through the Python/C API functions listed in
4450this document.
4451
4452To avoid memory corruption, extension writers should never try to
4453operate on Python objects with the functions exported by the C
4454library: \cfunction{malloc()}\ttindex{malloc()},
4455\cfunction{calloc()}\ttindex{calloc()},
4456\cfunction{realloc()}\ttindex{realloc()} and
4457\cfunction{free()}\ttindex{free()}. This will result in
4458mixed calls between the C allocator and the Python memory manager
4459with fatal consequences, because they implement different algorithms
4460and operate on different heaps. However, one may safely allocate and
4461release memory blocks with the C library allocator for individual
4462purposes, as shown in the following example:
4463
4464\begin{verbatim}
4465 PyObject *res;
4466 char *buf = (char *) malloc(BUFSIZ); /* for I/O */
4467
4468 if (buf == NULL)
4469 return PyErr_NoMemory();
4470 ...Do some I/O operation involving buf...
4471 res = PyString_FromString(buf);
4472 free(buf); /* malloc'ed */
4473 return res;
4474\end{verbatim}
4475
4476In this example, the memory request for the I/O buffer is handled by
4477the C library allocator. The Python memory manager is involved only
4478in the allocation of the string object returned as a result.
4479
4480In most situations, however, it is recommended to allocate memory from
4481the Python heap specifically because the latter is under control of
4482the Python memory manager. For example, this is required when the
4483interpreter is extended with new object types written in C. Another
4484reason for using the Python heap is the desire to \emph{inform} the
4485Python memory manager about the memory needs of the extension module.
4486Even when the requested memory is used exclusively for internal,
4487highly-specific purposes, delegating all memory requests to the Python
4488memory manager causes the interpreter to have a more accurate image of
4489its memory footprint as a whole. Consequently, under certain
4490circumstances, the Python memory manager may or may not trigger
4491appropriate actions, like garbage collection, memory compaction or
4492other preventive procedures. Note that by using the C library
4493allocator as shown in the previous example, the allocated memory for
4494the I/O buffer escapes completely the Python memory manager.
4495
4496
4497\section{Memory Interface \label{memoryInterface}}
4498
4499The following function sets, modeled after the ANSI C standard, are
4500available for allocating and releasing memory from the Python heap:
4501
4502
Fred Drake7d45d342000-08-11 17:07:32 +00004503\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
4504Allocates \var{n} bytes and returns a pointer of type \ctype{void*} to
Fred Drake659ebfa2000-04-03 15:42:13 +00004505the allocated memory, or \NULL{} if the request fails. Requesting zero
4506bytes returns a non-\NULL{} pointer.
4507\end{cfuncdesc}
4508
Fred Drake7d45d342000-08-11 17:07:32 +00004509\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004510Resizes the memory block pointed to by \var{p} to \var{n} bytes. The
4511contents will be unchanged to the minimum of the old and the new
4512sizes. If \var{p} is \NULL{}, the call is equivalent to
4513\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the memory block
4514is resized but is not freed, and the returned pointer is non-\NULL{}.
4515Unless \var{p} is \NULL{}, it must have been returned by a previous
4516call to \cfunction{PyMem_Malloc()} or \cfunction{PyMem_Realloc()}.
4517\end{cfuncdesc}
4518
Fred Drake7d45d342000-08-11 17:07:32 +00004519\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004520Frees the memory block pointed to by \var{p}, which must have been
4521returned by a previous call to \cfunction{PyMem_Malloc()} or
4522\cfunction{PyMem_Realloc()}. Otherwise, or if
4523\cfunction{PyMem_Free(p)} has been called before, undefined behaviour
4524occurs. If \var{p} is \NULL{}, no operation is performed.
4525\end{cfuncdesc}
4526
Fred Drake659ebfa2000-04-03 15:42:13 +00004527The following type-oriented macros are provided for convenience. Note
4528that \var{TYPE} refers to any C type.
4529
Fred Drakef913e542000-09-12 20:17:17 +00004530\begin{cfuncdesc}{\var{TYPE}*}{PyMem_New}{TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004531Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
4532sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
4533\ctype{\var{TYPE}*}.
4534\end{cfuncdesc}
4535
Fred Drakef913e542000-09-12 20:17:17 +00004536\begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
Fred Drake659ebfa2000-04-03 15:42:13 +00004537Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
4538to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
4539cast to \ctype{\var{TYPE}*}.
4540\end{cfuncdesc}
4541
Fred Drakef913e542000-09-12 20:17:17 +00004542\begin{cfuncdesc}{void}{PyMem_Del}{void *p}
Fred Drake659ebfa2000-04-03 15:42:13 +00004543Same as \cfunction{PyMem_Free()}.
4544\end{cfuncdesc}
4545
Fred Drakef913e542000-09-12 20:17:17 +00004546In addition, the following macro sets are provided for calling the
4547Python memory allocator directly, without involving the C API functions
4548listed above. However, note that their use does not preserve binary
4549compatibility accross Python versions and is therefore deprecated in
4550extension modules.
4551
4552\cfunction{PyMem_MALLOC()}, \cfunction{PyMem_REALLOC()}, \cfunction{PyMem_FREE()}.
4553
4554\cfunction{PyMem_NEW()}, \cfunction{PyMem_RESIZE()}, \cfunction{PyMem_DEL()}.
4555
Fred Drake659ebfa2000-04-03 15:42:13 +00004556
4557\section{Examples \label{memoryExamples}}
4558
4559Here is the example from section \ref{memoryOverview}, rewritten so
4560that the I/O buffer is allocated from the Python heap by using the
4561first function set:
4562
4563\begin{verbatim}
4564 PyObject *res;
4565 char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
4566
4567 if (buf == NULL)
4568 return PyErr_NoMemory();
4569 /* ...Do some I/O operation involving buf... */
4570 res = PyString_FromString(buf);
4571 PyMem_Free(buf); /* allocated with PyMem_Malloc */
4572 return res;
4573\end{verbatim}
4574
Fred Drakef913e542000-09-12 20:17:17 +00004575The same code using the type-oriented function set:
Fred Drake659ebfa2000-04-03 15:42:13 +00004576
4577\begin{verbatim}
4578 PyObject *res;
Fred Drakef913e542000-09-12 20:17:17 +00004579 char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
Fred Drake659ebfa2000-04-03 15:42:13 +00004580
4581 if (buf == NULL)
4582 return PyErr_NoMemory();
4583 /* ...Do some I/O operation involving buf... */
4584 res = PyString_FromString(buf);
Fred Drakef913e542000-09-12 20:17:17 +00004585 PyMem_Del(buf); /* allocated with PyMem_New */
Fred Drake659ebfa2000-04-03 15:42:13 +00004586 return res;
4587\end{verbatim}
4588
Fred Drakef913e542000-09-12 20:17:17 +00004589Note that in the two examples above, the buffer is always
4590manipulated via functions belonging to the same set. Indeed, it
Fred Drake659ebfa2000-04-03 15:42:13 +00004591is required to use the same memory API family for a given
4592memory block, so that the risk of mixing different allocators is
4593reduced to a minimum. The following code sequence contains two errors,
4594one of which is labeled as \emph{fatal} because it mixes two different
4595allocators operating on different heaps.
4596
4597\begin{verbatim}
Fred Drakef913e542000-09-12 20:17:17 +00004598char *buf1 = PyMem_New(char, BUFSIZ);
Fred Drake659ebfa2000-04-03 15:42:13 +00004599char *buf2 = (char *) malloc(BUFSIZ);
4600char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
4601...
Fred Drakef913e542000-09-12 20:17:17 +00004602PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004603free(buf2); /* Right -- allocated via malloc() */
Fred Drakef913e542000-09-12 20:17:17 +00004604free(buf1); /* Fatal -- should be PyMem_Del() */
Fred Drake659ebfa2000-04-03 15:42:13 +00004605\end{verbatim}
4606
4607In addition to the functions aimed at handling raw memory blocks from
4608the Python heap, objects in Python are allocated and released with
Fred Drakef913e542000-09-12 20:17:17 +00004609\cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()} and
4610\cfunction{PyObject_Del()}, or with their corresponding macros
4611\cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()} and
Fred Drakee06f0f92000-06-30 15:52:39 +00004612\cfunction{PyObject_DEL()}.
Fred Drake659ebfa2000-04-03 15:42:13 +00004613
Fred Drakee06f0f92000-06-30 15:52:39 +00004614These will be explained in the next chapter on defining and
4615implementing new object types in C.
Fred Drake659ebfa2000-04-03 15:42:13 +00004616
4617
Fred Drakeefd146c1999-02-15 15:30:45 +00004618\chapter{Defining New Object Types \label{newTypes}}
Guido van Rossum4a944d71997-08-14 20:35:38 +00004619
Fred Drakec6fa34e1998-04-02 06:47:24 +00004620\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
Fred Drakee058b4f1998-02-16 06:15:35 +00004621\end{cfuncdesc}
4622
Fred Drakef913e542000-09-12 20:17:17 +00004623\begin{cfuncdesc}{PyVarObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
Fred Drakee058b4f1998-02-16 06:15:35 +00004624\end{cfuncdesc}
4625
Fred Drakef913e542000-09-12 20:17:17 +00004626\begin{cfuncdesc}{void}{_PyObject_Del}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004627\end{cfuncdesc}
4628
Fred Drakef913e542000-09-12 20:17:17 +00004629\begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op,
4630 PyTypeObject *type}
4631\end{cfuncdesc}
4632
4633\begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op,
4634 PyTypeObject *type, int size}
4635\end{cfuncdesc}
4636
4637\begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type}
4638\end{cfuncdesc}
4639
4640\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type,
4641 int size}
4642\end{cfuncdesc}
4643
4644\begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op}
4645\end{cfuncdesc}
4646
4647\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW}{TYPE, PyTypeObject *type}
4648\end{cfuncdesc}
4649
4650\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
4651 int size}
4652\end{cfuncdesc}
4653
4654\begin{cfuncdesc}{void}{PyObject_DEL}{PyObject *op}
Fred Drakee058b4f1998-02-16 06:15:35 +00004655\end{cfuncdesc}
4656
Fred Drakeee814bf2000-11-28 22:34:32 +00004657\begin{cfuncdesc}{PyObject*}{Py_InitModule}{char *name,
4658 PyMethodDef *methods}
4659 Create a new module object based on a name and table of functions,
4660 returning the new module object.
4661\end{cfuncdesc}
4662
4663\begin{cfuncdesc}{PyObject*}{Py_InitModule3}{char *name,
4664 PyMethodDef *methods,
4665 char *doc}
4666 Create a new module object based on a name and table of functions,
4667 returning the new module object. If \var{doc} is non-\NULL, it will
4668 be used to define the docstring for the module.
4669\end{cfuncdesc}
4670
4671\begin{cfuncdesc}{PyObject*}{Py_InitModule4}{char *name,
4672 PyMethodDef *methods,
4673 char *doc, PyObject *self,
4674 int apiver}
4675 Create a new module object based on a name and table of functions,
4676 returning the new module object. If \var{doc} is non-\NULL, it will
4677 be used to define the docstring for the module. If \var{self} is
4678 non-\NULL, it will passed to the functions of the module as their
4679 (otherwise \NULL) first parameter. (This was added as an
4680 experimental feature, and there are no known uses in the current
4681 version of Python.) For \var{apiver}, the only value which should
4682 be passed is defined by the constant \constant{PYTHON_API_VERSION}.
4683
4684 \strong{Note:} Most uses of this function should probably be using
4685 the \cfunction{Py_InitModule3()} instead; only use this if you are
4686 sure you need it.
4687\end{cfuncdesc}
Guido van Rossum3c4378b1998-04-14 20:21:10 +00004688
4689PyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse
4690
4691Py_BuildValue
Guido van Rossumae110af1997-05-22 20:11:52 +00004692
Fred Drake659ebfa2000-04-03 15:42:13 +00004693DL_IMPORT
4694
4695Py*_Check
4696
4697_Py_NoneStruct
4698
4699
4700\section{Common Object Structures \label{common-structs}}
4701
Guido van Rossumae110af1997-05-22 20:11:52 +00004702PyObject, PyVarObject
4703
4704PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
4705
4706Typedefs:
4707unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
4708intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
Guido van Rossumae110af1997-05-22 20:11:52 +00004709destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
4710setattrofunc, cmpfunc, reprfunc, hashfunc
4711
Fred Drakea8455ab2000-06-16 19:58:42 +00004712\begin{ctypedesc}{PyCFunction}
4713Type of the functions used to implement most Python callables in C.
4714\end{ctypedesc}
4715
4716\begin{ctypedesc}{PyMethodDef}
4717Structure used to describe a method of an extension type. This
4718structure has four fields:
4719
4720\begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
4721 \lineiii{ml_name}{char *}{name of the method}
4722 \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
4723 \lineiii{ml_flags}{int}{flag bits indicating how the call should be
4724 constructed}
4725 \lineiii{ml_doc}{char *}{points to the contents of the docstring}
4726\end{tableiii}
4727\end{ctypedesc}
4728
4729\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef[] table,
4730 PyObject *ob, char *name}
4731Return a bound method object for an extension type implemented in C.
4732This function also handles the special attribute \member{__methods__},
4733returning a list of all the method names defined in \var{table}.
4734\end{cfuncdesc}
4735
Fred Drake659ebfa2000-04-03 15:42:13 +00004736
4737\section{Mapping Object Structures \label{mapping-structs}}
4738
4739\begin{ctypedesc}{PyMappingMethods}
4740Structure used to hold pointers to the functions used to implement the
4741mapping protocol for an extension type.
4742\end{ctypedesc}
4743
4744
4745\section{Number Object Structures \label{number-structs}}
4746
4747\begin{ctypedesc}{PyNumberMethods}
4748Structure used to hold pointers to the functions an extension type
4749uses to implement the number protocol.
4750\end{ctypedesc}
4751
4752
4753\section{Sequence Object Structures \label{sequence-structs}}
4754
4755\begin{ctypedesc}{PySequenceMethods}
4756Structure used to hold pointers to the functions which an object uses
4757to implement the sequence protocol.
4758\end{ctypedesc}
4759
4760
4761\section{Buffer Object Structures \label{buffer-structs}}
4762\sectionauthor{Greg J. Stein}{greg@lyra.org}
4763
4764The buffer interface exports a model where an object can expose its
4765internal data as a set of chunks of data, where each chunk is
4766specified as a pointer/length pair. These chunks are called
4767\dfn{segments} and are presumed to be non-contiguous in memory.
4768
4769If an object does not export the buffer interface, then its
4770\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
4771should be \NULL{}. Otherwise, the \member{tp_as_buffer} will point to
4772a \ctype{PyBufferProcs} structure.
4773
4774\strong{Note:} It is very important that your
4775\ctype{PyTypeObject} structure uses \code{Py_TPFLAGS_DEFAULT} for the
4776value of the \member{tp_flags} member rather than \code{0}. This
4777tells the Python runtime that your \ctype{PyBufferProcs} structure
4778contains the \member{bf_getcharbuffer} slot. Older versions of Python
4779did not have this member, so a new Python interpreter using an old
4780extension needs to be able to test for its presence before using it.
4781
4782\begin{ctypedesc}{PyBufferProcs}
4783Structure used to hold the function pointers which define an
4784implementation of the buffer protocol.
4785
4786The first slot is \member{bf_getreadbuffer}, of type
4787\ctype{getreadbufferproc}. If this slot is \NULL{}, then the object
4788does not support reading from the internal data. This is
4789non-sensical, so implementors should fill this in, but callers should
4790test that the slot contains a non-\NULL{} value.
4791
4792The next slot is \member{bf_getwritebuffer} having type
4793\ctype{getwritebufferproc}. This slot may be \NULL{} if the object
4794does not allow writing into its returned buffers.
4795
4796The third slot is \member{bf_getsegcount}, with type
4797\ctype{getsegcountproc}. This slot must not be \NULL{} and is used to
4798inform the caller how many segments the object contains. Simple
4799objects such as \ctype{PyString_Type} and
4800\ctype{PyBuffer_Type} objects contain a single segment.
4801
4802The last slot is \member{bf_getcharbuffer}, of type
4803\ctype{getcharbufferproc}. This slot will only be present if the
4804\code{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
4805\member{tp_flags} field of the object's \ctype{PyTypeObject}. Before using
4806this slot, the caller should test whether it is present by using the
4807\cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()} function.
4808If present, it may be \NULL, indicating that the object's contents
4809cannot be used as \emph{8-bit characters}.
4810The slot function may also raise an error if the object's contents
4811cannot be interpreted as 8-bit characters. For example, if the object
4812is an array which is configured to hold floating point values, an
4813exception may be raised if a caller attempts to use
4814\member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
4815This notion of exporting the internal buffers as ``text'' is used to
4816distinguish between objects that are binary in nature, and those which
4817have character-based content.
4818
4819\strong{Note:} The current policy seems to state that these characters
4820may be multi-byte characters. This implies that a buffer size of
4821\var{N} does not mean there are \var{N} characters present.
4822\end{ctypedesc}
4823
4824\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
4825Flag bit set in the type structure to indicate that the
4826\member{bf_getcharbuffer} slot is known. This being set does not
4827indicate that the object supports the buffer interface or that the
4828\member{bf_getcharbuffer} slot is non-\NULL.
4829\end{datadesc}
4830
4831\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
4832 (PyObject *self, int segment, void **ptrptr)}
4833Return a pointer to a readable segment of the buffer. This function
4834is allowed to raise an exception, in which case it must return
4835\code{-1}. The \var{segment} which is passed must be zero or
4836positive, and strictly less than the number of segments returned by
4837the \member{bf_getsegcount} slot function. On success, returns
4838\code{0} and sets \code{*\var{ptrptr}} to a pointer to the buffer
4839memory.
4840\end{ctypedesc}
4841
4842\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
4843 (PyObject *self, int segment, void **ptrptr)}
Fred Drake58c5a2a1999-08-04 13:13:24 +00004844Return a pointer to a writable memory buffer in \code{*\var{ptrptr}};
4845the memory buffer must correspond to buffer segment \var{segment}.
4846Must return \code{-1} and set an exception on error.
4847\exception{TypeError} should be raised if the object only supports
4848read-only buffers, and \exception{SystemError} should be raised when
4849\var{segment} specifies a segment that doesn't exist.
4850% Why doesn't it raise ValueError for this one?
Fred Drake659ebfa2000-04-03 15:42:13 +00004851% GJS: because you shouldn't be calling it with an invalid
4852% segment. That indicates a blatant programming error in the C
4853% code.
Fred Drake58c5a2a1999-08-04 13:13:24 +00004854\end{ctypedesc}
4855
Fred Drake659ebfa2000-04-03 15:42:13 +00004856\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
4857 (PyObject *self, int *lenp)}
4858Return the number of memory segments which comprise the buffer. If
4859\var{lenp} is not \NULL, the implementation must report the sum of the
4860sizes (in bytes) of all segments in \code{*\var{lenp}}.
4861The function cannot fail.
4862\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004863
Fred Drake659ebfa2000-04-03 15:42:13 +00004864\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
4865 (PyObject *self, int segment, const char **ptrptr)}
4866\end{ctypedesc}
Guido van Rossumae110af1997-05-22 20:11:52 +00004867
Guido van Rossumae110af1997-05-22 20:11:52 +00004868
Fred Drake659ebfa2000-04-03 15:42:13 +00004869% \chapter{Debugging \label{debugging}}
4870%
4871% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00004872
4873
Fred Drakeed773ef2000-09-21 21:35:22 +00004874\appendix
4875\chapter{Reporting Bugs}
4876\input{reportingbugs}
4877
Fred Drakef3aa0e01998-03-17 06:23:13 +00004878\input{api.ind} % Index -- must be last
Guido van Rossum9231c8f1997-05-15 21:43:21 +00004879
4880\end{document}