blob: bcbe13635073bf5619ce751db41d2bc9239eb558 [file] [log] [blame]
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001\documentstyle[twoside,11pt,myformat]{report}
2
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003\title{Python/C API Reference Manual}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00004
5\input{boilerplate}
6
7\makeindex % tell \index to actually write the .idx file
8
9
10\begin{document}
11
12\pagenumbering{roman}
13
14\maketitle
15
16\input{copyright}
17
18\begin{abstract}
19
20\noindent
21This manual documents the API used by C (or C++) programmers who want
22to write extension modules or embed Python. It is a companion to
23``Extending and Embedding the Python Interpreter'', which describes
24the general principles of extension writing but does not document the
25API functions in detail.
26
27\end{abstract}
28
29\pagebreak
30
31{
32\parskip = 0mm
33\tableofcontents
34}
35
36\pagebreak
37
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
182to receive a \emph{new} reference. When to ownership is transferred,
183the 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
206Incidentally, \code{PyTuple_SetItem()} is the \emph{only} way to set
207tuple items; \code{PyObject_SetItem()} refuses to do this since tuples
208are an immutable data type. You should only use
209\code{PyTuple_SetItem()} for tuples that you are creating yourself.
210
211Equivalent code for populating a list can be written using
212\code{PyList_New()} and \code{PyList_SetItem()}. Such code can also
213use \code{PySequence_SetItem()}; this illustrates the difference
214between the two:
215
216\begin{verbatim}
217PyObject *l, *x;
218l = PyList_New(3);
219x = PyInt_FromLong(1L);
220PyObject_SetItem(l, 0, x); Py_DECREF(x);
221x = PyInt_FromLong(2L);
222PyObject_SetItem(l, 1, x); Py_DECREF(x);
223x = PyString_FromString("three");
224PyObject_SetItem(l, 2, x); Py_DECREF(x);
225\end{verbatim}
226
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000227You might find it strange that the ``recommended'' approach takes more
228code. However, in practice, you will rarely use these ways of
229creating and populating a tuple or list. There's a generic function,
230\code{Py_BuildValue()}, that can create most common objects from C
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000231values, directed by a ``format string''. For example, the above two
232blocks of code could be replaced by the following (which also takes
233care of the error checking!):
234
235\begin{verbatim}
236PyObject *t, *l;
237t = Py_BuildValue("(iis)", 1, 2, "three");
238l = Py_BuildValue("[iis]", 1, 2, "three");
239\end{verbatim}
240
241It is much more common to use \code{PyObject_SetItem()} and friends
242with items whose references you are only borrowing, like arguments
243that were passed in to the function you are writing. In that case,
244their behaviour regarding reference counts is much saner, since you
245don't have to increment a reference count so you can give a reference
246away (``have it be stolen''). For example, this function sets all
247items of a list (actually, any mutable sequence) to a given item:
248
249\begin{verbatim}
250int set_all(PyObject *target, PyObject *item)
251{
252 int i, n;
253 n = PyObject_Length(target);
254 if (n < 0)
255 return -1;
256 for (i = 0; i < n; i++) {
257 if (PyObject_SetItem(target, i, item) < 0)
258 return -1;
259 }
260 return 0;
261}
262\end{verbatim}
263
264The situation is slightly different for function return values.
265While passing a reference to most functions does not change your
266ownership responsibilities for that reference, many functions that
267return a referece to an object give you ownership of the reference.
268The reason is simple: in many cases, the returned object is created
269on the fly, and the reference you get is the only reference to the
270object! Therefore, the generic functions that return object
271references, like \code{PyObject_GetItem()} and
272\code{PySequence_GetItem()}, always return a new reference (i.e., the
273caller becomes the owner of the reference).
274
275It is important to realize that whether you own a reference returned
276by a function depends on which function you call only -- \emph{the
277plumage} (i.e., the type of the type of the object passed as an
278argument to the function) \emph{don't enter into it!} Thus, if you
279extract an item from a list using \code{PyList_GetItem()}, yo don't
280own the reference -- but if you obtain the same item from the same
281list using \code{PySequence_GetItem()} (which happens to take exactly
282the same arguments), you do own a reference to the returned object.
283
284Here is an example of how you could write a function that computes the
285sum of the items in a list of integers; once using
286\code{PyList_GetItem()}, once using \code{PySequence_GetItem()}.
287
288\begin{verbatim}
289long sum_list(PyObject *list)
290{
291 int i, n;
292 long total = 0;
293 PyObject *item;
294 n = PyList_Size(list);
295 if (n < 0)
296 return -1; /* Not a list */
297 for (i = 0; i < n; i++) {
298 item = PyList_GetItem(list, i); /* Can't fail */
299 if (!PyInt_Check(item)) continue; /* Skip non-integers */
300 total += PyInt_AsLong(item);
301 }
302 return total;
303}
304\end{verbatim}
305
306\begin{verbatim}
307long sum_sequence(PyObject *sequence)
308{
309 int i, n;
310 long total = 0;
311 PyObject *item;
312 n = PyObject_Size(list);
313 if (n < 0)
314 return -1; /* Has no length */
315 for (i = 0; i < n; i++) {
316 item = PySequence_GetItem(list, i);
317 if (item == NULL)
318 return -1; /* Not a sequence, or other failure */
319 if (PyInt_Check(item))
320 total += PyInt_AsLong(item);
321 Py_DECREF(item); /* Discared reference ownership */
322 }
323 return total;
324}
325\end{verbatim}
326
327\subsection{Types}
328
329There are few other data types that play a significant role in
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000330the Python/C API; most are simple C types such as \code{int},
Guido van Rossum4a944d71997-08-14 20:35:38 +0000331\code{long}, \code{double} and \code{char *}. A few structure types
332are used to describe static tables used to list the functions exported
333by a module or the data attributes of a new object type. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000334be discussed together with the functions that use them.
335
336\section{Exceptions}
337
Guido van Rossum4a944d71997-08-14 20:35:38 +0000338The Python programmer only needs to deal with exceptions if specific
339error handling is required; unhandled exceptions are automatically
340propagated to the caller, then to the caller's caller, and so on, till
341they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000342user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000343
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000344For C programmers, however, error checking always has to be explicit.
345All functions in the Python/C API can raise exceptions, unless an
346explicit claim is made otherwise in a function's documentation. In
347general, when a function encounters an error, it sets an exception,
348discards any object references that it owns, and returns an
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000349error indicator -- usually \NULL{} or \code{-1}. A few functions
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000350return a Boolean true/false result, with false indicating an error.
351Very few functions return no explicit error indicator or have an
352ambiguous return value, and require explicit testing for errors with
353\code{PyErr_Occurred()}.
354
355Exception state is maintained in per-thread storage (this is
356equivalent to using global storage in an unthreaded application). A
357thread can be on one of two states: an exception has occurred, or not.
358The function \code{PyErr_Occurred()} can be used to check for this: it
359returns a borrowed reference to the exception type object when an
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000360exception has occurred, and \NULL{} otherwise. There are a number
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000361of functions to set the exception state: \code{PyErr_SetString()} is
362the most common (though not the most general) function to set the
363exception state, and \code{PyErr_Clear()} clears the exception state.
364
365The full exception state consists of three objects (all of which can
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000366be \NULL{} ): the exception type, the corresponding exception
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000367value, and the traceback. These have the same meanings as the Python
368object \code{sys.exc_type}, \code{sys.exc_value},
369\code{sys.exc_traceback}; however, they are not the same: the Python
370objects represent the last exception being handled by a Python
371\code{try...except} statement, while the C level exception state only
372exists while an exception is being passed on between C functions until
373it reaches the Python interpreter, which takes care of transferring it
374to \code{sys.exc_type} and friends.
375
376(Note that starting with Python 1.5, the preferred, thread-safe way to
377access the exception state from Python code is to call the function
378\code{sys.exc_info()}, which returns the per-thread exception state
379for Python code. Also, the semantics of both ways to access the
380exception state have changed so that a function which catches an
381exception will save and restore its thread's exception state so as to
382preserve the exception state of its caller. This prevents common bugs
383in exception handling code caused by an innocent-looking function
384overwriting the exception being handled; it also reduces the often
385unwanted lifetime extension for objects that are referenced by the
386stack frames in the traceback.)
387
388As a general principle, a function that calls another function to
389perform some task should check whether the called function raised an
390exception, and if so, pass the exception state on to its caller. It
391should discards any object references that it owns, and returns an
392error indicator, but it should \emph{not} set another exception --
393that would overwrite the exception that was just raised, and lose
394important reason about the exact cause of the error.
395
396A simple example of detecting exceptions and passing them on is shown
397in the \code{sum_sequence()} example above. It so happens that that
398example doesn't need to clean up any owned references when it detects
399an error. The following example function shows some error cleanup.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000400First, to remind you why you like Python, we show the equivalent
401Python code:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000402
403\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000404def incr_item(dict, key):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000405 try:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000406 item = dict[key]
407 except KeyError:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000408 item = 0
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000409 return item + 1
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000410\end{verbatim}
411
412Here is the corresponding C code, in all its glory:
413
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000414\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000415int incr_item(PyObject *dict, PyObject *key)
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000416{
417 /* Objects all initialized to NULL for Py_XDECREF */
418 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
419 int rv = -1; /* Return value initialized to -1 (faulure) */
420
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000421 item = PyObject_GetItem(dict, key);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000422 if (item == NULL) {
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000423 /* Handle keyError only: */
424 if (!PyErr_ExceptionMatches(PyExc_keyError)) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000425
426 /* Clear the error and use zero: */
427 PyErr_Clear();
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000428 item = PyInt_FromLong(0L);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000429 if (item == NULL) goto error;
430 }
431
432 const_one = PyInt_FromLong(1L);
433 if (const_one == NULL) goto error;
434
435 incremented_item = PyNumber_Add(item, const_one);
436 if (incremented_item == NULL) goto error;
437
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000438 if (PyObject_SetItem(dict, key, incremented_item) < 0) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000439 rv = 0; /* Success */
440 /* Continue with cleanup code */
441
442 error:
443 /* Cleanup code, shared by success and failure path */
444
445 /* Use Py_XDECREF() to ignore NULL references */
446 Py_XDECREF(item);
447 Py_XDECREF(const_one);
448 Py_XDECREF(incremented_item);
449
450 return rv; /* -1 for error, 0 for success */
451}
452\end{verbatim}
453
454This example represents an endorsed use of the \code{goto} statement
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000455in C! It illustrates the use of \code{PyErr_ExceptionMatches()} and
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000456\code{PyErr_Clear()} to handle specific exceptions, and the use of
457\code{Py_XDECREF()} to dispose of owned references that may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000458\NULL{} (note the `X' in the name; \code{Py_DECREF()} would crash
459when confronted with a \NULL{} reference). It is important that
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000460the variables used to hold owned references are initialized to
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000461\NULL{} for this to work; likewise, the proposed return value is
462initialized to \code{-1} (failure) and only set to success after
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000463the final call made is succesful.
464
Guido van Rossum59a61351997-08-14 20:34:33 +0000465
466\section{Embedding Python}
467
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000468The one important task that only embedders (as opposed to extension
469writers) of the Python interpreter have to worry about is the
470initialization, and possibly the finalization, of the Python
471interpreter. Most functionality of the interpreter can only be used
472after the interpreter has been initialized.
Guido van Rossum59a61351997-08-14 20:34:33 +0000473
Guido van Rossum4a944d71997-08-14 20:35:38 +0000474The basic initialization function is \code{Py_Initialize()}. This
475initializes the table of loaded modules, and creates the fundamental
476modules \code{__builtin__}, \code{__main__} and \code{sys}. It also
Guido van Rossum59a61351997-08-14 20:34:33 +0000477initializes the module search path (\code{sys.path}).
478
Guido van Rossum4a944d71997-08-14 20:35:38 +0000479\code{Py_Initialize()} does not set the ``script argument list''
480(\code{sys.argv}). If this variable is needed by Python code that
481will be executed later, it must be set explicitly with a call to
482\code{PySys_SetArgv(\var{argc}, \var{argv})} subsequent to the call
Guido van Rossum59a61351997-08-14 20:34:33 +0000483to \code{Py_Initialize()}.
484
Guido van Rossum42cefd01997-10-05 15:27:29 +0000485On most systems (in particular, on Unix and Windows, although the
486details are slightly different), \code{Py_Initialize()} calculates the
487module search path based upon its best guess for the location of the
488standard Python interpreter executable, assuming that the Python
489library is found in a fixed location relative to the Python
490interpreter executable. In particular, it looks for a directory named
491\code{lib/python1.5} (replacing \code{1.5} with the current
492interpreter version) relative to the parent directory where the
493executable named \code{python} is found on the shell command search
494path (the environment variable \code{\$PATH}).
495
496For instance, if the Python executable is found in
497\code{/usr/local/bin/python}, it will assume that the libraries are in
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000498\code{/usr/local/lib/python1.5}. (In fact, this particular path is
499also the ``fallback'' location, used when no executable file named
500\code{python} is found along \code{\$PATH}.) The user can override
501this behavior by setting the environment variable \code{\$PYTHONHOME},
502or insert additional directories in front of the standard path by
503setting \code{\$PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000504
Guido van Rossum4a944d71997-08-14 20:35:38 +0000505The embedding application can steer the search by calling
506\code{Py_SetProgramName(\var{file})} \emph{before} calling
Guido van Rossum09270b51997-08-15 18:57:32 +0000507\code{Py_Initialize()}. Note that \code{\$PYTHONHOME} still overrides
Guido van Rossum4a944d71997-08-14 20:35:38 +0000508this and \code{\$PYTHONPATH} is still inserted in front of the
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000509standard path. An application that requires total control has to
510provide its own implementation of \code{Py_GetPath()},
511\code{Py_GetPrefix()}, \code{Py_GetExecPrefix()},
512\code{Py_GetProgramFullPath()} (all defined in
513\file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000514
Guido van Rossum4a944d71997-08-14 20:35:38 +0000515Sometimes, it is desirable to ``uninitialize'' Python. For instance,
516the application may want to start over (make another call to
517\code{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000518use of Python and wants to free all memory allocated by Python. This
519can be accomplished by calling \code{Py_Finalize()}. The function
520\code{Py_IsInitialized()} returns true iff Python is currently in the
521initialized state. More information about these functions is given in
522a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000523
Guido van Rossum4a944d71997-08-14 20:35:38 +0000524
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000525\chapter{Basic Utilities}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000526
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000527XXX These utilities should be moved to some other section...
Guido van Rossum4a944d71997-08-14 20:35:38 +0000528
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000529\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
530Print a fatal error message and kill the process. No cleanup is
531performed. This function should only be invoked when a condition is
532detected that would make it dangerous to continue using the Python
533interpreter; e.g., when the object administration appears to be
534corrupted. On Unix, the standard C library function \code{abort()} is
535called which will attempt to produce a \file{core} file.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000536\end{cfuncdesc}
537
538\begin{cfuncdesc}{void}{Py_Exit}{int status}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000539Exit the current process. This calls \code{Py_Finalize()} and then
540calls the standard C library function \code{exit(0)}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000541\end{cfuncdesc}
542
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000543\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
544Register a cleanup function to be called by \code{Py_Finalize()}. The
545cleanup function will be called with no arguments and should return no
546value. At most 32 cleanup functions can be registered. When the
547registration is successful, \code{Py_AtExit} returns 0; on failure, it
548returns -1. The cleanup function registered last is called first.
549Each cleanup function will be called at most once.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000550\end{cfuncdesc}
551
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000552
553\chapter{Reference Counting}
554
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000555The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000556of Python objects.
557
558\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
559Increment the reference count for object \code{o}. The object must
560not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
561\code{Py_XINCREF()}.
562\end{cfuncdesc}
563
564\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
565Increment the reference count for object \code{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000566\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000567\end{cfuncdesc}
568
569\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
570Decrement the reference count for object \code{o}. The object must
571not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
572\code{Py_XDECREF()}. If the reference count reaches zero, the object's
573type's deallocation function (which must not be \NULL{}) is invoked.
574
575\strong{Warning:} The deallocation function can cause arbitrary Python
576code to be invoked (e.g. when a class instance with a \code{__del__()}
577method is deallocated). While exceptions in such code are not
578propagated, the executed code has free access to all Python global
579variables. This means that any object that is reachable from a global
580variable should be in a consistent state before \code{Py_DECREF()} is
581invoked. For example, code to delete an object from a list should
582copy a reference to the deleted object in a temporary variable, update
583the list data structure, and then call \code{Py_DECREF()} for the
584temporary variable.
585\end{cfuncdesc}
586
587\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
588Decrement the reference count for object \code{o}.The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000589\NULL{}, in which case the macro has no effect; otherwise the
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000590effect is the same as for \code{Py_DECREF()}, and the same warning
591applies.
592\end{cfuncdesc}
593
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000594The following functions or macros are only for internal use:
Guido van Rossumae110af1997-05-22 20:11:52 +0000595\code{_Py_Dealloc}, \code{_Py_ForgetReference}, \code{_Py_NewReference},
596as well as the global variable \code{_Py_RefTotal}.
597
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000598XXX Should mention Py_Malloc(), Py_Realloc(), Py_Free(),
599PyMem_Malloc(), PyMem_Realloc(), PyMem_Free(), PyMem_NEW(),
600PyMem_RESIZE(), PyMem_DEL(), PyMem_XDEL().
601
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000602
603\chapter{Exception Handling}
604
605The functions in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000606exceptions. It is important to understand some of the basics of
607Python exception handling. It works somewhat like the Unix
608\code{errno} variable: there is a global indicator (per thread) of the
609last error that occurred. Most functions don't clear this on success,
610but will set it to indicate the cause of the error on failure. Most
611functions also return an error indicator, usually \NULL{} if they are
612supposed to return a pointer, or -1 if they return an integer
613(exception: the \code{PyArg_Parse*()} functions return 1 for success and
6140 for failure). When a function must fail because of some function it
615called failed, it generally doesn't set the error indicator; the
616function it called already set it.
617
618The error indicator consists of three Python objects corresponding to
619the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
620\code{sys.exc_traceback}. API functions exist to interact with the
621error indicator in various ways. There is a separate error indicator
622for each thread.
623
624% XXX Order of these should be more thoughtful.
625% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000626
627\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000628Print a standard traceback to \code{sys.stderr} and clear the error
629indicator. Call this function only when the error indicator is set.
630(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000631\end{cfuncdesc}
632
Guido van Rossumae110af1997-05-22 20:11:52 +0000633\begin{cfuncdesc}{PyObject *}{PyErr_Occurred}{}
634Test whether the error indicator is set. If set, return the exception
635\code{type} (the first argument to the last call to one of the
636\code{PyErr_Set*()} functions or to \code{PyErr_Restore()}). If not
637set, return \NULL{}. You do not own a reference to the return value,
Guido van Rossum42cefd01997-10-05 15:27:29 +0000638so you do not need to \code{Py_DECREF()} it. Note: do not compare the
639return value to a specific exception; use
640\code{PyErr_ExceptionMatches} instead, shown below.
641\end{cfuncdesc}
642
643\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000644\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000645Equivalent to
646\code{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
647This should only be called when an exception is actually set.
648\end{cfuncdesc}
649
650\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000651\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000652Return true if the \var{given} exception matches the exception in
653\var{exc}. If \var{exc} is a class object, this also returns true
654when \var{given} is a subclass. If \var{exc} is a tuple, all
655exceptions in the tuple (and recursively in subtuples) are searched
656for a match. This should only be called when an exception is actually
657set.
658\end{cfuncdesc}
659
660\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000661\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000662Under certain circumstances, the values returned by
663\code{PyErr_Fetch()} below can be ``unnormalized'', meaning that
664\var{*exc} is a class object but \var{*val} is not an instance of the
665same class. This function can be used to instantiate the class in
666that case. If the values are already normalized, nothing happens.
Guido van Rossumae110af1997-05-22 20:11:52 +0000667\end{cfuncdesc}
668
669\begin{cfuncdesc}{void}{PyErr_Clear}{}
670Clear the error indicator. If the error indicator is not set, there
671is no effect.
672\end{cfuncdesc}
673
674\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue, PyObject **ptraceback}
675Retrieve the error indicator into three variables whose addresses are
676passed. If the error indicator is not set, set all three variables to
677\NULL{}. If it is set, it will be cleared and you own a reference to
678each object retrieved. The value and traceback object may be \NULL{}
679even when the type object is not. \strong{Note:} this function is
680normally only used by code that needs to handle exceptions or by code
681that needs to save and restore the error indicator temporarily.
682\end{cfuncdesc}
683
684\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value, PyObject *traceback}
685Set the error indicator from the three objects. If the error
686indicator is already set, it is cleared first. If the objects are
687\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
688and non-\NULL{} value or traceback. The exception type should be a
689string or class; if it is a class, the value should be an instance of
690that class. Do not pass an invalid exception type or value.
691(Violating these rules will cause subtle problems later.) This call
692takes away a reference to each object, i.e. you must own a reference
693to each object before the call and after the call you no longer own
694these references. (If you don't understand this, don't use this
695function. I warned you.) \strong{Note:} this function is normally
696only used by code that needs to save and restore the error indicator
697temporarily.
698\end{cfuncdesc}
699
700\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
701This is the most common way to set the error indicator. The first
702argument specifies the exception type; it is normally one of the
703standard exceptions, e.g. \code{PyExc_RuntimeError}. You need not
704increment its reference count. The second argument is an error
705message; it is converted to a string object.
706\end{cfuncdesc}
707
708\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
709This function is similar to \code{PyErr_SetString()} but lets you
710specify an arbitrary Python object for the ``value'' of the exception.
711You need not increment its reference count.
712\end{cfuncdesc}
713
714\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
715This is a shorthand for \code{PyErr_SetString(\var{type}, Py_None}.
716\end{cfuncdesc}
717
718\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
719This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
720\var{message})}, where \var{message} indicates that a built-in operation
721was invoked with an illegal argument. It is mostly for internal use.
722\end{cfuncdesc}
723
724\begin{cfuncdesc}{PyObject *}{PyErr_NoMemory}{}
725This is a shorthand for \code{PyErr_SetNone(PyExc_MemoryError)}; it
726returns \NULL{} so an object allocation function can write
727\code{return PyErr_NoMemory();} when it runs out of memory.
728\end{cfuncdesc}
729
730\begin{cfuncdesc}{PyObject *}{PyErr_SetFromErrno}{PyObject *type}
731This is a convenience function to raise an exception when a C library
732function has returned an error and set the C variable \code{errno}.
733It constructs a tuple object whose first item is the integer
734\code{errno} value and whose second item is the corresponding error
735message (gotten from \code{strerror()}), and then calls
736\code{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
737the \code{errno} value is \code{EINTR}, indicating an interrupted
738system call, this calls \code{PyErr_CheckSignals()}, and if that set
739the error indicator, leaves it set to that. The function always
740returns \NULL{}, so a wrapper function around a system call can write
741\code{return PyErr_NoMemory();} when the system call returns an error.
742\end{cfuncdesc}
743
744\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
745This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
746\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000747operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000748argument. It is mostly for internal use.
749\end{cfuncdesc}
750
751\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
752This function interacts with Python's signal handling. It checks
753whether a signal has been sent to the processes and if so, invokes the
754corresponding signal handler. If the \code{signal} module is
755supported, this can invoke a signal handler written in Python. In all
756cases, the default effect for \code{SIGINT} is to raise the
757\code{KeyboadInterrupt} exception. If an exception is raised the
758error indicator is set and the function returns 1; otherwise the
759function returns 0. The error indicator may or may not be cleared if
760it was previously set.
761\end{cfuncdesc}
762
763\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
764This function is obsolete (XXX or platform dependent?). It simulates
765the effect of a \code{SIGINT} signal arriving -- the next time
766\code{PyErr_CheckSignals()} is called, \code{KeyboadInterrupt} will be
767raised.
768\end{cfuncdesc}
769
Guido van Rossum42cefd01997-10-05 15:27:29 +0000770\begin{cfuncdesc}{PyObject *}{PyErr_NewException}{char *name,
771PyObject *base, PyObject *dict}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000772\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000773This utility function creates and returns a new exception object. The
774\var{name} argument must be the name of the new exception, a C string
775of the form \code{module.class}. The \var{base} and \var{dict}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000776arguments are normally \NULL{}. Normally, this creates a class
Guido van Rossum42cefd01997-10-05 15:27:29 +0000777object derived from the root for all exceptions, the built-in name
778\code{Exception} (accessible in C as \code{PyExc_Exception}). In this
779case the \code{__module__} attribute of the new class is set to the
780first part (up to the last dot) of the \var{name} argument, and the
781class name is set to the last part (after the last dot). When the
782user has specified the \code{-X} command line option to use string
783exceptions, for backward compatibility, or when the \var{base}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000784argument is not a class object (and not \NULL{}), a string object
Guido van Rossum42cefd01997-10-05 15:27:29 +0000785created from the entire \var{name} argument is returned. The
786\var{base} argument can be used to specify an alternate base class.
787The \var{dict} argument can be used to specify a dictionary of class
788variables and methods.
789\end{cfuncdesc}
790
791
Guido van Rossumae110af1997-05-22 20:11:52 +0000792\section{Standard Exceptions}
793
794All standard Python exceptions are available as global variables whose
795names are \code{PyExc_} followed by the Python exception name.
796These have the type \code{PyObject *}; they are all string objects.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000797For completeness, here are all the variables (the first four are new
798in Python 1.5a4):
799\code{PyExc_Exception},
800\code{PyExc_StandardError},
801\code{PyExc_ArithmeticError},
802\code{PyExc_LookupError},
Guido van Rossumae110af1997-05-22 20:11:52 +0000803\code{PyExc_AssertionError},
804\code{PyExc_AttributeError},
805\code{PyExc_EOFError},
806\code{PyExc_FloatingPointError},
807\code{PyExc_IOError},
808\code{PyExc_ImportError},
809\code{PyExc_IndexError},
810\code{PyExc_KeyError},
811\code{PyExc_KeyboardInterrupt},
812\code{PyExc_MemoryError},
813\code{PyExc_NameError},
814\code{PyExc_OverflowError},
815\code{PyExc_RuntimeError},
816\code{PyExc_SyntaxError},
817\code{PyExc_SystemError},
818\code{PyExc_SystemExit},
819\code{PyExc_TypeError},
820\code{PyExc_ValueError},
821\code{PyExc_ZeroDivisionError}.
822
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000823
824\chapter{Utilities}
825
826The functions in this chapter perform various utility tasks, such as
827parsing function arguments and constructing Python values from C
828values.
829
Guido van Rossum42cefd01997-10-05 15:27:29 +0000830\section{OS Utilities}
831
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000832\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
833Return true (nonzero) if the standard I/O file \code{fp} with name
834\code{filename} is deemed interactive. This is the case for files for
835which \code{isatty(fileno(fp))} is true. If the global flag
836\code{Py_InteractiveFlag} is true, this function also returns true if
837the \code{name} pointer is \NULL{} or if the name is equal to one of
838the strings \code{"<stdin>"} or \code{"???"}.
839\end{cfuncdesc}
840
841\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
842Return the time of last modification of the file \code{filename}.
843The result is encoded in the same way as the timestamp returned by
844the standard C library function \code{time()}.
845\end{cfuncdesc}
846
847
Guido van Rossum42cefd01997-10-05 15:27:29 +0000848\section{Importing modules}
849
850\begin{cfuncdesc}{PyObject *}{PyImport_ImportModule}{char *name}
851This is a simplified interface to \code{PyImport_ImportModuleEx}
852below, leaving the \var{globals} and \var{locals} arguments set to
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000853\NULL{}. When the \var{name} argument contains a dot (i.e., when
Guido van Rossum42cefd01997-10-05 15:27:29 +0000854it specifies a submodule of a package), the \var{fromlist} argument is
855set to the list \code{['*']} so that the return value is the named
856module rather than the top-level package containing it as would
857otherwise be the case. (Unfortunately, this has an additional side
858effect when \var{name} in fact specifies a subpackage instead of a
859submodule: the submodules specified in the package's \code{__all__}
860variable are loaded.) Return a new reference to the imported module,
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000861or \NULL{} with an exception set on failure (the module may still
Guido van Rossum42cefd01997-10-05 15:27:29 +0000862be created in this case).
863\end{cfuncdesc}
864
865\begin{cfuncdesc}{PyObject *}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000866\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000867Import a module. This is best described by referring to the built-in
868Python function \code{__import()__}, as the standard
869\code{__import__()} function calls this function directly.
870
Guido van Rossum42cefd01997-10-05 15:27:29 +0000871The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000872top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000873(the module may still be created in this case). Like for
874\code{__import__()}, the return value when a submodule of a package
875was requested is normally the top-level package, unless a non-empty
876\var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000877\end{cfuncdesc}
878
879\begin{cfuncdesc}{PyObject *}{PyImport_Import}{PyObject *name}
880This is a higher-level interface that calls the current ``import hook
881function''. It invokes the \code{__import__()} function from the
882\code{__builtins__} of the current globals. This means that the
883import is done using whatever import hooks are installed in the
884current environment, e.g. by \code{rexec} or \code{ihooks}.
885\end{cfuncdesc}
886
887\begin{cfuncdesc}{PyObject *}{PyImport_ReloadModule}{PyObject *m}
888Reload a module. This is best described by referring to the built-in
889Python function \code{reload()}, as the standard \code{reload()}
890function calls this function directly. Return a new reference to the
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000891reloaded module, or \NULL{} with an exception set on failure (the
Guido van Rossum42cefd01997-10-05 15:27:29 +0000892module still exists in this case).
893\end{cfuncdesc}
894
895\begin{cfuncdesc}{PyObject *}{PyImport_AddModule}{char *name}
896Return the module object corresponding to a module name. The
897\var{name} argument may be of the form \code{package.module}). First
898check the modules dictionary if there's one there, and if not, create
899a new one and insert in in the modules dictionary. Because the former
900action is most common, this does not return a new reference, and you
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000901do not own the returned reference. Return \NULL{} with an
Guido van Rossum42cefd01997-10-05 15:27:29 +0000902exception set on failure.
903\end{cfuncdesc}
904
905\begin{cfuncdesc}{PyObject *}{PyImport_ExecCodeModule}{char *name, PyObject *co}
906Given a module name (possibly of the form \code{package.module}) and a
907code object read from a Python bytecode file or obtained from the
908built-in function \code{compile()}, load the module. Return a new
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000909reference to the module object, or \NULL{} with an exception set
Guido van Rossum42cefd01997-10-05 15:27:29 +0000910if an error occurred (the module may still be created in this case).
911(This function would reload the module if it was already imported.)
912\end{cfuncdesc}
913
914\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
915Return the magic number for Python bytecode files (a.k.a. \code{.pyc}
916and \code{.pyo} files). The magic number should be present in the
917first four bytes of the bytecode file, in little-endian byte order.
918\end{cfuncdesc}
919
920\begin{cfuncdesc}{PyObject *}{PyImport_GetModuleDict}{}
921Return the dictionary used for the module administration
922(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
923variable.
924\end{cfuncdesc}
925
926\begin{cfuncdesc}{void}{_PyImport_Init}{}
927Initialize the import mechanism. For internal use only.
928\end{cfuncdesc}
929
930\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
931Empty the module table. For internal use only.
932\end{cfuncdesc}
933
934\begin{cfuncdesc}{void}{_PyImport_Fini}{}
935Finalize the import mechanism. For internal use only.
936\end{cfuncdesc}
937
938\begin{cvardesc}{extern PyObject *}{_PyImport_FindExtension}{char *, char *}
939For internal use only.
940\end{cvardesc}
941
942\begin{cvardesc}{extern PyObject *}{_PyImport_FixupExtension}{char *, char *}
943For internal use only.
944\end{cvardesc}
945
946\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *}
947Load a frozen module. Return \code{1} for success, \code{0} if the
948module is not found, and \code{-1} with an exception set if the
949initialization failed. To access the imported module on a successful
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000950load, use \code{PyImport_ImportModule())}.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000951(Note the misnomer -- this function would reload the module if it was
952already imported.)
953\end{cfuncdesc}
954
955\begin{ctypedesc}{struct _frozen}
956This is the structure type definition for frozen module descriptors,
957as generated by the \code{freeze} utility (see \file{Tools/freeze/} in
958the Python source distribution). Its definition is:
Guido van Rossum9faf4c51997-10-07 14:38:54 +0000959\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000960struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +0000961 char *name;
962 unsigned char *code;
963 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +0000964};
Guido van Rossum9faf4c51997-10-07 14:38:54 +0000965\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000966\end{ctypedesc}
967
968\begin{cvardesc}{struct _frozen *}{PyImport_FrozenModules}
969This pointer is initialized to point to an array of \code{struct
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000970_frozen} records, terminated by one whose members are all \NULL{}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000971or zero. When a frozen module is imported, it is searched in this
972table. Third party code could play tricks with this to provide a
973dynamically created collection of frozen modules.
974\end{cvardesc}
975
976
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000977\chapter{Debugging}
978
979XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
980
981
982\chapter{The Very High Level Layer}
983
984The functions in this chapter will let you execute Python source code
985given in a file or a buffer, but they will not let you interact in a
986more detailed way with the interpreter.
987
Guido van Rossumae110af1997-05-22 20:11:52 +0000988\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *, char *}
989\end{cfuncdesc}
990
991\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *}
992\end{cfuncdesc}
993
994\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *, char *}
995\end{cfuncdesc}
996
997\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *, char *}
998\end{cfuncdesc}
999
1000\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *, char *}
1001\end{cfuncdesc}
1002
1003\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseString}{char *, int}
1004\end{cfuncdesc}
1005
1006\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseFile}{FILE *, char *, int}
1007\end{cfuncdesc}
1008
Guido van Rossumb9046291997-08-21 02:28:57 +00001009\begin{cfuncdesc}{}{PyObject *PyRun_String}{char *, int, PyObject *, PyObject *}
Guido van Rossumae110af1997-05-22 20:11:52 +00001010\end{cfuncdesc}
1011
Guido van Rossumb9046291997-08-21 02:28:57 +00001012\begin{cfuncdesc}{}{PyObject *PyRun_File}{FILE *, char *, int, PyObject *, PyObject *}
Guido van Rossumae110af1997-05-22 20:11:52 +00001013\end{cfuncdesc}
1014
Guido van Rossumb9046291997-08-21 02:28:57 +00001015\begin{cfuncdesc}{}{PyObject *Py_CompileString}{char *, char *, int}
Guido van Rossumae110af1997-05-22 20:11:52 +00001016\end{cfuncdesc}
1017
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001018
1019\chapter{Abstract Objects Layer}
1020
1021The functions in this chapter interact with Python objects regardless
1022of their type, or with wide classes of object types (e.g. all
1023numerical types, or all sequence types). When used on object types
1024for which they do not apply, they will flag a Python exception.
1025
1026\section{Object Protocol}
1027
1028\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
1029Print an object \code{o}, on file \code{fp}. Returns -1 on error
1030The flags argument is used to enable certain printing
1031options. The only option currently supported is \code{Py_Print_RAW}.
1032\end{cfuncdesc}
1033
1034\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
1035Returns 1 if o has the attribute attr_name, and 0 otherwise.
1036This is equivalent to the Python expression:
1037\code{hasattr(o,attr_name)}.
1038This function always succeeds.
1039\end{cfuncdesc}
1040
1041\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o, char *attr_name}
Guido van Rossum59a61351997-08-14 20:34:33 +00001042Retrieve an attributed named attr_name from object o.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001043Returns the attribute value on success, or \NULL{} on failure.
1044This is the equivalent of the Python expression: \code{o.attr_name}.
1045\end{cfuncdesc}
1046
1047
1048\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
1049Returns 1 if o has the attribute attr_name, and 0 otherwise.
1050This is equivalent to the Python expression:
1051\code{hasattr(o,attr_name)}.
1052This function always succeeds.
1053\end{cfuncdesc}
1054
1055
1056\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o, PyObject *attr_name}
1057Retrieve an attributed named attr_name form object o.
1058Returns the attribute value on success, or \NULL{} on failure.
1059This is the equivalent of the Python expression: o.attr_name.
1060\end{cfuncdesc}
1061
1062
1063\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
1064Set the value of the attribute named \code{attr_name}, for object \code{o},
1065to the value \code{v}. Returns -1 on failure. This is
1066the equivalent of the Python statement: \code{o.attr_name=v}.
1067\end{cfuncdesc}
1068
1069
1070\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
1071Set the value of the attribute named \code{attr_name}, for
1072object \code{o},
1073to the value \code{v}. Returns -1 on failure. This is
1074the equivalent of the Python statement: \code{o.attr_name=v}.
1075\end{cfuncdesc}
1076
1077
1078\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
1079Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1080failure. This is the equivalent of the Python
1081statement: \code{del o.attr_name}.
1082\end{cfuncdesc}
1083
1084
1085\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
1086Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1087failure. This is the equivalent of the Python
1088statement: \code{del o.attr_name}.
1089\end{cfuncdesc}
1090
1091
1092\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
1093Compare the values of \code{o1} and \code{o2} using a routine provided by
1094\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1095The result of the comparison is returned in \code{result}. Returns
1096-1 on failure. This is the equivalent of the Python
1097statement: \code{result=cmp(o1,o2)}.
1098\end{cfuncdesc}
1099
1100
1101\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
1102Compare the values of \code{o1} and \code{o2} using a routine provided by
1103\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1104Returns the result of the comparison on success. On error,
1105the value returned is undefined. This is equivalent to the
1106Python expression: \code{cmp(o1,o2)}.
1107\end{cfuncdesc}
1108
1109
1110\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
1111Compute the string representation of object, \code{o}. Returns the
1112string representation on success, \NULL{} on failure. This is
1113the equivalent of the Python expression: \code{repr(o)}.
1114Called by the \code{repr()} built-in function and by reverse quotes.
1115\end{cfuncdesc}
1116
1117
1118\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
1119Compute the string representation of object, \code{o}. Returns the
1120string representation on success, \NULL{} on failure. This is
1121the equivalent of the Python expression: \code{str(o)}.
1122Called by the \code{str()} built-in function and by the \code{print}
1123statement.
1124\end{cfuncdesc}
1125
1126
1127\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
1128Determine if the object \code{o}, is callable. Return 1 if the
1129object is callable and 0 otherwise.
1130This function always succeeds.
1131\end{cfuncdesc}
1132
1133
1134\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object, PyObject *args}
1135Call a callable Python object \code{callable_object}, with
1136arguments given by the tuple \code{args}. If no arguments are
1137needed, then args may be \NULL{}. Returns the result of the
1138call on success, or \NULL{} on failure. This is the equivalent
1139of the Python expression: \code{apply(o, args)}.
1140\end{cfuncdesc}
1141
1142\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
1143Call a callable Python object \code{callable_object}, with a
1144variable number of C arguments. The C arguments are described
1145using a mkvalue-style format string. The format may be \NULL{},
1146indicating that no arguments are provided. Returns the
1147result of the call on success, or \NULL{} on failure. This is
1148the equivalent of the Python expression: \code{apply(o,args)}.
1149\end{cfuncdesc}
1150
1151
1152\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
1153Call the method named \code{m} of object \code{o} with a variable number of
1154C arguments. The C arguments are described by a mkvalue
1155format string. The format may be \NULL{}, indicating that no
1156arguments are provided. Returns the result of the call on
1157success, or \NULL{} on failure. This is the equivalent of the
1158Python expression: \code{o.method(args)}.
1159Note that Special method names, such as "\code{__add__}",
1160"\code{__getitem__}", and so on are not supported. The specific
1161abstract-object routines for these must be used.
1162\end{cfuncdesc}
1163
1164
1165\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
1166Compute and return the hash value of an object \code{o}. On
1167failure, return -1. This is the equivalent of the Python
1168expression: \code{hash(o)}.
1169\end{cfuncdesc}
1170
1171
1172\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
1173Returns 1 if the object \code{o} is considered to be true, and
11740 otherwise. This is equivalent to the Python expression:
1175\code{not not o}.
1176This function always succeeds.
1177\end{cfuncdesc}
1178
1179
1180\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1181On success, returns a type object corresponding to the object
1182type of object \code{o}. On failure, returns \NULL{}. This is
1183equivalent to the Python expression: \code{type(o)}.
1184\end{cfuncdesc}
1185
1186\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
1187Return the length of object \code{o}. If the object \code{o} provides
1188both sequence and mapping protocols, the sequence length is
1189returned. On error, -1 is returned. This is the equivalent
1190to the Python expression: \code{len(o)}.
1191\end{cfuncdesc}
1192
1193
1194\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
1195Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1196on failure. This is the equivalent of the Python expression:
1197\code{o[key]}.
1198\end{cfuncdesc}
1199
1200
1201\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
1202Map the object \code{key} to the value \code{v}.
1203Returns -1 on failure. This is the equivalent
1204of the Python statement: \code{o[key]=v}.
1205\end{cfuncdesc}
1206
1207
1208\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key, PyObject *v}
1209Delete the mapping for \code{key} from \code{*o}. Returns -1
1210on failure.
Guido van Rossum59a61351997-08-14 20:34:33 +00001211This is the equivalent of the Python statement: \code{del o[key]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001212\end{cfuncdesc}
1213
1214
1215\section{Number Protocol}
1216
1217\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
1218Returns 1 if the object \code{o} provides numeric protocols, and
1219false otherwise.
1220This function always succeeds.
1221\end{cfuncdesc}
1222
1223
1224\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
1225Returns the result of adding \code{o1} and \code{o2}, or null on failure.
1226This is the equivalent of the Python expression: \code{o1+o2}.
1227\end{cfuncdesc}
1228
1229
1230\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
1231Returns the result of subtracting \code{o2} from \code{o1}, or null on
1232failure. This is the equivalent of the Python expression:
1233\code{o1-o2}.
1234\end{cfuncdesc}
1235
1236
1237\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
1238Returns the result of multiplying \code{o1} and \code{o2}, or null on
1239failure. This is the equivalent of the Python expression:
1240\code{o1*o2}.
1241\end{cfuncdesc}
1242
1243
1244\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
1245Returns the result of dividing \code{o1} by \code{o2}, or null on failure.
1246This is the equivalent of the Python expression: \code{o1/o2}.
1247\end{cfuncdesc}
1248
1249
1250\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
1251Returns the remainder of dividing \code{o1} by \code{o2}, or null on
1252failure. This is the equivalent of the Python expression:
1253\code{o1\%o2}.
1254\end{cfuncdesc}
1255
1256
1257\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
1258See the built-in function divmod. Returns \NULL{} on failure.
1259This is the equivalent of the Python expression:
1260\code{divmod(o1,o2)}.
1261\end{cfuncdesc}
1262
1263
1264\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
1265See the built-in function pow. Returns \NULL{} on failure.
1266This is the equivalent of the Python expression:
1267\code{pow(o1,o2,o3)}, where \code{o3} is optional.
1268\end{cfuncdesc}
1269
1270
1271\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
1272Returns the negation of \code{o} on success, or null on failure.
1273This is the equivalent of the Python expression: \code{-o}.
1274\end{cfuncdesc}
1275
1276
1277\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
1278Returns \code{o} on success, or \NULL{} on failure.
1279This is the equivalent of the Python expression: \code{+o}.
1280\end{cfuncdesc}
1281
1282
1283\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
1284Returns the absolute value of \code{o}, or null on failure. This is
1285the equivalent of the Python expression: \code{abs(o)}.
1286\end{cfuncdesc}
1287
1288
1289\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
1290Returns the bitwise negation of \code{o} on success, or \NULL{} on
1291failure. This is the equivalent of the Python expression:
Guido van Rossum59a61351997-08-14 20:34:33 +00001292\code{\~o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001293\end{cfuncdesc}
1294
1295
1296\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
1297Returns the result of left shifting \code{o1} by \code{o2} on success, or
1298\NULL{} on failure. This is the equivalent of the Python
1299expression: \code{o1 << o2}.
1300\end{cfuncdesc}
1301
1302
1303\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
1304Returns the result of right shifting \code{o1} by \code{o2} on success, or
1305\NULL{} on failure. This is the equivalent of the Python
1306expression: \code{o1 >> o2}.
1307\end{cfuncdesc}
1308
1309
1310\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
1311Returns the result of "anding" \code{o2} and \code{o2} on success and \NULL{}
1312on failure. This is the equivalent of the Python
1313expression: \code{o1 and o2}.
1314\end{cfuncdesc}
1315
1316
1317\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
1318Returns the bitwise exclusive or of \code{o1} by \code{o2} on success, or
1319\NULL{} on failure. This is the equivalent of the Python
1320expression: \code{o1\^{ }o2}.
1321\end{cfuncdesc}
1322
1323\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Guido van Rossum59a61351997-08-14 20:34:33 +00001324Returns the result of \code{o1} and \code{o2} on success, or \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001325failure. This is the equivalent of the Python expression:
1326\code{o1 or o2}.
1327\end{cfuncdesc}
1328
1329
1330\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject *o1, PyObject *o2}
1331This function takes the addresses of two variables of type
1332\code{PyObject*}.
1333
1334If the objects pointed to by \code{*p1} and \code{*p2} have the same type,
1335increment their reference count and return 0 (success).
1336If the objects can be converted to a common numeric type,
1337replace \code{*p1} and \code{*p2} by their converted value (with 'new'
1338reference counts), and return 0.
1339If no conversion is possible, or if some other error occurs,
1340return -1 (failure) and don't increment the reference counts.
1341The call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1342statement \code{o1, o2 = coerce(o1, o2)}.
1343\end{cfuncdesc}
1344
1345
1346\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
1347Returns the \code{o} converted to an integer object on success, or
1348\NULL{} on failure. This is the equivalent of the Python
1349expression: \code{int(o)}.
1350\end{cfuncdesc}
1351
1352
1353\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
1354Returns the \code{o} converted to a long integer object on success,
1355or \NULL{} on failure. This is the equivalent of the Python
1356expression: \code{long(o)}.
1357\end{cfuncdesc}
1358
1359
1360\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
1361Returns the \code{o} converted to a float object on success, or \NULL{}
1362on failure. This is the equivalent of the Python expression:
1363\code{float(o)}.
1364\end{cfuncdesc}
1365
1366
1367\section{Sequence protocol}
1368
1369\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
1370Return 1 if the object provides sequence protocol, and 0
1371otherwise.
1372This function always succeeds.
1373\end{cfuncdesc}
1374
1375
1376\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
1377Return the concatination of \code{o1} and \code{o2} on success, and \NULL{} on
1378failure. This is the equivalent of the Python
1379expression: \code{o1+o2}.
1380\end{cfuncdesc}
1381
1382
1383\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Guido van Rossum59a61351997-08-14 20:34:33 +00001384Return the result of repeating sequence object \code{o} \code{count} times,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001385or \NULL{} on failure. This is the equivalent of the Python
1386expression: \code{o*count}.
1387\end{cfuncdesc}
1388
1389
1390\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
1391Return the ith element of \code{o}, or \NULL{} on failure. This is the
1392equivalent of the Python expression: \code{o[i]}.
1393\end{cfuncdesc}
1394
1395
1396\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
1397Return the slice of sequence object \code{o} between \code{i1} and \code{i2}, or
1398\NULL{} on failure. This is the equivalent of the Python
1399expression, \code{o[i1:i2]}.
1400\end{cfuncdesc}
1401
1402
1403\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
1404Assign object \code{v} to the \code{i}th element of \code{o}.
1405Returns -1 on failure. This is the equivalent of the Python
1406statement, \code{o[i]=v}.
1407\end{cfuncdesc}
1408
1409\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
1410Delete the \code{i}th element of object \code{v}. Returns
1411-1 on failure. This is the equivalent of the Python
1412statement: \code{del o[i]}.
1413\end{cfuncdesc}
1414
1415\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1, int i2, PyObject *v}
1416Assign the sequence object \code{v} to the slice in sequence
1417object \code{o} from \code{i1} to \code{i2}. This is the equivalent of the Python
1418statement, \code{o[i1:i2]=v}.
1419\end{cfuncdesc}
1420
1421\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
1422Delete the slice in sequence object, \code{o}, from \code{i1} to \code{i2}.
1423Returns -1 on failure. This is the equivalent of the Python
1424statement: \code{del o[i1:i2]}.
1425\end{cfuncdesc}
1426
1427\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1428Returns the \code{o} as a tuple on success, and \NULL{} on failure.
1429This is equivalent to the Python expression: \code{tuple(o)}.
1430\end{cfuncdesc}
1431
1432\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
1433Return the number of occurrences of \code{value} on \code{o}, that is,
1434return the number of keys for which \code{o[key]==value}. On
1435failure, return -1. This is equivalent to the Python
1436expression: \code{o.count(value)}.
1437\end{cfuncdesc}
1438
1439\begin{cfuncdesc}{int}{PySequence_In}{PyObject *o, PyObject *value}
1440Determine if \code{o} contains \code{value}. If an item in \code{o} is equal to
1441\code{value}, return 1, otherwise return 0. On error, return -1. This
1442is equivalent to the Python expression: \code{value in o}.
1443\end{cfuncdesc}
1444
1445\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Guido van Rossum59a61351997-08-14 20:34:33 +00001446Return the first index for which \code{o[i]==value}. On error,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001447return -1. This is equivalent to the Python
1448expression: \code{o.index(value)}.
1449\end{cfuncdesc}
1450
1451\section{Mapping protocol}
1452
1453\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
1454Return 1 if the object provides mapping protocol, and 0
1455otherwise.
1456This function always succeeds.
1457\end{cfuncdesc}
1458
1459
1460\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
1461Returns the number of keys in object \code{o} on success, and -1 on
1462failure. For objects that do not provide sequence protocol,
1463this is equivalent to the Python expression: \code{len(o)}.
1464\end{cfuncdesc}
1465
1466
1467\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
1468Remove the mapping for object \code{key} from the object \code{o}.
1469Return -1 on failure. This is equivalent to
1470the Python statement: \code{del o[key]}.
1471\end{cfuncdesc}
1472
1473
1474\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
1475Remove the mapping for object \code{key} from the object \code{o}.
1476Return -1 on failure. This is equivalent to
1477the Python statement: \code{del o[key]}.
1478\end{cfuncdesc}
1479
1480
1481\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
1482On success, return 1 if the mapping object has the key \code{key}
1483and 0 otherwise. This is equivalent to the Python expression:
1484\code{o.has_key(key)}.
1485This function always succeeds.
1486\end{cfuncdesc}
1487
1488
1489\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
1490Return 1 if the mapping object has the key \code{key}
1491and 0 otherwise. This is equivalent to the Python expression:
1492\code{o.has_key(key)}.
1493This function always succeeds.
1494\end{cfuncdesc}
1495
1496
1497\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
1498On success, return a list of the keys in object \code{o}. On
1499failure, return \NULL{}. This is equivalent to the Python
1500expression: \code{o.keys()}.
1501\end{cfuncdesc}
1502
1503
1504\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
1505On success, return a list of the values in object \code{o}. On
1506failure, return \NULL{}. This is equivalent to the Python
1507expression: \code{o.values()}.
1508\end{cfuncdesc}
1509
1510
1511\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
1512On success, return a list of the items in object \code{o}, where
1513each item is a tuple containing a key-value pair. On
1514failure, return \NULL{}. This is equivalent to the Python
1515expression: \code{o.items()}.
1516\end{cfuncdesc}
1517
1518\begin{cfuncdesc}{int}{PyMapping_Clear}{PyObject *o}
1519Make object \code{o} empty. Returns 1 on success and 0 on failure.
1520This is equivalent to the Python statement:
1521\code{for key in o.keys(): del o[key]}
1522\end{cfuncdesc}
1523
1524
1525\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
1526Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1527on failure. This is the equivalent of the Python expression:
1528\code{o[key]}.
1529\end{cfuncdesc}
1530
1531\begin{cfuncdesc}{PyObject*}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
1532Map the object \code{key} to the value \code{v} in object \code{o}. Returns
1533-1 on failure. This is the equivalent of the Python
1534statement: \code{o[key]=v}.
1535\end{cfuncdesc}
1536
1537
1538\section{Constructors}
1539
1540\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *file_name, char *mode}
1541On success, returns a new file object that is opened on the
1542file given by \code{file_name}, with a file mode given by \code{mode},
1543where \code{mode} has the same semantics as the standard C routine,
1544fopen. On failure, return -1.
1545\end{cfuncdesc}
1546
1547\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp, char *file_name, char *mode, int close_on_del}
1548Return a new file object for an already opened standard C
1549file pointer, \code{fp}. A file name, \code{file_name}, and open mode,
1550\code{mode}, must be provided as well as a flag, \code{close_on_del}, that
1551indicates whether the file is to be closed when the file
1552object is destroyed. On failure, return -1.
1553\end{cfuncdesc}
1554
1555\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
1556Returns a new float object with the value \code{v} on success, and
1557\NULL{} on failure.
1558\end{cfuncdesc}
1559
1560\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long v}
1561Returns a new int object with the value \code{v} on success, and
1562\NULL{} on failure.
1563\end{cfuncdesc}
1564
1565\begin{cfuncdesc}{PyObject*}{PyList_New}{int l}
1566Returns a new list of length \code{l} on success, and \NULL{} on
1567failure.
1568\end{cfuncdesc}
1569
1570\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
1571Returns a new long object with the value \code{v} on success, and
1572\NULL{} on failure.
1573\end{cfuncdesc}
1574
1575\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
1576Returns a new long object with the value \code{v} on success, and
1577\NULL{} on failure.
1578\end{cfuncdesc}
1579
1580\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1581Returns a new empty dictionary on success, and \NULL{} on
1582failure.
1583\end{cfuncdesc}
1584
1585\begin{cfuncdesc}{PyObject*}{PyString_FromString}{char *v}
1586Returns a new string object with the value \code{v} on success, and
1587\NULL{} on failure.
1588\end{cfuncdesc}
1589
1590\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{char *v, int l}
1591Returns a new string object with the value \code{v} and length \code{l}
1592on success, and \NULL{} on failure.
1593\end{cfuncdesc}
1594
1595\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int l}
1596Returns a new tuple of length \code{l} on success, and \NULL{} on
1597failure.
1598\end{cfuncdesc}
1599
1600
1601\chapter{Concrete Objects Layer}
1602
1603The functions in this chapter are specific to certain Python object
1604types. Passing them an object of the wrong type is not a good idea;
1605if you receive an object from a Python program and you are not sure
1606that it has the right type, you must perform a type check first;
1607e.g. to check that an object is a dictionary, use
1608\code{PyDict_Check()}.
1609
1610
1611\chapter{Defining New Object Types}
1612
1613\begin{cfuncdesc}{PyObject *}{_PyObject_New}{PyTypeObject *type}
1614\end{cfuncdesc}
1615
Guido van Rossumae110af1997-05-22 20:11:52 +00001616\begin{cfuncdesc}{PyObject *}{_PyObject_NewVar}{PyTypeObject *type, int size}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001617\end{cfuncdesc}
1618
Guido van Rossumae110af1997-05-22 20:11:52 +00001619\begin{cfuncdesc}{TYPE}{_PyObject_NEW}{TYPE, PyTypeObject *}
1620\end{cfuncdesc}
1621
1622\begin{cfuncdesc}{TYPE}{_PyObject_NEW_VAR}{TYPE, PyTypeObject *, int size}
1623\end{cfuncdesc}
1624
Guido van Rossum4a944d71997-08-14 20:35:38 +00001625\chapter{Initialization, Finalization, and Threads}
1626
Guido van Rossum4a944d71997-08-14 20:35:38 +00001627\begin{cfuncdesc}{void}{Py_Initialize}{}
1628Initialize the Python interpreter. In an application embedding
1629Python, this should be called before using any other Python/C API
1630functions; with the exception of \code{Py_SetProgramName()},
1631\code{PyEval_InitThreads()}, \code{PyEval_ReleaseLock()}, and
1632\code{PyEval_AcquireLock()}. This initializes the table of loaded
1633modules (\code{sys.modules}), and creates the fundamental modules
1634\code{__builtin__}, \code{__main__} and \code{sys}. It also
1635initializes the module search path (\code{sys.path}). It does not set
Guido van Rossum42cefd01997-10-05 15:27:29 +00001636\code{sys.argv}; use \code{PySys_SetArgv()} for that. This is a no-op
1637when called for a second time (without calling \code{Py_Finalize()}
1638first). There is no return value; it is a fatal error if the
1639initialization fails.
1640\end{cfuncdesc}
1641
1642\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001643\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001644Return true (nonzero) when the Python interpreter has been
1645initialized, false (zero) if not. After \code{Py_Finalize()} is
1646called, this returns false until \code{Py_Initialize()} is called
1647again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00001648\end{cfuncdesc}
1649
1650\begin{cfuncdesc}{void}{Py_Finalize}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001651\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001652Undo all initializations made by \code{Py_Initialize()} and subsequent
1653use of Python/C API functions, and destroy all sub-interpreters (see
1654\code{Py_NewInterpreter()} below) that were created and not yet
Guido van Rossum42cefd01997-10-05 15:27:29 +00001655destroyed since the last call to \code{Py_Initialize()}. Ideally,
1656this frees all memory allocated by the Python interpreter. This is a
1657no-op when called for a second time (without calling
1658\code{Py_Initialize()} again first). There is no return value; errors
Guido van Rossum4a944d71997-08-14 20:35:38 +00001659during finalization are ignored.
1660
1661This function is provided for a number of reasons. An embedding
1662application might want to restart Python without having to restart the
1663application itself. An application that has loaded the Python
1664interpreter from a dynamically loadable library (or DLL) might want to
1665free all memory allocated by Python before unloading the DLL. During a
1666hunt for memory leaks in an application a developer might want to free
1667all memory allocated by Python before exiting from the application.
1668
1669\emph{Bugs and caveats:} The destruction of modules and objects in
1670modules is done in random order; this may cause destructors
1671(\code{__del__} methods) to fail when they depend on other objects
1672(even functions) or modules. Dynamically loaded extension modules
1673loaded by Python are not unloaded. Small amounts of memory allocated
1674by the Python interpreter may not be freed (if you find a leak, please
1675report it). Memory tied up in circular references between objects is
1676not freed. Some memory allocated by extension modules may not be
1677freed. Some extension may not work properly if their initialization
1678routine is called more than once; this can happen if an applcation
1679calls \code{Py_Initialize()} and \code{Py_Finalize()} more than once.
1680\end{cfuncdesc}
1681
1682\begin{cfuncdesc}{PyThreadState *}{Py_NewInterpreter}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001683\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001684Create a new sub-interpreter. This is an (almost) totally separate
1685environment for the execution of Python code. In particular, the new
1686interpreter has separate, independent versions of all imported
1687modules, including the fundamental modules \code{__builtin__},
1688\code{__main__} and \code{sys}. The table of loaded modules
1689(\code{sys.modules}) and the module search path (\code{sys.path}) are
1690also separate. The new environment has no \code{sys.argv} variable.
1691It has new standard I/O stream file objects \code{sys.stdin},
1692\code{sys.stdout} and \code{sys.stderr} (however these refer to the
1693same underlying \code{FILE} structures in the C library).
1694
1695The return value points to the first thread state created in the new
1696sub-interpreter. This thread state is made the current thread state.
1697Note that no actual thread is created; see the discussion of thread
1698states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001699\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00001700is stored in the current thread state and there may not be a current
1701thread state. (Like all other Python/C API functions, the global
1702interpreter lock must be held before calling this function and is
1703still held when it returns; however, unlike most other Python/C API
1704functions, there needn't be a current thread state on entry.)
1705
1706Extension modules are shared between (sub-)interpreters as follows:
1707the first time a particular extension is imported, it is initialized
1708normally, and a (shallow) copy of its module's dictionary is
1709squirreled away. When the same extension is imported by another
1710(sub-)interpreter, a new module is initialized and filled with the
1711contents of this copy; the extension's \code{init} function is not
1712called. Note that this is different from what happens when as
1713extension is imported after the interpreter has been completely
1714re-initialized by calling \code{Py_Finalize()} and
1715\code{Py_Initialize()}; in that case, the extension's \code{init}
1716function \emph{is} called again.
1717
1718\emph{Bugs and caveats:} Because sub-interpreters (and the main
1719interpreter) are part of the same process, the insulation between them
1720isn't perfect -- for example, using low-level file operations like
1721\code{os.close()} they can (accidentally or maliciously) affect each
1722other's open files. Because of the way extensions are shared between
1723(sub-)interpreters, some extensions may not work properly; this is
1724especially likely when the extension makes use of (static) global
1725variables, or when the extension manipulates its module's dictionary
1726after its initialization. It is possible to insert objects created in
1727one sub-interpreter into a namespace of another sub-interpreter; this
1728should be done with great care to avoid sharing user-defined
1729functions, methods, instances or classes between sub-interpreters,
1730since import operations executed by such objects may affect the
1731wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
1732a hard-to-fix bug that will be addressed in a future release.)
1733\end{cfuncdesc}
1734
1735\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001736\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001737Destroy the (sub-)interpreter represented by the given thread state.
1738The given thread state must be the current thread state. See the
1739discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001740thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00001741interpreted are destroyed. (The global interpreter lock must be held
1742before calling this function and is still held when it returns.)
1743\code{Py_Finalize()} will destroy all sub-interpreters that haven't
1744been explicitly destroyed at that point.
1745\end{cfuncdesc}
1746
1747\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001748\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001749This function should be called before \code{Py_Initialize()} is called
1750for the first time, if it is called at all. It tells the interpreter
1751the value of the \code{argv[0]} argument to the \code{main()} function
1752of the program. This is used by \code{Py_GetPath()} and some other
1753functions below to find the Python run-time libraries relative to the
1754interpreter executable. The default value is \code{"python"}. The
1755argument should point to a zero-terminated character string in static
1756storage whose contents will not change for the duration of the
1757program's execution. No code in the Python interpreter will change
1758the contents of this storage.
1759\end{cfuncdesc}
1760
1761\begin{cfuncdesc}{char *}{Py_GetProgramName}{}
1762Return the program name set with \code{Py_SetProgramName()}, or the
1763default. The returned string points into static storage; the caller
1764should not modify its value.
1765\end{cfuncdesc}
1766
1767\begin{cfuncdesc}{char *}{Py_GetPrefix}{}
1768Return the ``prefix'' for installed platform-independent files. This
1769is derived through a number of complicated rules from the program name
1770set with \code{Py_SetProgramName()} and some environment variables;
1771for example, if the program name is \code{"/usr/local/bin/python"},
1772the prefix is \code{"/usr/local"}. The returned string points into
1773static storage; the caller should not modify its value. This
1774corresponds to the \code{prefix} variable in the top-level
1775\code{Makefile} and the \code{--prefix} argument to the
1776\code{configure} script at build time. The value is available to
1777Python code as \code{sys.prefix}. It is only useful on Unix. See
1778also the next function.
1779\end{cfuncdesc}
1780
1781\begin{cfuncdesc}{char *}{Py_GetExecPrefix}{}
1782Return the ``exec-prefix'' for installed platform-\emph{de}pendent
1783files. This is derived through a number of complicated rules from the
1784program name set with \code{Py_SetProgramName()} and some environment
1785variables; for example, if the program name is
1786\code{"/usr/local/bin/python"}, the exec-prefix is
1787\code{"/usr/local"}. The returned string points into static storage;
1788the caller should not modify its value. This corresponds to the
1789\code{exec_prefix} variable in the top-level \code{Makefile} and the
1790\code{--exec_prefix} argument to the \code{configure} script at build
1791time. The value is available to Python code as
1792\code{sys.exec_prefix}. It is only useful on Unix.
1793
1794Background: The exec-prefix differs from the prefix when platform
1795dependent files (such as executables and shared libraries) are
1796installed in a different directory tree. In a typical installation,
1797platform dependent files may be installed in the
1798\code{"/usr/local/plat"} subtree while platform independent may be
1799installed in \code{"/usr/local"}.
1800
1801Generally speaking, a platform is a combination of hardware and
1802software families, e.g. Sparc machines running the Solaris 2.x
1803operating system are considered the same platform, but Intel machines
1804running Solaris 2.x are another platform, and Intel machines running
1805Linux are yet another platform. Different major revisions of the same
1806operating system generally also form different platforms. Non-Unix
1807operating systems are a different story; the installation strategies
1808on those systems are so different that the prefix and exec-prefix are
1809meaningless, and set to the empty string. Note that compiled Python
1810bytecode files are platform independent (but not independent from the
1811Python version by which they were compiled!).
1812
1813System administrators will know how to configure the \code{mount} or
1814\code{automount} programs to share \code{"/usr/local"} between platforms
1815while having \code{"/usr/local/plat"} be a different filesystem for each
1816platform.
1817\end{cfuncdesc}
1818
1819\begin{cfuncdesc}{char *}{Py_GetProgramFullPath}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001820\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001821Return the full program name of the Python executable; this is
1822computed as a side-effect of deriving the default module search path
Guido van Rossum09270b51997-08-15 18:57:32 +00001823from the program name (set by \code{Py_SetProgramName()} above). The
Guido van Rossum4a944d71997-08-14 20:35:38 +00001824returned string points into static storage; the caller should not
1825modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00001826\code{sys.executable}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00001827\end{cfuncdesc}
1828
1829\begin{cfuncdesc}{char *}{Py_GetPath}{}
1830Return the default module search path; this is computed from the
Guido van Rossum09270b51997-08-15 18:57:32 +00001831program name (set by \code{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00001832environment variables. The returned string consists of a series of
1833directory names separated by a platform dependent delimiter character.
1834The delimiter character is \code{':'} on Unix, \code{';'} on
Guido van Rossum09270b51997-08-15 18:57:32 +00001835DOS/Windows, and \code{'\\n'} (the ASCII newline character) on
Guido van Rossum4a944d71997-08-14 20:35:38 +00001836Macintosh. The returned string points into static storage; the caller
1837should not modify its value. The value is available to Python code
1838as the list \code{sys.path}, which may be modified to change the
1839future search path for loaded modules.
1840
1841% XXX should give the exact rules
1842\end{cfuncdesc}
1843
1844\begin{cfuncdesc}{const char *}{Py_GetVersion}{}
1845Return the version of this Python interpreter. This is a string that
1846looks something like
1847
Guido van Rossum09270b51997-08-15 18:57:32 +00001848\begin{verbatim}
1849"1.5a3 (#67, Aug 1 1997, 22:34:28) [GCC 2.7.2.2]"
1850\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001851
1852The first word (up to the first space character) is the current Python
1853version; the first three characters are the major and minor version
1854separated by a period. The returned string points into static storage;
1855the caller should not modify its value. The value is available to
1856Python code as the list \code{sys.version}.
1857\end{cfuncdesc}
1858
1859\begin{cfuncdesc}{const char *}{Py_GetPlatform}{}
1860Return the platform identifier for the current platform. On Unix,
1861this is formed from the ``official'' name of the operating system,
1862converted to lower case, followed by the major revision number; e.g.,
1863for Solaris 2.x, which is also known as SunOS 5.x, the value is
1864\code{"sunos5"}. On Macintosh, it is \code{"mac"}. On Windows, it
1865is \code{"win"}. The returned string points into static storage;
1866the caller should not modify its value. The value is available to
1867Python code as \code{sys.platform}.
1868\end{cfuncdesc}
1869
1870\begin{cfuncdesc}{const char *}{Py_GetCopyright}{}
1871Return the official copyright string for the current Python version,
1872for example
1873
1874\code{"Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam"}
1875
1876The returned string points into static storage; the caller should not
1877modify its value. The value is available to Python code as the list
1878\code{sys.copyright}.
1879\end{cfuncdesc}
1880
1881\begin{cfuncdesc}{const char *}{Py_GetCompiler}{}
1882Return an indication of the compiler used to build the current Python
1883version, in square brackets, for example
1884
1885\code{"[GCC 2.7.2.2]"}
1886
1887The returned string points into static storage; the caller should not
1888modify its value. The value is available to Python code as part of
1889the variable \code{sys.version}.
1890\end{cfuncdesc}
1891
1892\begin{cfuncdesc}{const char *}{Py_GetBuildInfo}{}
1893Return information about the sequence number and build date and time
1894of the current Python interpreter instance, for example
1895
Guido van Rossum09270b51997-08-15 18:57:32 +00001896\begin{verbatim}
1897"#67, Aug 1 1997, 22:34:28"
1898\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001899
1900The returned string points into static storage; the caller should not
1901modify its value. The value is available to Python code as part of
1902the variable \code{sys.version}.
1903\end{cfuncdesc}
1904
1905\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
1906% XXX
1907\end{cfuncdesc}
1908
1909% XXX Other PySys thingies (doesn't really belong in this chapter)
1910
1911\section{Thread State and the Global Interpreter Lock}
1912
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001913The Python interpreter is not fully thread safe. In order to support
1914multi-threaded Python programs, there's a global lock that must be
1915held by the current thread before it can safely access Python objects.
1916Without the lock, even the simplest operations could cause problems in
1917a multi-threaded proram: for example, when two threads simultaneously
1918increment the reference count of the same object, the reference count
1919could end up being incremented only once instead of twice.
1920
1921Therefore, the rule exists that only the thread that has acquired the
1922global interpreter lock may operate on Python objects or call Python/C
1923API functions. In order to support multi-threaded Python programs,
1924the interpreter regularly release and reacquires the lock -- by
1925default, every ten bytecode instructions (this can be changed with
1926\code{sys.setcheckinterval()}). The lock is also released and
1927reacquired around potentially blocking I/O operations like reading or
1928writing a file, so that other threads can run while the thread that
1929requests the I/O is waiting for the I/O operation to complete.
1930
1931The Python interpreter needs to keep some bookkeeping information
1932separate per thread -- for this it uses a data structure called
1933PyThreadState. This is new in Python 1.5; in earlier versions, such
1934state was stored in global variables, and switching threads could
1935cause problems. In particular, exception handling is now thread safe,
1936when the application uses \code{sys.exc_info()} to access the exception
1937last raised in the current thread.
1938
1939There's one global variable left, however: the pointer to the current
1940PyThreadState structure. While most thread packages have a way to
1941store ``per-thread global data'', Python's internal platform
1942independent thread abstraction doesn't support this (yet). Therefore,
1943the current thread state must be manipulated explicitly.
1944
1945This is easy enough in most cases. Most code manipulating the global
1946interpreter lock has the following simple structure:
1947
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001948\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001949Save the thread state in a local variable.
1950Release the interpreter lock.
1951...Do some blocking I/O operation...
1952Reacquire the interpreter lock.
1953Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001954\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001955
1956This is so common that a pair of macros exists to simplify it:
1957
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001958\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001959Py_BEGIN_ALLOW_THREADS
1960...Do some blocking I/O operation...
1961Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001962\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001963
1964The BEGIN macro opens a new block and declares a hidden local
1965variable; the END macro closes the block. Another advantage of using
1966these two macros is that when Python is compiled without thread
1967support, they are defined empty, thus saving the thread state and lock
1968manipulations.
1969
1970When thread support is enabled, the block above expands to the
1971following code:
1972
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001973\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001974{
1975 PyThreadState *_save;
1976 _save = PyEval_SaveThread();
1977 ...Do some blocking I/O operation...
1978 PyEval_RestoreThread(_save);
1979}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001980\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001981
1982Using even lower level primitives, we can get roughly the same effect
1983as follows:
1984
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001985\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001986{
1987 PyThreadState *_save;
1988 _save = PyThreadState_Swap(NULL);
1989 PyEval_ReleaseLock();
1990 ...Do some blocking I/O operation...
1991 PyEval_AcquireLock();
1992 PyThreadState_Swap(_save);
1993}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001994\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001995
1996There are some subtle differences; in particular,
1997\code{PyEval_RestoreThread()} saves and restores the value of the
1998global variable \code{errno}, since the lock manipulation does not
1999guarantee that \code{errno} is left alone. Also, when thread support
2000is disabled, \code{PyEval_SaveThread()} and
2001\code{PyEval_RestoreThread()} don't manipulate the lock; in this case,
2002\code{PyEval_ReleaseLock()} and \code{PyEval_AcquireLock()} are not
2003available. (This is done so that dynamically loaded extensions
2004compiled with thread support enabled can be loaded by an interpreter
2005that was compiled with disabled thread support.)
2006
2007The global interpreter lock is used to protect the pointer to the
2008current thread state. When releasing the lock and saving the thread
2009state, the current thread state pointer must be retrieved before the
2010lock is released (since another thread could immediately acquire the
2011lock and store its own thread state in the global variable).
2012Reversely, when acquiring the lock and restoring the thread state, the
2013lock must be acquired before storing the thread state pointer.
2014
2015Why am I going on with so much detail about this? Because when
2016threads are created from C, they don't have the global interpreter
2017lock, nor is there a thread state data structure for them. Such
2018threads must bootstrap themselves into existence, by first creating a
2019thread state data structure, then acquiring the lock, and finally
2020storing their thread state pointer, before they can start using the
2021Python/C API. When they are done, they should reset the thread state
2022pointer, release the lock, and finally free their thread state data
2023structure.
2024
2025When creating a thread data structure, you need to provide an
2026interpreter state data structure. The interpreter state data
2027structure hold global data that is shared by all threads in an
2028interpreter, for example the module administration
2029(\code{sys.modules}). Depending on your needs, you can either create
2030a new interpreter state data structure, or share the interpreter state
2031data structure used by the Python main thread (to access the latter,
2032you must obtain the thread state and access its \code{interp} member;
2033this must be done by a thread that is created by Python or by the main
2034thread after Python is initialized).
2035
2036XXX More?
2037
2038\begin{ctypedesc}{PyInterpreterState}
2039\strong{(NEW in 1.5a3!)}
2040This data structure represents the state shared by a number of
2041cooperating threads. Threads belonging to the same interpreter
2042share their module administration and a few other internal items.
2043There are no public members in this structure.
2044
2045Threads belonging to different interpreters initially share nothing,
2046except process state like available memory, open file descriptors and
2047such. The global interpreter lock is also shared by all threads,
2048regardless of to which interpreter they belong.
2049\end{ctypedesc}
2050
2051\begin{ctypedesc}{PyThreadState}
2052\strong{(NEW in 1.5a3!)}
2053This data structure represents the state of a single thread. The only
2054public data member is \code{PyInterpreterState *interp}, which points
2055to this thread's interpreter state.
2056\end{ctypedesc}
2057
2058\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
2059Initialize and acquire the global interpreter lock. It should be
2060called in the main thread before creating a second thread or engaging
2061in any other thread operations such as \code{PyEval_ReleaseLock()} or
2062\code{PyEval_ReleaseThread(tstate)}. It is not needed before
2063calling \code{PyEval_SaveThread()} or \code{PyEval_RestoreThread()}.
2064
2065This is a no-op when called for a second time. It is safe to call
2066this function before calling \code{Py_Initialize()}.
2067
2068When only the main thread exists, no lock operations are needed. This
2069is a common situation (most Python programs do not use threads), and
2070the lock operations slow the interpreter down a bit. Therefore, the
2071lock is not created initially. This situation is equivalent to having
2072acquired the lock: when there is only a single thread, all object
2073accesses are safe. Therefore, when this function initializes the
2074lock, it also acquires it. Before the Python \code{thread} module
2075creates a new thread, knowing that either it has the lock or the lock
2076hasn't been created yet, it calls \code{PyEval_InitThreads()}. When
2077this call returns, it is guaranteed that the lock has been created and
2078that it has acquired it.
2079
2080It is \strong{not} safe to call this function when it is unknown which
2081thread (if any) currently has the global interpreter lock.
2082
2083This function is not available when thread support is disabled at
2084compile time.
2085\end{cfuncdesc}
2086
Guido van Rossum4a944d71997-08-14 20:35:38 +00002087\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002088\strong{(NEW in 1.5a3!)}
2089Acquire the global interpreter lock. The lock must have been created
2090earlier. If this thread already has the lock, a deadlock ensues.
2091This function is not available when thread support is disabled at
2092compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002093\end{cfuncdesc}
2094
2095\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002096\strong{(NEW in 1.5a3!)}
2097Release the global interpreter lock. The lock must have been created
2098earlier. This function is not available when thread support is
2099disabled at
2100compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002101\end{cfuncdesc}
2102
2103\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002104\strong{(NEW in 1.5a3!)}
2105Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002106state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002107have been created earlier. If this thread already has the lock,
2108deadlock ensues. This function is not available when thread support
2109is disabled at
2110compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002111\end{cfuncdesc}
2112
2113\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002114\strong{(NEW in 1.5a3!)}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002115Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002116interpreter lock. The lock must have been created earlier and must be
2117held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002118be \NULL{}, is only used to check that it represents the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002119thread state -- if it isn't, a fatal error is reported. This function
2120is not available when thread support is disabled at
2121compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002122\end{cfuncdesc}
2123
2124\begin{cfuncdesc}{PyThreadState *}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002125\strong{(Different return type in 1.5a3!)}
2126Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002127support is enabled) and reset the thread state to \NULL{},
2128returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002129the lock has been created, the current thread must have acquired it.
2130(This function is available even when thread support is disabled at
2131compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002132\end{cfuncdesc}
2133
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002134\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
2135\strong{(Different argument type in 1.5a3!)}
2136Acquire the interpreter lock (if it has been created and thread
2137support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002138must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002139thread must not have acquired it, otherwise deadlock ensues. (This
2140function is available even when thread support is disabled at compile
2141time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002142\end{cfuncdesc}
2143
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002144% XXX These aren't really C types, but the ctypedesc macro is the simplest!
2145\begin{ctypedesc}{Py_BEGIN_ALLOW_THREADS}
2146This macro expands to
2147\code{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
2148Note that it contains an opening brace; it must be matched with a
2149following \code{Py_END_ALLOW_THREADS} macro. See above for further
2150discussion of this macro. It is a no-op when thread support is
2151disabled at compile time.
2152\end{ctypedesc}
2153
2154\begin{ctypedesc}{Py_END_ALLOW_THREADS}
2155This macro expands to
2156\code{PyEval_RestoreThread(_save); \} }.
2157Note that it contains a closing brace; it must be matched with an
2158earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
2159discussion of this macro. It is a no-op when thread support is
2160disabled at compile time.
2161\end{ctypedesc}
2162
2163\begin{ctypedesc}{Py_BEGIN_BLOCK_THREADS}
2164This macro expands to \code{PyEval_RestoreThread(_save);} i.e. it
2165is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
2166brace. It is a no-op when thread support is disabled at compile
2167time.
2168\end{ctypedesc}
2169
2170\begin{ctypedesc}{Py_BEGIN_UNBLOCK_THREADS}
2171This macro expands to \code{_save = PyEval_SaveThread();} i.e. it is
2172equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
2173and variable declaration. It is a no-op when thread support is
2174disabled at compile time.
2175\end{ctypedesc}
2176
2177All of the following functions are only available when thread support
2178is enabled at compile time, and must be called only when the
2179interpreter lock has been created. They are all new in 1.5a3.
2180
2181\begin{cfuncdesc}{PyInterpreterState *}{PyInterpreterState_New}{}
2182Create a new interpreter state object. The interpreter lock must be
2183held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002184\end{cfuncdesc}
2185
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002186\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
2187Reset all information in an interpreter state object. The interpreter
2188lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002189\end{cfuncdesc}
2190
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002191\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
2192Destroy an interpreter state object. The interpreter lock need not be
2193held. The interpreter state must have been reset with a previous
2194call to \code{PyInterpreterState_Clear()}.
2195\end{cfuncdesc}
2196
2197\begin{cfuncdesc}{PyThreadState *}{PyThreadState_New}{PyInterpreterState *interp}
2198Create a new thread state object belonging to the given interpreter
2199object. The interpreter lock must be held.
2200\end{cfuncdesc}
2201
2202\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
2203Reset all information in a thread state object. The interpreter lock
2204must be held.
2205\end{cfuncdesc}
2206
2207\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
2208Destroy a thread state object. The interpreter lock need not be
2209held. The thread state must have been reset with a previous
2210call to \code{PyThreadState_Clear()}.
2211\end{cfuncdesc}
2212
2213\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Get}{}
2214Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002215When the current thread state is \NULL{}, this issues a fatal
2216error (so that the caller needn't check for \NULL{}.
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002217\end{cfuncdesc}
2218
2219\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Swap}{PyThreadState *tstate}
2220Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002221argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002222must be held.
2223\end{cfuncdesc}
2224
2225
2226\section{Defining New Object Types}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002227
Guido van Rossumae110af1997-05-22 20:11:52 +00002228XXX To be done:
2229
2230PyObject, PyVarObject
2231
2232PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
2233
2234Typedefs:
2235unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
2236intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
2237getreadbufferproc, getwritebufferproc, getsegcountproc,
2238destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
2239setattrofunc, cmpfunc, reprfunc, hashfunc
2240
2241PyNumberMethods
2242
2243PySequenceMethods
2244
2245PyMappingMethods
2246
2247PyBufferProcs
2248
2249PyTypeObject
2250
2251DL_IMPORT
2252
2253PyType_Type
2254
2255Py*_Check
2256
2257Py_None, _Py_NoneStruct
2258
2259_PyObject_New, _PyObject_NewVar
2260
2261PyObject_NEW, PyObject_NEW_VAR
2262
2263
2264\chapter{Specific Data Types}
2265
2266This chapter describes the functions that deal with specific types of
2267Python objects. It is structured like the ``family tree'' of Python
2268object types.
2269
2270
2271\section{Fundamental Objects}
2272
2273This section describes Python type objects and the singleton object
2274\code{None}.
2275
2276
2277\subsection{Type Objects}
2278
2279\begin{ctypedesc}{PyTypeObject}
2280
2281\end{ctypedesc}
2282
2283\begin{cvardesc}{PyObject *}{PyType_Type}
2284
2285\end{cvardesc}
2286
2287
2288\subsection{The None Object}
2289
2290\begin{cvardesc}{PyObject *}{Py_None}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002291XXX macro
Guido van Rossumae110af1997-05-22 20:11:52 +00002292\end{cvardesc}
2293
2294
2295\section{Sequence Objects}
2296
2297Generic operations on sequence objects were discussed in the previous
2298chapter; this section deals with the specific kinds of sequence
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002299objects that are intrinsic to the Python language.
Guido van Rossumae110af1997-05-22 20:11:52 +00002300
2301
2302\subsection{String Objects}
2303
2304\begin{ctypedesc}{PyStringObject}
2305This subtype of \code{PyObject} represents a Python string object.
2306\end{ctypedesc}
2307
2308\begin{cvardesc}{PyTypeObject}{PyString_Type}
2309This instance of \code{PyTypeObject} represents the Python string type.
2310\end{cvardesc}
2311
2312\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
2313
2314\end{cfuncdesc}
2315
2316\begin{cfuncdesc}{PyObject *}{PyString_FromStringAndSize}{const char *, int}
2317
2318\end{cfuncdesc}
2319
2320\begin{cfuncdesc}{PyObject *}{PyString_FromString}{const char *}
2321
2322\end{cfuncdesc}
2323
2324\begin{cfuncdesc}{int}{PyString_Size}{PyObject *}
2325
2326\end{cfuncdesc}
2327
2328\begin{cfuncdesc}{char *}{PyString_AsString}{PyObject *}
2329
2330\end{cfuncdesc}
2331
2332\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **, PyObject *}
2333
2334\end{cfuncdesc}
2335
2336\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **, PyObject *}
2337
2338\end{cfuncdesc}
2339
2340\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **, int}
2341
2342\end{cfuncdesc}
2343
2344\begin{cfuncdesc}{PyObject *}{PyString_Format}{PyObject *, PyObject *}
2345
2346\end{cfuncdesc}
2347
2348\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **}
2349
2350\end{cfuncdesc}
2351
2352\begin{cfuncdesc}{PyObject *}{PyString_InternFromString}{const char *}
2353
2354\end{cfuncdesc}
2355
2356\begin{cfuncdesc}{char *}{PyString_AS_STRING}{PyStringObject *}
2357
2358\end{cfuncdesc}
2359
2360\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyStringObject *}
2361
2362\end{cfuncdesc}
2363
2364
2365\subsection{Tuple Objects}
2366
2367\begin{ctypedesc}{PyTupleObject}
2368This subtype of \code{PyObject} represents a Python tuple object.
2369\end{ctypedesc}
2370
2371\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
2372This instance of \code{PyTypeObject} represents the Python tuple type.
2373\end{cvardesc}
2374
2375\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
2376Return true if the argument is a tuple object.
2377\end{cfuncdesc}
2378
2379\begin{cfuncdesc}{PyTupleObject *}{PyTuple_New}{int s}
2380Return a new tuple object of size \code{s}
2381\end{cfuncdesc}
2382
2383\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
2384akes a pointer to a tuple object, and returns the size
2385of that tuple.
2386\end{cfuncdesc}
2387
2388\begin{cfuncdesc}{PyObject *}{PyTuple_GetItem}{PyTupleObject *p, int pos}
2389returns the object at position \code{pos} in the tuple pointed
2390to by \code{p}.
2391\end{cfuncdesc}
2392
2393\begin{cfuncdesc}{PyObject *}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
2394does the same, but does no checking of it's
2395arguments.
2396\end{cfuncdesc}
2397
2398\begin{cfuncdesc}{PyTupleObject *}{PyTuple_GetSlice}{PyTupleObject *p,
2399 int low,
2400 int high}
2401takes a slice of the tuple pointed to by \code{p} from
2402\code{low} to \code{high} and returns it as a new tuple.
2403\end{cfuncdesc}
2404
2405\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyTupleObject *p,
2406 int pos,
2407 PyObject *o}
2408inserts a reference to object \code{o} at position \code{pos} of
2409the tuple pointed to by \code{p}. It returns 0 on success.
2410\end{cfuncdesc}
2411
2412\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyTupleObject *p,
2413 int pos,
2414 PyObject *o}
2415
2416does the same, but does no error checking, and
2417should \emph{only} be used to fill in brand new tuples.
2418\end{cfuncdesc}
2419
2420\begin{cfuncdesc}{PyTupleObject *}{_PyTuple_Resize}{PyTupleObject *p,
2421 int new,
2422 int last_is_sticky}
2423can be used to resize a tuple. Because tuples are
2424\emph{supposed} to be immutable, this should only be used if there is only
2425one module referencing the object. Do \emph{not} use this if the tuple may
2426already be known to some other part of the code. \code{last_is_sticky} is
2427a flag - if set, the tuple will grow or shrink at the front, otherwise
2428it will grow or shrink at the end. Think of this as destroying the old
2429tuple and creating a new one, only more efficiently.
2430\end{cfuncdesc}
2431
2432
2433\subsection{List Objects}
2434
2435\begin{ctypedesc}{PyListObject}
2436This subtype of \code{PyObject} represents a Python list object.
2437\end{ctypedesc}
2438
2439\begin{cvardesc}{PyTypeObject}{PyList_Type}
2440This instance of \code{PyTypeObject} represents the Python list type.
2441\end{cvardesc}
2442
2443\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
2444returns true if it's argument is a \code{PyListObject}
2445\end{cfuncdesc}
2446
2447\begin{cfuncdesc}{PyObject *}{PyList_New}{int size}
2448
2449\end{cfuncdesc}
2450
2451\begin{cfuncdesc}{int}{PyList_Size}{PyObject *}
2452
2453\end{cfuncdesc}
2454
2455\begin{cfuncdesc}{PyObject *}{PyList_GetItem}{PyObject *, int}
2456
2457\end{cfuncdesc}
2458
2459\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *, int, PyObject *}
2460
2461\end{cfuncdesc}
2462
2463\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *, int, PyObject *}
2464
2465\end{cfuncdesc}
2466
2467\begin{cfuncdesc}{int}{PyList_Append}{PyObject *, PyObject *}
2468
2469\end{cfuncdesc}
2470
2471\begin{cfuncdesc}{PyObject *}{PyList_GetSlice}{PyObject *, int, int}
2472
2473\end{cfuncdesc}
2474
2475\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *, int, int, PyObject *}
2476
2477\end{cfuncdesc}
2478
2479\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *}
2480
2481\end{cfuncdesc}
2482
2483\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *}
2484
2485\end{cfuncdesc}
2486
2487\begin{cfuncdesc}{PyObject *}{PyList_AsTuple}{PyObject *}
2488
2489\end{cfuncdesc}
2490
2491\begin{cfuncdesc}{PyObject *}{PyList_GET_ITEM}{PyObject *list, int i}
2492
2493\end{cfuncdesc}
2494
2495\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
2496
2497\end{cfuncdesc}
2498
2499
2500\section{Mapping Objects}
2501
2502\subsection{Dictionary Objects}
2503
2504\begin{ctypedesc}{PyDictObject}
2505This subtype of \code{PyObject} represents a Python dictionary object.
2506\end{ctypedesc}
2507
2508\begin{cvardesc}{PyTypeObject}{PyDict_Type}
2509This instance of \code{PyTypeObject} represents the Python dictionary type.
2510\end{cvardesc}
2511
2512\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
2513returns true if it's argument is a PyDictObject
2514\end{cfuncdesc}
2515
2516\begin{cfuncdesc}{PyDictObject *}{PyDict_New}{}
2517returns a new empty dictionary.
2518\end{cfuncdesc}
2519
2520\begin{cfuncdesc}{void}{PyDict_Clear}{PyDictObject *p}
2521empties an existing dictionary and deletes it.
2522\end{cfuncdesc}
2523
2524\begin{cfuncdesc}{int}{PyDict_SetItem}{PyDictObject *p,
2525 PyObject *key,
2526 PyObject *val}
2527inserts \code{value} into the dictionary with a key of
2528\code{key}. Both \code{key} and \code{value} should be PyObjects, and \code{key} should
2529be hashable.
2530\end{cfuncdesc}
2531
2532\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
2533 char *key,
2534 PyObject *val}
2535inserts \code{value} into the dictionary using \code{key}
2536as a key. \code{key} should be a char *
2537\end{cfuncdesc}
2538
2539\begin{cfuncdesc}{int}{PyDict_DelItem}{PyDictObject *p, PyObject *key}
2540removes the entry in dictionary \code{p} with key \code{key}.
2541\code{key} is a PyObject.
2542\end{cfuncdesc}
2543
2544\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyDictObject *p, char *key}
2545removes the entry in dictionary \code{p} which has a key
2546specified by the \code{char *}\code{key}.
2547\end{cfuncdesc}
2548
2549\begin{cfuncdesc}{PyObject *}{PyDict_GetItem}{PyDictObject *p, PyObject *key}
2550returns the object from dictionary \code{p} which has a key
2551\code{key}.
2552\end{cfuncdesc}
2553
2554\begin{cfuncdesc}{PyObject *}{PyDict_GetItemString}{PyDictObject *p, char *key}
2555does the same, but \code{key} is specified as a
2556\code{char *}, rather than a \code{PyObject *}.
2557\end{cfuncdesc}
2558
2559\begin{cfuncdesc}{PyListObject *}{PyDict_Items}{PyDictObject *p}
2560returns a PyListObject containing all the items
2561from the dictionary, as in the mapping method \code{items()} (see the Reference
2562Guide)
2563\end{cfuncdesc}
2564
2565\begin{cfuncdesc}{PyListObject *}{PyDict_Keys}{PyDictObject *p}
2566returns a PyListObject containing all the keys
2567from the dictionary, as in the mapping method \code{keys()} (see the Reference Guide)
2568\end{cfuncdesc}
2569
2570\begin{cfuncdesc}{PyListObject *}{PyDict_Values}{PyDictObject *p}
2571returns a PyListObject containing all the values
2572from the dictionary, as in the mapping method \code{values()} (see the Reference Guide)
2573\end{cfuncdesc}
2574
2575\begin{cfuncdesc}{int}{PyDict_Size}{PyDictObject *p}
2576returns the number of items in the dictionary.
2577\end{cfuncdesc}
2578
2579\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p,
2580 int ppos,
2581 PyObject **pkey,
2582 PyObject **pvalue}
2583
2584\end{cfuncdesc}
2585
2586
2587\section{Numeric Objects}
2588
2589\subsection{Plain Integer Objects}
2590
2591\begin{ctypedesc}{PyIntObject}
2592This subtype of \code{PyObject} represents a Python integer object.
2593\end{ctypedesc}
2594
2595\begin{cvardesc}{PyTypeObject}{PyInt_Type}
2596This instance of \code{PyTypeObject} represents the Python plain
2597integer type.
2598\end{cvardesc}
2599
2600\begin{cfuncdesc}{int}{PyInt_Check}{PyObject *}
2601
2602\end{cfuncdesc}
2603
2604\begin{cfuncdesc}{PyIntObject *}{PyInt_FromLong}{long ival}
2605creates a new integer object with a value of \code{ival}.
2606
2607The current implementation keeps an array of integer objects for all
2608integers between -1 and 100, when you create an int in that range you
2609actually just get back a reference to the existing object. So it should
2610be possible to change the value of 1. I suspect the behaviour of python
2611in this case is undefined. :-)
2612\end{cfuncdesc}
2613
2614\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyIntObject *io}
2615returns the value of the object \code{io}.
2616\end{cfuncdesc}
2617
2618\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
2619will first attempt to cast the object to a PyIntObject, if
2620it is not already one, and the return it's value.
2621\end{cfuncdesc}
2622
2623\begin{cfuncdesc}{long}{PyInt_GetMax}{}
2624returns the systems idea of the largest int it can handle
2625(LONG_MAX, as defined in the system header files)
2626\end{cfuncdesc}
2627
2628
2629\subsection{Long Integer Objects}
2630
2631\begin{ctypedesc}{PyLongObject}
2632This subtype of \code{PyObject} represents a Python long integer object.
2633\end{ctypedesc}
2634
2635\begin{cvardesc}{PyTypeObject}{PyLong_Type}
2636This instance of \code{PyTypeObject} represents the Python long integer type.
2637\end{cvardesc}
2638
2639\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
2640returns true if it's argument is a \code{PyLongObject}
2641\end{cfuncdesc}
2642
2643\begin{cfuncdesc}{PyObject *}{PyLong_FromLong}{long}
2644
2645\end{cfuncdesc}
2646
2647\begin{cfuncdesc}{PyObject *}{PyLong_FromUnsignedLong}{unsigned long}
2648
2649\end{cfuncdesc}
2650
2651\begin{cfuncdesc}{PyObject *}{PyLong_FromDouble}{double}
2652
2653\end{cfuncdesc}
2654
2655\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *}
2656
2657\end{cfuncdesc}
2658
2659\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject }
2660
2661\end{cfuncdesc}
2662
2663\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *}
2664
2665\end{cfuncdesc}
2666
2667\begin{cfuncdesc}{PyObject *}{*PyLong_FromString}{char *, char **, int}
2668
2669\end{cfuncdesc}
2670
2671
2672\subsection{Floating Point Objects}
2673
2674\begin{ctypedesc}{PyFloatObject}
2675This subtype of \code{PyObject} represents a Python floating point object.
2676\end{ctypedesc}
2677
2678\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2679This instance of \code{PyTypeObject} represents the Python floating
2680point type.
2681\end{cvardesc}
2682
2683\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2684returns true if it's argument is a \code{PyFloatObject}
2685\end{cfuncdesc}
2686
2687\begin{cfuncdesc}{PyObject *}{PyFloat_FromDouble}{double}
2688
2689\end{cfuncdesc}
2690
2691\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *}
2692
2693\end{cfuncdesc}
2694
2695\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyFloatObject *}
2696
2697\end{cfuncdesc}
2698
2699
2700\subsection{Complex Number Objects}
2701
2702\begin{ctypedesc}{Py_complex}
2703typedef struct {
2704 double real;
2705 double imag;
2706}
2707\end{ctypedesc}
2708
2709\begin{ctypedesc}{PyComplexObject}
2710This subtype of \code{PyObject} represents a Python complex number object.
2711\end{ctypedesc}
2712
2713\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2714This instance of \code{PyTypeObject} represents the Python complex
2715number type.
2716\end{cvardesc}
2717
2718\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2719returns true if it's argument is a \code{PyComplexObject}
2720\end{cfuncdesc}
2721
2722\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex, Py_complex}
2723
2724\end{cfuncdesc}
2725
2726\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex, Py_complex}
2727
2728\end{cfuncdesc}
2729
2730\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex}
2731
2732\end{cfuncdesc}
2733
2734\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex, Py_complex}
2735
2736\end{cfuncdesc}
2737
2738\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex, Py_complex}
2739
2740\end{cfuncdesc}
2741
2742\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex, Py_complex}
2743
2744\end{cfuncdesc}
2745
2746\begin{cfuncdesc}{PyObject *}{PyComplex_FromCComplex}{Py_complex}
2747
2748\end{cfuncdesc}
2749
2750\begin{cfuncdesc}{PyObject *}{PyComplex_FromDoubles}{double real, double imag}
2751
2752\end{cfuncdesc}
2753
2754\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2755
2756\end{cfuncdesc}
2757
2758\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2759
2760\end{cfuncdesc}
2761
2762\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2763
2764\end{cfuncdesc}
2765
2766
2767
2768\section{Other Objects}
2769
2770\subsection{File Objects}
2771
2772\begin{ctypedesc}{PyFileObject}
2773This subtype of \code{PyObject} represents a Python file object.
2774\end{ctypedesc}
2775
2776\begin{cvardesc}{PyTypeObject}{PyFile_Type}
2777This instance of \code{PyTypeObject} represents the Python file type.
2778\end{cvardesc}
2779
2780\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2781returns true if it's argument is a \code{PyFileObject}
2782\end{cfuncdesc}
2783
2784\begin{cfuncdesc}{PyObject *}{PyFile_FromString}{char *name, char *mode}
2785creates a new PyFileObject pointing to the file
2786specified in \code{name} with the mode specified in \code{mode}
2787\end{cfuncdesc}
2788
2789\begin{cfuncdesc}{PyObject *}{PyFile_FromFile}{FILE *fp,
2790 char *name, char *mode, int (*close})
2791creates a new PyFileObject from the already-open \code{fp}.
2792The function \code{close} will be called when the file should be closed.
2793\end{cfuncdesc}
2794
2795\begin{cfuncdesc}{FILE *}{PyFile_AsFile}{PyFileObject *p}
2796returns the file object associated with \code{p} as a \code{FILE *}
2797\end{cfuncdesc}
2798
2799\begin{cfuncdesc}{PyStringObject *}{PyFile_GetLine}{PyObject *p, int n}
2800undocumented as yet
2801\end{cfuncdesc}
2802
2803\begin{cfuncdesc}{PyStringObject *}{PyFile_Name}{PyObject *p}
2804returns the name of the file specified by \code{p} as a
2805PyStringObject
2806\end{cfuncdesc}
2807
2808\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2809on systems with \code{setvbuf} only
2810\end{cfuncdesc}
2811
2812\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyFileObject *p, int newflag}
2813same as the file object method \code{softspace}
2814\end{cfuncdesc}
2815
2816\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p}
2817writes object \code{obj} to file object \code{p}
2818\end{cfuncdesc}
2819
2820\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p}
2821writes string \code{s} to file object \code{p}
2822\end{cfuncdesc}
2823
2824
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002825\input{api.ind} % Index -- must be last
2826
2827\end{document}