blob: c030ef83c7725403fd63800887fb157281892f79 [file] [log] [blame]
Fred Drakedca87921998-01-13 16:53:23 +00001\documentclass[twoside,openright]{report}
Fred Drake1f8449a1998-01-09 05:36:43 +00002\usepackage{myformat}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00003
Guido van Rossum9faf4c51997-10-07 14:38:54 +00004\title{Python/C API Reference Manual}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00005
6\input{boilerplate}
7
8\makeindex % tell \index to actually write the .idx file
9
10
11\begin{document}
12
Fred Drake1f8449a1998-01-09 05:36:43 +000013\pagestyle{empty}
Guido van Rossum9231c8f1997-05-15 21:43:21 +000014\pagenumbering{roman}
15
16\maketitle
17
18\input{copyright}
19
20\begin{abstract}
21
22\noindent
Fred Drakeb0a78731998-01-13 18:51:10 +000023This manual documents the API used by \C{} (or \Cpp{}) programmers who want
Guido van Rossum9231c8f1997-05-15 21:43:21 +000024to write extension modules or embed Python. It is a companion to
25``Extending and Embedding the Python Interpreter'', which describes
26the general principles of extension writing but does not document the
27API functions in detail.
28
Guido van Rossum5b8a5231997-12-30 04:38:44 +000029\strong{Warning:} The current version of this document is incomplete.
30I hope that it is nevertheless useful. I will continue to work on it,
31and release new versions from time to time, independent from Python
32source code releases.
33
Guido van Rossum9231c8f1997-05-15 21:43:21 +000034\end{abstract}
35
Fred Drake4d4f9e71998-01-13 22:25:02 +000036\tableofcontents
Guido van Rossum9231c8f1997-05-15 21:43:21 +000037
38\pagenumbering{arabic}
39
Guido van Rossum5060b3b1997-08-17 18:02:23 +000040% XXX Consider moving all this back to ext.tex and giving api.tex
41% XXX a *really* short intro only.
Guido van Rossum9231c8f1997-05-15 21:43:21 +000042
43\chapter{Introduction}
44
Fred Drakeb0a78731998-01-13 18:51:10 +000045The Application Programmer's Interface to Python gives \C{} and \Cpp{}
Guido van Rossum59a61351997-08-14 20:34:33 +000046programmers access to the Python interpreter at a variety of levels.
Fred Drakeb0a78731998-01-13 18:51:10 +000047The API is equally usable from \Cpp{}, 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
Guido van Rossum580aa8d1997-11-25 15:34:51 +000051that 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
Fred Drakeb0a78731998-01-13 18:51:10 +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
Fred Drakeb0a78731998-01-13 18:51:10 +0000118place 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
Guido van Rossum4a944d71997-08-14 20:35:38 +0000120becomes 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
Fred Drakeb0a78731998-01-13 18:51:10 +0000153that are passed as arguments to \C{} functions in an extension module
Guido van Rossum4a944d71997-08-14 20:35:38 +0000154that are called from Python; the call mechanism guarantees to hold a
Guido van Rossum59a61351997-08-14 20:34:33 +0000155reference to every argument for the duration of the call.
156
Guido van Rossum4a944d71997-08-14 20:35:38 +0000157However, a common pitfall is to extract an object from a list and
158holding on to it for a while without incrementing its reference count.
159Some other operation might conceivably remove the object from the
160list, decrementing its reference count and possible deallocating it.
161The real danger is that innocent-looking operations may invoke
162arbitrary Python code which could do this; there is a code path which
163allows control to flow back to the user from a \code{Py_DECREF()}, so
Guido van Rossum59a61351997-08-14 20:34:33 +0000164almost any operation is potentially dangerous.
165
Guido van Rossum4a944d71997-08-14 20:35:38 +0000166A safe approach is to always use the generic operations (functions
167whose name begins with \code{PyObject_}, \code{PyNumber_},
168\code{PySequence_} or \code{PyMapping_}). These operations always
169increment the reference count of the object they return. This leaves
170the caller with the responsibility to call \code{Py_DECREF()} when
Guido van Rossum59a61351997-08-14 20:34:33 +0000171they are done with the result; this soon becomes second nature.
172
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000173\subsubsection{Reference Count Details}
174
175The reference count behavior of functions in the Python/C API is best
176expelained in terms of \emph{ownership of references}. Note that we
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000177talk of owning references, never of owning objects; objects are always
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000178shared! When a function owns a reference, it has to dispose of it
179properly -- either by passing ownership on (usually to its caller) or
180by calling \code{Py_DECREF()} or \code{Py_XDECREF()}. When a function
181passes ownership of a reference on to its caller, the caller is said
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000182to receive a \emph{new} reference. When no ownership is transferred,
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000183the caller is said to \emph{borrow} the reference. Nothing needs to
184be done for a borrowed reference.
185
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000186Conversely, when calling a function passes it a reference to an
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000187object, there are two possibilities: the function \emph{steals} a
188reference to the object, or it does not. Few functions steal
189references; the two notable exceptions are \code{PyList_SetItem()} and
190\code{PyTuple_SetItem()}, which steal a reference to the item (but not to
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000191the tuple or list into which the item it put!). These functions were
192designed to steal a reference because of a common idiom for populating
193a tuple or list with newly created objects; for example, the code to
194create the tuple \code{(1, 2, "three")} could look like this
195(forgetting about error handling for the moment; a better way to code
196this is shown below anyway):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000197
198\begin{verbatim}
199PyObject *t;
200t = PyTuple_New(3);
201PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
202PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
203PyTuple_SetItem(t, 2, PyString_FromString("three"));
204\end{verbatim}
205
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000206Incidentally, \code{PyTuple_SetItem()} is the \emph{only} way to set
207tuple items; \code{PySequence_SetItem()} and \code{PyObject_SetItem()}
208refuse to do this since tuples are an immutable data type. You should
209only use \code{PyTuple_SetItem()} for tuples that you are creating
210yourself.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000211
212Equivalent code for populating a list can be written using
213\code{PyList_New()} and \code{PyList_SetItem()}. Such code can also
214use \code{PySequence_SetItem()}; this illustrates the difference
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000215between the two (the extra \code{Py_DECREF()} calls):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000216
217\begin{verbatim}
218PyObject *l, *x;
219l = PyList_New(3);
220x = PyInt_FromLong(1L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000221PySequence_SetItem(l, 0, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000222x = PyInt_FromLong(2L);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000223PySequence_SetItem(l, 1, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000224x = PyString_FromString("three");
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000225PySequence_SetItem(l, 2, x); Py_DECREF(x);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000226\end{verbatim}
227
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000228You might find it strange that the ``recommended'' approach takes more
229code. However, in practice, you will rarely use these ways of
230creating and populating a tuple or list. There's a generic function,
Fred Drakeb0a78731998-01-13 18:51:10 +0000231\code{Py_BuildValue()}, that can create most common objects from \C{}
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000232values, directed by a ``format string''. For example, the above two
233blocks of code could be replaced by the following (which also takes
234care of the error checking!):
235
236\begin{verbatim}
237PyObject *t, *l;
238t = Py_BuildValue("(iis)", 1, 2, "three");
239l = Py_BuildValue("[iis]", 1, 2, "three");
240\end{verbatim}
241
242It is much more common to use \code{PyObject_SetItem()} and friends
243with items whose references you are only borrowing, like arguments
244that were passed in to the function you are writing. In that case,
245their behaviour regarding reference counts is much saner, since you
246don't have to increment a reference count so you can give a reference
247away (``have it be stolen''). For example, this function sets all
248items of a list (actually, any mutable sequence) to a given item:
249
250\begin{verbatim}
251int set_all(PyObject *target, PyObject *item)
252{
253 int i, n;
254 n = PyObject_Length(target);
255 if (n < 0)
256 return -1;
257 for (i = 0; i < n; i++) {
258 if (PyObject_SetItem(target, i, item) < 0)
259 return -1;
260 }
261 return 0;
262}
263\end{verbatim}
264
265The situation is slightly different for function return values.
266While passing a reference to most functions does not change your
267ownership responsibilities for that reference, many functions that
268return a referece to an object give you ownership of the reference.
269The reason is simple: in many cases, the returned object is created
270on the fly, and the reference you get is the only reference to the
271object! Therefore, the generic functions that return object
272references, like \code{PyObject_GetItem()} and
273\code{PySequence_GetItem()}, always return a new reference (i.e., the
274caller becomes the owner of the reference).
275
276It is important to realize that whether you own a reference returned
277by a function depends on which function you call only -- \emph{the
278plumage} (i.e., the type of the type of the object passed as an
279argument to the function) \emph{don't enter into it!} Thus, if you
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000280extract an item from a list using \code{PyList_GetItem()}, you don't
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000281own the reference -- but if you obtain the same item from the same
282list using \code{PySequence_GetItem()} (which happens to take exactly
283the same arguments), you do own a reference to the returned object.
284
285Here is an example of how you could write a function that computes the
286sum of the items in a list of integers; once using
287\code{PyList_GetItem()}, once using \code{PySequence_GetItem()}.
288
289\begin{verbatim}
290long sum_list(PyObject *list)
291{
292 int i, n;
293 long total = 0;
294 PyObject *item;
295 n = PyList_Size(list);
296 if (n < 0)
297 return -1; /* Not a list */
298 for (i = 0; i < n; i++) {
299 item = PyList_GetItem(list, i); /* Can't fail */
300 if (!PyInt_Check(item)) continue; /* Skip non-integers */
301 total += PyInt_AsLong(item);
302 }
303 return total;
304}
305\end{verbatim}
306
307\begin{verbatim}
308long sum_sequence(PyObject *sequence)
309{
310 int i, n;
311 long total = 0;
312 PyObject *item;
313 n = PyObject_Size(list);
314 if (n < 0)
315 return -1; /* Has no length */
316 for (i = 0; i < n; i++) {
317 item = PySequence_GetItem(list, i);
318 if (item == NULL)
319 return -1; /* Not a sequence, or other failure */
320 if (PyInt_Check(item))
321 total += PyInt_AsLong(item);
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000322 Py_DECREF(item); /* Discard reference ownership */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000323 }
324 return total;
325}
326\end{verbatim}
327
328\subsection{Types}
329
330There are few other data types that play a significant role in
Fred Drakeb0a78731998-01-13 18:51:10 +0000331the Python/C API; most are simple \C{} types such as \code{int},
Guido van Rossum4a944d71997-08-14 20:35:38 +0000332\code{long}, \code{double} and \code{char *}. A few structure types
333are used to describe static tables used to list the functions exported
334by a module or the data attributes of a new object type. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000335be discussed together with the functions that use them.
336
337\section{Exceptions}
338
Guido van Rossum4a944d71997-08-14 20:35:38 +0000339The Python programmer only needs to deal with exceptions if specific
340error handling is required; unhandled exceptions are automatically
341propagated to the caller, then to the caller's caller, and so on, till
342they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000343user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000344
Fred Drakeb0a78731998-01-13 18:51:10 +0000345For \C{} programmers, however, error checking always has to be explicit.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000346All functions in the Python/C API can raise exceptions, unless an
347explicit claim is made otherwise in a function's documentation. In
348general, when a function encounters an error, it sets an exception,
349discards any object references that it owns, and returns an
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000350error indicator -- usually \NULL{} or \code{-1}. A few functions
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000351return a Boolean true/false result, with false indicating an error.
352Very few functions return no explicit error indicator or have an
353ambiguous return value, and require explicit testing for errors with
354\code{PyErr_Occurred()}.
355
356Exception state is maintained in per-thread storage (this is
357equivalent to using global storage in an unthreaded application). A
358thread can be on one of two states: an exception has occurred, or not.
359The function \code{PyErr_Occurred()} can be used to check for this: it
360returns a borrowed reference to the exception type object when an
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000361exception has occurred, and \NULL{} otherwise. There are a number
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000362of functions to set the exception state: \code{PyErr_SetString()} is
363the most common (though not the most general) function to set the
364exception state, and \code{PyErr_Clear()} clears the exception state.
365
366The full exception state consists of three objects (all of which can
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000367be \NULL{} ): the exception type, the corresponding exception
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000368value, and the traceback. These have the same meanings as the Python
369object \code{sys.exc_type}, \code{sys.exc_value},
370\code{sys.exc_traceback}; however, they are not the same: the Python
371objects represent the last exception being handled by a Python
Fred Drakeb0a78731998-01-13 18:51:10 +0000372\code{try...except} statement, while the \C{} level exception state only
373exists while an exception is being passed on between \C{} functions until
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000374it reaches the Python interpreter, which takes care of transferring it
375to \code{sys.exc_type} and friends.
376
377(Note that starting with Python 1.5, the preferred, thread-safe way to
378access the exception state from Python code is to call the function
379\code{sys.exc_info()}, which returns the per-thread exception state
380for Python code. Also, the semantics of both ways to access the
381exception state have changed so that a function which catches an
382exception will save and restore its thread's exception state so as to
383preserve the exception state of its caller. This prevents common bugs
384in exception handling code caused by an innocent-looking function
385overwriting the exception being handled; it also reduces the often
386unwanted lifetime extension for objects that are referenced by the
387stack frames in the traceback.)
388
389As a general principle, a function that calls another function to
390perform some task should check whether the called function raised an
391exception, and if so, pass the exception state on to its caller. It
392should discards any object references that it owns, and returns an
393error indicator, but it should \emph{not} set another exception --
394that would overwrite the exception that was just raised, and lose
395important reason about the exact cause of the error.
396
397A simple example of detecting exceptions and passing them on is shown
398in the \code{sum_sequence()} example above. It so happens that that
399example doesn't need to clean up any owned references when it detects
400an error. The following example function shows some error cleanup.
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000401First, to remind you why you like Python, we show the equivalent
402Python code:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000403
404\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000405def incr_item(dict, key):
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000406 try:
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000407 item = dict[key]
408 except KeyError:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000409 item = 0
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000410 return item + 1
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000411\end{verbatim}
412
Fred Drakeb0a78731998-01-13 18:51:10 +0000413Here is the corresponding \C{} code, in all its glory:
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000414
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000415\begin{verbatim}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000416int incr_item(PyObject *dict, PyObject *key)
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000417{
418 /* Objects all initialized to NULL for Py_XDECREF */
419 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000420 int rv = -1; /* Return value initialized to -1 (failure) */
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000421
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000422 item = PyObject_GetItem(dict, key);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000423 if (item == NULL) {
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000424 /* Handle keyError only: */
425 if (!PyErr_ExceptionMatches(PyExc_keyError)) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000426
427 /* Clear the error and use zero: */
428 PyErr_Clear();
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000429 item = PyInt_FromLong(0L);
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000430 if (item == NULL) goto error;
431 }
432
433 const_one = PyInt_FromLong(1L);
434 if (const_one == NULL) goto error;
435
436 incremented_item = PyNumber_Add(item, const_one);
437 if (incremented_item == NULL) goto error;
438
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000439 if (PyObject_SetItem(dict, key, incremented_item) < 0) goto error;
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000440 rv = 0; /* Success */
441 /* Continue with cleanup code */
442
443 error:
444 /* Cleanup code, shared by success and failure path */
445
446 /* Use Py_XDECREF() to ignore NULL references */
447 Py_XDECREF(item);
448 Py_XDECREF(const_one);
449 Py_XDECREF(incremented_item);
450
451 return rv; /* -1 for error, 0 for success */
452}
453\end{verbatim}
454
455This example represents an endorsed use of the \code{goto} statement
Fred Drakeb0a78731998-01-13 18:51:10 +0000456in \C{}! It illustrates the use of \code{PyErr_ExceptionMatches()} and
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000457\code{PyErr_Clear()} to handle specific exceptions, and the use of
458\code{Py_XDECREF()} to dispose of owned references that may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000459\NULL{} (note the `X' in the name; \code{Py_DECREF()} would crash
460when confronted with a \NULL{} reference). It is important that
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000461the variables used to hold owned references are initialized to
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000462\NULL{} for this to work; likewise, the proposed return value is
463initialized to \code{-1} (failure) and only set to success after
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000464the final call made is successful.
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000465
Guido van Rossum59a61351997-08-14 20:34:33 +0000466
467\section{Embedding Python}
468
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000469The one important task that only embedders (as opposed to extension
470writers) of the Python interpreter have to worry about is the
471initialization, and possibly the finalization, of the Python
472interpreter. Most functionality of the interpreter can only be used
473after the interpreter has been initialized.
Guido van Rossum59a61351997-08-14 20:34:33 +0000474
Guido van Rossum4a944d71997-08-14 20:35:38 +0000475The basic initialization function is \code{Py_Initialize()}. This
476initializes the table of loaded modules, and creates the fundamental
477modules \code{__builtin__}, \code{__main__} and \code{sys}. It also
Guido van Rossum59a61351997-08-14 20:34:33 +0000478initializes the module search path (\code{sys.path}).
479
Guido van Rossum4a944d71997-08-14 20:35:38 +0000480\code{Py_Initialize()} does not set the ``script argument list''
481(\code{sys.argv}). If this variable is needed by Python code that
482will be executed later, it must be set explicitly with a call to
483\code{PySys_SetArgv(\var{argc}, \var{argv})} subsequent to the call
Guido van Rossum59a61351997-08-14 20:34:33 +0000484to \code{Py_Initialize()}.
485
Fred Drakeb0a78731998-01-13 18:51:10 +0000486On most systems (in particular, on \UNIX{} and Windows, although the
Guido van Rossum42cefd01997-10-05 15:27:29 +0000487details are slightly different), \code{Py_Initialize()} calculates the
488module search path based upon its best guess for the location of the
489standard Python interpreter executable, assuming that the Python
490library is found in a fixed location relative to the Python
491interpreter executable. In particular, it looks for a directory named
492\code{lib/python1.5} (replacing \code{1.5} with the current
493interpreter version) relative to the parent directory where the
494executable named \code{python} is found on the shell command search
495path (the environment variable \code{\$PATH}).
496
497For instance, if the Python executable is found in
498\code{/usr/local/bin/python}, it will assume that the libraries are in
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000499\code{/usr/local/lib/python1.5}. (In fact, this particular path is
500also the ``fallback'' location, used when no executable file named
501\code{python} is found along \code{\$PATH}.) The user can override
502this behavior by setting the environment variable \code{\$PYTHONHOME},
503or insert additional directories in front of the standard path by
504setting \code{\$PYTHONPATH}.
Guido van Rossum59a61351997-08-14 20:34:33 +0000505
Guido van Rossum4a944d71997-08-14 20:35:38 +0000506The embedding application can steer the search by calling
507\code{Py_SetProgramName(\var{file})} \emph{before} calling
Guido van Rossum09270b51997-08-15 18:57:32 +0000508\code{Py_Initialize()}. Note that \code{\$PYTHONHOME} still overrides
Guido van Rossum4a944d71997-08-14 20:35:38 +0000509this and \code{\$PYTHONPATH} is still inserted in front of the
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000510standard path. An application that requires total control has to
511provide its own implementation of \code{Py_GetPath()},
512\code{Py_GetPrefix()}, \code{Py_GetExecPrefix()},
513\code{Py_GetProgramFullPath()} (all defined in
514\file{Modules/getpath.c}).
Guido van Rossum59a61351997-08-14 20:34:33 +0000515
Guido van Rossum4a944d71997-08-14 20:35:38 +0000516Sometimes, it is desirable to ``uninitialize'' Python. For instance,
517the application may want to start over (make another call to
518\code{Py_Initialize()}) or the application is simply done with its
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000519use of Python and wants to free all memory allocated by Python. This
520can be accomplished by calling \code{Py_Finalize()}. The function
521\code{Py_IsInitialized()} returns true iff Python is currently in the
522initialized state. More information about these functions is given in
523a later chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000524
Guido van Rossum4a944d71997-08-14 20:35:38 +0000525
Fred Drakee5bf8b21998-02-12 21:22:28 +0000526\chapter{The Very High Level Layer}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000527
Fred Drakee5bf8b21998-02-12 21:22:28 +0000528The functions in this chapter will let you execute Python source code
529given in a file or a buffer, but they will not let you interact in a
530more detailed way with the interpreter.
Guido van Rossum4a944d71997-08-14 20:35:38 +0000531
Fred Drakee5bf8b21998-02-12 21:22:28 +0000532\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *, char *}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000533\end{cfuncdesc}
534
Fred Drakee5bf8b21998-02-12 21:22:28 +0000535\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000536\end{cfuncdesc}
537
Fred Drakee5bf8b21998-02-12 21:22:28 +0000538\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *, char *}
539\end{cfuncdesc}
540
541\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *, char *}
542\end{cfuncdesc}
543
544\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *, char *}
545\end{cfuncdesc}
546
547\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseString}{char *, int}
548\end{cfuncdesc}
549
550\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseFile}{FILE *, char *, int}
551\end{cfuncdesc}
552
553\begin{cfuncdesc}{PyObject *}{PyRun_String}{char *, int, PyObject *, PyObject *}
554\end{cfuncdesc}
555
556\begin{cfuncdesc}{PyObject *}{PyRun_File}{FILE *, char *, int, PyObject *, PyObject *}
557\end{cfuncdesc}
558
559\begin{cfuncdesc}{PyObject *}{Py_CompileString}{char *, char *, int}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000560\end{cfuncdesc}
561
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000562
563\chapter{Reference Counting}
564
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000565The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000566of Python objects.
567
568\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
569Increment the reference count for object \code{o}. The object must
570not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
571\code{Py_XINCREF()}.
572\end{cfuncdesc}
573
574\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
575Increment the reference count for object \code{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000576\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000577\end{cfuncdesc}
578
579\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
580Decrement the reference count for object \code{o}. The object must
581not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
582\code{Py_XDECREF()}. If the reference count reaches zero, the object's
583type's deallocation function (which must not be \NULL{}) is invoked.
584
585\strong{Warning:} The deallocation function can cause arbitrary Python
586code to be invoked (e.g. when a class instance with a \code{__del__()}
587method is deallocated). While exceptions in such code are not
588propagated, the executed code has free access to all Python global
589variables. This means that any object that is reachable from a global
590variable should be in a consistent state before \code{Py_DECREF()} is
591invoked. For example, code to delete an object from a list should
592copy a reference to the deleted object in a temporary variable, update
593the list data structure, and then call \code{Py_DECREF()} for the
594temporary variable.
595\end{cfuncdesc}
596
597\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
598Decrement the reference count for object \code{o}.The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000599\NULL{}, in which case the macro has no effect; otherwise the
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000600effect is the same as for \code{Py_DECREF()}, and the same warning
601applies.
602\end{cfuncdesc}
603
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000604The following functions or macros are only for internal use:
Guido van Rossumae110af1997-05-22 20:11:52 +0000605\code{_Py_Dealloc}, \code{_Py_ForgetReference}, \code{_Py_NewReference},
606as well as the global variable \code{_Py_RefTotal}.
607
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000608XXX Should mention Py_Malloc(), Py_Realloc(), Py_Free(),
609PyMem_Malloc(), PyMem_Realloc(), PyMem_Free(), PyMem_NEW(),
610PyMem_RESIZE(), PyMem_DEL(), PyMem_XDEL().
611
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000612
613\chapter{Exception Handling}
614
615The functions in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000616exceptions. It is important to understand some of the basics of
Fred Drakeb0a78731998-01-13 18:51:10 +0000617Python exception handling. It works somewhat like the \UNIX{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000618\code{errno} variable: there is a global indicator (per thread) of the
619last error that occurred. Most functions don't clear this on success,
620but will set it to indicate the cause of the error on failure. Most
621functions also return an error indicator, usually \NULL{} if they are
622supposed to return a pointer, or -1 if they return an integer
623(exception: the \code{PyArg_Parse*()} functions return 1 for success and
Guido van Rossum5b8a5231997-12-30 04:38:44 +00006240 for failure). When a function must fail because some function it
Guido van Rossumae110af1997-05-22 20:11:52 +0000625called failed, it generally doesn't set the error indicator; the
626function it called already set it.
627
628The error indicator consists of three Python objects corresponding to
629the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
630\code{sys.exc_traceback}. API functions exist to interact with the
631error indicator in various ways. There is a separate error indicator
632for each thread.
633
634% XXX Order of these should be more thoughtful.
635% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000636
637\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000638Print a standard traceback to \code{sys.stderr} and clear the error
639indicator. Call this function only when the error indicator is set.
640(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000641\end{cfuncdesc}
642
Guido van Rossumae110af1997-05-22 20:11:52 +0000643\begin{cfuncdesc}{PyObject *}{PyErr_Occurred}{}
644Test whether the error indicator is set. If set, return the exception
645\code{type} (the first argument to the last call to one of the
646\code{PyErr_Set*()} functions or to \code{PyErr_Restore()}). If not
647set, return \NULL{}. You do not own a reference to the return value,
Guido van Rossum42cefd01997-10-05 15:27:29 +0000648so you do not need to \code{Py_DECREF()} it. Note: do not compare the
649return value to a specific exception; use
650\code{PyErr_ExceptionMatches} instead, shown below.
651\end{cfuncdesc}
652
653\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000654\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000655Equivalent to
656\code{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
657This should only be called when an exception is actually set.
658\end{cfuncdesc}
659
660\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000661\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000662Return true if the \var{given} exception matches the exception in
663\var{exc}. If \var{exc} is a class object, this also returns true
664when \var{given} is a subclass. If \var{exc} is a tuple, all
665exceptions in the tuple (and recursively in subtuples) are searched
666for a match. This should only be called when an exception is actually
667set.
668\end{cfuncdesc}
669
670\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000671\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000672Under certain circumstances, the values returned by
673\code{PyErr_Fetch()} below can be ``unnormalized'', meaning that
674\var{*exc} is a class object but \var{*val} is not an instance of the
675same class. This function can be used to instantiate the class in
676that case. If the values are already normalized, nothing happens.
Guido van Rossumae110af1997-05-22 20:11:52 +0000677\end{cfuncdesc}
678
679\begin{cfuncdesc}{void}{PyErr_Clear}{}
680Clear the error indicator. If the error indicator is not set, there
681is no effect.
682\end{cfuncdesc}
683
684\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue, PyObject **ptraceback}
685Retrieve the error indicator into three variables whose addresses are
686passed. If the error indicator is not set, set all three variables to
687\NULL{}. If it is set, it will be cleared and you own a reference to
688each object retrieved. The value and traceback object may be \NULL{}
689even when the type object is not. \strong{Note:} this function is
690normally only used by code that needs to handle exceptions or by code
691that needs to save and restore the error indicator temporarily.
692\end{cfuncdesc}
693
694\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value, PyObject *traceback}
695Set the error indicator from the three objects. If the error
696indicator is already set, it is cleared first. If the objects are
697\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
698and non-\NULL{} value or traceback. The exception type should be a
699string or class; if it is a class, the value should be an instance of
700that class. Do not pass an invalid exception type or value.
701(Violating these rules will cause subtle problems later.) This call
702takes away a reference to each object, i.e. you must own a reference
703to each object before the call and after the call you no longer own
704these references. (If you don't understand this, don't use this
705function. I warned you.) \strong{Note:} this function is normally
706only used by code that needs to save and restore the error indicator
707temporarily.
708\end{cfuncdesc}
709
710\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
711This is the most common way to set the error indicator. The first
712argument specifies the exception type; it is normally one of the
713standard exceptions, e.g. \code{PyExc_RuntimeError}. You need not
714increment its reference count. The second argument is an error
715message; it is converted to a string object.
716\end{cfuncdesc}
717
718\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
719This function is similar to \code{PyErr_SetString()} but lets you
720specify an arbitrary Python object for the ``value'' of the exception.
721You need not increment its reference count.
722\end{cfuncdesc}
723
724\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
725This is a shorthand for \code{PyErr_SetString(\var{type}, Py_None}.
726\end{cfuncdesc}
727
728\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
729This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
730\var{message})}, where \var{message} indicates that a built-in operation
731was invoked with an illegal argument. It is mostly for internal use.
732\end{cfuncdesc}
733
734\begin{cfuncdesc}{PyObject *}{PyErr_NoMemory}{}
735This is a shorthand for \code{PyErr_SetNone(PyExc_MemoryError)}; it
736returns \NULL{} so an object allocation function can write
737\code{return PyErr_NoMemory();} when it runs out of memory.
738\end{cfuncdesc}
739
740\begin{cfuncdesc}{PyObject *}{PyErr_SetFromErrno}{PyObject *type}
Fred Drakeb0a78731998-01-13 18:51:10 +0000741This is a convenience function to raise an exception when a \C{} library
742function has returned an error and set the \C{} variable \code{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000743It constructs a tuple object whose first item is the integer
744\code{errno} value and whose second item is the corresponding error
745message (gotten from \code{strerror()}), and then calls
746\code{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
747the \code{errno} value is \code{EINTR}, indicating an interrupted
748system call, this calls \code{PyErr_CheckSignals()}, and if that set
749the error indicator, leaves it set to that. The function always
750returns \NULL{}, so a wrapper function around a system call can write
751\code{return PyErr_NoMemory();} when the system call returns an error.
752\end{cfuncdesc}
753
754\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
755This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
756\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000757operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000758argument. It is mostly for internal use.
759\end{cfuncdesc}
760
761\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
762This function interacts with Python's signal handling. It checks
763whether a signal has been sent to the processes and if so, invokes the
764corresponding signal handler. If the \code{signal} module is
765supported, this can invoke a signal handler written in Python. In all
766cases, the default effect for \code{SIGINT} is to raise the
767\code{KeyboadInterrupt} exception. If an exception is raised the
768error indicator is set and the function returns 1; otherwise the
769function returns 0. The error indicator may or may not be cleared if
770it was previously set.
771\end{cfuncdesc}
772
773\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
774This function is obsolete (XXX or platform dependent?). It simulates
775the effect of a \code{SIGINT} signal arriving -- the next time
776\code{PyErr_CheckSignals()} is called, \code{KeyboadInterrupt} will be
777raised.
778\end{cfuncdesc}
779
Guido van Rossum42cefd01997-10-05 15:27:29 +0000780\begin{cfuncdesc}{PyObject *}{PyErr_NewException}{char *name,
781PyObject *base, PyObject *dict}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000782\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000783This utility function creates and returns a new exception object. The
Fred Drakeb0a78731998-01-13 18:51:10 +0000784\var{name} argument must be the name of the new exception, a \C{} string
Guido van Rossum42cefd01997-10-05 15:27:29 +0000785of the form \code{module.class}. The \var{base} and \var{dict}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000786arguments are normally \NULL{}. Normally, this creates a class
Guido van Rossum42cefd01997-10-05 15:27:29 +0000787object derived from the root for all exceptions, the built-in name
Fred Drakeb0a78731998-01-13 18:51:10 +0000788\code{Exception} (accessible in \C{} as \code{PyExc_Exception}). In this
Guido van Rossum42cefd01997-10-05 15:27:29 +0000789case the \code{__module__} attribute of the new class is set to the
790first part (up to the last dot) of the \var{name} argument, and the
791class name is set to the last part (after the last dot). When the
792user has specified the \code{-X} command line option to use string
793exceptions, for backward compatibility, or when the \var{base}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000794argument is not a class object (and not \NULL{}), a string object
Guido van Rossum42cefd01997-10-05 15:27:29 +0000795created from the entire \var{name} argument is returned. The
796\var{base} argument can be used to specify an alternate base class.
797The \var{dict} argument can be used to specify a dictionary of class
798variables and methods.
799\end{cfuncdesc}
800
801
Guido van Rossumae110af1997-05-22 20:11:52 +0000802\section{Standard Exceptions}
803
804All standard Python exceptions are available as global variables whose
805names are \code{PyExc_} followed by the Python exception name.
806These have the type \code{PyObject *}; they are all string objects.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000807For completeness, here are all the variables (the first four are new
808in Python 1.5a4):
809\code{PyExc_Exception},
810\code{PyExc_StandardError},
811\code{PyExc_ArithmeticError},
812\code{PyExc_LookupError},
Guido van Rossumae110af1997-05-22 20:11:52 +0000813\code{PyExc_AssertionError},
814\code{PyExc_AttributeError},
815\code{PyExc_EOFError},
816\code{PyExc_FloatingPointError},
817\code{PyExc_IOError},
818\code{PyExc_ImportError},
819\code{PyExc_IndexError},
820\code{PyExc_KeyError},
821\code{PyExc_KeyboardInterrupt},
822\code{PyExc_MemoryError},
823\code{PyExc_NameError},
824\code{PyExc_OverflowError},
825\code{PyExc_RuntimeError},
826\code{PyExc_SyntaxError},
827\code{PyExc_SystemError},
828\code{PyExc_SystemExit},
829\code{PyExc_TypeError},
830\code{PyExc_ValueError},
831\code{PyExc_ZeroDivisionError}.
832
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000833
834\chapter{Utilities}
835
836The functions in this chapter perform various utility tasks, such as
Fred Drakeb0a78731998-01-13 18:51:10 +0000837parsing function arguments and constructing Python values from \C{}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000838values.
839
Guido van Rossum42cefd01997-10-05 15:27:29 +0000840\section{OS Utilities}
841
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000842\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
843Return true (nonzero) if the standard I/O file \code{fp} with name
844\code{filename} is deemed interactive. This is the case for files for
845which \code{isatty(fileno(fp))} is true. If the global flag
846\code{Py_InteractiveFlag} is true, this function also returns true if
847the \code{name} pointer is \NULL{} or if the name is equal to one of
848the strings \code{"<stdin>"} or \code{"???"}.
849\end{cfuncdesc}
850
851\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
852Return the time of last modification of the file \code{filename}.
853The result is encoded in the same way as the timestamp returned by
Fred Drakeb0a78731998-01-13 18:51:10 +0000854the standard \C{} library function \code{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000855\end{cfuncdesc}
856
857
Fred Drakee5bf8b21998-02-12 21:22:28 +0000858\section{Process Control}
859
860\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
861Print a fatal error message and kill the process. No cleanup is
862performed. This function should only be invoked when a condition is
863detected that would make it dangerous to continue using the Python
864interpreter; e.g., when the object administration appears to be
865corrupted. On \UNIX{}, the standard \C{} library function \code{abort()} is
866called which will attempt to produce a \file{core} file.
867\end{cfuncdesc}
868
869\begin{cfuncdesc}{void}{Py_Exit}{int status}
870Exit the current process. This calls \code{Py_Finalize()} and then
871calls the standard \C{} library function \code{exit(\var{status})}.
872\end{cfuncdesc}
873
874\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
875Register a cleanup function to be called by \cfunction{Py_Finalize()}.
876The cleanup function will be called with no arguments and should
877return no value. At most 32 cleanup functions can be registered.
878When the registration is successful, \cfunction{Py_AtExit()} returns
879\code{0}; on failure, it returns \code{-1}. The cleanup function
880registered last is called first. Each cleanup function will be called
881at most once. Since Python's internal finallization will have
882completed before the cleanup function, no Python APIs should be called
883by \var{func}.
884\end{cfuncdesc}
885
886
887\section{Importing Modules}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000888
889\begin{cfuncdesc}{PyObject *}{PyImport_ImportModule}{char *name}
890This is a simplified interface to \code{PyImport_ImportModuleEx}
891below, leaving the \var{globals} and \var{locals} arguments set to
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000892\NULL{}. When the \var{name} argument contains a dot (i.e., when
Guido van Rossum42cefd01997-10-05 15:27:29 +0000893it specifies a submodule of a package), the \var{fromlist} argument is
894set to the list \code{['*']} so that the return value is the named
895module rather than the top-level package containing it as would
896otherwise be the case. (Unfortunately, this has an additional side
897effect when \var{name} in fact specifies a subpackage instead of a
898submodule: the submodules specified in the package's \code{__all__}
899variable are loaded.) Return a new reference to the imported module,
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000900or \NULL{} with an exception set on failure (the module may still
Guido van Rossum42cefd01997-10-05 15:27:29 +0000901be created in this case).
902\end{cfuncdesc}
903
904\begin{cfuncdesc}{PyObject *}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000905\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000906Import a module. This is best described by referring to the built-in
907Python function \code{__import()__}, as the standard
908\code{__import__()} function calls this function directly.
909
Guido van Rossum42cefd01997-10-05 15:27:29 +0000910The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000911top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000912(the module may still be created in this case). Like for
913\code{__import__()}, the return value when a submodule of a package
914was requested is normally the top-level package, unless a non-empty
915\var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000916\end{cfuncdesc}
917
918\begin{cfuncdesc}{PyObject *}{PyImport_Import}{PyObject *name}
919This is a higher-level interface that calls the current ``import hook
920function''. It invokes the \code{__import__()} function from the
921\code{__builtins__} of the current globals. This means that the
922import is done using whatever import hooks are installed in the
923current environment, e.g. by \code{rexec} or \code{ihooks}.
924\end{cfuncdesc}
925
926\begin{cfuncdesc}{PyObject *}{PyImport_ReloadModule}{PyObject *m}
927Reload a module. This is best described by referring to the built-in
928Python function \code{reload()}, as the standard \code{reload()}
929function calls this function directly. Return a new reference to the
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000930reloaded module, or \NULL{} with an exception set on failure (the
Guido van Rossum42cefd01997-10-05 15:27:29 +0000931module still exists in this case).
932\end{cfuncdesc}
933
934\begin{cfuncdesc}{PyObject *}{PyImport_AddModule}{char *name}
935Return the module object corresponding to a module name. The
936\var{name} argument may be of the form \code{package.module}). First
937check the modules dictionary if there's one there, and if not, create
938a new one and insert in in the modules dictionary. Because the former
939action is most common, this does not return a new reference, and you
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000940do not own the returned reference. Return \NULL{} with an
Guido van Rossum42cefd01997-10-05 15:27:29 +0000941exception set on failure.
942\end{cfuncdesc}
943
944\begin{cfuncdesc}{PyObject *}{PyImport_ExecCodeModule}{char *name, PyObject *co}
945Given a module name (possibly of the form \code{package.module}) and a
946code object read from a Python bytecode file or obtained from the
947built-in function \code{compile()}, load the module. Return a new
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000948reference to the module object, or \NULL{} with an exception set
Guido van Rossum42cefd01997-10-05 15:27:29 +0000949if an error occurred (the module may still be created in this case).
950(This function would reload the module if it was already imported.)
951\end{cfuncdesc}
952
953\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
954Return the magic number for Python bytecode files (a.k.a. \code{.pyc}
955and \code{.pyo} files). The magic number should be present in the
956first four bytes of the bytecode file, in little-endian byte order.
957\end{cfuncdesc}
958
959\begin{cfuncdesc}{PyObject *}{PyImport_GetModuleDict}{}
960Return the dictionary used for the module administration
961(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
962variable.
963\end{cfuncdesc}
964
965\begin{cfuncdesc}{void}{_PyImport_Init}{}
966Initialize the import mechanism. For internal use only.
967\end{cfuncdesc}
968
969\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
970Empty the module table. For internal use only.
971\end{cfuncdesc}
972
973\begin{cfuncdesc}{void}{_PyImport_Fini}{}
974Finalize the import mechanism. For internal use only.
975\end{cfuncdesc}
976
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000977\begin{cfuncdesc}{extern PyObject *}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000978For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000979\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000980
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000981\begin{cfuncdesc}{extern PyObject *}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000982For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000983\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000984
985\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *}
986Load a frozen module. Return \code{1} for success, \code{0} if the
987module is not found, and \code{-1} with an exception set if the
988initialization failed. To access the imported module on a successful
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000989load, use \code{PyImport_ImportModule())}.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000990(Note the misnomer -- this function would reload the module if it was
991already imported.)
992\end{cfuncdesc}
993
994\begin{ctypedesc}{struct _frozen}
995This is the structure type definition for frozen module descriptors,
996as generated by the \code{freeze} utility (see \file{Tools/freeze/} in
997the Python source distribution). Its definition is:
Guido van Rossum9faf4c51997-10-07 14:38:54 +0000998\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000999struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001000 char *name;
1001 unsigned char *code;
1002 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001003};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001004\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001005\end{ctypedesc}
1006
1007\begin{cvardesc}{struct _frozen *}{PyImport_FrozenModules}
1008This pointer is initialized to point to an array of \code{struct
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001009_frozen} records, terminated by one whose members are all \NULL{}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001010or zero. When a frozen module is imported, it is searched in this
1011table. Third party code could play tricks with this to provide a
1012dynamically created collection of frozen modules.
1013\end{cvardesc}
1014
1015
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001016\chapter{Abstract Objects Layer}
1017
1018The functions in this chapter interact with Python objects regardless
1019of their type, or with wide classes of object types (e.g. all
1020numerical types, or all sequence types). When used on object types
1021for which they do not apply, they will flag a Python exception.
1022
1023\section{Object Protocol}
1024
1025\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
1026Print an object \code{o}, on file \code{fp}. Returns -1 on error
1027The flags argument is used to enable certain printing
1028options. The only option currently supported is \code{Py_Print_RAW}.
1029\end{cfuncdesc}
1030
1031\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
1032Returns 1 if o has the attribute attr_name, and 0 otherwise.
1033This is equivalent to the Python expression:
1034\code{hasattr(o,attr_name)}.
1035This function always succeeds.
1036\end{cfuncdesc}
1037
1038\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o, char *attr_name}
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001039Retrieve an attribute named attr_name from object o.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001040Returns the attribute value on success, or \NULL{} on failure.
1041This is the equivalent of the Python expression: \code{o.attr_name}.
1042\end{cfuncdesc}
1043
1044
1045\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
1046Returns 1 if o has the attribute attr_name, and 0 otherwise.
1047This is equivalent to the Python expression:
1048\code{hasattr(o,attr_name)}.
1049This function always succeeds.
1050\end{cfuncdesc}
1051
1052
1053\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o, PyObject *attr_name}
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001054Retrieve an attribute named attr_name from object o.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001055Returns the attribute value on success, or \NULL{} on failure.
1056This is the equivalent of the Python expression: o.attr_name.
1057\end{cfuncdesc}
1058
1059
1060\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
1061Set the value of the attribute named \code{attr_name}, for object \code{o},
1062to the value \code{v}. Returns -1 on failure. This is
1063the equivalent of the Python statement: \code{o.attr_name=v}.
1064\end{cfuncdesc}
1065
1066
1067\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
1068Set the value of the attribute named \code{attr_name}, for
1069object \code{o},
1070to the value \code{v}. Returns -1 on failure. This is
1071the equivalent of the Python statement: \code{o.attr_name=v}.
1072\end{cfuncdesc}
1073
1074
1075\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
1076Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1077failure. This is the equivalent of the Python
1078statement: \code{del o.attr_name}.
1079\end{cfuncdesc}
1080
1081
1082\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
1083Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1084failure. This is the equivalent of the Python
1085statement: \code{del o.attr_name}.
1086\end{cfuncdesc}
1087
1088
1089\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
1090Compare the values of \code{o1} and \code{o2} using a routine provided by
1091\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1092The result of the comparison is returned in \code{result}. Returns
1093-1 on failure. This is the equivalent of the Python
1094statement: \code{result=cmp(o1,o2)}.
1095\end{cfuncdesc}
1096
1097
1098\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
1099Compare the values of \code{o1} and \code{o2} using a routine provided by
1100\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1101Returns the result of the comparison on success. On error,
1102the value returned is undefined. This is equivalent to the
1103Python expression: \code{cmp(o1,o2)}.
1104\end{cfuncdesc}
1105
1106
1107\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
1108Compute the string representation of object, \code{o}. Returns the
1109string representation on success, \NULL{} on failure. This is
1110the equivalent of the Python expression: \code{repr(o)}.
1111Called by the \code{repr()} built-in function and by reverse quotes.
1112\end{cfuncdesc}
1113
1114
1115\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
1116Compute the string representation of object, \code{o}. Returns the
1117string representation on success, \NULL{} on failure. This is
1118the equivalent of the Python expression: \code{str(o)}.
1119Called by the \code{str()} built-in function and by the \code{print}
1120statement.
1121\end{cfuncdesc}
1122
1123
1124\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
1125Determine if the object \code{o}, is callable. Return 1 if the
1126object is callable and 0 otherwise.
1127This function always succeeds.
1128\end{cfuncdesc}
1129
1130
1131\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object, PyObject *args}
1132Call a callable Python object \code{callable_object}, with
1133arguments given by the tuple \code{args}. If no arguments are
1134needed, then args may be \NULL{}. Returns the result of the
1135call on success, or \NULL{} on failure. This is the equivalent
1136of the Python expression: \code{apply(o, args)}.
1137\end{cfuncdesc}
1138
1139\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
1140Call a callable Python object \code{callable_object}, with a
Fred Drakeb0a78731998-01-13 18:51:10 +00001141variable number of \C{} arguments. The \C{} arguments are described
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001142using a mkvalue-style format string. The format may be \NULL{},
1143indicating that no arguments are provided. Returns the
1144result of the call on success, or \NULL{} on failure. This is
1145the equivalent of the Python expression: \code{apply(o,args)}.
1146\end{cfuncdesc}
1147
1148
1149\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
1150Call the method named \code{m} of object \code{o} with a variable number of
Fred Drakeb0a78731998-01-13 18:51:10 +00001151C arguments. The \C{} arguments are described by a mkvalue
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001152format string. The format may be \NULL{}, indicating that no
1153arguments are provided. Returns the result of the call on
1154success, or \NULL{} on failure. This is the equivalent of the
1155Python expression: \code{o.method(args)}.
1156Note that Special method names, such as "\code{__add__}",
1157"\code{__getitem__}", and so on are not supported. The specific
1158abstract-object routines for these must be used.
1159\end{cfuncdesc}
1160
1161
1162\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
1163Compute and return the hash value of an object \code{o}. On
1164failure, return -1. This is the equivalent of the Python
1165expression: \code{hash(o)}.
1166\end{cfuncdesc}
1167
1168
1169\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
1170Returns 1 if the object \code{o} is considered to be true, and
11710 otherwise. This is equivalent to the Python expression:
1172\code{not not o}.
1173This function always succeeds.
1174\end{cfuncdesc}
1175
1176
1177\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1178On success, returns a type object corresponding to the object
1179type of object \code{o}. On failure, returns \NULL{}. This is
1180equivalent to the Python expression: \code{type(o)}.
1181\end{cfuncdesc}
1182
1183\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
1184Return the length of object \code{o}. If the object \code{o} provides
1185both sequence and mapping protocols, the sequence length is
1186returned. On error, -1 is returned. This is the equivalent
1187to the Python expression: \code{len(o)}.
1188\end{cfuncdesc}
1189
1190
1191\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
1192Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1193on failure. This is the equivalent of the Python expression:
1194\code{o[key]}.
1195\end{cfuncdesc}
1196
1197
1198\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
1199Map the object \code{key} to the value \code{v}.
1200Returns -1 on failure. This is the equivalent
1201of the Python statement: \code{o[key]=v}.
1202\end{cfuncdesc}
1203
1204
1205\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key, PyObject *v}
1206Delete the mapping for \code{key} from \code{*o}. Returns -1
1207on failure.
Guido van Rossum59a61351997-08-14 20:34:33 +00001208This is the equivalent of the Python statement: \code{del o[key]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001209\end{cfuncdesc}
1210
1211
1212\section{Number Protocol}
1213
1214\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
1215Returns 1 if the object \code{o} provides numeric protocols, and
1216false otherwise.
1217This function always succeeds.
1218\end{cfuncdesc}
1219
1220
1221\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
1222Returns the result of adding \code{o1} and \code{o2}, or null on failure.
1223This is the equivalent of the Python expression: \code{o1+o2}.
1224\end{cfuncdesc}
1225
1226
1227\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
1228Returns the result of subtracting \code{o2} from \code{o1}, or null on
1229failure. This is the equivalent of the Python expression:
1230\code{o1-o2}.
1231\end{cfuncdesc}
1232
1233
1234\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
1235Returns the result of multiplying \code{o1} and \code{o2}, or null on
1236failure. This is the equivalent of the Python expression:
1237\code{o1*o2}.
1238\end{cfuncdesc}
1239
1240
1241\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
1242Returns the result of dividing \code{o1} by \code{o2}, or null on failure.
1243This is the equivalent of the Python expression: \code{o1/o2}.
1244\end{cfuncdesc}
1245
1246
1247\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
1248Returns the remainder of dividing \code{o1} by \code{o2}, or null on
1249failure. This is the equivalent of the Python expression:
1250\code{o1\%o2}.
1251\end{cfuncdesc}
1252
1253
1254\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
1255See the built-in function divmod. Returns \NULL{} on failure.
1256This is the equivalent of the Python expression:
1257\code{divmod(o1,o2)}.
1258\end{cfuncdesc}
1259
1260
1261\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
1262See the built-in function pow. Returns \NULL{} on failure.
1263This is the equivalent of the Python expression:
1264\code{pow(o1,o2,o3)}, where \code{o3} is optional.
1265\end{cfuncdesc}
1266
1267
1268\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
1269Returns the negation of \code{o} on success, or null on failure.
1270This is the equivalent of the Python expression: \code{-o}.
1271\end{cfuncdesc}
1272
1273
1274\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
1275Returns \code{o} on success, or \NULL{} on failure.
1276This is the equivalent of the Python expression: \code{+o}.
1277\end{cfuncdesc}
1278
1279
1280\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
1281Returns the absolute value of \code{o}, or null on failure. This is
1282the equivalent of the Python expression: \code{abs(o)}.
1283\end{cfuncdesc}
1284
1285
1286\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
1287Returns the bitwise negation of \code{o} on success, or \NULL{} on
1288failure. This is the equivalent of the Python expression:
Guido van Rossum59a61351997-08-14 20:34:33 +00001289\code{\~o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001290\end{cfuncdesc}
1291
1292
1293\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
1294Returns the result of left shifting \code{o1} by \code{o2} on success, or
1295\NULL{} on failure. This is the equivalent of the Python
1296expression: \code{o1 << o2}.
1297\end{cfuncdesc}
1298
1299
1300\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
1301Returns the result of right shifting \code{o1} by \code{o2} on success, or
1302\NULL{} on failure. This is the equivalent of the Python
1303expression: \code{o1 >> o2}.
1304\end{cfuncdesc}
1305
1306
1307\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
1308Returns the result of "anding" \code{o2} and \code{o2} on success and \NULL{}
1309on failure. This is the equivalent of the Python
1310expression: \code{o1 and o2}.
1311\end{cfuncdesc}
1312
1313
1314\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
1315Returns the bitwise exclusive or of \code{o1} by \code{o2} on success, or
1316\NULL{} on failure. This is the equivalent of the Python
1317expression: \code{o1\^{ }o2}.
1318\end{cfuncdesc}
1319
1320\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Guido van Rossum59a61351997-08-14 20:34:33 +00001321Returns the result of \code{o1} and \code{o2} on success, or \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001322failure. This is the equivalent of the Python expression:
1323\code{o1 or o2}.
1324\end{cfuncdesc}
1325
1326
1327\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject *o1, PyObject *o2}
1328This function takes the addresses of two variables of type
1329\code{PyObject*}.
1330
1331If the objects pointed to by \code{*p1} and \code{*p2} have the same type,
1332increment their reference count and return 0 (success).
1333If the objects can be converted to a common numeric type,
1334replace \code{*p1} and \code{*p2} by their converted value (with 'new'
1335reference counts), and return 0.
1336If no conversion is possible, or if some other error occurs,
1337return -1 (failure) and don't increment the reference counts.
1338The call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1339statement \code{o1, o2 = coerce(o1, o2)}.
1340\end{cfuncdesc}
1341
1342
1343\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
1344Returns the \code{o} converted to an integer object on success, or
1345\NULL{} on failure. This is the equivalent of the Python
1346expression: \code{int(o)}.
1347\end{cfuncdesc}
1348
1349
1350\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
1351Returns the \code{o} converted to a long integer object on success,
1352or \NULL{} on failure. This is the equivalent of the Python
1353expression: \code{long(o)}.
1354\end{cfuncdesc}
1355
1356
1357\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
1358Returns the \code{o} converted to a float object on success, or \NULL{}
1359on failure. This is the equivalent of the Python expression:
1360\code{float(o)}.
1361\end{cfuncdesc}
1362
1363
Fred Drakef44617d1998-02-12 20:57:15 +00001364\section{Sequence Protocol}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001365
1366\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
1367Return 1 if the object provides sequence protocol, and 0
1368otherwise.
1369This function always succeeds.
1370\end{cfuncdesc}
1371
1372
1373\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001374Return the concatenation of \code{o1} and \code{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001375failure. This is the equivalent of the Python
1376expression: \code{o1+o2}.
1377\end{cfuncdesc}
1378
1379
1380\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Guido van Rossum59a61351997-08-14 20:34:33 +00001381Return the result of repeating sequence object \code{o} \code{count} times,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001382or \NULL{} on failure. This is the equivalent of the Python
1383expression: \code{o*count}.
1384\end{cfuncdesc}
1385
1386
1387\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
1388Return the ith element of \code{o}, or \NULL{} on failure. This is the
1389equivalent of the Python expression: \code{o[i]}.
1390\end{cfuncdesc}
1391
1392
1393\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
1394Return the slice of sequence object \code{o} between \code{i1} and \code{i2}, or
1395\NULL{} on failure. This is the equivalent of the Python
1396expression, \code{o[i1:i2]}.
1397\end{cfuncdesc}
1398
1399
1400\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
1401Assign object \code{v} to the \code{i}th element of \code{o}.
1402Returns -1 on failure. This is the equivalent of the Python
1403statement, \code{o[i]=v}.
1404\end{cfuncdesc}
1405
1406\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
1407Delete the \code{i}th element of object \code{v}. Returns
1408-1 on failure. This is the equivalent of the Python
1409statement: \code{del o[i]}.
1410\end{cfuncdesc}
1411
1412\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1, int i2, PyObject *v}
1413Assign the sequence object \code{v} to the slice in sequence
1414object \code{o} from \code{i1} to \code{i2}. This is the equivalent of the Python
1415statement, \code{o[i1:i2]=v}.
1416\end{cfuncdesc}
1417
1418\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
1419Delete the slice in sequence object, \code{o}, from \code{i1} to \code{i2}.
1420Returns -1 on failure. This is the equivalent of the Python
1421statement: \code{del o[i1:i2]}.
1422\end{cfuncdesc}
1423
1424\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1425Returns the \code{o} as a tuple on success, and \NULL{} on failure.
1426This is equivalent to the Python expression: \code{tuple(o)}.
1427\end{cfuncdesc}
1428
1429\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
1430Return the number of occurrences of \code{value} on \code{o}, that is,
1431return the number of keys for which \code{o[key]==value}. On
1432failure, return -1. This is equivalent to the Python
1433expression: \code{o.count(value)}.
1434\end{cfuncdesc}
1435
1436\begin{cfuncdesc}{int}{PySequence_In}{PyObject *o, PyObject *value}
1437Determine if \code{o} contains \code{value}. If an item in \code{o} is equal to
1438\code{value}, return 1, otherwise return 0. On error, return -1. This
1439is equivalent to the Python expression: \code{value in o}.
1440\end{cfuncdesc}
1441
1442\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Guido van Rossum59a61351997-08-14 20:34:33 +00001443Return the first index for which \code{o[i]==value}. On error,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001444return -1. This is equivalent to the Python
1445expression: \code{o.index(value)}.
1446\end{cfuncdesc}
1447
Fred Drakef44617d1998-02-12 20:57:15 +00001448\section{Mapping Protocol}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001449
1450\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
1451Return 1 if the object provides mapping protocol, and 0
1452otherwise.
1453This function always succeeds.
1454\end{cfuncdesc}
1455
1456
1457\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
1458Returns the number of keys in object \code{o} on success, and -1 on
1459failure. For objects that do not provide sequence protocol,
1460this is equivalent to the Python expression: \code{len(o)}.
1461\end{cfuncdesc}
1462
1463
1464\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
1465Remove the mapping for object \code{key} from the object \code{o}.
1466Return -1 on failure. This is equivalent to
1467the Python statement: \code{del o[key]}.
1468\end{cfuncdesc}
1469
1470
1471\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
1472Remove the mapping for object \code{key} from the object \code{o}.
1473Return -1 on failure. This is equivalent to
1474the Python statement: \code{del o[key]}.
1475\end{cfuncdesc}
1476
1477
1478\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
1479On success, return 1 if the mapping object has the key \code{key}
1480and 0 otherwise. This is equivalent to the Python expression:
1481\code{o.has_key(key)}.
1482This function always succeeds.
1483\end{cfuncdesc}
1484
1485
1486\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
1487Return 1 if the mapping object has the key \code{key}
1488and 0 otherwise. This is equivalent to the Python expression:
1489\code{o.has_key(key)}.
1490This function always succeeds.
1491\end{cfuncdesc}
1492
1493
1494\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
1495On success, return a list of the keys in object \code{o}. On
1496failure, return \NULL{}. This is equivalent to the Python
1497expression: \code{o.keys()}.
1498\end{cfuncdesc}
1499
1500
1501\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
1502On success, return a list of the values in object \code{o}. On
1503failure, return \NULL{}. This is equivalent to the Python
1504expression: \code{o.values()}.
1505\end{cfuncdesc}
1506
1507
1508\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
1509On success, return a list of the items in object \code{o}, where
1510each item is a tuple containing a key-value pair. On
1511failure, return \NULL{}. This is equivalent to the Python
1512expression: \code{o.items()}.
1513\end{cfuncdesc}
1514
1515\begin{cfuncdesc}{int}{PyMapping_Clear}{PyObject *o}
1516Make object \code{o} empty. Returns 1 on success and 0 on failure.
1517This is equivalent to the Python statement:
1518\code{for key in o.keys(): del o[key]}
1519\end{cfuncdesc}
1520
1521
1522\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
1523Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1524on failure. This is the equivalent of the Python expression:
1525\code{o[key]}.
1526\end{cfuncdesc}
1527
1528\begin{cfuncdesc}{PyObject*}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
1529Map the object \code{key} to the value \code{v} in object \code{o}. Returns
1530-1 on failure. This is the equivalent of the Python
1531statement: \code{o[key]=v}.
1532\end{cfuncdesc}
1533
1534
1535\section{Constructors}
1536
1537\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *file_name, char *mode}
1538On success, returns a new file object that is opened on the
1539file given by \code{file_name}, with a file mode given by \code{mode},
Fred Drakeb0a78731998-01-13 18:51:10 +00001540where \code{mode} has the same semantics as the standard \C{} routine,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001541fopen. On failure, return -1.
1542\end{cfuncdesc}
1543
1544\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp, char *file_name, char *mode, int close_on_del}
Fred Drakeb0a78731998-01-13 18:51:10 +00001545Return a new file object for an already opened standard \C{}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001546file pointer, \code{fp}. A file name, \code{file_name}, and open mode,
1547\code{mode}, must be provided as well as a flag, \code{close_on_del}, that
1548indicates whether the file is to be closed when the file
1549object is destroyed. On failure, return -1.
1550\end{cfuncdesc}
1551
1552\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
1553Returns a new float object with the value \code{v} on success, and
1554\NULL{} on failure.
1555\end{cfuncdesc}
1556
1557\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long v}
1558Returns a new int object with the value \code{v} on success, and
1559\NULL{} on failure.
1560\end{cfuncdesc}
1561
1562\begin{cfuncdesc}{PyObject*}{PyList_New}{int l}
1563Returns a new list of length \code{l} on success, and \NULL{} on
1564failure.
1565\end{cfuncdesc}
1566
1567\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
1568Returns a new long object with the value \code{v} on success, and
1569\NULL{} on failure.
1570\end{cfuncdesc}
1571
1572\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
1573Returns a new long object with the value \code{v} on success, and
1574\NULL{} on failure.
1575\end{cfuncdesc}
1576
1577\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1578Returns a new empty dictionary on success, and \NULL{} on
1579failure.
1580\end{cfuncdesc}
1581
1582\begin{cfuncdesc}{PyObject*}{PyString_FromString}{char *v}
1583Returns a new string object with the value \code{v} on success, and
1584\NULL{} on failure.
1585\end{cfuncdesc}
1586
1587\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{char *v, int l}
1588Returns a new string object with the value \code{v} and length \code{l}
1589on success, and \NULL{} on failure.
1590\end{cfuncdesc}
1591
1592\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int l}
1593Returns a new tuple of length \code{l} on success, and \NULL{} on
1594failure.
1595\end{cfuncdesc}
1596
1597
1598\chapter{Concrete Objects Layer}
1599
1600The functions in this chapter are specific to certain Python object
1601types. Passing them an object of the wrong type is not a good idea;
1602if you receive an object from a Python program and you are not sure
1603that it has the right type, you must perform a type check first;
1604e.g. to check that an object is a dictionary, use
Fred Drakee5bf8b21998-02-12 21:22:28 +00001605\cfunction{PyDict_Check()}. The chapter is structured like the
1606``family tree'' of Python object types.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001607
1608
Fred Drakee5bf8b21998-02-12 21:22:28 +00001609\section{Fundamental Objects}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001610
Fred Drakee5bf8b21998-02-12 21:22:28 +00001611This section describes Python type objects and the singleton object
1612\code{None}.
1613
1614
1615\subsection{Type Objects}
1616
1617\begin{ctypedesc}{PyTypeObject}
1618
1619\end{ctypedesc}
1620
1621\begin{cvardesc}{PyObject *}{PyType_Type}
1622
1623\end{cvardesc}
1624
1625
1626\subsection{The None Object}
1627
1628\begin{cvardesc}{PyObject *}{Py_None}
1629XXX macro
1630\end{cvardesc}
1631
1632
1633\section{Sequence Objects}
1634
1635Generic operations on sequence objects were discussed in the previous
1636chapter; this section deals with the specific kinds of sequence
1637objects that are intrinsic to the Python language.
1638
1639
1640\subsection{String Objects}
1641
1642\begin{ctypedesc}{PyStringObject}
1643This subtype of \code{PyObject} represents a Python string object.
1644\end{ctypedesc}
1645
1646\begin{cvardesc}{PyTypeObject}{PyString_Type}
1647This instance of \code{PyTypeObject} represents the Python string type.
1648\end{cvardesc}
1649
1650\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
1651
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001652\end{cfuncdesc}
1653
Fred Drakee5bf8b21998-02-12 21:22:28 +00001654\begin{cfuncdesc}{PyObject *}{PyString_FromStringAndSize}{const char *, int}
1655
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001656\end{cfuncdesc}
1657
Fred Drakee5bf8b21998-02-12 21:22:28 +00001658\begin{cfuncdesc}{PyObject *}{PyString_FromString}{const char *}
1659
Guido van Rossumae110af1997-05-22 20:11:52 +00001660\end{cfuncdesc}
1661
Fred Drakee5bf8b21998-02-12 21:22:28 +00001662\begin{cfuncdesc}{int}{PyString_Size}{PyObject *}
1663
Guido van Rossumae110af1997-05-22 20:11:52 +00001664\end{cfuncdesc}
1665
Fred Drakee5bf8b21998-02-12 21:22:28 +00001666\begin{cfuncdesc}{char *}{PyString_AsString}{PyObject *}
1667
1668\end{cfuncdesc}
1669
1670\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **, PyObject *}
1671
1672\end{cfuncdesc}
1673
1674\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **, PyObject *}
1675
1676\end{cfuncdesc}
1677
1678\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **, int}
1679
1680\end{cfuncdesc}
1681
1682\begin{cfuncdesc}{PyObject *}{PyString_Format}{PyObject *, PyObject *}
1683
1684\end{cfuncdesc}
1685
1686\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **}
1687
1688\end{cfuncdesc}
1689
1690\begin{cfuncdesc}{PyObject *}{PyString_InternFromString}{const char *}
1691
1692\end{cfuncdesc}
1693
1694\begin{cfuncdesc}{char *}{PyString_AS_STRING}{PyStringObject *}
1695
1696\end{cfuncdesc}
1697
1698\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyStringObject *}
1699
1700\end{cfuncdesc}
1701
1702
1703\subsection{Tuple Objects}
1704
1705\begin{ctypedesc}{PyTupleObject}
1706This subtype of \code{PyObject} represents a Python tuple object.
1707\end{ctypedesc}
1708
1709\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
1710This instance of \code{PyTypeObject} represents the Python tuple type.
1711\end{cvardesc}
1712
1713\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
1714Return true if the argument is a tuple object.
1715\end{cfuncdesc}
1716
1717\begin{cfuncdesc}{PyTupleObject *}{PyTuple_New}{int s}
1718Return a new tuple object of size \code{s}
1719\end{cfuncdesc}
1720
1721\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
1722akes a pointer to a tuple object, and returns the size
1723of that tuple.
1724\end{cfuncdesc}
1725
1726\begin{cfuncdesc}{PyObject *}{PyTuple_GetItem}{PyTupleObject *p, int pos}
1727returns the object at position \code{pos} in the tuple pointed
1728to by \code{p}.
1729\end{cfuncdesc}
1730
1731\begin{cfuncdesc}{PyObject *}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
1732does the same, but does no checking of it's
1733arguments.
1734\end{cfuncdesc}
1735
1736\begin{cfuncdesc}{PyTupleObject *}{PyTuple_GetSlice}{PyTupleObject *p,
1737 int low,
1738 int high}
1739takes a slice of the tuple pointed to by \code{p} from
1740\code{low} to \code{high} and returns it as a new tuple.
1741\end{cfuncdesc}
1742
1743\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyTupleObject *p,
1744 int pos,
1745 PyObject *o}
1746inserts a reference to object \code{o} at position \code{pos} of
1747the tuple pointed to by \code{p}. It returns 0 on success.
1748\end{cfuncdesc}
1749
1750\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyTupleObject *p,
1751 int pos,
1752 PyObject *o}
1753
1754does the same, but does no error checking, and
1755should \emph{only} be used to fill in brand new tuples.
1756\end{cfuncdesc}
1757
1758\begin{cfuncdesc}{PyTupleObject *}{_PyTuple_Resize}{PyTupleObject *p,
1759 int new,
1760 int last_is_sticky}
1761can be used to resize a tuple. Because tuples are
1762\emph{supposed} to be immutable, this should only be used if there is only
1763one module referencing the object. Do \emph{not} use this if the tuple may
1764already be known to some other part of the code. \code{last_is_sticky} is
1765a flag - if set, the tuple will grow or shrink at the front, otherwise
1766it will grow or shrink at the end. Think of this as destroying the old
1767tuple and creating a new one, only more efficiently.
1768\end{cfuncdesc}
1769
1770
1771\subsection{List Objects}
1772
1773\begin{ctypedesc}{PyListObject}
1774This subtype of \code{PyObject} represents a Python list object.
1775\end{ctypedesc}
1776
1777\begin{cvardesc}{PyTypeObject}{PyList_Type}
1778This instance of \code{PyTypeObject} represents the Python list type.
1779\end{cvardesc}
1780
1781\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
1782returns true if it's argument is a \code{PyListObject}
1783\end{cfuncdesc}
1784
1785\begin{cfuncdesc}{PyObject *}{PyList_New}{int size}
1786
1787\end{cfuncdesc}
1788
1789\begin{cfuncdesc}{int}{PyList_Size}{PyObject *}
1790
1791\end{cfuncdesc}
1792
1793\begin{cfuncdesc}{PyObject *}{PyList_GetItem}{PyObject *, int}
1794
1795\end{cfuncdesc}
1796
1797\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *, int, PyObject *}
1798
1799\end{cfuncdesc}
1800
1801\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *, int, PyObject *}
1802
1803\end{cfuncdesc}
1804
1805\begin{cfuncdesc}{int}{PyList_Append}{PyObject *, PyObject *}
1806
1807\end{cfuncdesc}
1808
1809\begin{cfuncdesc}{PyObject *}{PyList_GetSlice}{PyObject *, int, int}
1810
1811\end{cfuncdesc}
1812
1813\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *, int, int, PyObject *}
1814
1815\end{cfuncdesc}
1816
1817\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *}
1818
1819\end{cfuncdesc}
1820
1821\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *}
1822
1823\end{cfuncdesc}
1824
1825\begin{cfuncdesc}{PyObject *}{PyList_AsTuple}{PyObject *}
1826
1827\end{cfuncdesc}
1828
1829\begin{cfuncdesc}{PyObject *}{PyList_GET_ITEM}{PyObject *list, int i}
1830
1831\end{cfuncdesc}
1832
1833\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
1834
1835\end{cfuncdesc}
1836
1837
1838\section{Mapping Objects}
1839
1840\subsection{Dictionary Objects}
1841
1842\begin{ctypedesc}{PyDictObject}
1843This subtype of \code{PyObject} represents a Python dictionary object.
1844\end{ctypedesc}
1845
1846\begin{cvardesc}{PyTypeObject}{PyDict_Type}
1847This instance of \code{PyTypeObject} represents the Python dictionary type.
1848\end{cvardesc}
1849
1850\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
1851returns true if it's argument is a PyDictObject
1852\end{cfuncdesc}
1853
1854\begin{cfuncdesc}{PyDictObject *}{PyDict_New}{}
1855returns a new empty dictionary.
1856\end{cfuncdesc}
1857
1858\begin{cfuncdesc}{void}{PyDict_Clear}{PyDictObject *p}
1859empties an existing dictionary and deletes it.
1860\end{cfuncdesc}
1861
1862\begin{cfuncdesc}{int}{PyDict_SetItem}{PyDictObject *p,
1863 PyObject *key,
1864 PyObject *val}
1865inserts \code{value} into the dictionary with a key of
1866\code{key}. Both \code{key} and \code{value} should be PyObjects, and \code{key} should
1867be hashable.
1868\end{cfuncdesc}
1869
1870\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
1871 char *key,
1872 PyObject *val}
1873inserts \code{value} into the dictionary using \code{key}
1874as a key. \code{key} should be a char *
1875\end{cfuncdesc}
1876
1877\begin{cfuncdesc}{int}{PyDict_DelItem}{PyDictObject *p, PyObject *key}
1878removes the entry in dictionary \code{p} with key \code{key}.
1879\code{key} is a PyObject.
1880\end{cfuncdesc}
1881
1882\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyDictObject *p, char *key}
1883removes the entry in dictionary \code{p} which has a key
1884specified by the \code{char *}\code{key}.
1885\end{cfuncdesc}
1886
1887\begin{cfuncdesc}{PyObject *}{PyDict_GetItem}{PyDictObject *p, PyObject *key}
1888returns the object from dictionary \code{p} which has a key
1889\code{key}.
1890\end{cfuncdesc}
1891
1892\begin{cfuncdesc}{PyObject *}{PyDict_GetItemString}{PyDictObject *p, char *key}
1893does the same, but \code{key} is specified as a
1894\code{char *}, rather than a \code{PyObject *}.
1895\end{cfuncdesc}
1896
1897\begin{cfuncdesc}{PyListObject *}{PyDict_Items}{PyDictObject *p}
1898returns a PyListObject containing all the items
1899from the dictionary, as in the mapping method \code{items()} (see the Reference
1900Guide)
1901\end{cfuncdesc}
1902
1903\begin{cfuncdesc}{PyListObject *}{PyDict_Keys}{PyDictObject *p}
1904returns a PyListObject containing all the keys
1905from the dictionary, as in the mapping method \code{keys()} (see the Reference Guide)
1906\end{cfuncdesc}
1907
1908\begin{cfuncdesc}{PyListObject *}{PyDict_Values}{PyDictObject *p}
1909returns a PyListObject containing all the values
1910from the dictionary, as in the mapping method \code{values()} (see the Reference Guide)
1911\end{cfuncdesc}
1912
1913\begin{cfuncdesc}{int}{PyDict_Size}{PyDictObject *p}
1914returns the number of items in the dictionary.
1915\end{cfuncdesc}
1916
1917\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p,
1918 int ppos,
1919 PyObject **pkey,
1920 PyObject **pvalue}
1921
1922\end{cfuncdesc}
1923
1924
1925\section{Numeric Objects}
1926
1927\subsection{Plain Integer Objects}
1928
1929\begin{ctypedesc}{PyIntObject}
1930This subtype of \code{PyObject} represents a Python integer object.
1931\end{ctypedesc}
1932
1933\begin{cvardesc}{PyTypeObject}{PyInt_Type}
1934This instance of \code{PyTypeObject} represents the Python plain
1935integer type.
1936\end{cvardesc}
1937
1938\begin{cfuncdesc}{int}{PyInt_Check}{PyObject *}
1939
1940\end{cfuncdesc}
1941
1942\begin{cfuncdesc}{PyIntObject *}{PyInt_FromLong}{long ival}
1943creates a new integer object with a value of \code{ival}.
1944
1945The current implementation keeps an array of integer objects for all
1946integers between -1 and 100, when you create an int in that range you
1947actually just get back a reference to the existing object. So it should
1948be possible to change the value of 1. I suspect the behaviour of python
1949in this case is undefined. :-)
1950\end{cfuncdesc}
1951
1952\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyIntObject *io}
1953returns the value of the object \code{io}.
1954\end{cfuncdesc}
1955
1956\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
1957will first attempt to cast the object to a PyIntObject, if
1958it is not already one, and the return it's value.
1959\end{cfuncdesc}
1960
1961\begin{cfuncdesc}{long}{PyInt_GetMax}{}
1962returns the systems idea of the largest int it can handle
1963(LONG_MAX, as defined in the system header files)
1964\end{cfuncdesc}
1965
1966
1967\subsection{Long Integer Objects}
1968
1969\begin{ctypedesc}{PyLongObject}
1970This subtype of \code{PyObject} represents a Python long integer object.
1971\end{ctypedesc}
1972
1973\begin{cvardesc}{PyTypeObject}{PyLong_Type}
1974This instance of \code{PyTypeObject} represents the Python long integer type.
1975\end{cvardesc}
1976
1977\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
1978returns true if it's argument is a \code{PyLongObject}
1979\end{cfuncdesc}
1980
1981\begin{cfuncdesc}{PyObject *}{PyLong_FromLong}{long}
1982
1983\end{cfuncdesc}
1984
1985\begin{cfuncdesc}{PyObject *}{PyLong_FromUnsignedLong}{unsigned long}
1986
1987\end{cfuncdesc}
1988
1989\begin{cfuncdesc}{PyObject *}{PyLong_FromDouble}{double}
1990
1991\end{cfuncdesc}
1992
1993\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *}
1994
1995\end{cfuncdesc}
1996
1997\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject }
1998
1999\end{cfuncdesc}
2000
2001\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *}
2002
2003\end{cfuncdesc}
2004
2005\begin{cfuncdesc}{PyObject *}{PyLong_FromString}{char *, char **, int}
2006
2007\end{cfuncdesc}
2008
2009
2010\subsection{Floating Point Objects}
2011
2012\begin{ctypedesc}{PyFloatObject}
2013This subtype of \code{PyObject} represents a Python floating point object.
2014\end{ctypedesc}
2015
2016\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2017This instance of \code{PyTypeObject} represents the Python floating
2018point type.
2019\end{cvardesc}
2020
2021\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2022returns true if it's argument is a \code{PyFloatObject}
2023\end{cfuncdesc}
2024
2025\begin{cfuncdesc}{PyObject *}{PyFloat_FromDouble}{double}
2026
2027\end{cfuncdesc}
2028
2029\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *}
2030
2031\end{cfuncdesc}
2032
2033\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyFloatObject *}
2034
2035\end{cfuncdesc}
2036
2037
2038\subsection{Complex Number Objects}
2039
2040\begin{ctypedesc}{Py_complex}
2041typedef struct {
2042 double real;
2043 double imag;
2044}
2045\end{ctypedesc}
2046
2047\begin{ctypedesc}{PyComplexObject}
2048This subtype of \code{PyObject} represents a Python complex number object.
2049\end{ctypedesc}
2050
2051\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2052This instance of \code{PyTypeObject} represents the Python complex
2053number type.
2054\end{cvardesc}
2055
2056\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2057returns true if it's argument is a \code{PyComplexObject}
2058\end{cfuncdesc}
2059
2060\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex, Py_complex}
2061
2062\end{cfuncdesc}
2063
2064\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex, Py_complex}
2065
2066\end{cfuncdesc}
2067
2068\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex}
2069
2070\end{cfuncdesc}
2071
2072\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex, Py_complex}
2073
2074\end{cfuncdesc}
2075
2076\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex, Py_complex}
2077
2078\end{cfuncdesc}
2079
2080\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex, Py_complex}
2081
2082\end{cfuncdesc}
2083
2084\begin{cfuncdesc}{PyObject *}{PyComplex_FromCComplex}{Py_complex}
2085
2086\end{cfuncdesc}
2087
2088\begin{cfuncdesc}{PyObject *}{PyComplex_FromDoubles}{double real, double imag}
2089
2090\end{cfuncdesc}
2091
2092\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2093
2094\end{cfuncdesc}
2095
2096\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2097
2098\end{cfuncdesc}
2099
2100\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2101
2102\end{cfuncdesc}
2103
2104
2105
2106\section{Other Objects}
2107
2108\subsection{File Objects}
2109
2110\begin{ctypedesc}{PyFileObject}
2111This subtype of \code{PyObject} represents a Python file object.
2112\end{ctypedesc}
2113
2114\begin{cvardesc}{PyTypeObject}{PyFile_Type}
2115This instance of \code{PyTypeObject} represents the Python file type.
2116\end{cvardesc}
2117
2118\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2119returns true if it's argument is a \code{PyFileObject}
2120\end{cfuncdesc}
2121
2122\begin{cfuncdesc}{PyObject *}{PyFile_FromString}{char *name, char *mode}
2123creates a new PyFileObject pointing to the file
2124specified in \code{name} with the mode specified in \code{mode}
2125\end{cfuncdesc}
2126
2127\begin{cfuncdesc}{PyObject *}{PyFile_FromFile}{FILE *fp,
2128 char *name, char *mode, int (*close})
2129creates a new PyFileObject from the already-open \code{fp}.
2130The function \code{close} will be called when the file should be closed.
2131\end{cfuncdesc}
2132
2133\begin{cfuncdesc}{FILE *}{PyFile_AsFile}{PyFileObject *p}
2134returns the file object associated with \code{p} as a \code{FILE *}
2135\end{cfuncdesc}
2136
2137\begin{cfuncdesc}{PyStringObject *}{PyFile_GetLine}{PyObject *p, int n}
2138undocumented as yet
2139\end{cfuncdesc}
2140
2141\begin{cfuncdesc}{PyStringObject *}{PyFile_Name}{PyObject *p}
2142returns the name of the file specified by \code{p} as a
2143PyStringObject
2144\end{cfuncdesc}
2145
2146\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2147on systems with \code{setvbuf} only
2148\end{cfuncdesc}
2149
2150\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyFileObject *p, int newflag}
2151same as the file object method \code{softspace}
2152\end{cfuncdesc}
2153
2154\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p}
2155writes object \code{obj} to file object \code{p}
2156\end{cfuncdesc}
2157
2158\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p}
2159writes string \code{s} to file object \code{p}
2160\end{cfuncdesc}
2161
2162
2163\subsection{CObjects}
2164
2165XXX
2166
2167
Guido van Rossum4a944d71997-08-14 20:35:38 +00002168\chapter{Initialization, Finalization, and Threads}
2169
Guido van Rossum4a944d71997-08-14 20:35:38 +00002170\begin{cfuncdesc}{void}{Py_Initialize}{}
2171Initialize the Python interpreter. In an application embedding
2172Python, this should be called before using any other Python/C API
2173functions; with the exception of \code{Py_SetProgramName()},
2174\code{PyEval_InitThreads()}, \code{PyEval_ReleaseLock()}, and
2175\code{PyEval_AcquireLock()}. This initializes the table of loaded
2176modules (\code{sys.modules}), and creates the fundamental modules
2177\code{__builtin__}, \code{__main__} and \code{sys}. It also
2178initializes the module search path (\code{sys.path}). It does not set
Guido van Rossum42cefd01997-10-05 15:27:29 +00002179\code{sys.argv}; use \code{PySys_SetArgv()} for that. This is a no-op
2180when called for a second time (without calling \code{Py_Finalize()}
2181first). There is no return value; it is a fatal error if the
2182initialization fails.
2183\end{cfuncdesc}
2184
2185\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002186\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +00002187Return true (nonzero) when the Python interpreter has been
2188initialized, false (zero) if not. After \code{Py_Finalize()} is
2189called, this returns false until \code{Py_Initialize()} is called
2190again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002191\end{cfuncdesc}
2192
2193\begin{cfuncdesc}{void}{Py_Finalize}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002194\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002195Undo all initializations made by \code{Py_Initialize()} and subsequent
2196use of Python/C API functions, and destroy all sub-interpreters (see
2197\code{Py_NewInterpreter()} below) that were created and not yet
Guido van Rossum42cefd01997-10-05 15:27:29 +00002198destroyed since the last call to \code{Py_Initialize()}. Ideally,
2199this frees all memory allocated by the Python interpreter. This is a
2200no-op when called for a second time (without calling
2201\code{Py_Initialize()} again first). There is no return value; errors
Guido van Rossum4a944d71997-08-14 20:35:38 +00002202during finalization are ignored.
2203
2204This function is provided for a number of reasons. An embedding
2205application might want to restart Python without having to restart the
2206application itself. An application that has loaded the Python
2207interpreter from a dynamically loadable library (or DLL) might want to
2208free all memory allocated by Python before unloading the DLL. During a
2209hunt for memory leaks in an application a developer might want to free
2210all memory allocated by Python before exiting from the application.
2211
2212\emph{Bugs and caveats:} The destruction of modules and objects in
2213modules is done in random order; this may cause destructors
2214(\code{__del__} methods) to fail when they depend on other objects
2215(even functions) or modules. Dynamically loaded extension modules
2216loaded by Python are not unloaded. Small amounts of memory allocated
2217by the Python interpreter may not be freed (if you find a leak, please
2218report it). Memory tied up in circular references between objects is
2219not freed. Some memory allocated by extension modules may not be
2220freed. Some extension may not work properly if their initialization
2221routine is called more than once; this can happen if an applcation
2222calls \code{Py_Initialize()} and \code{Py_Finalize()} more than once.
2223\end{cfuncdesc}
2224
2225\begin{cfuncdesc}{PyThreadState *}{Py_NewInterpreter}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002226\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002227Create a new sub-interpreter. This is an (almost) totally separate
2228environment for the execution of Python code. In particular, the new
2229interpreter has separate, independent versions of all imported
2230modules, including the fundamental modules \code{__builtin__},
2231\code{__main__} and \code{sys}. The table of loaded modules
2232(\code{sys.modules}) and the module search path (\code{sys.path}) are
2233also separate. The new environment has no \code{sys.argv} variable.
2234It has new standard I/O stream file objects \code{sys.stdin},
2235\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drakeb0a78731998-01-13 18:51:10 +00002236same underlying \code{FILE} structures in the \C{} library).
Guido van Rossum4a944d71997-08-14 20:35:38 +00002237
2238The return value points to the first thread state created in the new
2239sub-interpreter. This thread state is made the current thread state.
2240Note that no actual thread is created; see the discussion of thread
2241states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002242\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00002243is stored in the current thread state and there may not be a current
2244thread state. (Like all other Python/C API functions, the global
2245interpreter lock must be held before calling this function and is
2246still held when it returns; however, unlike most other Python/C API
2247functions, there needn't be a current thread state on entry.)
2248
2249Extension modules are shared between (sub-)interpreters as follows:
2250the first time a particular extension is imported, it is initialized
2251normally, and a (shallow) copy of its module's dictionary is
2252squirreled away. When the same extension is imported by another
2253(sub-)interpreter, a new module is initialized and filled with the
2254contents of this copy; the extension's \code{init} function is not
2255called. Note that this is different from what happens when as
2256extension is imported after the interpreter has been completely
2257re-initialized by calling \code{Py_Finalize()} and
2258\code{Py_Initialize()}; in that case, the extension's \code{init}
2259function \emph{is} called again.
2260
2261\emph{Bugs and caveats:} Because sub-interpreters (and the main
2262interpreter) are part of the same process, the insulation between them
2263isn't perfect -- for example, using low-level file operations like
2264\code{os.close()} they can (accidentally or maliciously) affect each
2265other's open files. Because of the way extensions are shared between
2266(sub-)interpreters, some extensions may not work properly; this is
2267especially likely when the extension makes use of (static) global
2268variables, or when the extension manipulates its module's dictionary
2269after its initialization. It is possible to insert objects created in
2270one sub-interpreter into a namespace of another sub-interpreter; this
2271should be done with great care to avoid sharing user-defined
2272functions, methods, instances or classes between sub-interpreters,
2273since import operations executed by such objects may affect the
2274wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
2275a hard-to-fix bug that will be addressed in a future release.)
2276\end{cfuncdesc}
2277
2278\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002279\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002280Destroy the (sub-)interpreter represented by the given thread state.
2281The given thread state must be the current thread state. See the
2282discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002283thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00002284interpreted are destroyed. (The global interpreter lock must be held
2285before calling this function and is still held when it returns.)
2286\code{Py_Finalize()} will destroy all sub-interpreters that haven't
2287been explicitly destroyed at that point.
2288\end{cfuncdesc}
2289
2290\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002291\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002292This function should be called before \code{Py_Initialize()} is called
2293for the first time, if it is called at all. It tells the interpreter
2294the value of the \code{argv[0]} argument to the \code{main()} function
2295of the program. This is used by \code{Py_GetPath()} and some other
2296functions below to find the Python run-time libraries relative to the
2297interpreter executable. The default value is \code{"python"}. The
2298argument should point to a zero-terminated character string in static
2299storage whose contents will not change for the duration of the
2300program's execution. No code in the Python interpreter will change
2301the contents of this storage.
2302\end{cfuncdesc}
2303
2304\begin{cfuncdesc}{char *}{Py_GetProgramName}{}
2305Return the program name set with \code{Py_SetProgramName()}, or the
2306default. The returned string points into static storage; the caller
2307should not modify its value.
2308\end{cfuncdesc}
2309
2310\begin{cfuncdesc}{char *}{Py_GetPrefix}{}
2311Return the ``prefix'' for installed platform-independent files. This
2312is derived through a number of complicated rules from the program name
2313set with \code{Py_SetProgramName()} and some environment variables;
2314for example, if the program name is \code{"/usr/local/bin/python"},
2315the prefix is \code{"/usr/local"}. The returned string points into
2316static storage; the caller should not modify its value. This
2317corresponds to the \code{prefix} variable in the top-level
2318\code{Makefile} and the \code{--prefix} argument to the
2319\code{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00002320Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00002321also the next function.
2322\end{cfuncdesc}
2323
2324\begin{cfuncdesc}{char *}{Py_GetExecPrefix}{}
2325Return the ``exec-prefix'' for installed platform-\emph{de}pendent
2326files. This is derived through a number of complicated rules from the
2327program name set with \code{Py_SetProgramName()} and some environment
2328variables; for example, if the program name is
2329\code{"/usr/local/bin/python"}, the exec-prefix is
2330\code{"/usr/local"}. The returned string points into static storage;
2331the caller should not modify its value. This corresponds to the
2332\code{exec_prefix} variable in the top-level \code{Makefile} and the
2333\code{--exec_prefix} argument to the \code{configure} script at build
2334time. The value is available to Python code as
Fred Drakeb0a78731998-01-13 18:51:10 +00002335\code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002336
2337Background: The exec-prefix differs from the prefix when platform
2338dependent files (such as executables and shared libraries) are
2339installed in a different directory tree. In a typical installation,
2340platform dependent files may be installed in the
2341\code{"/usr/local/plat"} subtree while platform independent may be
2342installed in \code{"/usr/local"}.
2343
2344Generally speaking, a platform is a combination of hardware and
2345software families, e.g. Sparc machines running the Solaris 2.x
2346operating system are considered the same platform, but Intel machines
2347running Solaris 2.x are another platform, and Intel machines running
2348Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00002349operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002350operating systems are a different story; the installation strategies
2351on those systems are so different that the prefix and exec-prefix are
2352meaningless, and set to the empty string. Note that compiled Python
2353bytecode files are platform independent (but not independent from the
2354Python version by which they were compiled!).
2355
2356System administrators will know how to configure the \code{mount} or
2357\code{automount} programs to share \code{"/usr/local"} between platforms
2358while having \code{"/usr/local/plat"} be a different filesystem for each
2359platform.
2360\end{cfuncdesc}
2361
2362\begin{cfuncdesc}{char *}{Py_GetProgramFullPath}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002363\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002364Return the full program name of the Python executable; this is
2365computed as a side-effect of deriving the default module search path
Guido van Rossum09270b51997-08-15 18:57:32 +00002366from the program name (set by \code{Py_SetProgramName()} above). The
Guido van Rossum4a944d71997-08-14 20:35:38 +00002367returned string points into static storage; the caller should not
2368modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00002369\code{sys.executable}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002370\end{cfuncdesc}
2371
2372\begin{cfuncdesc}{char *}{Py_GetPath}{}
2373Return the default module search path; this is computed from the
Guido van Rossum09270b51997-08-15 18:57:32 +00002374program name (set by \code{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00002375environment variables. The returned string consists of a series of
2376directory names separated by a platform dependent delimiter character.
Fred Drakee5bc4971998-02-12 23:36:49 +00002377The delimiter character is \code{':'} on \UNIX{}, \code{';'} on
2378DOS/Windows, and \code{'\\n'} (the \ASCII{} newline character) on
2379Macintosh. The returned string points into static storage; the caller
Guido van Rossum4a944d71997-08-14 20:35:38 +00002380should not modify its value. The value is available to Python code
2381as the list \code{sys.path}, which may be modified to change the
2382future search path for loaded modules.
2383
2384% XXX should give the exact rules
2385\end{cfuncdesc}
2386
2387\begin{cfuncdesc}{const char *}{Py_GetVersion}{}
2388Return the version of this Python interpreter. This is a string that
2389looks something like
2390
Guido van Rossum09270b51997-08-15 18:57:32 +00002391\begin{verbatim}
2392"1.5a3 (#67, Aug 1 1997, 22:34:28) [GCC 2.7.2.2]"
2393\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002394
2395The first word (up to the first space character) is the current Python
2396version; the first three characters are the major and minor version
2397separated by a period. The returned string points into static storage;
2398the caller should not modify its value. The value is available to
2399Python code as the list \code{sys.version}.
2400\end{cfuncdesc}
2401
2402\begin{cfuncdesc}{const char *}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00002403Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00002404this is formed from the ``official'' name of the operating system,
2405converted to lower case, followed by the major revision number; e.g.,
2406for Solaris 2.x, which is also known as SunOS 5.x, the value is
2407\code{"sunos5"}. On Macintosh, it is \code{"mac"}. On Windows, it
2408is \code{"win"}. The returned string points into static storage;
2409the caller should not modify its value. The value is available to
2410Python code as \code{sys.platform}.
2411\end{cfuncdesc}
2412
2413\begin{cfuncdesc}{const char *}{Py_GetCopyright}{}
2414Return the official copyright string for the current Python version,
2415for example
2416
2417\code{"Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam"}
2418
2419The returned string points into static storage; the caller should not
2420modify its value. The value is available to Python code as the list
2421\code{sys.copyright}.
2422\end{cfuncdesc}
2423
2424\begin{cfuncdesc}{const char *}{Py_GetCompiler}{}
2425Return an indication of the compiler used to build the current Python
2426version, in square brackets, for example
2427
2428\code{"[GCC 2.7.2.2]"}
2429
2430The returned string points into static storage; the caller should not
2431modify its value. The value is available to Python code as part of
2432the variable \code{sys.version}.
2433\end{cfuncdesc}
2434
2435\begin{cfuncdesc}{const char *}{Py_GetBuildInfo}{}
2436Return information about the sequence number and build date and time
2437of the current Python interpreter instance, for example
2438
Guido van Rossum09270b51997-08-15 18:57:32 +00002439\begin{verbatim}
2440"#67, Aug 1 1997, 22:34:28"
2441\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002442
2443The returned string points into static storage; the caller should not
2444modify its value. The value is available to Python code as part of
2445the variable \code{sys.version}.
2446\end{cfuncdesc}
2447
2448\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
2449% XXX
2450\end{cfuncdesc}
2451
2452% XXX Other PySys thingies (doesn't really belong in this chapter)
2453
2454\section{Thread State and the Global Interpreter Lock}
2455
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002456The Python interpreter is not fully thread safe. In order to support
2457multi-threaded Python programs, there's a global lock that must be
2458held by the current thread before it can safely access Python objects.
2459Without the lock, even the simplest operations could cause problems in
2460a multi-threaded proram: for example, when two threads simultaneously
2461increment the reference count of the same object, the reference count
2462could end up being incremented only once instead of twice.
2463
2464Therefore, the rule exists that only the thread that has acquired the
2465global interpreter lock may operate on Python objects or call Python/C
2466API functions. In order to support multi-threaded Python programs,
2467the interpreter regularly release and reacquires the lock -- by
2468default, every ten bytecode instructions (this can be changed with
2469\code{sys.setcheckinterval()}). The lock is also released and
2470reacquired around potentially blocking I/O operations like reading or
2471writing a file, so that other threads can run while the thread that
2472requests the I/O is waiting for the I/O operation to complete.
2473
2474The Python interpreter needs to keep some bookkeeping information
2475separate per thread -- for this it uses a data structure called
2476PyThreadState. This is new in Python 1.5; in earlier versions, such
2477state was stored in global variables, and switching threads could
2478cause problems. In particular, exception handling is now thread safe,
2479when the application uses \code{sys.exc_info()} to access the exception
2480last raised in the current thread.
2481
2482There's one global variable left, however: the pointer to the current
2483PyThreadState structure. While most thread packages have a way to
2484store ``per-thread global data'', Python's internal platform
2485independent thread abstraction doesn't support this (yet). Therefore,
2486the current thread state must be manipulated explicitly.
2487
2488This is easy enough in most cases. Most code manipulating the global
2489interpreter lock has the following simple structure:
2490
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002491\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002492Save the thread state in a local variable.
2493Release the interpreter lock.
2494...Do some blocking I/O operation...
2495Reacquire the interpreter lock.
2496Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002497\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002498
2499This is so common that a pair of macros exists to simplify it:
2500
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002501\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002502Py_BEGIN_ALLOW_THREADS
2503...Do some blocking I/O operation...
2504Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002505\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002506
2507The BEGIN macro opens a new block and declares a hidden local
2508variable; the END macro closes the block. Another advantage of using
2509these two macros is that when Python is compiled without thread
2510support, they are defined empty, thus saving the thread state and lock
2511manipulations.
2512
2513When thread support is enabled, the block above expands to the
2514following code:
2515
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002516\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002517{
2518 PyThreadState *_save;
2519 _save = PyEval_SaveThread();
2520 ...Do some blocking I/O operation...
2521 PyEval_RestoreThread(_save);
2522}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002523\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002524
2525Using even lower level primitives, we can get roughly the same effect
2526as follows:
2527
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002528\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002529{
2530 PyThreadState *_save;
2531 _save = PyThreadState_Swap(NULL);
2532 PyEval_ReleaseLock();
2533 ...Do some blocking I/O operation...
2534 PyEval_AcquireLock();
2535 PyThreadState_Swap(_save);
2536}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002537\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002538
2539There are some subtle differences; in particular,
2540\code{PyEval_RestoreThread()} saves and restores the value of the
2541global variable \code{errno}, since the lock manipulation does not
2542guarantee that \code{errno} is left alone. Also, when thread support
2543is disabled, \code{PyEval_SaveThread()} and
2544\code{PyEval_RestoreThread()} don't manipulate the lock; in this case,
2545\code{PyEval_ReleaseLock()} and \code{PyEval_AcquireLock()} are not
2546available. (This is done so that dynamically loaded extensions
2547compiled with thread support enabled can be loaded by an interpreter
2548that was compiled with disabled thread support.)
2549
2550The global interpreter lock is used to protect the pointer to the
2551current thread state. When releasing the lock and saving the thread
2552state, the current thread state pointer must be retrieved before the
2553lock is released (since another thread could immediately acquire the
2554lock and store its own thread state in the global variable).
2555Reversely, when acquiring the lock and restoring the thread state, the
2556lock must be acquired before storing the thread state pointer.
2557
2558Why am I going on with so much detail about this? Because when
Fred Drakeb0a78731998-01-13 18:51:10 +00002559threads are created from \C{}, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002560lock, nor is there a thread state data structure for them. Such
2561threads must bootstrap themselves into existence, by first creating a
2562thread state data structure, then acquiring the lock, and finally
2563storing their thread state pointer, before they can start using the
2564Python/C API. When they are done, they should reset the thread state
2565pointer, release the lock, and finally free their thread state data
2566structure.
2567
2568When creating a thread data structure, you need to provide an
2569interpreter state data structure. The interpreter state data
2570structure hold global data that is shared by all threads in an
2571interpreter, for example the module administration
2572(\code{sys.modules}). Depending on your needs, you can either create
2573a new interpreter state data structure, or share the interpreter state
2574data structure used by the Python main thread (to access the latter,
2575you must obtain the thread state and access its \code{interp} member;
2576this must be done by a thread that is created by Python or by the main
2577thread after Python is initialized).
2578
2579XXX More?
2580
2581\begin{ctypedesc}{PyInterpreterState}
2582\strong{(NEW in 1.5a3!)}
2583This data structure represents the state shared by a number of
2584cooperating threads. Threads belonging to the same interpreter
2585share their module administration and a few other internal items.
2586There are no public members in this structure.
2587
2588Threads belonging to different interpreters initially share nothing,
2589except process state like available memory, open file descriptors and
2590such. The global interpreter lock is also shared by all threads,
2591regardless of to which interpreter they belong.
2592\end{ctypedesc}
2593
2594\begin{ctypedesc}{PyThreadState}
2595\strong{(NEW in 1.5a3!)}
2596This data structure represents the state of a single thread. The only
2597public data member is \code{PyInterpreterState *interp}, which points
2598to this thread's interpreter state.
2599\end{ctypedesc}
2600
2601\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
2602Initialize and acquire the global interpreter lock. It should be
2603called in the main thread before creating a second thread or engaging
2604in any other thread operations such as \code{PyEval_ReleaseLock()} or
2605\code{PyEval_ReleaseThread(tstate)}. It is not needed before
2606calling \code{PyEval_SaveThread()} or \code{PyEval_RestoreThread()}.
2607
2608This is a no-op when called for a second time. It is safe to call
2609this function before calling \code{Py_Initialize()}.
2610
2611When only the main thread exists, no lock operations are needed. This
2612is a common situation (most Python programs do not use threads), and
2613the lock operations slow the interpreter down a bit. Therefore, the
2614lock is not created initially. This situation is equivalent to having
2615acquired the lock: when there is only a single thread, all object
2616accesses are safe. Therefore, when this function initializes the
2617lock, it also acquires it. Before the Python \code{thread} module
2618creates a new thread, knowing that either it has the lock or the lock
2619hasn't been created yet, it calls \code{PyEval_InitThreads()}. When
2620this call returns, it is guaranteed that the lock has been created and
2621that it has acquired it.
2622
2623It is \strong{not} safe to call this function when it is unknown which
2624thread (if any) currently has the global interpreter lock.
2625
2626This function is not available when thread support is disabled at
2627compile time.
2628\end{cfuncdesc}
2629
Guido van Rossum4a944d71997-08-14 20:35:38 +00002630\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002631\strong{(NEW in 1.5a3!)}
2632Acquire the global interpreter lock. The lock must have been created
2633earlier. If this thread already has the lock, a deadlock ensues.
2634This function is not available when thread support is disabled at
2635compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002636\end{cfuncdesc}
2637
2638\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002639\strong{(NEW in 1.5a3!)}
2640Release the global interpreter lock. The lock must have been created
2641earlier. This function is not available when thread support is
2642disabled at
2643compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002644\end{cfuncdesc}
2645
2646\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002647\strong{(NEW in 1.5a3!)}
2648Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002649state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002650have been created earlier. If this thread already has the lock,
2651deadlock ensues. This function is not available when thread support
2652is disabled at
2653compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002654\end{cfuncdesc}
2655
2656\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002657\strong{(NEW in 1.5a3!)}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002658Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002659interpreter lock. The lock must have been created earlier and must be
2660held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002661be \NULL{}, is only used to check that it represents the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002662thread state -- if it isn't, a fatal error is reported. This function
2663is not available when thread support is disabled at
2664compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002665\end{cfuncdesc}
2666
2667\begin{cfuncdesc}{PyThreadState *}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002668\strong{(Different return type in 1.5a3!)}
2669Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002670support is enabled) and reset the thread state to \NULL{},
2671returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002672the lock has been created, the current thread must have acquired it.
2673(This function is available even when thread support is disabled at
2674compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002675\end{cfuncdesc}
2676
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002677\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
2678\strong{(Different argument type in 1.5a3!)}
2679Acquire the interpreter lock (if it has been created and thread
2680support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002681must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002682thread must not have acquired it, otherwise deadlock ensues. (This
2683function is available even when thread support is disabled at compile
2684time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002685\end{cfuncdesc}
2686
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002687% XXX These aren't really C types, but the ctypedesc macro is the simplest!
2688\begin{ctypedesc}{Py_BEGIN_ALLOW_THREADS}
2689This macro expands to
2690\code{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
2691Note that it contains an opening brace; it must be matched with a
2692following \code{Py_END_ALLOW_THREADS} macro. See above for further
2693discussion of this macro. It is a no-op when thread support is
2694disabled at compile time.
2695\end{ctypedesc}
2696
2697\begin{ctypedesc}{Py_END_ALLOW_THREADS}
2698This macro expands to
2699\code{PyEval_RestoreThread(_save); \} }.
2700Note that it contains a closing brace; it must be matched with an
2701earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
2702discussion of this macro. It is a no-op when thread support is
2703disabled at compile time.
2704\end{ctypedesc}
2705
2706\begin{ctypedesc}{Py_BEGIN_BLOCK_THREADS}
2707This macro expands to \code{PyEval_RestoreThread(_save);} i.e. it
2708is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
2709brace. It is a no-op when thread support is disabled at compile
2710time.
2711\end{ctypedesc}
2712
2713\begin{ctypedesc}{Py_BEGIN_UNBLOCK_THREADS}
2714This macro expands to \code{_save = PyEval_SaveThread();} i.e. it is
2715equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
2716and variable declaration. It is a no-op when thread support is
2717disabled at compile time.
2718\end{ctypedesc}
2719
2720All of the following functions are only available when thread support
2721is enabled at compile time, and must be called only when the
2722interpreter lock has been created. They are all new in 1.5a3.
2723
2724\begin{cfuncdesc}{PyInterpreterState *}{PyInterpreterState_New}{}
2725Create a new interpreter state object. The interpreter lock must be
2726held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002727\end{cfuncdesc}
2728
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002729\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
2730Reset all information in an interpreter state object. The interpreter
2731lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002732\end{cfuncdesc}
2733
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002734\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
2735Destroy an interpreter state object. The interpreter lock need not be
2736held. The interpreter state must have been reset with a previous
2737call to \code{PyInterpreterState_Clear()}.
2738\end{cfuncdesc}
2739
2740\begin{cfuncdesc}{PyThreadState *}{PyThreadState_New}{PyInterpreterState *interp}
2741Create a new thread state object belonging to the given interpreter
2742object. The interpreter lock must be held.
2743\end{cfuncdesc}
2744
2745\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
2746Reset all information in a thread state object. The interpreter lock
2747must be held.
2748\end{cfuncdesc}
2749
2750\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
2751Destroy a thread state object. The interpreter lock need not be
2752held. The thread state must have been reset with a previous
2753call to \code{PyThreadState_Clear()}.
2754\end{cfuncdesc}
2755
2756\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Get}{}
2757Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002758When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00002759error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002760\end{cfuncdesc}
2761
2762\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Swap}{PyThreadState *tstate}
2763Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002764argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002765must be held.
2766\end{cfuncdesc}
2767
2768
2769\section{Defining New Object Types}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002770
Guido van Rossumae110af1997-05-22 20:11:52 +00002771XXX To be done:
2772
2773PyObject, PyVarObject
2774
2775PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
2776
2777Typedefs:
2778unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
2779intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
2780getreadbufferproc, getwritebufferproc, getsegcountproc,
2781destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
2782setattrofunc, cmpfunc, reprfunc, hashfunc
2783
2784PyNumberMethods
2785
2786PySequenceMethods
2787
2788PyMappingMethods
2789
2790PyBufferProcs
2791
2792PyTypeObject
2793
2794DL_IMPORT
2795
2796PyType_Type
2797
2798Py*_Check
2799
2800Py_None, _Py_NoneStruct
2801
2802_PyObject_New, _PyObject_NewVar
2803
2804PyObject_NEW, PyObject_NEW_VAR
2805
2806
Fred Drakee5bf8b21998-02-12 21:22:28 +00002807\chapter{Defining New Object Types}
Guido van Rossumae110af1997-05-22 20:11:52 +00002808
Fred Drakee5bf8b21998-02-12 21:22:28 +00002809\begin{cfuncdesc}{PyObject *}{_PyObject_New}{PyTypeObject *type}
Guido van Rossumae110af1997-05-22 20:11:52 +00002810\end{cfuncdesc}
2811
Fred Drakee5bf8b21998-02-12 21:22:28 +00002812\begin{cfuncdesc}{PyObject *}{_PyObject_NewVar}{PyTypeObject *type, int size}
Guido van Rossumae110af1997-05-22 20:11:52 +00002813\end{cfuncdesc}
2814
Fred Drakee5bf8b21998-02-12 21:22:28 +00002815\begin{cfuncdesc}{TYPE}{_PyObject_NEW}{TYPE, PyTypeObject *}
Guido van Rossumae110af1997-05-22 20:11:52 +00002816\end{cfuncdesc}
2817
Fred Drakee5bf8b21998-02-12 21:22:28 +00002818\begin{cfuncdesc}{TYPE}{_PyObject_NEW_VAR}{TYPE, PyTypeObject *, int size}
Guido van Rossumae110af1997-05-22 20:11:52 +00002819\end{cfuncdesc}
2820
Guido van Rossumae110af1997-05-22 20:11:52 +00002821
Fred Drakee5bf8b21998-02-12 21:22:28 +00002822\chapter{Debugging}
Guido van Rossumae110af1997-05-22 20:11:52 +00002823
Fred Drakee5bf8b21998-02-12 21:22:28 +00002824XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
Guido van Rossum5b8a5231997-12-30 04:38:44 +00002825
2826
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002827\input{api.ind} % Index -- must be last
2828
2829\end{document}