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