blob: a39e15dc7137d416fec433fbb48ed1900d6d58e9 [file] [log] [blame]
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001\documentstyle[twoside,11pt,myformat]{report}
2
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
12\pagenumbering{roman}
13
14\maketitle
15
16\input{copyright}
17
18\begin{abstract}
19
20\noindent
21This manual documents the API used by C (or C++) programmers who want
22to write extension modules or embed Python. It is a companion to
23``Extending and Embedding the Python Interpreter'', which describes
24the general principles of extension writing but does not document the
25API functions in detail.
26
Guido van Rossum5b8a5231997-12-30 04:38:44 +000027\strong{Warning:} The current version of this document is incomplete.
28I hope that it is nevertheless useful. I will continue to work on it,
29and release new versions from time to time, independent from Python
30source code releases.
31
Guido van Rossum9231c8f1997-05-15 21:43:21 +000032\end{abstract}
33
34\pagebreak
35
36{
37\parskip = 0mm
38\tableofcontents
39}
40
41\pagebreak
42
43\pagenumbering{arabic}
44
Guido van Rossum5060b3b1997-08-17 18:02:23 +000045% XXX Consider moving all this back to ext.tex and giving api.tex
46% XXX a *really* short intro only.
Guido van Rossum9231c8f1997-05-15 21:43:21 +000047
48\chapter{Introduction}
49
Guido van Rossum59a61351997-08-14 20:34:33 +000050The Application Programmer's Interface to Python gives C and C++
51programmers access to the Python interpreter at a variety of levels.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000052The API is equally usable from C++, but for brevity it is generally
53referred to as the Python/C API. There are two fundamentally
54different reasons for using the Python/C API. The first reason is to
55write ``extension modules'' for specific purposes; these are C modules
56that extend the Python interpreter. This is probably the most common
57use. The second reason is to use Python as a component in a larger
58application; this technique is generally referred to as ``embedding''
Guido van Rossum59a61351997-08-14 20:34:33 +000059Python in an application.
60
Guido van Rossum4a944d71997-08-14 20:35:38 +000061Writing an extension module is a relatively well-understood process,
62where a ``cookbook'' approach works well. There are several tools
63that automate the process to some extent. While people have embedded
64Python in other applications since its early existence, the process of
65embedding Python is less straightforward that writing an extension.
66Python 1.5 introduces a number of new API functions as well as some
67changes to the build process that make embedding much simpler.
Guido van Rossum580aa8d1997-11-25 15:34:51 +000068This manual describes the 1.5 state of affair.
Guido van Rossum59a61351997-08-14 20:34:33 +000069% XXX Eventually, take the historical notes out
70
Guido van Rossum4a944d71997-08-14 20:35:38 +000071Many API functions are useful independent of whether you're embedding
72or extending Python; moreover, most applications that embed Python
73will need to provide a custom extension as well, so it's probably a
74good idea to become familiar with writing an extension before
Guido van Rossum59a61351997-08-14 20:34:33 +000075attempting to embed Python in a real application.
76
Guido van Rossum580aa8d1997-11-25 15:34:51 +000077\section{Include Files}
78
79All function, type and macro definitions needed to use the Python/C
80API are included in your code by the following line:
81
82\code{\#include "Python.h"}
83
84This implies inclusion of the following standard header files:
85stdio.h, string.h, errno.h, and stdlib.h (if available).
86
87All user visible names defined by Python.h (except those defined by
88the included standard headers) have one of the prefixes \code{Py} or
89\code{_Py}. Names beginning with \code{_Py} are for internal use
90only. Structure member names do not have a reserved prefix.
91
92Important: user code should never define names that begin with
93\code{Py} or \code{_Py}. This confuses the reader, and jeopardizes
94the portability of the user code to future Python versions, which may
95define additional names beginning with one of these prefixes.
96
Guido van Rossum59a61351997-08-14 20:34:33 +000097\section{Objects, Types and Reference Counts}
98
Guido van Rossum580aa8d1997-11-25 15:34:51 +000099Most Python/C API functions have one or more arguments as well as a
100return value of type \code{PyObject *}. This type is a pointer
101(obviously!) to an opaque data type representing an arbitrary Python
102object. Since all Python object types are treated the same way by the
103Python language in most situations (e.g., assignments, scope rules,
104and argument passing), it is only fitting that they should be
Guido van Rossum59a61351997-08-14 20:34:33 +0000105represented by a single C type. All Python objects live on the heap:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000106you never declare an automatic or static variable of type
Guido van Rossum4a944d71997-08-14 20:35:38 +0000107\code{PyObject}, only pointer variables of type \code{PyObject *} can
Guido van Rossum59a61351997-08-14 20:34:33 +0000108be declared.
109
Guido van Rossum4a944d71997-08-14 20:35:38 +0000110All Python objects (even Python integers) have a ``type'' and a
111``reference count''. An object's type determines what kind of object
112it is (e.g., an integer, a list, or a user-defined function; there are
113many more as explained in the Python Language Reference Manual). For
114each of the well-known types there is a macro to check whether an
115object is of that type; for instance, \code{PyList_Check(a)} is true
Guido van Rossum59a61351997-08-14 20:34:33 +0000116iff the object pointed to by \code{a} is a Python list.
117
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000118\subsection{Reference Counts}
119
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000120The reference count is important because today's computers have a
Guido van Rossum4a944d71997-08-14 20:35:38 +0000121finite (and often severly limited) memory size; it counts how many
122different places there are that have a reference to an object. Such a
123place could be another object, or a global (or static) C variable, or
124a local variable in some C function. When an object's reference count
125becomes zero, the object is deallocated. If it contains references to
126other objects, their reference count is decremented. Those other
127objects may be deallocated in turn, if this decrement makes their
128reference count become zero, and so on. (There's an obvious problem
129with objects that reference each other here; for now, the solution is
Guido van Rossum59a61351997-08-14 20:34:33 +0000130``don't do that''.)
131
Guido van Rossum4a944d71997-08-14 20:35:38 +0000132Reference counts are always manipulated explicitly. The normal way is
133to use the macro \code{Py_INCREF(a)} to increment an object's
134reference count by one, and \code{Py_DECREF(a)} to decrement it by
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000135one. The decref macro is considerably more complex than the incref one,
Guido van Rossum4a944d71997-08-14 20:35:38 +0000136since it must check whether the reference count becomes zero and then
137cause the object's deallocator, which is a function pointer contained
138in the object's type structure. The type-specific deallocator takes
139care of decrementing the reference counts for other objects contained
140in the object, and so on, if this is a compound object type such as a
141list. There's no chance that the reference count can overflow; at
142least as many bits are used to hold the reference count as there are
143distinct memory locations in virtual memory (assuming
144\code{sizeof(long) >= sizeof(char *)}). Thus, the reference count
Guido van Rossum59a61351997-08-14 20:34:33 +0000145increment is a simple operation.
146
Guido van Rossum4a944d71997-08-14 20:35:38 +0000147It is not necessary to increment an object's reference count for every
148local variable that contains a pointer to an object. In theory, the
149oject's reference count goes up by one when the variable is made to
150point to it and it goes down by one when the variable goes out of
151scope. However, these two cancel each other out, so at the end the
152reference count hasn't changed. The only real reason to use the
153reference count is to prevent the object from being deallocated as
154long as our variable is pointing to it. If we know that there is at
155least one other reference to the object that lives at least as long as
156our variable, there is no need to increment the reference count
157temporarily. An important situation where this arises is in objects
158that are passed as arguments to C functions in an extension module
159that are called from Python; the call mechanism guarantees to hold a
Guido van Rossum59a61351997-08-14 20:34:33 +0000160reference to every argument for the duration of the call.
161
Guido van Rossum4a944d71997-08-14 20:35:38 +0000162However, a common pitfall is to extract an object from a list and
163holding on to it for a while without incrementing its reference count.
164Some other operation might conceivably remove the object from the
165list, decrementing its reference count and possible deallocating it.
166The real danger is that innocent-looking operations may invoke
167arbitrary Python code which could do this; there is a code path which
168allows control to flow back to the user from a \code{Py_DECREF()}, so
Guido van Rossum59a61351997-08-14 20:34:33 +0000169almost any operation is potentially dangerous.
170
Guido van Rossum4a944d71997-08-14 20:35:38 +0000171A safe approach is to always use the generic operations (functions
172whose name begins with \code{PyObject_}, \code{PyNumber_},
173\code{PySequence_} or \code{PyMapping_}). These operations always
174increment the reference count of the object they return. This leaves
175the caller with the responsibility to call \code{Py_DECREF()} when
Guido van Rossum59a61351997-08-14 20:34:33 +0000176they are done with the result; this soon becomes second nature.
177
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000178\subsubsection{Reference Count Details}
179
180The reference count behavior of functions in the Python/C API is best
181expelained in terms of \emph{ownership of references}. Note that we
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000182talk of owning references, never of owning objects; objects are always
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000183shared! When a function owns a reference, it has to dispose of it
184properly -- either by passing ownership on (usually to its caller) or
185by calling \code{Py_DECREF()} or \code{Py_XDECREF()}. When a function
186passes ownership of a reference on to its caller, the caller is said
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000187to receive a \emph{new} reference. When no ownership is transferred,
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000188the caller is said to \emph{borrow} the reference. Nothing needs to
189be done for a borrowed reference.
190
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000191Conversely, when calling a function passes it a reference to an
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000192object, there are two possibilities: the function \emph{steals} a
193reference to the object, or it does not. Few functions steal
194references; the two notable exceptions are \code{PyList_SetItem()} and
195\code{PyTuple_SetItem()}, which steal a reference to the item (but not to
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000196the tuple or list into which the item it put!). These functions were
197designed to steal a reference because of a common idiom for populating
198a tuple or list with newly created objects; for example, the code to
199create the tuple \code{(1, 2, "three")} could look like this
200(forgetting about error handling for the moment; a better way to code
201this is shown below anyway):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000202
203\begin{verbatim}
204PyObject *t;
205t = PyTuple_New(3);
206PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
207PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
208PyTuple_SetItem(t, 2, PyString_FromString("three"));
209\end{verbatim}
210
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000211Incidentally, \code{PyTuple_SetItem()} is the \emph{only} way to set
212tuple items; \code{PySequence_SetItem()} and \code{PyObject_SetItem()}
213refuse to do this since tuples are an immutable data type. You should
214only use \code{PyTuple_SetItem()} for tuples that you are creating
215yourself.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000216
217Equivalent code for populating a list can be written using
218\code{PyList_New()} and \code{PyList_SetItem()}. Such code can also
219use \code{PySequence_SetItem()}; this illustrates the difference
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000220between the two (the extra \code{Py_DECREF()} calls):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000221
222\begin{verbatim}
223PyObject *l, *x;
224l = PyList_New(3);
225x = PyInt_FromLong(1L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000226PySequence_SetItem(l, 0, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000227x = PyInt_FromLong(2L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000228PySequence_SetItem(l, 1, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000229x = PyString_FromString("three");
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000230PySequence_SetItem(l, 2, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000231\end{verbatim}
232
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000233You might find it strange that the ``recommended'' approach takes more
234code. However, in practice, you will rarely use these ways of
235creating and populating a tuple or list. There's a generic function,
236\code{Py_BuildValue()}, that can create most common objects from C
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000237values, directed by a ``format string''. For example, the above two
238blocks of code could be replaced by the following (which also takes
239care of the error checking!):
240
241\begin{verbatim}
242PyObject *t, *l;
243t = Py_BuildValue("(iis)", 1, 2, "three");
244l = Py_BuildValue("[iis]", 1, 2, "three");
245\end{verbatim}
246
247It is much more common to use \code{PyObject_SetItem()} and friends
248with items whose references you are only borrowing, like arguments
249that were passed in to the function you are writing. In that case,
250their behaviour regarding reference counts is much saner, since you
251don't have to increment a reference count so you can give a reference
252away (``have it be stolen''). For example, this function sets all
253items of a list (actually, any mutable sequence) to a given item:
254
255\begin{verbatim}
256int set_all(PyObject *target, PyObject *item)
257{
258 int i, n;
259 n = PyObject_Length(target);
260 if (n < 0)
261 return -1;
262 for (i = 0; i < n; i++) {
263 if (PyObject_SetItem(target, i, item) < 0)
264 return -1;
265 }
266 return 0;
267}
268\end{verbatim}
269
270The situation is slightly different for function return values.
271While passing a reference to most functions does not change your
272ownership responsibilities for that reference, many functions that
273return a referece to an object give you ownership of the reference.
274The reason is simple: in many cases, the returned object is created
275on the fly, and the reference you get is the only reference to the
276object! Therefore, the generic functions that return object
277references, like \code{PyObject_GetItem()} and
278\code{PySequence_GetItem()}, always return a new reference (i.e., the
279caller becomes the owner of the reference).
280
281It is important to realize that whether you own a reference returned
282by a function depends on which function you call only -- \emph{the
283plumage} (i.e., the type of the type of the object passed as an
284argument to the function) \emph{don't enter into it!} Thus, if you
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000285extract an item from a list using \code{PyList_GetItem()}, you don't
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000286own the reference -- but if you obtain the same item from the same
287list using \code{PySequence_GetItem()} (which happens to take exactly
288the same arguments), you do own a reference to the returned object.
289
290Here is an example of how you could write a function that computes the
291sum of the items in a list of integers; once using
292\code{PyList_GetItem()}, once using \code{PySequence_GetItem()}.
293
294\begin{verbatim}
295long sum_list(PyObject *list)
296{
297 int i, n;
298 long total = 0;
299 PyObject *item;
300 n = PyList_Size(list);
301 if (n < 0)
302 return -1; /* Not a list */
303 for (i = 0; i < n; i++) {
304 item = PyList_GetItem(list, i); /* Can't fail */
305 if (!PyInt_Check(item)) continue; /* Skip non-integers */
306 total += PyInt_AsLong(item);
307 }
308 return total;
309}
310\end{verbatim}
311
312\begin{verbatim}
313long sum_sequence(PyObject *sequence)
314{
315 int i, n;
316 long total = 0;
317 PyObject *item;
318 n = PyObject_Size(list);
319 if (n < 0)
320 return -1; /* Has no length */
321 for (i = 0; i < n; i++) {
322 item = PySequence_GetItem(list, i);
323 if (item == NULL)
324 return -1; /* Not a sequence, or other failure */
325 if (PyInt_Check(item))
326 total += PyInt_AsLong(item);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000327 Py_DECREF(item); /* Discard reference ownership */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000328 }
329 return total;
330}
331\end{verbatim}
332
333\subsection{Types}
334
335There are few other data types that play a significant role in
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000336the Python/C API; most are simple C types such as \code{int},
Guido van Rossum4a944d71997-08-14 20:35:38 +0000337\code{long}, \code{double} and \code{char *}. A few structure types
338are used to describe static tables used to list the functions exported
339by a module or the data attributes of a new object type. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000340be discussed together with the functions that use them.
341
342\section{Exceptions}
343
Guido van Rossum4a944d71997-08-14 20:35:38 +0000344The Python programmer only needs to deal with exceptions if specific
345error handling is required; unhandled exceptions are automatically
346propagated to the caller, then to the caller's caller, and so on, till
347they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000348user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000349
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000350For C programmers, however, error checking always has to be explicit.
351All functions in the Python/C API can raise exceptions, unless an
352explicit claim is made otherwise in a function's documentation. In
353general, when a function encounters an error, it sets an exception,
354discards any object references that it owns, and returns an
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000355error indicator -- usually \NULL{} or \code{-1}. A few functions
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000356return a Boolean true/false result, with false indicating an error.
357Very few functions return no explicit error indicator or have an
358ambiguous return value, and require explicit testing for errors with
359\code{PyErr_Occurred()}.
360
361Exception state is maintained in per-thread storage (this is
362equivalent to using global storage in an unthreaded application). A
363thread can be on one of two states: an exception has occurred, or not.
364The function \code{PyErr_Occurred()} can be used to check for this: it
365returns a borrowed reference to the exception type object when an
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000366exception has occurred, and \NULL{} otherwise. There are a number
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000367of functions to set the exception state: \code{PyErr_SetString()} is
368the most common (though not the most general) function to set the
369exception state, and \code{PyErr_Clear()} clears the exception state.
370
371The full exception state consists of three objects (all of which can
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000372be \NULL{} ): the exception type, the corresponding exception
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000373value, and the traceback. These have the same meanings as the Python
374object \code{sys.exc_type}, \code{sys.exc_value},
375\code{sys.exc_traceback}; however, they are not the same: the Python
376objects represent the last exception being handled by a Python
377\code{try...except} statement, while the C level exception state only
378exists while an exception is being passed on between C functions until
379it reaches the Python interpreter, which takes care of transferring it
380to \code{sys.exc_type} and friends.
381
382(Note that starting with Python 1.5, the preferred, thread-safe way to
383access the exception state from Python code is to call the function
384\code{sys.exc_info()}, which returns the per-thread exception state
385for Python code. Also, the semantics of both ways to access the
386exception state have changed so that a function which catches an
387exception will save and restore its thread's exception state so as to
388preserve the exception state of its caller. This prevents common bugs
389in exception handling code caused by an innocent-looking function
390overwriting the exception being handled; it also reduces the often
391unwanted lifetime extension for objects that are referenced by the
392stack frames in the traceback.)
393
394As a general principle, a function that calls another function to
395perform some task should check whether the called function raised an
396exception, and if so, pass the exception state on to its caller. It
397should discards any object references that it owns, and returns an
398error indicator, but it should \emph{not} set another exception --
399that would overwrite the exception that was just raised, and lose
400important reason about the exact cause of the error.
401
402A simple example of detecting exceptions and passing them on is shown
403in the \code{sum_sequence()} example above. It so happens that that
404example doesn't need to clean up any owned references when it detects
405an error. The following example function shows some error cleanup.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000406First, to remind you why you like Python, we show the equivalent
407Python code:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000408
409\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000410def incr_item(dict, key):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000411 try:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000412 item = dict[key]
413 except KeyError:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000414 item = 0
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000415 return item + 1
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000416\end{verbatim}
417
418Here is the corresponding C code, in all its glory:
419
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000420\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000421int incr_item(PyObject *dict, PyObject *key)
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000422{
423 /* Objects all initialized to NULL for Py_XDECREF */
424 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000425 int rv = -1; /* Return value initialized to -1 (failure) */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000426
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000427 item = PyObject_GetItem(dict, key);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000428 if (item == NULL) {
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000429 /* Handle keyError only: */
430 if (!PyErr_ExceptionMatches(PyExc_keyError)) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000431
432 /* Clear the error and use zero: */
433 PyErr_Clear();
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000434 item = PyInt_FromLong(0L);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000435 if (item == NULL) goto error;
436 }
437
438 const_one = PyInt_FromLong(1L);
439 if (const_one == NULL) goto error;
440
441 incremented_item = PyNumber_Add(item, const_one);
442 if (incremented_item == NULL) goto error;
443
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000444 if (PyObject_SetItem(dict, key, incremented_item) < 0) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000445 rv = 0; /* Success */
446 /* Continue with cleanup code */
447
448 error:
449 /* Cleanup code, shared by success and failure path */
450
451 /* Use Py_XDECREF() to ignore NULL references */
452 Py_XDECREF(item);
453 Py_XDECREF(const_one);
454 Py_XDECREF(incremented_item);
455
456 return rv; /* -1 for error, 0 for success */
457}
458\end{verbatim}
459
460This example represents an endorsed use of the \code{goto} statement
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000461in C! It illustrates the use of \code{PyErr_ExceptionMatches()} and
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000462\code{PyErr_Clear()} to handle specific exceptions, and the use of
463\code{Py_XDECREF()} to dispose of owned references that may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000464\NULL{} (note the `X' in the name; \code{Py_DECREF()} would crash
465when confronted with a \NULL{} reference). It is important that
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000466the variables used to hold owned references are initialized to
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000467\NULL{} for this to work; likewise, the proposed return value is
468initialized to \code{-1} (failure) and only set to success after
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000469the final call made is successful.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000470
Guido van Rossum59a61351997-08-14 20:34:33 +0000471
472\section{Embedding Python}
473
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000474The one important task that only embedders (as opposed to extension
475writers) of the Python interpreter have to worry about is the
476initialization, and possibly the finalization, of the Python
477interpreter. Most functionality of the interpreter can only be used
478after the interpreter has been initialized.
Guido van Rossum59a61351997-08-14 20:34:33 +0000479
Guido van Rossum4a944d71997-08-14 20:35:38 +0000480The basic initialization function is \code{Py_Initialize()}. This
481initializes the table of loaded modules, and creates the fundamental
482modules \code{__builtin__}, \code{__main__} and \code{sys}. It also
Guido van Rossum59a61351997-08-14 20:34:33 +0000483initializes the module search path (\code{sys.path}).
484
Guido van Rossum4a944d71997-08-14 20:35:38 +0000485\code{Py_Initialize()} does not set the ``script argument list''
486(\code{sys.argv}). If this variable is needed by Python code that
487will be executed later, it must be set explicitly with a call to
488\code{PySys_SetArgv(\var{argc}, \var{argv})} subsequent to the call
Guido van Rossum59a61351997-08-14 20:34:33 +0000489to \code{Py_Initialize()}.
490
Guido van Rossum42cefd01997-10-05 15:27:29 +0000491On most systems (in particular, on Unix and Windows, although the
492details are slightly different), \code{Py_Initialize()} calculates the
493module search path based upon its best guess for the location of the
494standard Python interpreter executable, assuming that the Python
495library is found in a fixed location relative to the Python
496interpreter executable. In particular, it looks for a directory named
497\code{lib/python1.5} (replacing \code{1.5} with the current
498interpreter version) relative to the parent directory where the
499executable named \code{python} is found on the shell command search
500path (the environment variable \code{\$PATH}).
501
502For instance, if the Python executable is found in
503\code{/usr/local/bin/python}, it will assume that the libraries are in
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000504\code{/usr/local/lib/python1.5}. (In fact, this particular path is
505also the ``fallback'' location, used when no executable file named
506\code{python} is found along \code{\$PATH}.) The user can override
507this behavior by setting the environment variable \code{\$PYTHONHOME},
508or insert additional directories in front of the standard path by
509setting \code{\$PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000510
Guido van Rossum4a944d71997-08-14 20:35:38 +0000511The embedding application can steer the search by calling
512\code{Py_SetProgramName(\var{file})} \emph{before} calling
Guido van Rossum09270b51997-08-15 18:57:32 +0000513\code{Py_Initialize()}. Note that \code{\$PYTHONHOME} still overrides
Guido van Rossum4a944d71997-08-14 20:35:38 +0000514this and \code{\$PYTHONPATH} is still inserted in front of the
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000515standard path. An application that requires total control has to
516provide its own implementation of \code{Py_GetPath()},
517\code{Py_GetPrefix()}, \code{Py_GetExecPrefix()},
518\code{Py_GetProgramFullPath()} (all defined in
519\file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000520
Guido van Rossum4a944d71997-08-14 20:35:38 +0000521Sometimes, it is desirable to ``uninitialize'' Python. For instance,
522the application may want to start over (make another call to
523\code{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000524use of Python and wants to free all memory allocated by Python. This
525can be accomplished by calling \code{Py_Finalize()}. The function
526\code{Py_IsInitialized()} returns true iff Python is currently in the
527initialized state. More information about these functions is given in
528a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000529
Guido van Rossum4a944d71997-08-14 20:35:38 +0000530
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000531\chapter{Basic Utilities}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000532
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000533XXX These utilities should be moved to some other section...
Guido van Rossum4a944d71997-08-14 20:35:38 +0000534
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000535\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
536Print a fatal error message and kill the process. No cleanup is
537performed. This function should only be invoked when a condition is
538detected that would make it dangerous to continue using the Python
539interpreter; e.g., when the object administration appears to be
540corrupted. On Unix, the standard C library function \code{abort()} is
541called which will attempt to produce a \file{core} file.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000542\end{cfuncdesc}
543
544\begin{cfuncdesc}{void}{Py_Exit}{int status}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000545Exit the current process. This calls \code{Py_Finalize()} and then
546calls the standard C library function \code{exit(0)}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000547\end{cfuncdesc}
548
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000549\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
550Register a cleanup function to be called by \code{Py_Finalize()}. The
551cleanup function will be called with no arguments and should return no
552value. At most 32 cleanup functions can be registered. When the
553registration is successful, \code{Py_AtExit} returns 0; on failure, it
554returns -1. The cleanup function registered last is called first.
555Each cleanup function will be called at most once.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000556\end{cfuncdesc}
557
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000558
559\chapter{Reference Counting}
560
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000561The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000562of Python objects.
563
564\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
565Increment the reference count for object \code{o}. The object must
566not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
567\code{Py_XINCREF()}.
568\end{cfuncdesc}
569
570\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
571Increment the reference count for object \code{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000572\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000573\end{cfuncdesc}
574
575\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
576Decrement the reference count for object \code{o}. The object must
577not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
578\code{Py_XDECREF()}. If the reference count reaches zero, the object's
579type's deallocation function (which must not be \NULL{}) is invoked.
580
581\strong{Warning:} The deallocation function can cause arbitrary Python
582code to be invoked (e.g. when a class instance with a \code{__del__()}
583method is deallocated). While exceptions in such code are not
584propagated, the executed code has free access to all Python global
585variables. This means that any object that is reachable from a global
586variable should be in a consistent state before \code{Py_DECREF()} is
587invoked. For example, code to delete an object from a list should
588copy a reference to the deleted object in a temporary variable, update
589the list data structure, and then call \code{Py_DECREF()} for the
590temporary variable.
591\end{cfuncdesc}
592
593\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
594Decrement the reference count for object \code{o}.The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000595\NULL{}, in which case the macro has no effect; otherwise the
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000596effect is the same as for \code{Py_DECREF()}, and the same warning
597applies.
598\end{cfuncdesc}
599
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000600The following functions or macros are only for internal use:
Guido van Rossumae110af1997-05-22 20:11:52 +0000601\code{_Py_Dealloc}, \code{_Py_ForgetReference}, \code{_Py_NewReference},
602as well as the global variable \code{_Py_RefTotal}.
603
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000604XXX Should mention Py_Malloc(), Py_Realloc(), Py_Free(),
605PyMem_Malloc(), PyMem_Realloc(), PyMem_Free(), PyMem_NEW(),
606PyMem_RESIZE(), PyMem_DEL(), PyMem_XDEL().
607
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000608
609\chapter{Exception Handling}
610
611The functions in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000612exceptions. It is important to understand some of the basics of
613Python exception handling. It works somewhat like the Unix
614\code{errno} variable: there is a global indicator (per thread) of the
615last error that occurred. Most functions don't clear this on success,
616but will set it to indicate the cause of the error on failure. Most
617functions also return an error indicator, usually \NULL{} if they are
618supposed to return a pointer, or -1 if they return an integer
619(exception: the \code{PyArg_Parse*()} functions return 1 for success and
Guido van Rossum5b8a5231997-12-30 04:38:44 +00006200 for failure). When a function must fail because some function it
Guido van Rossumae110af1997-05-22 20:11:52 +0000621called failed, it generally doesn't set the error indicator; the
622function it called already set it.
623
624The error indicator consists of three Python objects corresponding to
625the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
626\code{sys.exc_traceback}. API functions exist to interact with the
627error indicator in various ways. There is a separate error indicator
628for each thread.
629
630% XXX Order of these should be more thoughtful.
631% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000632
633\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000634Print a standard traceback to \code{sys.stderr} and clear the error
635indicator. Call this function only when the error indicator is set.
636(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000637\end{cfuncdesc}
638
Guido van Rossumae110af1997-05-22 20:11:52 +0000639\begin{cfuncdesc}{PyObject *}{PyErr_Occurred}{}
640Test whether the error indicator is set. If set, return the exception
641\code{type} (the first argument to the last call to one of the
642\code{PyErr_Set*()} functions or to \code{PyErr_Restore()}). If not
643set, return \NULL{}. You do not own a reference to the return value,
Guido van Rossum42cefd01997-10-05 15:27:29 +0000644so you do not need to \code{Py_DECREF()} it. Note: do not compare the
645return value to a specific exception; use
646\code{PyErr_ExceptionMatches} instead, shown below.
647\end{cfuncdesc}
648
649\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000650\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000651Equivalent to
652\code{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
653This should only be called when an exception is actually set.
654\end{cfuncdesc}
655
656\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000657\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000658Return true if the \var{given} exception matches the exception in
659\var{exc}. If \var{exc} is a class object, this also returns true
660when \var{given} is a subclass. If \var{exc} is a tuple, all
661exceptions in the tuple (and recursively in subtuples) are searched
662for a match. This should only be called when an exception is actually
663set.
664\end{cfuncdesc}
665
666\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000667\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000668Under certain circumstances, the values returned by
669\code{PyErr_Fetch()} below can be ``unnormalized'', meaning that
670\var{*exc} is a class object but \var{*val} is not an instance of the
671same class. This function can be used to instantiate the class in
672that case. If the values are already normalized, nothing happens.
Guido van Rossumae110af1997-05-22 20:11:52 +0000673\end{cfuncdesc}
674
675\begin{cfuncdesc}{void}{PyErr_Clear}{}
676Clear the error indicator. If the error indicator is not set, there
677is no effect.
678\end{cfuncdesc}
679
680\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue, PyObject **ptraceback}
681Retrieve the error indicator into three variables whose addresses are
682passed. If the error indicator is not set, set all three variables to
683\NULL{}. If it is set, it will be cleared and you own a reference to
684each object retrieved. The value and traceback object may be \NULL{}
685even when the type object is not. \strong{Note:} this function is
686normally only used by code that needs to handle exceptions or by code
687that needs to save and restore the error indicator temporarily.
688\end{cfuncdesc}
689
690\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value, PyObject *traceback}
691Set the error indicator from the three objects. If the error
692indicator is already set, it is cleared first. If the objects are
693\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
694and non-\NULL{} value or traceback. The exception type should be a
695string or class; if it is a class, the value should be an instance of
696that class. Do not pass an invalid exception type or value.
697(Violating these rules will cause subtle problems later.) This call
698takes away a reference to each object, i.e. you must own a reference
699to each object before the call and after the call you no longer own
700these references. (If you don't understand this, don't use this
701function. I warned you.) \strong{Note:} this function is normally
702only used by code that needs to save and restore the error indicator
703temporarily.
704\end{cfuncdesc}
705
706\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
707This is the most common way to set the error indicator. The first
708argument specifies the exception type; it is normally one of the
709standard exceptions, e.g. \code{PyExc_RuntimeError}. You need not
710increment its reference count. The second argument is an error
711message; it is converted to a string object.
712\end{cfuncdesc}
713
714\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
715This function is similar to \code{PyErr_SetString()} but lets you
716specify an arbitrary Python object for the ``value'' of the exception.
717You need not increment its reference count.
718\end{cfuncdesc}
719
720\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
721This is a shorthand for \code{PyErr_SetString(\var{type}, Py_None}.
722\end{cfuncdesc}
723
724\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
725This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
726\var{message})}, where \var{message} indicates that a built-in operation
727was invoked with an illegal argument. It is mostly for internal use.
728\end{cfuncdesc}
729
730\begin{cfuncdesc}{PyObject *}{PyErr_NoMemory}{}
731This is a shorthand for \code{PyErr_SetNone(PyExc_MemoryError)}; it
732returns \NULL{} so an object allocation function can write
733\code{return PyErr_NoMemory();} when it runs out of memory.
734\end{cfuncdesc}
735
736\begin{cfuncdesc}{PyObject *}{PyErr_SetFromErrno}{PyObject *type}
737This is a convenience function to raise an exception when a C library
738function has returned an error and set the C variable \code{errno}.
739It constructs a tuple object whose first item is the integer
740\code{errno} value and whose second item is the corresponding error
741message (gotten from \code{strerror()}), and then calls
742\code{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
743the \code{errno} value is \code{EINTR}, indicating an interrupted
744system call, this calls \code{PyErr_CheckSignals()}, and if that set
745the error indicator, leaves it set to that. The function always
746returns \NULL{}, so a wrapper function around a system call can write
747\code{return PyErr_NoMemory();} when the system call returns an error.
748\end{cfuncdesc}
749
750\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
751This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
752\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000753operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000754argument. It is mostly for internal use.
755\end{cfuncdesc}
756
757\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
758This function interacts with Python's signal handling. It checks
759whether a signal has been sent to the processes and if so, invokes the
760corresponding signal handler. If the \code{signal} module is
761supported, this can invoke a signal handler written in Python. In all
762cases, the default effect for \code{SIGINT} is to raise the
763\code{KeyboadInterrupt} exception. If an exception is raised the
764error indicator is set and the function returns 1; otherwise the
765function returns 0. The error indicator may or may not be cleared if
766it was previously set.
767\end{cfuncdesc}
768
769\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
770This function is obsolete (XXX or platform dependent?). It simulates
771the effect of a \code{SIGINT} signal arriving -- the next time
772\code{PyErr_CheckSignals()} is called, \code{KeyboadInterrupt} will be
773raised.
774\end{cfuncdesc}
775
Guido van Rossum42cefd01997-10-05 15:27:29 +0000776\begin{cfuncdesc}{PyObject *}{PyErr_NewException}{char *name,
777PyObject *base, PyObject *dict}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000778\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000779This utility function creates and returns a new exception object. The
780\var{name} argument must be the name of the new exception, a C string
781of the form \code{module.class}. The \var{base} and \var{dict}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000782arguments are normally \NULL{}. Normally, this creates a class
Guido van Rossum42cefd01997-10-05 15:27:29 +0000783object derived from the root for all exceptions, the built-in name
784\code{Exception} (accessible in C as \code{PyExc_Exception}). In this
785case the \code{__module__} attribute of the new class is set to the
786first part (up to the last dot) of the \var{name} argument, and the
787class name is set to the last part (after the last dot). When the
788user has specified the \code{-X} command line option to use string
789exceptions, for backward compatibility, or when the \var{base}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000790argument is not a class object (and not \NULL{}), a string object
Guido van Rossum42cefd01997-10-05 15:27:29 +0000791created from the entire \var{name} argument is returned. The
792\var{base} argument can be used to specify an alternate base class.
793The \var{dict} argument can be used to specify a dictionary of class
794variables and methods.
795\end{cfuncdesc}
796
797
Guido van Rossumae110af1997-05-22 20:11:52 +0000798\section{Standard Exceptions}
799
800All standard Python exceptions are available as global variables whose
801names are \code{PyExc_} followed by the Python exception name.
802These have the type \code{PyObject *}; they are all string objects.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000803For completeness, here are all the variables (the first four are new
804in Python 1.5a4):
805\code{PyExc_Exception},
806\code{PyExc_StandardError},
807\code{PyExc_ArithmeticError},
808\code{PyExc_LookupError},
Guido van Rossumae110af1997-05-22 20:11:52 +0000809\code{PyExc_AssertionError},
810\code{PyExc_AttributeError},
811\code{PyExc_EOFError},
812\code{PyExc_FloatingPointError},
813\code{PyExc_IOError},
814\code{PyExc_ImportError},
815\code{PyExc_IndexError},
816\code{PyExc_KeyError},
817\code{PyExc_KeyboardInterrupt},
818\code{PyExc_MemoryError},
819\code{PyExc_NameError},
820\code{PyExc_OverflowError},
821\code{PyExc_RuntimeError},
822\code{PyExc_SyntaxError},
823\code{PyExc_SystemError},
824\code{PyExc_SystemExit},
825\code{PyExc_TypeError},
826\code{PyExc_ValueError},
827\code{PyExc_ZeroDivisionError}.
828
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000829
830\chapter{Utilities}
831
832The functions in this chapter perform various utility tasks, such as
833parsing function arguments and constructing Python values from C
834values.
835
Guido van Rossum42cefd01997-10-05 15:27:29 +0000836\section{OS Utilities}
837
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000838\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
839Return true (nonzero) if the standard I/O file \code{fp} with name
840\code{filename} is deemed interactive. This is the case for files for
841which \code{isatty(fileno(fp))} is true. If the global flag
842\code{Py_InteractiveFlag} is true, this function also returns true if
843the \code{name} pointer is \NULL{} or if the name is equal to one of
844the strings \code{"<stdin>"} or \code{"???"}.
845\end{cfuncdesc}
846
847\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
848Return the time of last modification of the file \code{filename}.
849The result is encoded in the same way as the timestamp returned by
850the standard C library function \code{time()}.
851\end{cfuncdesc}
852
853
Guido van Rossum42cefd01997-10-05 15:27:29 +0000854\section{Importing modules}
855
856\begin{cfuncdesc}{PyObject *}{PyImport_ImportModule}{char *name}
857This is a simplified interface to \code{PyImport_ImportModuleEx}
858below, leaving the \var{globals} and \var{locals} arguments set to
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000859\NULL{}. When the \var{name} argument contains a dot (i.e., when
Guido van Rossum42cefd01997-10-05 15:27:29 +0000860it specifies a submodule of a package), the \var{fromlist} argument is
861set to the list \code{['*']} so that the return value is the named
862module rather than the top-level package containing it as would
863otherwise be the case. (Unfortunately, this has an additional side
864effect when \var{name} in fact specifies a subpackage instead of a
865submodule: the submodules specified in the package's \code{__all__}
866variable are loaded.) Return a new reference to the imported module,
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000867or \NULL{} with an exception set on failure (the module may still
Guido van Rossum42cefd01997-10-05 15:27:29 +0000868be created in this case).
869\end{cfuncdesc}
870
871\begin{cfuncdesc}{PyObject *}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000872\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000873Import a module. This is best described by referring to the built-in
874Python function \code{__import()__}, as the standard
875\code{__import__()} function calls this function directly.
876
Guido van Rossum42cefd01997-10-05 15:27:29 +0000877The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000878top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000879(the module may still be created in this case). Like for
880\code{__import__()}, the return value when a submodule of a package
881was requested is normally the top-level package, unless a non-empty
882\var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000883\end{cfuncdesc}
884
885\begin{cfuncdesc}{PyObject *}{PyImport_Import}{PyObject *name}
886This is a higher-level interface that calls the current ``import hook
887function''. It invokes the \code{__import__()} function from the
888\code{__builtins__} of the current globals. This means that the
889import is done using whatever import hooks are installed in the
890current environment, e.g. by \code{rexec} or \code{ihooks}.
891\end{cfuncdesc}
892
893\begin{cfuncdesc}{PyObject *}{PyImport_ReloadModule}{PyObject *m}
894Reload a module. This is best described by referring to the built-in
895Python function \code{reload()}, as the standard \code{reload()}
896function calls this function directly. Return a new reference to the
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000897reloaded module, or \NULL{} with an exception set on failure (the
Guido van Rossum42cefd01997-10-05 15:27:29 +0000898module still exists in this case).
899\end{cfuncdesc}
900
901\begin{cfuncdesc}{PyObject *}{PyImport_AddModule}{char *name}
902Return the module object corresponding to a module name. The
903\var{name} argument may be of the form \code{package.module}). First
904check the modules dictionary if there's one there, and if not, create
905a new one and insert in in the modules dictionary. Because the former
906action is most common, this does not return a new reference, and you
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000907do not own the returned reference. Return \NULL{} with an
Guido van Rossum42cefd01997-10-05 15:27:29 +0000908exception set on failure.
909\end{cfuncdesc}
910
911\begin{cfuncdesc}{PyObject *}{PyImport_ExecCodeModule}{char *name, PyObject *co}
912Given a module name (possibly of the form \code{package.module}) and a
913code object read from a Python bytecode file or obtained from the
914built-in function \code{compile()}, load the module. Return a new
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000915reference to the module object, or \NULL{} with an exception set
Guido van Rossum42cefd01997-10-05 15:27:29 +0000916if an error occurred (the module may still be created in this case).
917(This function would reload the module if it was already imported.)
918\end{cfuncdesc}
919
920\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
921Return the magic number for Python bytecode files (a.k.a. \code{.pyc}
922and \code{.pyo} files). The magic number should be present in the
923first four bytes of the bytecode file, in little-endian byte order.
924\end{cfuncdesc}
925
926\begin{cfuncdesc}{PyObject *}{PyImport_GetModuleDict}{}
927Return the dictionary used for the module administration
928(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
929variable.
930\end{cfuncdesc}
931
932\begin{cfuncdesc}{void}{_PyImport_Init}{}
933Initialize the import mechanism. For internal use only.
934\end{cfuncdesc}
935
936\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
937Empty the module table. For internal use only.
938\end{cfuncdesc}
939
940\begin{cfuncdesc}{void}{_PyImport_Fini}{}
941Finalize the import mechanism. For internal use only.
942\end{cfuncdesc}
943
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000944\begin{cfuncdesc}{extern PyObject *}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000945For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000946\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000947
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000948\begin{cfuncdesc}{extern PyObject *}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000949For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000950\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000951
952\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *}
953Load a frozen module. Return \code{1} for success, \code{0} if the
954module is not found, and \code{-1} with an exception set if the
955initialization failed. To access the imported module on a successful
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000956load, use \code{PyImport_ImportModule())}.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000957(Note the misnomer -- this function would reload the module if it was
958already imported.)
959\end{cfuncdesc}
960
961\begin{ctypedesc}{struct _frozen}
962This is the structure type definition for frozen module descriptors,
963as generated by the \code{freeze} utility (see \file{Tools/freeze/} in
964the Python source distribution). Its definition is:
Guido van Rossum9faf4c51997-10-07 14:38:54 +0000965\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000966struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +0000967 char *name;
968 unsigned char *code;
969 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +0000970};
Guido van Rossum9faf4c51997-10-07 14:38:54 +0000971\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000972\end{ctypedesc}
973
974\begin{cvardesc}{struct _frozen *}{PyImport_FrozenModules}
975This pointer is initialized to point to an array of \code{struct
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000976_frozen} records, terminated by one whose members are all \NULL{}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000977or zero. When a frozen module is imported, it is searched in this
978table. Third party code could play tricks with this to provide a
979dynamically created collection of frozen modules.
980\end{cvardesc}
981
982
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000983\chapter{Debugging}
984
985XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
986
987
988\chapter{The Very High Level Layer}
989
990The functions in this chapter will let you execute Python source code
991given in a file or a buffer, but they will not let you interact in a
992more detailed way with the interpreter.
993
Guido van Rossumae110af1997-05-22 20:11:52 +0000994\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *, char *}
995\end{cfuncdesc}
996
997\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *}
998\end{cfuncdesc}
999
1000\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *, char *}
1001\end{cfuncdesc}
1002
1003\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *, char *}
1004\end{cfuncdesc}
1005
1006\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *, char *}
1007\end{cfuncdesc}
1008
1009\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseString}{char *, int}
1010\end{cfuncdesc}
1011
1012\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseFile}{FILE *, char *, int}
1013\end{cfuncdesc}
1014
Guido van Rossumb9046291997-08-21 02:28:57 +00001015\begin{cfuncdesc}{}{PyObject *PyRun_String}{char *, int, PyObject *, PyObject *}
Guido van Rossumae110af1997-05-22 20:11:52 +00001016\end{cfuncdesc}
1017
Guido van Rossumb9046291997-08-21 02:28:57 +00001018\begin{cfuncdesc}{}{PyObject *PyRun_File}{FILE *, char *, int, PyObject *, PyObject *}
Guido van Rossumae110af1997-05-22 20:11:52 +00001019\end{cfuncdesc}
1020
Guido van Rossumb9046291997-08-21 02:28:57 +00001021\begin{cfuncdesc}{}{PyObject *Py_CompileString}{char *, char *, int}
Guido van Rossumae110af1997-05-22 20:11:52 +00001022\end{cfuncdesc}
1023
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001024
1025\chapter{Abstract Objects Layer}
1026
1027The functions in this chapter interact with Python objects regardless
1028of their type, or with wide classes of object types (e.g. all
1029numerical types, or all sequence types). When used on object types
1030for which they do not apply, they will flag a Python exception.
1031
1032\section{Object Protocol}
1033
1034\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
1035Print an object \code{o}, on file \code{fp}. Returns -1 on error
1036The flags argument is used to enable certain printing
1037options. The only option currently supported is \code{Py_Print_RAW}.
1038\end{cfuncdesc}
1039
1040\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
1041Returns 1 if o has the attribute attr_name, and 0 otherwise.
1042This is equivalent to the Python expression:
1043\code{hasattr(o,attr_name)}.
1044This function always succeeds.
1045\end{cfuncdesc}
1046
1047\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o, char *attr_name}
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001048Retrieve an attribute named attr_name from object o.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001049Returns the attribute value on success, or \NULL{} on failure.
1050This is the equivalent of the Python expression: \code{o.attr_name}.
1051\end{cfuncdesc}
1052
1053
1054\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
1055Returns 1 if o has the attribute attr_name, and 0 otherwise.
1056This is equivalent to the Python expression:
1057\code{hasattr(o,attr_name)}.
1058This function always succeeds.
1059\end{cfuncdesc}
1060
1061
1062\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o, PyObject *attr_name}
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001063Retrieve an attribute named attr_name from object o.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001064Returns the attribute value on success, or \NULL{} on failure.
1065This is the equivalent of the Python expression: o.attr_name.
1066\end{cfuncdesc}
1067
1068
1069\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
1070Set the value of the attribute named \code{attr_name}, for object \code{o},
1071to the value \code{v}. Returns -1 on failure. This is
1072the equivalent of the Python statement: \code{o.attr_name=v}.
1073\end{cfuncdesc}
1074
1075
1076\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
1077Set the value of the attribute named \code{attr_name}, for
1078object \code{o},
1079to the value \code{v}. Returns -1 on failure. This is
1080the equivalent of the Python statement: \code{o.attr_name=v}.
1081\end{cfuncdesc}
1082
1083
1084\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
1085Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1086failure. This is the equivalent of the Python
1087statement: \code{del o.attr_name}.
1088\end{cfuncdesc}
1089
1090
1091\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
1092Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1093failure. This is the equivalent of the Python
1094statement: \code{del o.attr_name}.
1095\end{cfuncdesc}
1096
1097
1098\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
1099Compare the values of \code{o1} and \code{o2} using a routine provided by
1100\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1101The result of the comparison is returned in \code{result}. Returns
1102-1 on failure. This is the equivalent of the Python
1103statement: \code{result=cmp(o1,o2)}.
1104\end{cfuncdesc}
1105
1106
1107\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
1108Compare the values of \code{o1} and \code{o2} using a routine provided by
1109\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1110Returns the result of the comparison on success. On error,
1111the value returned is undefined. This is equivalent to the
1112Python expression: \code{cmp(o1,o2)}.
1113\end{cfuncdesc}
1114
1115
1116\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
1117Compute the string representation of object, \code{o}. Returns the
1118string representation on success, \NULL{} on failure. This is
1119the equivalent of the Python expression: \code{repr(o)}.
1120Called by the \code{repr()} built-in function and by reverse quotes.
1121\end{cfuncdesc}
1122
1123
1124\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
1125Compute the string representation of object, \code{o}. Returns the
1126string representation on success, \NULL{} on failure. This is
1127the equivalent of the Python expression: \code{str(o)}.
1128Called by the \code{str()} built-in function and by the \code{print}
1129statement.
1130\end{cfuncdesc}
1131
1132
1133\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
1134Determine if the object \code{o}, is callable. Return 1 if the
1135object is callable and 0 otherwise.
1136This function always succeeds.
1137\end{cfuncdesc}
1138
1139
1140\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object, PyObject *args}
1141Call a callable Python object \code{callable_object}, with
1142arguments given by the tuple \code{args}. If no arguments are
1143needed, then args may be \NULL{}. Returns the result of the
1144call on success, or \NULL{} on failure. This is the equivalent
1145of the Python expression: \code{apply(o, args)}.
1146\end{cfuncdesc}
1147
1148\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
1149Call a callable Python object \code{callable_object}, with a
1150variable number of C arguments. The C arguments are described
1151using a mkvalue-style format string. The format may be \NULL{},
1152indicating that no arguments are provided. Returns the
1153result of the call on success, or \NULL{} on failure. This is
1154the equivalent of the Python expression: \code{apply(o,args)}.
1155\end{cfuncdesc}
1156
1157
1158\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
1159Call the method named \code{m} of object \code{o} with a variable number of
1160C arguments. The C arguments are described by a mkvalue
1161format string. The format may be \NULL{}, indicating that no
1162arguments are provided. Returns the result of the call on
1163success, or \NULL{} on failure. This is the equivalent of the
1164Python expression: \code{o.method(args)}.
1165Note that Special method names, such as "\code{__add__}",
1166"\code{__getitem__}", and so on are not supported. The specific
1167abstract-object routines for these must be used.
1168\end{cfuncdesc}
1169
1170
1171\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
1172Compute and return the hash value of an object \code{o}. On
1173failure, return -1. This is the equivalent of the Python
1174expression: \code{hash(o)}.
1175\end{cfuncdesc}
1176
1177
1178\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
1179Returns 1 if the object \code{o} is considered to be true, and
11800 otherwise. This is equivalent to the Python expression:
1181\code{not not o}.
1182This function always succeeds.
1183\end{cfuncdesc}
1184
1185
1186\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1187On success, returns a type object corresponding to the object
1188type of object \code{o}. On failure, returns \NULL{}. This is
1189equivalent to the Python expression: \code{type(o)}.
1190\end{cfuncdesc}
1191
1192\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
1193Return the length of object \code{o}. If the object \code{o} provides
1194both sequence and mapping protocols, the sequence length is
1195returned. On error, -1 is returned. This is the equivalent
1196to the Python expression: \code{len(o)}.
1197\end{cfuncdesc}
1198
1199
1200\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
1201Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1202on failure. This is the equivalent of the Python expression:
1203\code{o[key]}.
1204\end{cfuncdesc}
1205
1206
1207\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
1208Map the object \code{key} to the value \code{v}.
1209Returns -1 on failure. This is the equivalent
1210of the Python statement: \code{o[key]=v}.
1211\end{cfuncdesc}
1212
1213
1214\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key, PyObject *v}
1215Delete the mapping for \code{key} from \code{*o}. Returns -1
1216on failure.
Guido van Rossum59a61351997-08-14 20:34:33 +00001217This is the equivalent of the Python statement: \code{del o[key]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001218\end{cfuncdesc}
1219
1220
1221\section{Number Protocol}
1222
1223\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
1224Returns 1 if the object \code{o} provides numeric protocols, and
1225false otherwise.
1226This function always succeeds.
1227\end{cfuncdesc}
1228
1229
1230\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
1231Returns the result of adding \code{o1} and \code{o2}, or null on failure.
1232This is the equivalent of the Python expression: \code{o1+o2}.
1233\end{cfuncdesc}
1234
1235
1236\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
1237Returns the result of subtracting \code{o2} from \code{o1}, or null on
1238failure. This is the equivalent of the Python expression:
1239\code{o1-o2}.
1240\end{cfuncdesc}
1241
1242
1243\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
1244Returns the result of multiplying \code{o1} and \code{o2}, or null on
1245failure. This is the equivalent of the Python expression:
1246\code{o1*o2}.
1247\end{cfuncdesc}
1248
1249
1250\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
1251Returns the result of dividing \code{o1} by \code{o2}, or null on failure.
1252This is the equivalent of the Python expression: \code{o1/o2}.
1253\end{cfuncdesc}
1254
1255
1256\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
1257Returns the remainder of dividing \code{o1} by \code{o2}, or null on
1258failure. This is the equivalent of the Python expression:
1259\code{o1\%o2}.
1260\end{cfuncdesc}
1261
1262
1263\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
1264See the built-in function divmod. Returns \NULL{} on failure.
1265This is the equivalent of the Python expression:
1266\code{divmod(o1,o2)}.
1267\end{cfuncdesc}
1268
1269
1270\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
1271See the built-in function pow. Returns \NULL{} on failure.
1272This is the equivalent of the Python expression:
1273\code{pow(o1,o2,o3)}, where \code{o3} is optional.
1274\end{cfuncdesc}
1275
1276
1277\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
1278Returns the negation of \code{o} on success, or null on failure.
1279This is the equivalent of the Python expression: \code{-o}.
1280\end{cfuncdesc}
1281
1282
1283\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
1284Returns \code{o} on success, or \NULL{} on failure.
1285This is the equivalent of the Python expression: \code{+o}.
1286\end{cfuncdesc}
1287
1288
1289\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
1290Returns the absolute value of \code{o}, or null on failure. This is
1291the equivalent of the Python expression: \code{abs(o)}.
1292\end{cfuncdesc}
1293
1294
1295\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
1296Returns the bitwise negation of \code{o} on success, or \NULL{} on
1297failure. This is the equivalent of the Python expression:
Guido van Rossum59a61351997-08-14 20:34:33 +00001298\code{\~o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001299\end{cfuncdesc}
1300
1301
1302\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
1303Returns the result of left shifting \code{o1} by \code{o2} on success, or
1304\NULL{} on failure. This is the equivalent of the Python
1305expression: \code{o1 << o2}.
1306\end{cfuncdesc}
1307
1308
1309\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
1310Returns the result of right shifting \code{o1} by \code{o2} on success, or
1311\NULL{} on failure. This is the equivalent of the Python
1312expression: \code{o1 >> o2}.
1313\end{cfuncdesc}
1314
1315
1316\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
1317Returns the result of "anding" \code{o2} and \code{o2} on success and \NULL{}
1318on failure. This is the equivalent of the Python
1319expression: \code{o1 and o2}.
1320\end{cfuncdesc}
1321
1322
1323\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
1324Returns the bitwise exclusive or of \code{o1} by \code{o2} on success, or
1325\NULL{} on failure. This is the equivalent of the Python
1326expression: \code{o1\^{ }o2}.
1327\end{cfuncdesc}
1328
1329\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Guido van Rossum59a61351997-08-14 20:34:33 +00001330Returns the result of \code{o1} and \code{o2} on success, or \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001331failure. This is the equivalent of the Python expression:
1332\code{o1 or o2}.
1333\end{cfuncdesc}
1334
1335
1336\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject *o1, PyObject *o2}
1337This function takes the addresses of two variables of type
1338\code{PyObject*}.
1339
1340If the objects pointed to by \code{*p1} and \code{*p2} have the same type,
1341increment their reference count and return 0 (success).
1342If the objects can be converted to a common numeric type,
1343replace \code{*p1} and \code{*p2} by their converted value (with 'new'
1344reference counts), and return 0.
1345If no conversion is possible, or if some other error occurs,
1346return -1 (failure) and don't increment the reference counts.
1347The call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1348statement \code{o1, o2 = coerce(o1, o2)}.
1349\end{cfuncdesc}
1350
1351
1352\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
1353Returns the \code{o} converted to an integer object on success, or
1354\NULL{} on failure. This is the equivalent of the Python
1355expression: \code{int(o)}.
1356\end{cfuncdesc}
1357
1358
1359\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
1360Returns the \code{o} converted to a long integer object on success,
1361or \NULL{} on failure. This is the equivalent of the Python
1362expression: \code{long(o)}.
1363\end{cfuncdesc}
1364
1365
1366\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
1367Returns the \code{o} converted to a float object on success, or \NULL{}
1368on failure. This is the equivalent of the Python expression:
1369\code{float(o)}.
1370\end{cfuncdesc}
1371
1372
1373\section{Sequence protocol}
1374
1375\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
1376Return 1 if the object provides sequence protocol, and 0
1377otherwise.
1378This function always succeeds.
1379\end{cfuncdesc}
1380
1381
1382\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001383Return the concatenation of \code{o1} and \code{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001384failure. This is the equivalent of the Python
1385expression: \code{o1+o2}.
1386\end{cfuncdesc}
1387
1388
1389\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Guido van Rossum59a61351997-08-14 20:34:33 +00001390Return the result of repeating sequence object \code{o} \code{count} times,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001391or \NULL{} on failure. This is the equivalent of the Python
1392expression: \code{o*count}.
1393\end{cfuncdesc}
1394
1395
1396\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
1397Return the ith element of \code{o}, or \NULL{} on failure. This is the
1398equivalent of the Python expression: \code{o[i]}.
1399\end{cfuncdesc}
1400
1401
1402\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
1403Return the slice of sequence object \code{o} between \code{i1} and \code{i2}, or
1404\NULL{} on failure. This is the equivalent of the Python
1405expression, \code{o[i1:i2]}.
1406\end{cfuncdesc}
1407
1408
1409\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
1410Assign object \code{v} to the \code{i}th element of \code{o}.
1411Returns -1 on failure. This is the equivalent of the Python
1412statement, \code{o[i]=v}.
1413\end{cfuncdesc}
1414
1415\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
1416Delete the \code{i}th element of object \code{v}. Returns
1417-1 on failure. This is the equivalent of the Python
1418statement: \code{del o[i]}.
1419\end{cfuncdesc}
1420
1421\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1, int i2, PyObject *v}
1422Assign the sequence object \code{v} to the slice in sequence
1423object \code{o} from \code{i1} to \code{i2}. This is the equivalent of the Python
1424statement, \code{o[i1:i2]=v}.
1425\end{cfuncdesc}
1426
1427\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
1428Delete the slice in sequence object, \code{o}, from \code{i1} to \code{i2}.
1429Returns -1 on failure. This is the equivalent of the Python
1430statement: \code{del o[i1:i2]}.
1431\end{cfuncdesc}
1432
1433\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1434Returns the \code{o} as a tuple on success, and \NULL{} on failure.
1435This is equivalent to the Python expression: \code{tuple(o)}.
1436\end{cfuncdesc}
1437
1438\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
1439Return the number of occurrences of \code{value} on \code{o}, that is,
1440return the number of keys for which \code{o[key]==value}. On
1441failure, return -1. This is equivalent to the Python
1442expression: \code{o.count(value)}.
1443\end{cfuncdesc}
1444
1445\begin{cfuncdesc}{int}{PySequence_In}{PyObject *o, PyObject *value}
1446Determine if \code{o} contains \code{value}. If an item in \code{o} is equal to
1447\code{value}, return 1, otherwise return 0. On error, return -1. This
1448is equivalent to the Python expression: \code{value in o}.
1449\end{cfuncdesc}
1450
1451\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Guido van Rossum59a61351997-08-14 20:34:33 +00001452Return the first index for which \code{o[i]==value}. On error,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001453return -1. This is equivalent to the Python
1454expression: \code{o.index(value)}.
1455\end{cfuncdesc}
1456
1457\section{Mapping protocol}
1458
1459\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
1460Return 1 if the object provides mapping protocol, and 0
1461otherwise.
1462This function always succeeds.
1463\end{cfuncdesc}
1464
1465
1466\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
1467Returns the number of keys in object \code{o} on success, and -1 on
1468failure. For objects that do not provide sequence protocol,
1469this is equivalent to the Python expression: \code{len(o)}.
1470\end{cfuncdesc}
1471
1472
1473\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
1474Remove the mapping for object \code{key} from the object \code{o}.
1475Return -1 on failure. This is equivalent to
1476the Python statement: \code{del o[key]}.
1477\end{cfuncdesc}
1478
1479
1480\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
1481Remove the mapping for object \code{key} from the object \code{o}.
1482Return -1 on failure. This is equivalent to
1483the Python statement: \code{del o[key]}.
1484\end{cfuncdesc}
1485
1486
1487\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
1488On success, return 1 if the mapping object has the key \code{key}
1489and 0 otherwise. This is equivalent to the Python expression:
1490\code{o.has_key(key)}.
1491This function always succeeds.
1492\end{cfuncdesc}
1493
1494
1495\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
1496Return 1 if the mapping object has the key \code{key}
1497and 0 otherwise. This is equivalent to the Python expression:
1498\code{o.has_key(key)}.
1499This function always succeeds.
1500\end{cfuncdesc}
1501
1502
1503\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
1504On success, return a list of the keys in object \code{o}. On
1505failure, return \NULL{}. This is equivalent to the Python
1506expression: \code{o.keys()}.
1507\end{cfuncdesc}
1508
1509
1510\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
1511On success, return a list of the values in object \code{o}. On
1512failure, return \NULL{}. This is equivalent to the Python
1513expression: \code{o.values()}.
1514\end{cfuncdesc}
1515
1516
1517\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
1518On success, return a list of the items in object \code{o}, where
1519each item is a tuple containing a key-value pair. On
1520failure, return \NULL{}. This is equivalent to the Python
1521expression: \code{o.items()}.
1522\end{cfuncdesc}
1523
1524\begin{cfuncdesc}{int}{PyMapping_Clear}{PyObject *o}
1525Make object \code{o} empty. Returns 1 on success and 0 on failure.
1526This is equivalent to the Python statement:
1527\code{for key in o.keys(): del o[key]}
1528\end{cfuncdesc}
1529
1530
1531\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
1532Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1533on failure. This is the equivalent of the Python expression:
1534\code{o[key]}.
1535\end{cfuncdesc}
1536
1537\begin{cfuncdesc}{PyObject*}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
1538Map the object \code{key} to the value \code{v} in object \code{o}. Returns
1539-1 on failure. This is the equivalent of the Python
1540statement: \code{o[key]=v}.
1541\end{cfuncdesc}
1542
1543
1544\section{Constructors}
1545
1546\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *file_name, char *mode}
1547On success, returns a new file object that is opened on the
1548file given by \code{file_name}, with a file mode given by \code{mode},
1549where \code{mode} has the same semantics as the standard C routine,
1550fopen. On failure, return -1.
1551\end{cfuncdesc}
1552
1553\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp, char *file_name, char *mode, int close_on_del}
1554Return a new file object for an already opened standard C
1555file pointer, \code{fp}. A file name, \code{file_name}, and open mode,
1556\code{mode}, must be provided as well as a flag, \code{close_on_del}, that
1557indicates whether the file is to be closed when the file
1558object is destroyed. On failure, return -1.
1559\end{cfuncdesc}
1560
1561\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
1562Returns a new float object with the value \code{v} on success, and
1563\NULL{} on failure.
1564\end{cfuncdesc}
1565
1566\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long v}
1567Returns a new int object with the value \code{v} on success, and
1568\NULL{} on failure.
1569\end{cfuncdesc}
1570
1571\begin{cfuncdesc}{PyObject*}{PyList_New}{int l}
1572Returns a new list of length \code{l} on success, and \NULL{} on
1573failure.
1574\end{cfuncdesc}
1575
1576\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
1577Returns a new long object with the value \code{v} on success, and
1578\NULL{} on failure.
1579\end{cfuncdesc}
1580
1581\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
1582Returns a new long object with the value \code{v} on success, and
1583\NULL{} on failure.
1584\end{cfuncdesc}
1585
1586\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1587Returns a new empty dictionary on success, and \NULL{} on
1588failure.
1589\end{cfuncdesc}
1590
1591\begin{cfuncdesc}{PyObject*}{PyString_FromString}{char *v}
1592Returns a new string object with the value \code{v} on success, and
1593\NULL{} on failure.
1594\end{cfuncdesc}
1595
1596\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{char *v, int l}
1597Returns a new string object with the value \code{v} and length \code{l}
1598on success, and \NULL{} on failure.
1599\end{cfuncdesc}
1600
1601\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int l}
1602Returns a new tuple of length \code{l} on success, and \NULL{} on
1603failure.
1604\end{cfuncdesc}
1605
1606
1607\chapter{Concrete Objects Layer}
1608
1609The functions in this chapter are specific to certain Python object
1610types. Passing them an object of the wrong type is not a good idea;
1611if you receive an object from a Python program and you are not sure
1612that it has the right type, you must perform a type check first;
1613e.g. to check that an object is a dictionary, use
1614\code{PyDict_Check()}.
1615
1616
1617\chapter{Defining New Object Types}
1618
1619\begin{cfuncdesc}{PyObject *}{_PyObject_New}{PyTypeObject *type}
1620\end{cfuncdesc}
1621
Guido van Rossumae110af1997-05-22 20:11:52 +00001622\begin{cfuncdesc}{PyObject *}{_PyObject_NewVar}{PyTypeObject *type, int size}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001623\end{cfuncdesc}
1624
Guido van Rossumae110af1997-05-22 20:11:52 +00001625\begin{cfuncdesc}{TYPE}{_PyObject_NEW}{TYPE, PyTypeObject *}
1626\end{cfuncdesc}
1627
1628\begin{cfuncdesc}{TYPE}{_PyObject_NEW_VAR}{TYPE, PyTypeObject *, int size}
1629\end{cfuncdesc}
1630
Guido van Rossum4a944d71997-08-14 20:35:38 +00001631\chapter{Initialization, Finalization, and Threads}
1632
Guido van Rossum4a944d71997-08-14 20:35:38 +00001633\begin{cfuncdesc}{void}{Py_Initialize}{}
1634Initialize the Python interpreter. In an application embedding
1635Python, this should be called before using any other Python/C API
1636functions; with the exception of \code{Py_SetProgramName()},
1637\code{PyEval_InitThreads()}, \code{PyEval_ReleaseLock()}, and
1638\code{PyEval_AcquireLock()}. This initializes the table of loaded
1639modules (\code{sys.modules}), and creates the fundamental modules
1640\code{__builtin__}, \code{__main__} and \code{sys}. It also
1641initializes the module search path (\code{sys.path}). It does not set
Guido van Rossum42cefd01997-10-05 15:27:29 +00001642\code{sys.argv}; use \code{PySys_SetArgv()} for that. This is a no-op
1643when called for a second time (without calling \code{Py_Finalize()}
1644first). There is no return value; it is a fatal error if the
1645initialization fails.
1646\end{cfuncdesc}
1647
1648\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001649\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001650Return true (nonzero) when the Python interpreter has been
1651initialized, false (zero) if not. After \code{Py_Finalize()} is
1652called, this returns false until \code{Py_Initialize()} is called
1653again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00001654\end{cfuncdesc}
1655
1656\begin{cfuncdesc}{void}{Py_Finalize}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001657\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001658Undo all initializations made by \code{Py_Initialize()} and subsequent
1659use of Python/C API functions, and destroy all sub-interpreters (see
1660\code{Py_NewInterpreter()} below) that were created and not yet
Guido van Rossum42cefd01997-10-05 15:27:29 +00001661destroyed since the last call to \code{Py_Initialize()}. Ideally,
1662this frees all memory allocated by the Python interpreter. This is a
1663no-op when called for a second time (without calling
1664\code{Py_Initialize()} again first). There is no return value; errors
Guido van Rossum4a944d71997-08-14 20:35:38 +00001665during finalization are ignored.
1666
1667This function is provided for a number of reasons. An embedding
1668application might want to restart Python without having to restart the
1669application itself. An application that has loaded the Python
1670interpreter from a dynamically loadable library (or DLL) might want to
1671free all memory allocated by Python before unloading the DLL. During a
1672hunt for memory leaks in an application a developer might want to free
1673all memory allocated by Python before exiting from the application.
1674
1675\emph{Bugs and caveats:} The destruction of modules and objects in
1676modules is done in random order; this may cause destructors
1677(\code{__del__} methods) to fail when they depend on other objects
1678(even functions) or modules. Dynamically loaded extension modules
1679loaded by Python are not unloaded. Small amounts of memory allocated
1680by the Python interpreter may not be freed (if you find a leak, please
1681report it). Memory tied up in circular references between objects is
1682not freed. Some memory allocated by extension modules may not be
1683freed. Some extension may not work properly if their initialization
1684routine is called more than once; this can happen if an applcation
1685calls \code{Py_Initialize()} and \code{Py_Finalize()} more than once.
1686\end{cfuncdesc}
1687
1688\begin{cfuncdesc}{PyThreadState *}{Py_NewInterpreter}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001689\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001690Create a new sub-interpreter. This is an (almost) totally separate
1691environment for the execution of Python code. In particular, the new
1692interpreter has separate, independent versions of all imported
1693modules, including the fundamental modules \code{__builtin__},
1694\code{__main__} and \code{sys}. The table of loaded modules
1695(\code{sys.modules}) and the module search path (\code{sys.path}) are
1696also separate. The new environment has no \code{sys.argv} variable.
1697It has new standard I/O stream file objects \code{sys.stdin},
1698\code{sys.stdout} and \code{sys.stderr} (however these refer to the
1699same underlying \code{FILE} structures in the C library).
1700
1701The return value points to the first thread state created in the new
1702sub-interpreter. This thread state is made the current thread state.
1703Note that no actual thread is created; see the discussion of thread
1704states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001705\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00001706is stored in the current thread state and there may not be a current
1707thread state. (Like all other Python/C API functions, the global
1708interpreter lock must be held before calling this function and is
1709still held when it returns; however, unlike most other Python/C API
1710functions, there needn't be a current thread state on entry.)
1711
1712Extension modules are shared between (sub-)interpreters as follows:
1713the first time a particular extension is imported, it is initialized
1714normally, and a (shallow) copy of its module's dictionary is
1715squirreled away. When the same extension is imported by another
1716(sub-)interpreter, a new module is initialized and filled with the
1717contents of this copy; the extension's \code{init} function is not
1718called. Note that this is different from what happens when as
1719extension is imported after the interpreter has been completely
1720re-initialized by calling \code{Py_Finalize()} and
1721\code{Py_Initialize()}; in that case, the extension's \code{init}
1722function \emph{is} called again.
1723
1724\emph{Bugs and caveats:} Because sub-interpreters (and the main
1725interpreter) are part of the same process, the insulation between them
1726isn't perfect -- for example, using low-level file operations like
1727\code{os.close()} they can (accidentally or maliciously) affect each
1728other's open files. Because of the way extensions are shared between
1729(sub-)interpreters, some extensions may not work properly; this is
1730especially likely when the extension makes use of (static) global
1731variables, or when the extension manipulates its module's dictionary
1732after its initialization. It is possible to insert objects created in
1733one sub-interpreter into a namespace of another sub-interpreter; this
1734should be done with great care to avoid sharing user-defined
1735functions, methods, instances or classes between sub-interpreters,
1736since import operations executed by such objects may affect the
1737wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
1738a hard-to-fix bug that will be addressed in a future release.)
1739\end{cfuncdesc}
1740
1741\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001742\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001743Destroy the (sub-)interpreter represented by the given thread state.
1744The given thread state must be the current thread state. See the
1745discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001746thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00001747interpreted are destroyed. (The global interpreter lock must be held
1748before calling this function and is still held when it returns.)
1749\code{Py_Finalize()} will destroy all sub-interpreters that haven't
1750been explicitly destroyed at that point.
1751\end{cfuncdesc}
1752
1753\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001754\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001755This function should be called before \code{Py_Initialize()} is called
1756for the first time, if it is called at all. It tells the interpreter
1757the value of the \code{argv[0]} argument to the \code{main()} function
1758of the program. This is used by \code{Py_GetPath()} and some other
1759functions below to find the Python run-time libraries relative to the
1760interpreter executable. The default value is \code{"python"}. The
1761argument should point to a zero-terminated character string in static
1762storage whose contents will not change for the duration of the
1763program's execution. No code in the Python interpreter will change
1764the contents of this storage.
1765\end{cfuncdesc}
1766
1767\begin{cfuncdesc}{char *}{Py_GetProgramName}{}
1768Return the program name set with \code{Py_SetProgramName()}, or the
1769default. The returned string points into static storage; the caller
1770should not modify its value.
1771\end{cfuncdesc}
1772
1773\begin{cfuncdesc}{char *}{Py_GetPrefix}{}
1774Return the ``prefix'' for installed platform-independent files. This
1775is derived through a number of complicated rules from the program name
1776set with \code{Py_SetProgramName()} and some environment variables;
1777for example, if the program name is \code{"/usr/local/bin/python"},
1778the prefix is \code{"/usr/local"}. The returned string points into
1779static storage; the caller should not modify its value. This
1780corresponds to the \code{prefix} variable in the top-level
1781\code{Makefile} and the \code{--prefix} argument to the
1782\code{configure} script at build time. The value is available to
1783Python code as \code{sys.prefix}. It is only useful on Unix. See
1784also the next function.
1785\end{cfuncdesc}
1786
1787\begin{cfuncdesc}{char *}{Py_GetExecPrefix}{}
1788Return the ``exec-prefix'' for installed platform-\emph{de}pendent
1789files. This is derived through a number of complicated rules from the
1790program name set with \code{Py_SetProgramName()} and some environment
1791variables; for example, if the program name is
1792\code{"/usr/local/bin/python"}, the exec-prefix is
1793\code{"/usr/local"}. The returned string points into static storage;
1794the caller should not modify its value. This corresponds to the
1795\code{exec_prefix} variable in the top-level \code{Makefile} and the
1796\code{--exec_prefix} argument to the \code{configure} script at build
1797time. The value is available to Python code as
1798\code{sys.exec_prefix}. It is only useful on Unix.
1799
1800Background: The exec-prefix differs from the prefix when platform
1801dependent files (such as executables and shared libraries) are
1802installed in a different directory tree. In a typical installation,
1803platform dependent files may be installed in the
1804\code{"/usr/local/plat"} subtree while platform independent may be
1805installed in \code{"/usr/local"}.
1806
1807Generally speaking, a platform is a combination of hardware and
1808software families, e.g. Sparc machines running the Solaris 2.x
1809operating system are considered the same platform, but Intel machines
1810running Solaris 2.x are another platform, and Intel machines running
1811Linux are yet another platform. Different major revisions of the same
1812operating system generally also form different platforms. Non-Unix
1813operating systems are a different story; the installation strategies
1814on those systems are so different that the prefix and exec-prefix are
1815meaningless, and set to the empty string. Note that compiled Python
1816bytecode files are platform independent (but not independent from the
1817Python version by which they were compiled!).
1818
1819System administrators will know how to configure the \code{mount} or
1820\code{automount} programs to share \code{"/usr/local"} between platforms
1821while having \code{"/usr/local/plat"} be a different filesystem for each
1822platform.
1823\end{cfuncdesc}
1824
1825\begin{cfuncdesc}{char *}{Py_GetProgramFullPath}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001826\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001827Return the full program name of the Python executable; this is
1828computed as a side-effect of deriving the default module search path
Guido van Rossum09270b51997-08-15 18:57:32 +00001829from the program name (set by \code{Py_SetProgramName()} above). The
Guido van Rossum4a944d71997-08-14 20:35:38 +00001830returned string points into static storage; the caller should not
1831modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00001832\code{sys.executable}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00001833\end{cfuncdesc}
1834
1835\begin{cfuncdesc}{char *}{Py_GetPath}{}
1836Return the default module search path; this is computed from the
Guido van Rossum09270b51997-08-15 18:57:32 +00001837program name (set by \code{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00001838environment variables. The returned string consists of a series of
1839directory names separated by a platform dependent delimiter character.
1840The delimiter character is \code{':'} on Unix, \code{';'} on
Guido van Rossum09270b51997-08-15 18:57:32 +00001841DOS/Windows, and \code{'\\n'} (the ASCII newline character) on
Guido van Rossum4a944d71997-08-14 20:35:38 +00001842Macintosh. The returned string points into static storage; the caller
1843should not modify its value. The value is available to Python code
1844as the list \code{sys.path}, which may be modified to change the
1845future search path for loaded modules.
1846
1847% XXX should give the exact rules
1848\end{cfuncdesc}
1849
1850\begin{cfuncdesc}{const char *}{Py_GetVersion}{}
1851Return the version of this Python interpreter. This is a string that
1852looks something like
1853
Guido van Rossum09270b51997-08-15 18:57:32 +00001854\begin{verbatim}
1855"1.5a3 (#67, Aug 1 1997, 22:34:28) [GCC 2.7.2.2]"
1856\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001857
1858The first word (up to the first space character) is the current Python
1859version; the first three characters are the major and minor version
1860separated by a period. The returned string points into static storage;
1861the caller should not modify its value. The value is available to
1862Python code as the list \code{sys.version}.
1863\end{cfuncdesc}
1864
1865\begin{cfuncdesc}{const char *}{Py_GetPlatform}{}
1866Return the platform identifier for the current platform. On Unix,
1867this is formed from the ``official'' name of the operating system,
1868converted to lower case, followed by the major revision number; e.g.,
1869for Solaris 2.x, which is also known as SunOS 5.x, the value is
1870\code{"sunos5"}. On Macintosh, it is \code{"mac"}. On Windows, it
1871is \code{"win"}. The returned string points into static storage;
1872the caller should not modify its value. The value is available to
1873Python code as \code{sys.platform}.
1874\end{cfuncdesc}
1875
1876\begin{cfuncdesc}{const char *}{Py_GetCopyright}{}
1877Return the official copyright string for the current Python version,
1878for example
1879
1880\code{"Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam"}
1881
1882The returned string points into static storage; the caller should not
1883modify its value. The value is available to Python code as the list
1884\code{sys.copyright}.
1885\end{cfuncdesc}
1886
1887\begin{cfuncdesc}{const char *}{Py_GetCompiler}{}
1888Return an indication of the compiler used to build the current Python
1889version, in square brackets, for example
1890
1891\code{"[GCC 2.7.2.2]"}
1892
1893The returned string points into static storage; the caller should not
1894modify its value. The value is available to Python code as part of
1895the variable \code{sys.version}.
1896\end{cfuncdesc}
1897
1898\begin{cfuncdesc}{const char *}{Py_GetBuildInfo}{}
1899Return information about the sequence number and build date and time
1900of the current Python interpreter instance, for example
1901
Guido van Rossum09270b51997-08-15 18:57:32 +00001902\begin{verbatim}
1903"#67, Aug 1 1997, 22:34:28"
1904\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001905
1906The returned string points into static storage; the caller should not
1907modify its value. The value is available to Python code as part of
1908the variable \code{sys.version}.
1909\end{cfuncdesc}
1910
1911\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
1912% XXX
1913\end{cfuncdesc}
1914
1915% XXX Other PySys thingies (doesn't really belong in this chapter)
1916
1917\section{Thread State and the Global Interpreter Lock}
1918
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001919The Python interpreter is not fully thread safe. In order to support
1920multi-threaded Python programs, there's a global lock that must be
1921held by the current thread before it can safely access Python objects.
1922Without the lock, even the simplest operations could cause problems in
1923a multi-threaded proram: for example, when two threads simultaneously
1924increment the reference count of the same object, the reference count
1925could end up being incremented only once instead of twice.
1926
1927Therefore, the rule exists that only the thread that has acquired the
1928global interpreter lock may operate on Python objects or call Python/C
1929API functions. In order to support multi-threaded Python programs,
1930the interpreter regularly release and reacquires the lock -- by
1931default, every ten bytecode instructions (this can be changed with
1932\code{sys.setcheckinterval()}). The lock is also released and
1933reacquired around potentially blocking I/O operations like reading or
1934writing a file, so that other threads can run while the thread that
1935requests the I/O is waiting for the I/O operation to complete.
1936
1937The Python interpreter needs to keep some bookkeeping information
1938separate per thread -- for this it uses a data structure called
1939PyThreadState. This is new in Python 1.5; in earlier versions, such
1940state was stored in global variables, and switching threads could
1941cause problems. In particular, exception handling is now thread safe,
1942when the application uses \code{sys.exc_info()} to access the exception
1943last raised in the current thread.
1944
1945There's one global variable left, however: the pointer to the current
1946PyThreadState structure. While most thread packages have a way to
1947store ``per-thread global data'', Python's internal platform
1948independent thread abstraction doesn't support this (yet). Therefore,
1949the current thread state must be manipulated explicitly.
1950
1951This is easy enough in most cases. Most code manipulating the global
1952interpreter lock has the following simple structure:
1953
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001954\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001955Save the thread state in a local variable.
1956Release the interpreter lock.
1957...Do some blocking I/O operation...
1958Reacquire the interpreter lock.
1959Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001960\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001961
1962This is so common that a pair of macros exists to simplify it:
1963
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001964\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001965Py_BEGIN_ALLOW_THREADS
1966...Do some blocking I/O operation...
1967Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001968\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001969
1970The BEGIN macro opens a new block and declares a hidden local
1971variable; the END macro closes the block. Another advantage of using
1972these two macros is that when Python is compiled without thread
1973support, they are defined empty, thus saving the thread state and lock
1974manipulations.
1975
1976When thread support is enabled, the block above expands to the
1977following code:
1978
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001979\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001980{
1981 PyThreadState *_save;
1982 _save = PyEval_SaveThread();
1983 ...Do some blocking I/O operation...
1984 PyEval_RestoreThread(_save);
1985}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001986\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001987
1988Using even lower level primitives, we can get roughly the same effect
1989as follows:
1990
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001991\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001992{
1993 PyThreadState *_save;
1994 _save = PyThreadState_Swap(NULL);
1995 PyEval_ReleaseLock();
1996 ...Do some blocking I/O operation...
1997 PyEval_AcquireLock();
1998 PyThreadState_Swap(_save);
1999}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002000\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002001
2002There are some subtle differences; in particular,
2003\code{PyEval_RestoreThread()} saves and restores the value of the
2004global variable \code{errno}, since the lock manipulation does not
2005guarantee that \code{errno} is left alone. Also, when thread support
2006is disabled, \code{PyEval_SaveThread()} and
2007\code{PyEval_RestoreThread()} don't manipulate the lock; in this case,
2008\code{PyEval_ReleaseLock()} and \code{PyEval_AcquireLock()} are not
2009available. (This is done so that dynamically loaded extensions
2010compiled with thread support enabled can be loaded by an interpreter
2011that was compiled with disabled thread support.)
2012
2013The global interpreter lock is used to protect the pointer to the
2014current thread state. When releasing the lock and saving the thread
2015state, the current thread state pointer must be retrieved before the
2016lock is released (since another thread could immediately acquire the
2017lock and store its own thread state in the global variable).
2018Reversely, when acquiring the lock and restoring the thread state, the
2019lock must be acquired before storing the thread state pointer.
2020
2021Why am I going on with so much detail about this? Because when
2022threads are created from C, they don't have the global interpreter
2023lock, nor is there a thread state data structure for them. Such
2024threads must bootstrap themselves into existence, by first creating a
2025thread state data structure, then acquiring the lock, and finally
2026storing their thread state pointer, before they can start using the
2027Python/C API. When they are done, they should reset the thread state
2028pointer, release the lock, and finally free their thread state data
2029structure.
2030
2031When creating a thread data structure, you need to provide an
2032interpreter state data structure. The interpreter state data
2033structure hold global data that is shared by all threads in an
2034interpreter, for example the module administration
2035(\code{sys.modules}). Depending on your needs, you can either create
2036a new interpreter state data structure, or share the interpreter state
2037data structure used by the Python main thread (to access the latter,
2038you must obtain the thread state and access its \code{interp} member;
2039this must be done by a thread that is created by Python or by the main
2040thread after Python is initialized).
2041
2042XXX More?
2043
2044\begin{ctypedesc}{PyInterpreterState}
2045\strong{(NEW in 1.5a3!)}
2046This data structure represents the state shared by a number of
2047cooperating threads. Threads belonging to the same interpreter
2048share their module administration and a few other internal items.
2049There are no public members in this structure.
2050
2051Threads belonging to different interpreters initially share nothing,
2052except process state like available memory, open file descriptors and
2053such. The global interpreter lock is also shared by all threads,
2054regardless of to which interpreter they belong.
2055\end{ctypedesc}
2056
2057\begin{ctypedesc}{PyThreadState}
2058\strong{(NEW in 1.5a3!)}
2059This data structure represents the state of a single thread. The only
2060public data member is \code{PyInterpreterState *interp}, which points
2061to this thread's interpreter state.
2062\end{ctypedesc}
2063
2064\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
2065Initialize and acquire the global interpreter lock. It should be
2066called in the main thread before creating a second thread or engaging
2067in any other thread operations such as \code{PyEval_ReleaseLock()} or
2068\code{PyEval_ReleaseThread(tstate)}. It is not needed before
2069calling \code{PyEval_SaveThread()} or \code{PyEval_RestoreThread()}.
2070
2071This is a no-op when called for a second time. It is safe to call
2072this function before calling \code{Py_Initialize()}.
2073
2074When only the main thread exists, no lock operations are needed. This
2075is a common situation (most Python programs do not use threads), and
2076the lock operations slow the interpreter down a bit. Therefore, the
2077lock is not created initially. This situation is equivalent to having
2078acquired the lock: when there is only a single thread, all object
2079accesses are safe. Therefore, when this function initializes the
2080lock, it also acquires it. Before the Python \code{thread} module
2081creates a new thread, knowing that either it has the lock or the lock
2082hasn't been created yet, it calls \code{PyEval_InitThreads()}. When
2083this call returns, it is guaranteed that the lock has been created and
2084that it has acquired it.
2085
2086It is \strong{not} safe to call this function when it is unknown which
2087thread (if any) currently has the global interpreter lock.
2088
2089This function is not available when thread support is disabled at
2090compile time.
2091\end{cfuncdesc}
2092
Guido van Rossum4a944d71997-08-14 20:35:38 +00002093\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002094\strong{(NEW in 1.5a3!)}
2095Acquire the global interpreter lock. The lock must have been created
2096earlier. If this thread already has the lock, a deadlock ensues.
2097This function is not available when thread support is disabled at
2098compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002099\end{cfuncdesc}
2100
2101\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002102\strong{(NEW in 1.5a3!)}
2103Release the global interpreter lock. The lock must have been created
2104earlier. This function is not available when thread support is
2105disabled at
2106compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002107\end{cfuncdesc}
2108
2109\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002110\strong{(NEW in 1.5a3!)}
2111Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002112state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002113have been created earlier. If this thread already has the lock,
2114deadlock ensues. This function is not available when thread support
2115is disabled at
2116compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002117\end{cfuncdesc}
2118
2119\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002120\strong{(NEW in 1.5a3!)}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002121Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002122interpreter lock. The lock must have been created earlier and must be
2123held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002124be \NULL{}, is only used to check that it represents the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002125thread state -- if it isn't, a fatal error is reported. This function
2126is not available when thread support is disabled at
2127compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002128\end{cfuncdesc}
2129
2130\begin{cfuncdesc}{PyThreadState *}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002131\strong{(Different return type in 1.5a3!)}
2132Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002133support is enabled) and reset the thread state to \NULL{},
2134returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002135the lock has been created, the current thread must have acquired it.
2136(This function is available even when thread support is disabled at
2137compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002138\end{cfuncdesc}
2139
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002140\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
2141\strong{(Different argument type in 1.5a3!)}
2142Acquire the interpreter lock (if it has been created and thread
2143support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002144must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002145thread must not have acquired it, otherwise deadlock ensues. (This
2146function is available even when thread support is disabled at compile
2147time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002148\end{cfuncdesc}
2149
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002150% XXX These aren't really C types, but the ctypedesc macro is the simplest!
2151\begin{ctypedesc}{Py_BEGIN_ALLOW_THREADS}
2152This macro expands to
2153\code{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
2154Note that it contains an opening brace; it must be matched with a
2155following \code{Py_END_ALLOW_THREADS} macro. See above for further
2156discussion of this macro. It is a no-op when thread support is
2157disabled at compile time.
2158\end{ctypedesc}
2159
2160\begin{ctypedesc}{Py_END_ALLOW_THREADS}
2161This macro expands to
2162\code{PyEval_RestoreThread(_save); \} }.
2163Note that it contains a closing brace; it must be matched with an
2164earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
2165discussion of this macro. It is a no-op when thread support is
2166disabled at compile time.
2167\end{ctypedesc}
2168
2169\begin{ctypedesc}{Py_BEGIN_BLOCK_THREADS}
2170This macro expands to \code{PyEval_RestoreThread(_save);} i.e. it
2171is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
2172brace. It is a no-op when thread support is disabled at compile
2173time.
2174\end{ctypedesc}
2175
2176\begin{ctypedesc}{Py_BEGIN_UNBLOCK_THREADS}
2177This macro expands to \code{_save = PyEval_SaveThread();} i.e. it is
2178equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
2179and variable declaration. It is a no-op when thread support is
2180disabled at compile time.
2181\end{ctypedesc}
2182
2183All of the following functions are only available when thread support
2184is enabled at compile time, and must be called only when the
2185interpreter lock has been created. They are all new in 1.5a3.
2186
2187\begin{cfuncdesc}{PyInterpreterState *}{PyInterpreterState_New}{}
2188Create a new interpreter state object. The interpreter lock must be
2189held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002190\end{cfuncdesc}
2191
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002192\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
2193Reset all information in an interpreter state object. The interpreter
2194lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002195\end{cfuncdesc}
2196
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002197\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
2198Destroy an interpreter state object. The interpreter lock need not be
2199held. The interpreter state must have been reset with a previous
2200call to \code{PyInterpreterState_Clear()}.
2201\end{cfuncdesc}
2202
2203\begin{cfuncdesc}{PyThreadState *}{PyThreadState_New}{PyInterpreterState *interp}
2204Create a new thread state object belonging to the given interpreter
2205object. The interpreter lock must be held.
2206\end{cfuncdesc}
2207
2208\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
2209Reset all information in a thread state object. The interpreter lock
2210must be held.
2211\end{cfuncdesc}
2212
2213\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
2214Destroy a thread state object. The interpreter lock need not be
2215held. The thread state must have been reset with a previous
2216call to \code{PyThreadState_Clear()}.
2217\end{cfuncdesc}
2218
2219\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Get}{}
2220Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002221When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00002222error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002223\end{cfuncdesc}
2224
2225\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Swap}{PyThreadState *tstate}
2226Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002227argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002228must be held.
2229\end{cfuncdesc}
2230
2231
2232\section{Defining New Object Types}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002233
Guido van Rossumae110af1997-05-22 20:11:52 +00002234XXX To be done:
2235
2236PyObject, PyVarObject
2237
2238PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
2239
2240Typedefs:
2241unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
2242intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
2243getreadbufferproc, getwritebufferproc, getsegcountproc,
2244destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
2245setattrofunc, cmpfunc, reprfunc, hashfunc
2246
2247PyNumberMethods
2248
2249PySequenceMethods
2250
2251PyMappingMethods
2252
2253PyBufferProcs
2254
2255PyTypeObject
2256
2257DL_IMPORT
2258
2259PyType_Type
2260
2261Py*_Check
2262
2263Py_None, _Py_NoneStruct
2264
2265_PyObject_New, _PyObject_NewVar
2266
2267PyObject_NEW, PyObject_NEW_VAR
2268
2269
2270\chapter{Specific Data Types}
2271
2272This chapter describes the functions that deal with specific types of
2273Python objects. It is structured like the ``family tree'' of Python
2274object types.
2275
2276
2277\section{Fundamental Objects}
2278
2279This section describes Python type objects and the singleton object
2280\code{None}.
2281
2282
2283\subsection{Type Objects}
2284
2285\begin{ctypedesc}{PyTypeObject}
2286
2287\end{ctypedesc}
2288
2289\begin{cvardesc}{PyObject *}{PyType_Type}
2290
2291\end{cvardesc}
2292
2293
2294\subsection{The None Object}
2295
2296\begin{cvardesc}{PyObject *}{Py_None}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002297XXX macro
Guido van Rossumae110af1997-05-22 20:11:52 +00002298\end{cvardesc}
2299
2300
2301\section{Sequence Objects}
2302
2303Generic operations on sequence objects were discussed in the previous
2304chapter; this section deals with the specific kinds of sequence
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002305objects that are intrinsic to the Python language.
Guido van Rossumae110af1997-05-22 20:11:52 +00002306
2307
2308\subsection{String Objects}
2309
2310\begin{ctypedesc}{PyStringObject}
2311This subtype of \code{PyObject} represents a Python string object.
2312\end{ctypedesc}
2313
2314\begin{cvardesc}{PyTypeObject}{PyString_Type}
2315This instance of \code{PyTypeObject} represents the Python string type.
2316\end{cvardesc}
2317
2318\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
2319
2320\end{cfuncdesc}
2321
2322\begin{cfuncdesc}{PyObject *}{PyString_FromStringAndSize}{const char *, int}
2323
2324\end{cfuncdesc}
2325
2326\begin{cfuncdesc}{PyObject *}{PyString_FromString}{const char *}
2327
2328\end{cfuncdesc}
2329
2330\begin{cfuncdesc}{int}{PyString_Size}{PyObject *}
2331
2332\end{cfuncdesc}
2333
2334\begin{cfuncdesc}{char *}{PyString_AsString}{PyObject *}
2335
2336\end{cfuncdesc}
2337
2338\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **, PyObject *}
2339
2340\end{cfuncdesc}
2341
2342\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **, PyObject *}
2343
2344\end{cfuncdesc}
2345
2346\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **, int}
2347
2348\end{cfuncdesc}
2349
2350\begin{cfuncdesc}{PyObject *}{PyString_Format}{PyObject *, PyObject *}
2351
2352\end{cfuncdesc}
2353
2354\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **}
2355
2356\end{cfuncdesc}
2357
2358\begin{cfuncdesc}{PyObject *}{PyString_InternFromString}{const char *}
2359
2360\end{cfuncdesc}
2361
2362\begin{cfuncdesc}{char *}{PyString_AS_STRING}{PyStringObject *}
2363
2364\end{cfuncdesc}
2365
2366\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyStringObject *}
2367
2368\end{cfuncdesc}
2369
2370
2371\subsection{Tuple Objects}
2372
2373\begin{ctypedesc}{PyTupleObject}
2374This subtype of \code{PyObject} represents a Python tuple object.
2375\end{ctypedesc}
2376
2377\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
2378This instance of \code{PyTypeObject} represents the Python tuple type.
2379\end{cvardesc}
2380
2381\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
2382Return true if the argument is a tuple object.
2383\end{cfuncdesc}
2384
2385\begin{cfuncdesc}{PyTupleObject *}{PyTuple_New}{int s}
2386Return a new tuple object of size \code{s}
2387\end{cfuncdesc}
2388
2389\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
2390akes a pointer to a tuple object, and returns the size
2391of that tuple.
2392\end{cfuncdesc}
2393
2394\begin{cfuncdesc}{PyObject *}{PyTuple_GetItem}{PyTupleObject *p, int pos}
2395returns the object at position \code{pos} in the tuple pointed
2396to by \code{p}.
2397\end{cfuncdesc}
2398
2399\begin{cfuncdesc}{PyObject *}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
2400does the same, but does no checking of it's
2401arguments.
2402\end{cfuncdesc}
2403
2404\begin{cfuncdesc}{PyTupleObject *}{PyTuple_GetSlice}{PyTupleObject *p,
2405 int low,
2406 int high}
2407takes a slice of the tuple pointed to by \code{p} from
2408\code{low} to \code{high} and returns it as a new tuple.
2409\end{cfuncdesc}
2410
2411\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyTupleObject *p,
2412 int pos,
2413 PyObject *o}
2414inserts a reference to object \code{o} at position \code{pos} of
2415the tuple pointed to by \code{p}. It returns 0 on success.
2416\end{cfuncdesc}
2417
2418\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyTupleObject *p,
2419 int pos,
2420 PyObject *o}
2421
2422does the same, but does no error checking, and
2423should \emph{only} be used to fill in brand new tuples.
2424\end{cfuncdesc}
2425
2426\begin{cfuncdesc}{PyTupleObject *}{_PyTuple_Resize}{PyTupleObject *p,
2427 int new,
2428 int last_is_sticky}
2429can be used to resize a tuple. Because tuples are
2430\emph{supposed} to be immutable, this should only be used if there is only
2431one module referencing the object. Do \emph{not} use this if the tuple may
2432already be known to some other part of the code. \code{last_is_sticky} is
2433a flag - if set, the tuple will grow or shrink at the front, otherwise
2434it will grow or shrink at the end. Think of this as destroying the old
2435tuple and creating a new one, only more efficiently.
2436\end{cfuncdesc}
2437
2438
2439\subsection{List Objects}
2440
2441\begin{ctypedesc}{PyListObject}
2442This subtype of \code{PyObject} represents a Python list object.
2443\end{ctypedesc}
2444
2445\begin{cvardesc}{PyTypeObject}{PyList_Type}
2446This instance of \code{PyTypeObject} represents the Python list type.
2447\end{cvardesc}
2448
2449\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
2450returns true if it's argument is a \code{PyListObject}
2451\end{cfuncdesc}
2452
2453\begin{cfuncdesc}{PyObject *}{PyList_New}{int size}
2454
2455\end{cfuncdesc}
2456
2457\begin{cfuncdesc}{int}{PyList_Size}{PyObject *}
2458
2459\end{cfuncdesc}
2460
2461\begin{cfuncdesc}{PyObject *}{PyList_GetItem}{PyObject *, int}
2462
2463\end{cfuncdesc}
2464
2465\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *, int, PyObject *}
2466
2467\end{cfuncdesc}
2468
2469\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *, int, PyObject *}
2470
2471\end{cfuncdesc}
2472
2473\begin{cfuncdesc}{int}{PyList_Append}{PyObject *, PyObject *}
2474
2475\end{cfuncdesc}
2476
2477\begin{cfuncdesc}{PyObject *}{PyList_GetSlice}{PyObject *, int, int}
2478
2479\end{cfuncdesc}
2480
2481\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *, int, int, PyObject *}
2482
2483\end{cfuncdesc}
2484
2485\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *}
2486
2487\end{cfuncdesc}
2488
2489\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *}
2490
2491\end{cfuncdesc}
2492
2493\begin{cfuncdesc}{PyObject *}{PyList_AsTuple}{PyObject *}
2494
2495\end{cfuncdesc}
2496
2497\begin{cfuncdesc}{PyObject *}{PyList_GET_ITEM}{PyObject *list, int i}
2498
2499\end{cfuncdesc}
2500
2501\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
2502
2503\end{cfuncdesc}
2504
2505
2506\section{Mapping Objects}
2507
2508\subsection{Dictionary Objects}
2509
2510\begin{ctypedesc}{PyDictObject}
2511This subtype of \code{PyObject} represents a Python dictionary object.
2512\end{ctypedesc}
2513
2514\begin{cvardesc}{PyTypeObject}{PyDict_Type}
2515This instance of \code{PyTypeObject} represents the Python dictionary type.
2516\end{cvardesc}
2517
2518\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
2519returns true if it's argument is a PyDictObject
2520\end{cfuncdesc}
2521
2522\begin{cfuncdesc}{PyDictObject *}{PyDict_New}{}
2523returns a new empty dictionary.
2524\end{cfuncdesc}
2525
2526\begin{cfuncdesc}{void}{PyDict_Clear}{PyDictObject *p}
2527empties an existing dictionary and deletes it.
2528\end{cfuncdesc}
2529
2530\begin{cfuncdesc}{int}{PyDict_SetItem}{PyDictObject *p,
2531 PyObject *key,
2532 PyObject *val}
2533inserts \code{value} into the dictionary with a key of
2534\code{key}. Both \code{key} and \code{value} should be PyObjects, and \code{key} should
2535be hashable.
2536\end{cfuncdesc}
2537
2538\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
2539 char *key,
2540 PyObject *val}
2541inserts \code{value} into the dictionary using \code{key}
2542as a key. \code{key} should be a char *
2543\end{cfuncdesc}
2544
2545\begin{cfuncdesc}{int}{PyDict_DelItem}{PyDictObject *p, PyObject *key}
2546removes the entry in dictionary \code{p} with key \code{key}.
2547\code{key} is a PyObject.
2548\end{cfuncdesc}
2549
2550\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyDictObject *p, char *key}
2551removes the entry in dictionary \code{p} which has a key
2552specified by the \code{char *}\code{key}.
2553\end{cfuncdesc}
2554
2555\begin{cfuncdesc}{PyObject *}{PyDict_GetItem}{PyDictObject *p, PyObject *key}
2556returns the object from dictionary \code{p} which has a key
2557\code{key}.
2558\end{cfuncdesc}
2559
2560\begin{cfuncdesc}{PyObject *}{PyDict_GetItemString}{PyDictObject *p, char *key}
2561does the same, but \code{key} is specified as a
2562\code{char *}, rather than a \code{PyObject *}.
2563\end{cfuncdesc}
2564
2565\begin{cfuncdesc}{PyListObject *}{PyDict_Items}{PyDictObject *p}
2566returns a PyListObject containing all the items
2567from the dictionary, as in the mapping method \code{items()} (see the Reference
2568Guide)
2569\end{cfuncdesc}
2570
2571\begin{cfuncdesc}{PyListObject *}{PyDict_Keys}{PyDictObject *p}
2572returns a PyListObject containing all the keys
2573from the dictionary, as in the mapping method \code{keys()} (see the Reference Guide)
2574\end{cfuncdesc}
2575
2576\begin{cfuncdesc}{PyListObject *}{PyDict_Values}{PyDictObject *p}
2577returns a PyListObject containing all the values
2578from the dictionary, as in the mapping method \code{values()} (see the Reference Guide)
2579\end{cfuncdesc}
2580
2581\begin{cfuncdesc}{int}{PyDict_Size}{PyDictObject *p}
2582returns the number of items in the dictionary.
2583\end{cfuncdesc}
2584
2585\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p,
2586 int ppos,
2587 PyObject **pkey,
2588 PyObject **pvalue}
2589
2590\end{cfuncdesc}
2591
2592
2593\section{Numeric Objects}
2594
2595\subsection{Plain Integer Objects}
2596
2597\begin{ctypedesc}{PyIntObject}
2598This subtype of \code{PyObject} represents a Python integer object.
2599\end{ctypedesc}
2600
2601\begin{cvardesc}{PyTypeObject}{PyInt_Type}
2602This instance of \code{PyTypeObject} represents the Python plain
2603integer type.
2604\end{cvardesc}
2605
2606\begin{cfuncdesc}{int}{PyInt_Check}{PyObject *}
2607
2608\end{cfuncdesc}
2609
2610\begin{cfuncdesc}{PyIntObject *}{PyInt_FromLong}{long ival}
2611creates a new integer object with a value of \code{ival}.
2612
2613The current implementation keeps an array of integer objects for all
2614integers between -1 and 100, when you create an int in that range you
2615actually just get back a reference to the existing object. So it should
2616be possible to change the value of 1. I suspect the behaviour of python
2617in this case is undefined. :-)
2618\end{cfuncdesc}
2619
2620\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyIntObject *io}
2621returns the value of the object \code{io}.
2622\end{cfuncdesc}
2623
2624\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
2625will first attempt to cast the object to a PyIntObject, if
2626it is not already one, and the return it's value.
2627\end{cfuncdesc}
2628
2629\begin{cfuncdesc}{long}{PyInt_GetMax}{}
2630returns the systems idea of the largest int it can handle
2631(LONG_MAX, as defined in the system header files)
2632\end{cfuncdesc}
2633
2634
2635\subsection{Long Integer Objects}
2636
2637\begin{ctypedesc}{PyLongObject}
2638This subtype of \code{PyObject} represents a Python long integer object.
2639\end{ctypedesc}
2640
2641\begin{cvardesc}{PyTypeObject}{PyLong_Type}
2642This instance of \code{PyTypeObject} represents the Python long integer type.
2643\end{cvardesc}
2644
2645\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
2646returns true if it's argument is a \code{PyLongObject}
2647\end{cfuncdesc}
2648
2649\begin{cfuncdesc}{PyObject *}{PyLong_FromLong}{long}
2650
2651\end{cfuncdesc}
2652
2653\begin{cfuncdesc}{PyObject *}{PyLong_FromUnsignedLong}{unsigned long}
2654
2655\end{cfuncdesc}
2656
2657\begin{cfuncdesc}{PyObject *}{PyLong_FromDouble}{double}
2658
2659\end{cfuncdesc}
2660
2661\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *}
2662
2663\end{cfuncdesc}
2664
2665\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject }
2666
2667\end{cfuncdesc}
2668
2669\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *}
2670
2671\end{cfuncdesc}
2672
2673\begin{cfuncdesc}{PyObject *}{*PyLong_FromString}{char *, char **, int}
2674
2675\end{cfuncdesc}
2676
2677
2678\subsection{Floating Point Objects}
2679
2680\begin{ctypedesc}{PyFloatObject}
2681This subtype of \code{PyObject} represents a Python floating point object.
2682\end{ctypedesc}
2683
2684\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2685This instance of \code{PyTypeObject} represents the Python floating
2686point type.
2687\end{cvardesc}
2688
2689\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2690returns true if it's argument is a \code{PyFloatObject}
2691\end{cfuncdesc}
2692
2693\begin{cfuncdesc}{PyObject *}{PyFloat_FromDouble}{double}
2694
2695\end{cfuncdesc}
2696
2697\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *}
2698
2699\end{cfuncdesc}
2700
2701\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyFloatObject *}
2702
2703\end{cfuncdesc}
2704
2705
2706\subsection{Complex Number Objects}
2707
2708\begin{ctypedesc}{Py_complex}
2709typedef struct {
2710 double real;
2711 double imag;
2712}
2713\end{ctypedesc}
2714
2715\begin{ctypedesc}{PyComplexObject}
2716This subtype of \code{PyObject} represents a Python complex number object.
2717\end{ctypedesc}
2718
2719\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2720This instance of \code{PyTypeObject} represents the Python complex
2721number type.
2722\end{cvardesc}
2723
2724\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2725returns true if it's argument is a \code{PyComplexObject}
2726\end{cfuncdesc}
2727
2728\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex, Py_complex}
2729
2730\end{cfuncdesc}
2731
2732\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex, Py_complex}
2733
2734\end{cfuncdesc}
2735
2736\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex}
2737
2738\end{cfuncdesc}
2739
2740\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex, Py_complex}
2741
2742\end{cfuncdesc}
2743
2744\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex, Py_complex}
2745
2746\end{cfuncdesc}
2747
2748\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex, Py_complex}
2749
2750\end{cfuncdesc}
2751
2752\begin{cfuncdesc}{PyObject *}{PyComplex_FromCComplex}{Py_complex}
2753
2754\end{cfuncdesc}
2755
2756\begin{cfuncdesc}{PyObject *}{PyComplex_FromDoubles}{double real, double imag}
2757
2758\end{cfuncdesc}
2759
2760\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2761
2762\end{cfuncdesc}
2763
2764\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2765
2766\end{cfuncdesc}
2767
2768\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2769
2770\end{cfuncdesc}
2771
2772
2773
2774\section{Other Objects}
2775
2776\subsection{File Objects}
2777
2778\begin{ctypedesc}{PyFileObject}
2779This subtype of \code{PyObject} represents a Python file object.
2780\end{ctypedesc}
2781
2782\begin{cvardesc}{PyTypeObject}{PyFile_Type}
2783This instance of \code{PyTypeObject} represents the Python file type.
2784\end{cvardesc}
2785
2786\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2787returns true if it's argument is a \code{PyFileObject}
2788\end{cfuncdesc}
2789
2790\begin{cfuncdesc}{PyObject *}{PyFile_FromString}{char *name, char *mode}
2791creates a new PyFileObject pointing to the file
2792specified in \code{name} with the mode specified in \code{mode}
2793\end{cfuncdesc}
2794
2795\begin{cfuncdesc}{PyObject *}{PyFile_FromFile}{FILE *fp,
2796 char *name, char *mode, int (*close})
2797creates a new PyFileObject from the already-open \code{fp}.
2798The function \code{close} will be called when the file should be closed.
2799\end{cfuncdesc}
2800
2801\begin{cfuncdesc}{FILE *}{PyFile_AsFile}{PyFileObject *p}
2802returns the file object associated with \code{p} as a \code{FILE *}
2803\end{cfuncdesc}
2804
2805\begin{cfuncdesc}{PyStringObject *}{PyFile_GetLine}{PyObject *p, int n}
2806undocumented as yet
2807\end{cfuncdesc}
2808
2809\begin{cfuncdesc}{PyStringObject *}{PyFile_Name}{PyObject *p}
2810returns the name of the file specified by \code{p} as a
2811PyStringObject
2812\end{cfuncdesc}
2813
2814\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2815on systems with \code{setvbuf} only
2816\end{cfuncdesc}
2817
2818\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyFileObject *p, int newflag}
2819same as the file object method \code{softspace}
2820\end{cfuncdesc}
2821
2822\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p}
2823writes object \code{obj} to file object \code{p}
2824\end{cfuncdesc}
2825
2826\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p}
2827writes string \code{s} to file object \code{p}
2828\end{cfuncdesc}
2829
2830
Guido van Rossum5b8a5231997-12-30 04:38:44 +00002831\subsection{CObjects}
2832
2833XXX
2834
2835
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002836\input{api.ind} % Index -- must be last
2837
2838\end{document}