blob: 780034a7879e6e0bc5bb4e35f35cda8213b9454f [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
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000526\chapter{Basic Utilities}
Guido van Rossum4a944d71997-08-14 20:35:38 +0000527
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000528XXX These utilities should be moved to some other section...
Guido van Rossum4a944d71997-08-14 20:35:38 +0000529
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000530\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
531Print a fatal error message and kill the process. No cleanup is
532performed. This function should only be invoked when a condition is
533detected that would make it dangerous to continue using the Python
534interpreter; e.g., when the object administration appears to be
Fred Drakeb0a78731998-01-13 18:51:10 +0000535corrupted. On \UNIX{}, the standard \C{} library function \code{abort()} is
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000536called which will attempt to produce a \file{core} file.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000537\end{cfuncdesc}
538
539\begin{cfuncdesc}{void}{Py_Exit}{int status}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000540Exit the current process. This calls \code{Py_Finalize()} and then
Fred Drakefaa1afe1998-02-12 20:51:02 +0000541calls the standard \C{} library function \code{exit(\var{status})}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000542\end{cfuncdesc}
543
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000544\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
Fred Drakec6c921a1998-01-26 19:16:27 +0000545Register a cleanup function to be called by \cfunction{Py_Finalize()}.
546The cleanup function will be called with no arguments and should
547return no value. At most 32 cleanup functions can be registered.
548When the registration is successful, \cfunction{Py_AtExit()} returns
549\code{0}; on failure, it returns \code{-1}. The cleanup function
550registered last is called first. Each cleanup function will be called
551at most once. Since Python's internal finallization will have
552completed before the cleanup function, no Python APIs should be called
553by \var{func}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000554\end{cfuncdesc}
555
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000556
557\chapter{Reference Counting}
558
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000559The macros in this section are used for managing reference counts
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000560of Python objects.
561
562\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
563Increment the reference count for object \code{o}. The object must
564not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
565\code{Py_XINCREF()}.
566\end{cfuncdesc}
567
568\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
569Increment the reference count for object \code{o}. The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000570\NULL{}, in which case the macro has no effect.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000571\end{cfuncdesc}
572
573\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
574Decrement the reference count for object \code{o}. The object must
575not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
576\code{Py_XDECREF()}. If the reference count reaches zero, the object's
577type's deallocation function (which must not be \NULL{}) is invoked.
578
579\strong{Warning:} The deallocation function can cause arbitrary Python
580code to be invoked (e.g. when a class instance with a \code{__del__()}
581method is deallocated). While exceptions in such code are not
582propagated, the executed code has free access to all Python global
583variables. This means that any object that is reachable from a global
584variable should be in a consistent state before \code{Py_DECREF()} is
585invoked. For example, code to delete an object from a list should
586copy a reference to the deleted object in a temporary variable, update
587the list data structure, and then call \code{Py_DECREF()} for the
588temporary variable.
589\end{cfuncdesc}
590
591\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
592Decrement the reference count for object \code{o}.The object may be
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000593\NULL{}, in which case the macro has no effect; otherwise the
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000594effect is the same as for \code{Py_DECREF()}, and the same warning
595applies.
596\end{cfuncdesc}
597
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000598The following functions or macros are only for internal use:
Guido van Rossumae110af1997-05-22 20:11:52 +0000599\code{_Py_Dealloc}, \code{_Py_ForgetReference}, \code{_Py_NewReference},
600as well as the global variable \code{_Py_RefTotal}.
601
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000602XXX Should mention Py_Malloc(), Py_Realloc(), Py_Free(),
603PyMem_Malloc(), PyMem_Realloc(), PyMem_Free(), PyMem_NEW(),
604PyMem_RESIZE(), PyMem_DEL(), PyMem_XDEL().
605
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000606
607\chapter{Exception Handling}
608
609The functions in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000610exceptions. It is important to understand some of the basics of
Fred Drakeb0a78731998-01-13 18:51:10 +0000611Python exception handling. It works somewhat like the \UNIX{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000612\code{errno} variable: there is a global indicator (per thread) of the
613last error that occurred. Most functions don't clear this on success,
614but will set it to indicate the cause of the error on failure. Most
615functions also return an error indicator, usually \NULL{} if they are
616supposed to return a pointer, or -1 if they return an integer
617(exception: the \code{PyArg_Parse*()} functions return 1 for success and
Guido van Rossum5b8a5231997-12-30 04:38:44 +00006180 for failure). When a function must fail because some function it
Guido van Rossumae110af1997-05-22 20:11:52 +0000619called failed, it generally doesn't set the error indicator; the
620function it called already set it.
621
622The error indicator consists of three Python objects corresponding to
623the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
624\code{sys.exc_traceback}. API functions exist to interact with the
625error indicator in various ways. There is a separate error indicator
626for each thread.
627
628% XXX Order of these should be more thoughtful.
629% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000630
631\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000632Print a standard traceback to \code{sys.stderr} and clear the error
633indicator. Call this function only when the error indicator is set.
634(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000635\end{cfuncdesc}
636
Guido van Rossumae110af1997-05-22 20:11:52 +0000637\begin{cfuncdesc}{PyObject *}{PyErr_Occurred}{}
638Test whether the error indicator is set. If set, return the exception
639\code{type} (the first argument to the last call to one of the
640\code{PyErr_Set*()} functions or to \code{PyErr_Restore()}). If not
641set, return \NULL{}. You do not own a reference to the return value,
Guido van Rossum42cefd01997-10-05 15:27:29 +0000642so you do not need to \code{Py_DECREF()} it. Note: do not compare the
643return value to a specific exception; use
644\code{PyErr_ExceptionMatches} instead, shown below.
645\end{cfuncdesc}
646
647\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000648\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000649Equivalent to
650\code{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
651This should only be called when an exception is actually set.
652\end{cfuncdesc}
653
654\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000655\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000656Return true if the \var{given} exception matches the exception in
657\var{exc}. If \var{exc} is a class object, this also returns true
658when \var{given} is a subclass. If \var{exc} is a tuple, all
659exceptions in the tuple (and recursively in subtuples) are searched
660for a match. This should only be called when an exception is actually
661set.
662\end{cfuncdesc}
663
664\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000665\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000666Under certain circumstances, the values returned by
667\code{PyErr_Fetch()} below can be ``unnormalized'', meaning that
668\var{*exc} is a class object but \var{*val} is not an instance of the
669same class. This function can be used to instantiate the class in
670that case. If the values are already normalized, nothing happens.
Guido van Rossumae110af1997-05-22 20:11:52 +0000671\end{cfuncdesc}
672
673\begin{cfuncdesc}{void}{PyErr_Clear}{}
674Clear the error indicator. If the error indicator is not set, there
675is no effect.
676\end{cfuncdesc}
677
678\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue, PyObject **ptraceback}
679Retrieve the error indicator into three variables whose addresses are
680passed. If the error indicator is not set, set all three variables to
681\NULL{}. If it is set, it will be cleared and you own a reference to
682each object retrieved. The value and traceback object may be \NULL{}
683even when the type object is not. \strong{Note:} this function is
684normally only used by code that needs to handle exceptions or by code
685that needs to save and restore the error indicator temporarily.
686\end{cfuncdesc}
687
688\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value, PyObject *traceback}
689Set the error indicator from the three objects. If the error
690indicator is already set, it is cleared first. If the objects are
691\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
692and non-\NULL{} value or traceback. The exception type should be a
693string or class; if it is a class, the value should be an instance of
694that class. Do not pass an invalid exception type or value.
695(Violating these rules will cause subtle problems later.) This call
696takes away a reference to each object, i.e. you must own a reference
697to each object before the call and after the call you no longer own
698these references. (If you don't understand this, don't use this
699function. I warned you.) \strong{Note:} this function is normally
700only used by code that needs to save and restore the error indicator
701temporarily.
702\end{cfuncdesc}
703
704\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
705This is the most common way to set the error indicator. The first
706argument specifies the exception type; it is normally one of the
707standard exceptions, e.g. \code{PyExc_RuntimeError}. You need not
708increment its reference count. The second argument is an error
709message; it is converted to a string object.
710\end{cfuncdesc}
711
712\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
713This function is similar to \code{PyErr_SetString()} but lets you
714specify an arbitrary Python object for the ``value'' of the exception.
715You need not increment its reference count.
716\end{cfuncdesc}
717
718\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
719This is a shorthand for \code{PyErr_SetString(\var{type}, Py_None}.
720\end{cfuncdesc}
721
722\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
723This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
724\var{message})}, where \var{message} indicates that a built-in operation
725was invoked with an illegal argument. It is mostly for internal use.
726\end{cfuncdesc}
727
728\begin{cfuncdesc}{PyObject *}{PyErr_NoMemory}{}
729This is a shorthand for \code{PyErr_SetNone(PyExc_MemoryError)}; it
730returns \NULL{} so an object allocation function can write
731\code{return PyErr_NoMemory();} when it runs out of memory.
732\end{cfuncdesc}
733
734\begin{cfuncdesc}{PyObject *}{PyErr_SetFromErrno}{PyObject *type}
Fred Drakeb0a78731998-01-13 18:51:10 +0000735This is a convenience function to raise an exception when a \C{} library
736function has returned an error and set the \C{} variable \code{errno}.
Guido van Rossumae110af1997-05-22 20:11:52 +0000737It constructs a tuple object whose first item is the integer
738\code{errno} value and whose second item is the corresponding error
739message (gotten from \code{strerror()}), and then calls
740\code{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
741the \code{errno} value is \code{EINTR}, indicating an interrupted
742system call, this calls \code{PyErr_CheckSignals()}, and if that set
743the error indicator, leaves it set to that. The function always
744returns \NULL{}, so a wrapper function around a system call can write
745\code{return PyErr_NoMemory();} when the system call returns an error.
746\end{cfuncdesc}
747
748\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
749This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
750\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000751operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000752argument. It is mostly for internal use.
753\end{cfuncdesc}
754
755\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
756This function interacts with Python's signal handling. It checks
757whether a signal has been sent to the processes and if so, invokes the
758corresponding signal handler. If the \code{signal} module is
759supported, this can invoke a signal handler written in Python. In all
760cases, the default effect for \code{SIGINT} is to raise the
761\code{KeyboadInterrupt} exception. If an exception is raised the
762error indicator is set and the function returns 1; otherwise the
763function returns 0. The error indicator may or may not be cleared if
764it was previously set.
765\end{cfuncdesc}
766
767\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
768This function is obsolete (XXX or platform dependent?). It simulates
769the effect of a \code{SIGINT} signal arriving -- the next time
770\code{PyErr_CheckSignals()} is called, \code{KeyboadInterrupt} will be
771raised.
772\end{cfuncdesc}
773
Guido van Rossum42cefd01997-10-05 15:27:29 +0000774\begin{cfuncdesc}{PyObject *}{PyErr_NewException}{char *name,
775PyObject *base, PyObject *dict}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000776\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000777This utility function creates and returns a new exception object. The
Fred Drakeb0a78731998-01-13 18:51:10 +0000778\var{name} argument must be the name of the new exception, a \C{} string
Guido van Rossum42cefd01997-10-05 15:27:29 +0000779of the form \code{module.class}. The \var{base} and \var{dict}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000780arguments are normally \NULL{}. Normally, this creates a class
Guido van Rossum42cefd01997-10-05 15:27:29 +0000781object derived from the root for all exceptions, the built-in name
Fred Drakeb0a78731998-01-13 18:51:10 +0000782\code{Exception} (accessible in \C{} as \code{PyExc_Exception}). In this
Guido van Rossum42cefd01997-10-05 15:27:29 +0000783case the \code{__module__} attribute of the new class is set to the
784first part (up to the last dot) of the \var{name} argument, and the
785class name is set to the last part (after the last dot). When the
786user has specified the \code{-X} command line option to use string
787exceptions, for backward compatibility, or when the \var{base}
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000788argument is not a class object (and not \NULL{}), a string object
Guido van Rossum42cefd01997-10-05 15:27:29 +0000789created from the entire \var{name} argument is returned. The
790\var{base} argument can be used to specify an alternate base class.
791The \var{dict} argument can be used to specify a dictionary of class
792variables and methods.
793\end{cfuncdesc}
794
795
Guido van Rossumae110af1997-05-22 20:11:52 +0000796\section{Standard Exceptions}
797
798All standard Python exceptions are available as global variables whose
799names are \code{PyExc_} followed by the Python exception name.
800These have the type \code{PyObject *}; they are all string objects.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000801For completeness, here are all the variables (the first four are new
802in Python 1.5a4):
803\code{PyExc_Exception},
804\code{PyExc_StandardError},
805\code{PyExc_ArithmeticError},
806\code{PyExc_LookupError},
Guido van Rossumae110af1997-05-22 20:11:52 +0000807\code{PyExc_AssertionError},
808\code{PyExc_AttributeError},
809\code{PyExc_EOFError},
810\code{PyExc_FloatingPointError},
811\code{PyExc_IOError},
812\code{PyExc_ImportError},
813\code{PyExc_IndexError},
814\code{PyExc_KeyError},
815\code{PyExc_KeyboardInterrupt},
816\code{PyExc_MemoryError},
817\code{PyExc_NameError},
818\code{PyExc_OverflowError},
819\code{PyExc_RuntimeError},
820\code{PyExc_SyntaxError},
821\code{PyExc_SystemError},
822\code{PyExc_SystemExit},
823\code{PyExc_TypeError},
824\code{PyExc_ValueError},
825\code{PyExc_ZeroDivisionError}.
826
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000827
828\chapter{Utilities}
829
830The functions in this chapter perform various utility tasks, such as
Fred Drakeb0a78731998-01-13 18:51:10 +0000831parsing function arguments and constructing Python values from \C{}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000832values.
833
Guido van Rossum42cefd01997-10-05 15:27:29 +0000834\section{OS Utilities}
835
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000836\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
837Return true (nonzero) if the standard I/O file \code{fp} with name
838\code{filename} is deemed interactive. This is the case for files for
839which \code{isatty(fileno(fp))} is true. If the global flag
840\code{Py_InteractiveFlag} is true, this function also returns true if
841the \code{name} pointer is \NULL{} or if the name is equal to one of
842the strings \code{"<stdin>"} or \code{"???"}.
843\end{cfuncdesc}
844
845\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
846Return the time of last modification of the file \code{filename}.
847The result is encoded in the same way as the timestamp returned by
Fred Drakeb0a78731998-01-13 18:51:10 +0000848the standard \C{} library function \code{time()}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000849\end{cfuncdesc}
850
851
Guido van Rossum42cefd01997-10-05 15:27:29 +0000852\section{Importing modules}
853
854\begin{cfuncdesc}{PyObject *}{PyImport_ImportModule}{char *name}
855This is a simplified interface to \code{PyImport_ImportModuleEx}
856below, leaving the \var{globals} and \var{locals} arguments set to
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000857\NULL{}. When the \var{name} argument contains a dot (i.e., when
Guido van Rossum42cefd01997-10-05 15:27:29 +0000858it specifies a submodule of a package), the \var{fromlist} argument is
859set to the list \code{['*']} so that the return value is the named
860module rather than the top-level package containing it as would
861otherwise be the case. (Unfortunately, this has an additional side
862effect when \var{name} in fact specifies a subpackage instead of a
863submodule: the submodules specified in the package's \code{__all__}
864variable are loaded.) Return a new reference to the imported module,
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000865or \NULL{} with an exception set on failure (the module may still
Guido van Rossum42cefd01997-10-05 15:27:29 +0000866be created in this case).
867\end{cfuncdesc}
868
869\begin{cfuncdesc}{PyObject *}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000870\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000871Import a module. This is best described by referring to the built-in
872Python function \code{__import()__}, as the standard
873\code{__import__()} function calls this function directly.
874
Guido van Rossum42cefd01997-10-05 15:27:29 +0000875The return value is a new reference to the imported module or
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000876top-level package, or \NULL{} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000877(the module may still be created in this case). Like for
878\code{__import__()}, the return value when a submodule of a package
879was requested is normally the top-level package, unless a non-empty
880\var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000881\end{cfuncdesc}
882
883\begin{cfuncdesc}{PyObject *}{PyImport_Import}{PyObject *name}
884This is a higher-level interface that calls the current ``import hook
885function''. It invokes the \code{__import__()} function from the
886\code{__builtins__} of the current globals. This means that the
887import is done using whatever import hooks are installed in the
888current environment, e.g. by \code{rexec} or \code{ihooks}.
889\end{cfuncdesc}
890
891\begin{cfuncdesc}{PyObject *}{PyImport_ReloadModule}{PyObject *m}
892Reload a module. This is best described by referring to the built-in
893Python function \code{reload()}, as the standard \code{reload()}
894function calls this function directly. Return a new reference to the
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000895reloaded module, or \NULL{} with an exception set on failure (the
Guido van Rossum42cefd01997-10-05 15:27:29 +0000896module still exists in this case).
897\end{cfuncdesc}
898
899\begin{cfuncdesc}{PyObject *}{PyImport_AddModule}{char *name}
900Return the module object corresponding to a module name. The
901\var{name} argument may be of the form \code{package.module}). First
902check the modules dictionary if there's one there, and if not, create
903a new one and insert in in the modules dictionary. Because the former
904action is most common, this does not return a new reference, and you
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000905do not own the returned reference. Return \NULL{} with an
Guido van Rossum42cefd01997-10-05 15:27:29 +0000906exception set on failure.
907\end{cfuncdesc}
908
909\begin{cfuncdesc}{PyObject *}{PyImport_ExecCodeModule}{char *name, PyObject *co}
910Given a module name (possibly of the form \code{package.module}) and a
911code object read from a Python bytecode file or obtained from the
912built-in function \code{compile()}, load the module. Return a new
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000913reference to the module object, or \NULL{} with an exception set
Guido van Rossum42cefd01997-10-05 15:27:29 +0000914if an error occurred (the module may still be created in this case).
915(This function would reload the module if it was already imported.)
916\end{cfuncdesc}
917
918\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
919Return the magic number for Python bytecode files (a.k.a. \code{.pyc}
920and \code{.pyo} files). The magic number should be present in the
921first four bytes of the bytecode file, in little-endian byte order.
922\end{cfuncdesc}
923
924\begin{cfuncdesc}{PyObject *}{PyImport_GetModuleDict}{}
925Return the dictionary used for the module administration
926(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
927variable.
928\end{cfuncdesc}
929
930\begin{cfuncdesc}{void}{_PyImport_Init}{}
931Initialize the import mechanism. For internal use only.
932\end{cfuncdesc}
933
934\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
935Empty the module table. For internal use only.
936\end{cfuncdesc}
937
938\begin{cfuncdesc}{void}{_PyImport_Fini}{}
939Finalize the import mechanism. For internal use only.
940\end{cfuncdesc}
941
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000942\begin{cfuncdesc}{extern PyObject *}{_PyImport_FindExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000943For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000944\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000945
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000946\begin{cfuncdesc}{extern PyObject *}{_PyImport_FixupExtension}{char *, char *}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000947For internal use only.
Guido van Rossum5b8a5231997-12-30 04:38:44 +0000948\end{cfuncdesc}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000949
950\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *}
951Load a frozen module. Return \code{1} for success, \code{0} if the
952module is not found, and \code{-1} with an exception set if the
953initialization failed. To access the imported module on a successful
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000954load, use \code{PyImport_ImportModule())}.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000955(Note the misnomer -- this function would reload the module if it was
956already imported.)
957\end{cfuncdesc}
958
959\begin{ctypedesc}{struct _frozen}
960This is the structure type definition for frozen module descriptors,
961as generated by the \code{freeze} utility (see \file{Tools/freeze/} in
962the Python source distribution). Its definition is:
Guido van Rossum9faf4c51997-10-07 14:38:54 +0000963\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000964struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +0000965 char *name;
966 unsigned char *code;
967 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +0000968};
Guido van Rossum9faf4c51997-10-07 14:38:54 +0000969\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000970\end{ctypedesc}
971
972\begin{cvardesc}{struct _frozen *}{PyImport_FrozenModules}
973This pointer is initialized to point to an array of \code{struct
Guido van Rossum580aa8d1997-11-25 15:34:51 +0000974_frozen} records, terminated by one whose members are all \NULL{}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000975or zero. When a frozen module is imported, it is searched in this
976table. Third party code could play tricks with this to provide a
977dynamically created collection of frozen modules.
978\end{cvardesc}
979
980
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000981\chapter{Debugging}
982
983XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
984
985
986\chapter{The Very High Level Layer}
987
988The functions in this chapter will let you execute Python source code
989given in a file or a buffer, but they will not let you interact in a
990more detailed way with the interpreter.
991
Guido van Rossumae110af1997-05-22 20:11:52 +0000992\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *, char *}
993\end{cfuncdesc}
994
995\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *}
996\end{cfuncdesc}
997
998\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *, char *}
999\end{cfuncdesc}
1000
1001\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *, char *}
1002\end{cfuncdesc}
1003
1004\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *, char *}
1005\end{cfuncdesc}
1006
1007\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseString}{char *, int}
1008\end{cfuncdesc}
1009
1010\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseFile}{FILE *, char *, int}
1011\end{cfuncdesc}
1012
Fred Drake85a5c521998-01-02 03:24:19 +00001013\begin{cfuncdesc}{PyObject *}{PyRun_String}{char *, int, PyObject *, PyObject *}
Guido van Rossumae110af1997-05-22 20:11:52 +00001014\end{cfuncdesc}
1015
Fred Drake85a5c521998-01-02 03:24:19 +00001016\begin{cfuncdesc}{PyObject *}{PyRun_File}{FILE *, char *, int, PyObject *, PyObject *}
Guido van Rossumae110af1997-05-22 20:11:52 +00001017\end{cfuncdesc}
1018
Fred Drake85a5c521998-01-02 03:24:19 +00001019\begin{cfuncdesc}{PyObject *}{Py_CompileString}{char *, char *, int}
Guido van Rossumae110af1997-05-22 20:11:52 +00001020\end{cfuncdesc}
1021
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001022
1023\chapter{Abstract Objects Layer}
1024
1025The functions in this chapter interact with Python objects regardless
1026of their type, or with wide classes of object types (e.g. all
1027numerical types, or all sequence types). When used on object types
1028for which they do not apply, they will flag a Python exception.
1029
1030\section{Object Protocol}
1031
1032\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
1033Print an object \code{o}, on file \code{fp}. Returns -1 on error
1034The flags argument is used to enable certain printing
1035options. The only option currently supported is \code{Py_Print_RAW}.
1036\end{cfuncdesc}
1037
1038\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
1039Returns 1 if o has the attribute attr_name, and 0 otherwise.
1040This is equivalent to the Python expression:
1041\code{hasattr(o,attr_name)}.
1042This function always succeeds.
1043\end{cfuncdesc}
1044
1045\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o, char *attr_name}
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001046Retrieve an attribute named attr_name from object o.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001047Returns the attribute value on success, or \NULL{} on failure.
1048This is the equivalent of the Python expression: \code{o.attr_name}.
1049\end{cfuncdesc}
1050
1051
1052\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
1053Returns 1 if o has the attribute attr_name, and 0 otherwise.
1054This is equivalent to the Python expression:
1055\code{hasattr(o,attr_name)}.
1056This function always succeeds.
1057\end{cfuncdesc}
1058
1059
1060\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o, PyObject *attr_name}
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001061Retrieve an attribute named attr_name from object o.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001062Returns the attribute value on success, or \NULL{} on failure.
1063This is the equivalent of the Python expression: o.attr_name.
1064\end{cfuncdesc}
1065
1066
1067\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
1068Set the value of the attribute named \code{attr_name}, for object \code{o},
1069to the value \code{v}. Returns -1 on failure. This is
1070the equivalent of the Python statement: \code{o.attr_name=v}.
1071\end{cfuncdesc}
1072
1073
1074\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
1075Set the value of the attribute named \code{attr_name}, for
1076object \code{o},
1077to the value \code{v}. Returns -1 on failure. This is
1078the equivalent of the Python statement: \code{o.attr_name=v}.
1079\end{cfuncdesc}
1080
1081
1082\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *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_DelAttr}{PyObject *o, PyObject *attr_name}
1090Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1091failure. This is the equivalent of the Python
1092statement: \code{del o.attr_name}.
1093\end{cfuncdesc}
1094
1095
1096\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
1097Compare the values of \code{o1} and \code{o2} using a routine provided by
1098\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1099The result of the comparison is returned in \code{result}. Returns
1100-1 on failure. This is the equivalent of the Python
1101statement: \code{result=cmp(o1,o2)}.
1102\end{cfuncdesc}
1103
1104
1105\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
1106Compare the values of \code{o1} and \code{o2} using a routine provided by
1107\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1108Returns the result of the comparison on success. On error,
1109the value returned is undefined. This is equivalent to the
1110Python expression: \code{cmp(o1,o2)}.
1111\end{cfuncdesc}
1112
1113
1114\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
1115Compute the string representation of object, \code{o}. Returns the
1116string representation on success, \NULL{} on failure. This is
1117the equivalent of the Python expression: \code{repr(o)}.
1118Called by the \code{repr()} built-in function and by reverse quotes.
1119\end{cfuncdesc}
1120
1121
1122\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
1123Compute the string representation of object, \code{o}. Returns the
1124string representation on success, \NULL{} on failure. This is
1125the equivalent of the Python expression: \code{str(o)}.
1126Called by the \code{str()} built-in function and by the \code{print}
1127statement.
1128\end{cfuncdesc}
1129
1130
1131\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
1132Determine if the object \code{o}, is callable. Return 1 if the
1133object is callable and 0 otherwise.
1134This function always succeeds.
1135\end{cfuncdesc}
1136
1137
1138\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object, PyObject *args}
1139Call a callable Python object \code{callable_object}, with
1140arguments given by the tuple \code{args}. If no arguments are
1141needed, then args may be \NULL{}. Returns the result of the
1142call on success, or \NULL{} on failure. This is the equivalent
1143of the Python expression: \code{apply(o, args)}.
1144\end{cfuncdesc}
1145
1146\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
1147Call a callable Python object \code{callable_object}, with a
Fred Drakeb0a78731998-01-13 18:51:10 +00001148variable number of \C{} arguments. The \C{} arguments are described
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001149using a mkvalue-style format string. The format may be \NULL{},
1150indicating that no arguments are provided. Returns the
1151result of the call on success, or \NULL{} on failure. This is
1152the equivalent of the Python expression: \code{apply(o,args)}.
1153\end{cfuncdesc}
1154
1155
1156\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
1157Call the method named \code{m} of object \code{o} with a variable number of
Fred Drakeb0a78731998-01-13 18:51:10 +00001158C arguments. The \C{} arguments are described by a mkvalue
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001159format string. The format may be \NULL{}, indicating that no
1160arguments are provided. Returns the result of the call on
1161success, or \NULL{} on failure. This is the equivalent of the
1162Python expression: \code{o.method(args)}.
1163Note that Special method names, such as "\code{__add__}",
1164"\code{__getitem__}", and so on are not supported. The specific
1165abstract-object routines for these must be used.
1166\end{cfuncdesc}
1167
1168
1169\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
1170Compute and return the hash value of an object \code{o}. On
1171failure, return -1. This is the equivalent of the Python
1172expression: \code{hash(o)}.
1173\end{cfuncdesc}
1174
1175
1176\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
1177Returns 1 if the object \code{o} is considered to be true, and
11780 otherwise. This is equivalent to the Python expression:
1179\code{not not o}.
1180This function always succeeds.
1181\end{cfuncdesc}
1182
1183
1184\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1185On success, returns a type object corresponding to the object
1186type of object \code{o}. On failure, returns \NULL{}. This is
1187equivalent to the Python expression: \code{type(o)}.
1188\end{cfuncdesc}
1189
1190\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
1191Return the length of object \code{o}. If the object \code{o} provides
1192both sequence and mapping protocols, the sequence length is
1193returned. On error, -1 is returned. This is the equivalent
1194to the Python expression: \code{len(o)}.
1195\end{cfuncdesc}
1196
1197
1198\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
1199Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1200on failure. This is the equivalent of the Python expression:
1201\code{o[key]}.
1202\end{cfuncdesc}
1203
1204
1205\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
1206Map the object \code{key} to the value \code{v}.
1207Returns -1 on failure. This is the equivalent
1208of the Python statement: \code{o[key]=v}.
1209\end{cfuncdesc}
1210
1211
1212\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key, PyObject *v}
1213Delete the mapping for \code{key} from \code{*o}. Returns -1
1214on failure.
Guido van Rossum59a61351997-08-14 20:34:33 +00001215This is the equivalent of the Python statement: \code{del o[key]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001216\end{cfuncdesc}
1217
1218
1219\section{Number Protocol}
1220
1221\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
1222Returns 1 if the object \code{o} provides numeric protocols, and
1223false otherwise.
1224This function always succeeds.
1225\end{cfuncdesc}
1226
1227
1228\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
1229Returns the result of adding \code{o1} and \code{o2}, or null on failure.
1230This is the equivalent of the Python expression: \code{o1+o2}.
1231\end{cfuncdesc}
1232
1233
1234\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
1235Returns the result of subtracting \code{o2} from \code{o1}, 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_Multiply}{PyObject *o1, PyObject *o2}
1242Returns the result of multiplying \code{o1} and \code{o2}, or null on
1243failure. This is the equivalent of the Python expression:
1244\code{o1*o2}.
1245\end{cfuncdesc}
1246
1247
1248\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
1249Returns the result of dividing \code{o1} by \code{o2}, or null on failure.
1250This is the equivalent of the Python expression: \code{o1/o2}.
1251\end{cfuncdesc}
1252
1253
1254\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
1255Returns the remainder of dividing \code{o1} by \code{o2}, or null on
1256failure. This is the equivalent of the Python expression:
1257\code{o1\%o2}.
1258\end{cfuncdesc}
1259
1260
1261\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
1262See the built-in function divmod. Returns \NULL{} on failure.
1263This is the equivalent of the Python expression:
1264\code{divmod(o1,o2)}.
1265\end{cfuncdesc}
1266
1267
1268\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
1269See the built-in function pow. Returns \NULL{} on failure.
1270This is the equivalent of the Python expression:
1271\code{pow(o1,o2,o3)}, where \code{o3} is optional.
1272\end{cfuncdesc}
1273
1274
1275\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
1276Returns the negation of \code{o} on success, or null on failure.
1277This is the equivalent of the Python expression: \code{-o}.
1278\end{cfuncdesc}
1279
1280
1281\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
1282Returns \code{o} on success, or \NULL{} on failure.
1283This is the equivalent of the Python expression: \code{+o}.
1284\end{cfuncdesc}
1285
1286
1287\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
1288Returns the absolute value of \code{o}, or null on failure. This is
1289the equivalent of the Python expression: \code{abs(o)}.
1290\end{cfuncdesc}
1291
1292
1293\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
1294Returns the bitwise negation of \code{o} on success, or \NULL{} on
1295failure. This is the equivalent of the Python expression:
Guido van Rossum59a61351997-08-14 20:34:33 +00001296\code{\~o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001297\end{cfuncdesc}
1298
1299
1300\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
1301Returns the result of left 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_Rshift}{PyObject *o1, PyObject *o2}
1308Returns the result of right shifting \code{o1} by \code{o2} on success, or
1309\NULL{} on failure. This is the equivalent of the Python
1310expression: \code{o1 >> o2}.
1311\end{cfuncdesc}
1312
1313
1314\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
1315Returns the result of "anding" \code{o2} and \code{o2} on success and \NULL{}
1316on failure. This is the equivalent of the Python
1317expression: \code{o1 and o2}.
1318\end{cfuncdesc}
1319
1320
1321\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
1322Returns the bitwise exclusive or of \code{o1} by \code{o2} on success, or
1323\NULL{} on failure. This is the equivalent of the Python
1324expression: \code{o1\^{ }o2}.
1325\end{cfuncdesc}
1326
1327\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Guido van Rossum59a61351997-08-14 20:34:33 +00001328Returns the result of \code{o1} and \code{o2} on success, or \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001329failure. This is the equivalent of the Python expression:
1330\code{o1 or o2}.
1331\end{cfuncdesc}
1332
1333
1334\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject *o1, PyObject *o2}
1335This function takes the addresses of two variables of type
1336\code{PyObject*}.
1337
1338If the objects pointed to by \code{*p1} and \code{*p2} have the same type,
1339increment their reference count and return 0 (success).
1340If the objects can be converted to a common numeric type,
1341replace \code{*p1} and \code{*p2} by their converted value (with 'new'
1342reference counts), and return 0.
1343If no conversion is possible, or if some other error occurs,
1344return -1 (failure) and don't increment the reference counts.
1345The call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1346statement \code{o1, o2 = coerce(o1, o2)}.
1347\end{cfuncdesc}
1348
1349
1350\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
1351Returns the \code{o} converted to an integer object on success, or
1352\NULL{} on failure. This is the equivalent of the Python
1353expression: \code{int(o)}.
1354\end{cfuncdesc}
1355
1356
1357\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
1358Returns the \code{o} converted to a long integer object on success,
1359or \NULL{} on failure. This is the equivalent of the Python
1360expression: \code{long(o)}.
1361\end{cfuncdesc}
1362
1363
1364\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
1365Returns the \code{o} converted to a float object on success, or \NULL{}
1366on failure. This is the equivalent of the Python expression:
1367\code{float(o)}.
1368\end{cfuncdesc}
1369
1370
Fred Drakef44617d1998-02-12 20:57:15 +00001371\section{Sequence Protocol}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001372
1373\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
1374Return 1 if the object provides sequence protocol, and 0
1375otherwise.
1376This function always succeeds.
1377\end{cfuncdesc}
1378
1379
1380\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
Guido van Rossum5b8a5231997-12-30 04:38:44 +00001381Return the concatenation of \code{o1} and \code{o2} on success, and \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001382failure. This is the equivalent of the Python
1383expression: \code{o1+o2}.
1384\end{cfuncdesc}
1385
1386
1387\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Guido van Rossum59a61351997-08-14 20:34:33 +00001388Return the result of repeating sequence object \code{o} \code{count} times,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001389or \NULL{} on failure. This is the equivalent of the Python
1390expression: \code{o*count}.
1391\end{cfuncdesc}
1392
1393
1394\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
1395Return the ith element of \code{o}, or \NULL{} on failure. This is the
1396equivalent of the Python expression: \code{o[i]}.
1397\end{cfuncdesc}
1398
1399
1400\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
1401Return the slice of sequence object \code{o} between \code{i1} and \code{i2}, or
1402\NULL{} on failure. This is the equivalent of the Python
1403expression, \code{o[i1:i2]}.
1404\end{cfuncdesc}
1405
1406
1407\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
1408Assign object \code{v} to the \code{i}th element of \code{o}.
1409Returns -1 on failure. This is the equivalent of the Python
1410statement, \code{o[i]=v}.
1411\end{cfuncdesc}
1412
1413\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
1414Delete the \code{i}th element of object \code{v}. Returns
1415-1 on failure. This is the equivalent of the Python
1416statement: \code{del o[i]}.
1417\end{cfuncdesc}
1418
1419\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1, int i2, PyObject *v}
1420Assign the sequence object \code{v} to the slice in sequence
1421object \code{o} from \code{i1} to \code{i2}. This is the equivalent of the Python
1422statement, \code{o[i1:i2]=v}.
1423\end{cfuncdesc}
1424
1425\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
1426Delete the slice in sequence object, \code{o}, from \code{i1} to \code{i2}.
1427Returns -1 on failure. This is the equivalent of the Python
1428statement: \code{del o[i1:i2]}.
1429\end{cfuncdesc}
1430
1431\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1432Returns the \code{o} as a tuple on success, and \NULL{} on failure.
1433This is equivalent to the Python expression: \code{tuple(o)}.
1434\end{cfuncdesc}
1435
1436\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
1437Return the number of occurrences of \code{value} on \code{o}, that is,
1438return the number of keys for which \code{o[key]==value}. On
1439failure, return -1. This is equivalent to the Python
1440expression: \code{o.count(value)}.
1441\end{cfuncdesc}
1442
1443\begin{cfuncdesc}{int}{PySequence_In}{PyObject *o, PyObject *value}
1444Determine if \code{o} contains \code{value}. If an item in \code{o} is equal to
1445\code{value}, return 1, otherwise return 0. On error, return -1. This
1446is equivalent to the Python expression: \code{value in o}.
1447\end{cfuncdesc}
1448
1449\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Guido van Rossum59a61351997-08-14 20:34:33 +00001450Return the first index for which \code{o[i]==value}. On error,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001451return -1. This is equivalent to the Python
1452expression: \code{o.index(value)}.
1453\end{cfuncdesc}
1454
Fred Drakef44617d1998-02-12 20:57:15 +00001455\section{Mapping Protocol}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001456
1457\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
1458Return 1 if the object provides mapping protocol, and 0
1459otherwise.
1460This function always succeeds.
1461\end{cfuncdesc}
1462
1463
1464\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
1465Returns the number of keys in object \code{o} on success, and -1 on
1466failure. For objects that do not provide sequence protocol,
1467this is equivalent to the Python expression: \code{len(o)}.
1468\end{cfuncdesc}
1469
1470
1471\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *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_DelItem}{PyObject *o, PyObject *key}
1479Remove the mapping for object \code{key} from the object \code{o}.
1480Return -1 on failure. This is equivalent to
1481the Python statement: \code{del o[key]}.
1482\end{cfuncdesc}
1483
1484
1485\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
1486On success, return 1 if the mapping object has the key \code{key}
1487and 0 otherwise. This is equivalent to the Python expression:
1488\code{o.has_key(key)}.
1489This function always succeeds.
1490\end{cfuncdesc}
1491
1492
1493\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
1494Return 1 if the mapping object has the key \code{key}
1495and 0 otherwise. This is equivalent to the Python expression:
1496\code{o.has_key(key)}.
1497This function always succeeds.
1498\end{cfuncdesc}
1499
1500
1501\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
1502On success, return a list of the keys in object \code{o}. On
1503failure, return \NULL{}. This is equivalent to the Python
1504expression: \code{o.keys()}.
1505\end{cfuncdesc}
1506
1507
1508\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
1509On success, return a list of the values in object \code{o}. On
1510failure, return \NULL{}. This is equivalent to the Python
1511expression: \code{o.values()}.
1512\end{cfuncdesc}
1513
1514
1515\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
1516On success, return a list of the items in object \code{o}, where
1517each item is a tuple containing a key-value pair. On
1518failure, return \NULL{}. This is equivalent to the Python
1519expression: \code{o.items()}.
1520\end{cfuncdesc}
1521
1522\begin{cfuncdesc}{int}{PyMapping_Clear}{PyObject *o}
1523Make object \code{o} empty. Returns 1 on success and 0 on failure.
1524This is equivalent to the Python statement:
1525\code{for key in o.keys(): del o[key]}
1526\end{cfuncdesc}
1527
1528
1529\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
1530Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1531on failure. This is the equivalent of the Python expression:
1532\code{o[key]}.
1533\end{cfuncdesc}
1534
1535\begin{cfuncdesc}{PyObject*}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
1536Map the object \code{key} to the value \code{v} in object \code{o}. Returns
1537-1 on failure. This is the equivalent of the Python
1538statement: \code{o[key]=v}.
1539\end{cfuncdesc}
1540
1541
1542\section{Constructors}
1543
1544\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *file_name, char *mode}
1545On success, returns a new file object that is opened on the
1546file given by \code{file_name}, with a file mode given by \code{mode},
Fred Drakeb0a78731998-01-13 18:51:10 +00001547where \code{mode} has the same semantics as the standard \C{} routine,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001548fopen. On failure, return -1.
1549\end{cfuncdesc}
1550
1551\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp, char *file_name, char *mode, int close_on_del}
Fred Drakeb0a78731998-01-13 18:51:10 +00001552Return a new file object for an already opened standard \C{}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001553file pointer, \code{fp}. A file name, \code{file_name}, and open mode,
1554\code{mode}, must be provided as well as a flag, \code{close_on_del}, that
1555indicates whether the file is to be closed when the file
1556object is destroyed. On failure, return -1.
1557\end{cfuncdesc}
1558
1559\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
1560Returns a new float object with the value \code{v} on success, and
1561\NULL{} on failure.
1562\end{cfuncdesc}
1563
1564\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long v}
1565Returns a new int object with the value \code{v} on success, and
1566\NULL{} on failure.
1567\end{cfuncdesc}
1568
1569\begin{cfuncdesc}{PyObject*}{PyList_New}{int l}
1570Returns a new list of length \code{l} on success, and \NULL{} on
1571failure.
1572\end{cfuncdesc}
1573
1574\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
1575Returns a new long object with the value \code{v} on success, and
1576\NULL{} on failure.
1577\end{cfuncdesc}
1578
1579\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
1580Returns a new long object with the value \code{v} on success, and
1581\NULL{} on failure.
1582\end{cfuncdesc}
1583
1584\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1585Returns a new empty dictionary on success, and \NULL{} on
1586failure.
1587\end{cfuncdesc}
1588
1589\begin{cfuncdesc}{PyObject*}{PyString_FromString}{char *v}
1590Returns a new string object with the value \code{v} on success, and
1591\NULL{} on failure.
1592\end{cfuncdesc}
1593
1594\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{char *v, int l}
1595Returns a new string object with the value \code{v} and length \code{l}
1596on success, and \NULL{} on failure.
1597\end{cfuncdesc}
1598
1599\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int l}
1600Returns a new tuple of length \code{l} on success, and \NULL{} on
1601failure.
1602\end{cfuncdesc}
1603
1604
1605\chapter{Concrete Objects Layer}
1606
1607The functions in this chapter are specific to certain Python object
1608types. Passing them an object of the wrong type is not a good idea;
1609if you receive an object from a Python program and you are not sure
1610that it has the right type, you must perform a type check first;
1611e.g. to check that an object is a dictionary, use
1612\code{PyDict_Check()}.
1613
1614
1615\chapter{Defining New Object Types}
1616
1617\begin{cfuncdesc}{PyObject *}{_PyObject_New}{PyTypeObject *type}
1618\end{cfuncdesc}
1619
Guido van Rossumae110af1997-05-22 20:11:52 +00001620\begin{cfuncdesc}{PyObject *}{_PyObject_NewVar}{PyTypeObject *type, int size}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001621\end{cfuncdesc}
1622
Guido van Rossumae110af1997-05-22 20:11:52 +00001623\begin{cfuncdesc}{TYPE}{_PyObject_NEW}{TYPE, PyTypeObject *}
1624\end{cfuncdesc}
1625
1626\begin{cfuncdesc}{TYPE}{_PyObject_NEW_VAR}{TYPE, PyTypeObject *, int size}
1627\end{cfuncdesc}
1628
Guido van Rossum4a944d71997-08-14 20:35:38 +00001629\chapter{Initialization, Finalization, and Threads}
1630
Guido van Rossum4a944d71997-08-14 20:35:38 +00001631\begin{cfuncdesc}{void}{Py_Initialize}{}
1632Initialize the Python interpreter. In an application embedding
1633Python, this should be called before using any other Python/C API
1634functions; with the exception of \code{Py_SetProgramName()},
1635\code{PyEval_InitThreads()}, \code{PyEval_ReleaseLock()}, and
1636\code{PyEval_AcquireLock()}. This initializes the table of loaded
1637modules (\code{sys.modules}), and creates the fundamental modules
1638\code{__builtin__}, \code{__main__} and \code{sys}. It also
1639initializes the module search path (\code{sys.path}). It does not set
Guido van Rossum42cefd01997-10-05 15:27:29 +00001640\code{sys.argv}; use \code{PySys_SetArgv()} for that. This is a no-op
1641when called for a second time (without calling \code{Py_Finalize()}
1642first). There is no return value; it is a fatal error if the
1643initialization fails.
1644\end{cfuncdesc}
1645
1646\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001647\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001648Return true (nonzero) when the Python interpreter has been
1649initialized, false (zero) if not. After \code{Py_Finalize()} is
1650called, this returns false until \code{Py_Initialize()} is called
1651again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00001652\end{cfuncdesc}
1653
1654\begin{cfuncdesc}{void}{Py_Finalize}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001655\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001656Undo all initializations made by \code{Py_Initialize()} and subsequent
1657use of Python/C API functions, and destroy all sub-interpreters (see
1658\code{Py_NewInterpreter()} below) that were created and not yet
Guido van Rossum42cefd01997-10-05 15:27:29 +00001659destroyed since the last call to \code{Py_Initialize()}. Ideally,
1660this frees all memory allocated by the Python interpreter. This is a
1661no-op when called for a second time (without calling
1662\code{Py_Initialize()} again first). There is no return value; errors
Guido van Rossum4a944d71997-08-14 20:35:38 +00001663during finalization are ignored.
1664
1665This function is provided for a number of reasons. An embedding
1666application might want to restart Python without having to restart the
1667application itself. An application that has loaded the Python
1668interpreter from a dynamically loadable library (or DLL) might want to
1669free all memory allocated by Python before unloading the DLL. During a
1670hunt for memory leaks in an application a developer might want to free
1671all memory allocated by Python before exiting from the application.
1672
1673\emph{Bugs and caveats:} The destruction of modules and objects in
1674modules is done in random order; this may cause destructors
1675(\code{__del__} methods) to fail when they depend on other objects
1676(even functions) or modules. Dynamically loaded extension modules
1677loaded by Python are not unloaded. Small amounts of memory allocated
1678by the Python interpreter may not be freed (if you find a leak, please
1679report it). Memory tied up in circular references between objects is
1680not freed. Some memory allocated by extension modules may not be
1681freed. Some extension may not work properly if their initialization
1682routine is called more than once; this can happen if an applcation
1683calls \code{Py_Initialize()} and \code{Py_Finalize()} more than once.
1684\end{cfuncdesc}
1685
1686\begin{cfuncdesc}{PyThreadState *}{Py_NewInterpreter}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001687\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001688Create a new sub-interpreter. This is an (almost) totally separate
1689environment for the execution of Python code. In particular, the new
1690interpreter has separate, independent versions of all imported
1691modules, including the fundamental modules \code{__builtin__},
1692\code{__main__} and \code{sys}. The table of loaded modules
1693(\code{sys.modules}) and the module search path (\code{sys.path}) are
1694also separate. The new environment has no \code{sys.argv} variable.
1695It has new standard I/O stream file objects \code{sys.stdin},
1696\code{sys.stdout} and \code{sys.stderr} (however these refer to the
Fred Drakeb0a78731998-01-13 18:51:10 +00001697same underlying \code{FILE} structures in the \C{} library).
Guido van Rossum4a944d71997-08-14 20:35:38 +00001698
1699The return value points to the first thread state created in the new
1700sub-interpreter. This thread state is made the current thread state.
1701Note that no actual thread is created; see the discussion of thread
1702states below. If creation of the new interpreter is unsuccessful,
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001703\NULL{} is returned; no exception is set since the exception state
Guido van Rossum4a944d71997-08-14 20:35:38 +00001704is stored in the current thread state and there may not be a current
1705thread state. (Like all other Python/C API functions, the global
1706interpreter lock must be held before calling this function and is
1707still held when it returns; however, unlike most other Python/C API
1708functions, there needn't be a current thread state on entry.)
1709
1710Extension modules are shared between (sub-)interpreters as follows:
1711the first time a particular extension is imported, it is initialized
1712normally, and a (shallow) copy of its module's dictionary is
1713squirreled away. When the same extension is imported by another
1714(sub-)interpreter, a new module is initialized and filled with the
1715contents of this copy; the extension's \code{init} function is not
1716called. Note that this is different from what happens when as
1717extension is imported after the interpreter has been completely
1718re-initialized by calling \code{Py_Finalize()} and
1719\code{Py_Initialize()}; in that case, the extension's \code{init}
1720function \emph{is} called again.
1721
1722\emph{Bugs and caveats:} Because sub-interpreters (and the main
1723interpreter) are part of the same process, the insulation between them
1724isn't perfect -- for example, using low-level file operations like
1725\code{os.close()} they can (accidentally or maliciously) affect each
1726other's open files. Because of the way extensions are shared between
1727(sub-)interpreters, some extensions may not work properly; this is
1728especially likely when the extension makes use of (static) global
1729variables, or when the extension manipulates its module's dictionary
1730after its initialization. It is possible to insert objects created in
1731one sub-interpreter into a namespace of another sub-interpreter; this
1732should be done with great care to avoid sharing user-defined
1733functions, methods, instances or classes between sub-interpreters,
1734since import operations executed by such objects may affect the
1735wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
1736a hard-to-fix bug that will be addressed in a future release.)
1737\end{cfuncdesc}
1738
1739\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001740\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001741Destroy the (sub-)interpreter represented by the given thread state.
1742The given thread state must be the current thread state. See the
1743discussion of thread states below. When the call returns, the current
Guido van Rossum580aa8d1997-11-25 15:34:51 +00001744thread state is \NULL{}. All thread states associated with this
Guido van Rossum4a944d71997-08-14 20:35:38 +00001745interpreted are destroyed. (The global interpreter lock must be held
1746before calling this function and is still held when it returns.)
1747\code{Py_Finalize()} will destroy all sub-interpreters that haven't
1748been explicitly destroyed at that point.
1749\end{cfuncdesc}
1750
1751\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001752\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001753This function should be called before \code{Py_Initialize()} is called
1754for the first time, if it is called at all. It tells the interpreter
1755the value of the \code{argv[0]} argument to the \code{main()} function
1756of the program. This is used by \code{Py_GetPath()} and some other
1757functions below to find the Python run-time libraries relative to the
1758interpreter executable. The default value is \code{"python"}. The
1759argument should point to a zero-terminated character string in static
1760storage whose contents will not change for the duration of the
1761program's execution. No code in the Python interpreter will change
1762the contents of this storage.
1763\end{cfuncdesc}
1764
1765\begin{cfuncdesc}{char *}{Py_GetProgramName}{}
1766Return the program name set with \code{Py_SetProgramName()}, or the
1767default. The returned string points into static storage; the caller
1768should not modify its value.
1769\end{cfuncdesc}
1770
1771\begin{cfuncdesc}{char *}{Py_GetPrefix}{}
1772Return the ``prefix'' for installed platform-independent files. This
1773is derived through a number of complicated rules from the program name
1774set with \code{Py_SetProgramName()} and some environment variables;
1775for example, if the program name is \code{"/usr/local/bin/python"},
1776the prefix is \code{"/usr/local"}. The returned string points into
1777static storage; the caller should not modify its value. This
1778corresponds to the \code{prefix} variable in the top-level
1779\code{Makefile} and the \code{--prefix} argument to the
1780\code{configure} script at build time. The value is available to
Fred Drakeb0a78731998-01-13 18:51:10 +00001781Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
Guido van Rossum4a944d71997-08-14 20:35:38 +00001782also the next function.
1783\end{cfuncdesc}
1784
1785\begin{cfuncdesc}{char *}{Py_GetExecPrefix}{}
1786Return the ``exec-prefix'' for installed platform-\emph{de}pendent
1787files. This is derived through a number of complicated rules from the
1788program name set with \code{Py_SetProgramName()} and some environment
1789variables; for example, if the program name is
1790\code{"/usr/local/bin/python"}, the exec-prefix is
1791\code{"/usr/local"}. The returned string points into static storage;
1792the caller should not modify its value. This corresponds to the
1793\code{exec_prefix} variable in the top-level \code{Makefile} and the
1794\code{--exec_prefix} argument to the \code{configure} script at build
1795time. The value is available to Python code as
Fred Drakeb0a78731998-01-13 18:51:10 +00001796\code{sys.exec_prefix}. It is only useful on \UNIX{}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00001797
1798Background: The exec-prefix differs from the prefix when platform
1799dependent files (such as executables and shared libraries) are
1800installed in a different directory tree. In a typical installation,
1801platform dependent files may be installed in the
1802\code{"/usr/local/plat"} subtree while platform independent may be
1803installed in \code{"/usr/local"}.
1804
1805Generally speaking, a platform is a combination of hardware and
1806software families, e.g. Sparc machines running the Solaris 2.x
1807operating system are considered the same platform, but Intel machines
1808running Solaris 2.x are another platform, and Intel machines running
1809Linux are yet another platform. Different major revisions of the same
Fred Drakeb0a78731998-01-13 18:51:10 +00001810operating system generally also form different platforms. Non-\UNIX{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001811operating systems are a different story; the installation strategies
1812on those systems are so different that the prefix and exec-prefix are
1813meaningless, and set to the empty string. Note that compiled Python
1814bytecode files are platform independent (but not independent from the
1815Python version by which they were compiled!).
1816
1817System administrators will know how to configure the \code{mount} or
1818\code{automount} programs to share \code{"/usr/local"} between platforms
1819while having \code{"/usr/local/plat"} be a different filesystem for each
1820platform.
1821\end{cfuncdesc}
1822
1823\begin{cfuncdesc}{char *}{Py_GetProgramFullPath}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001824\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001825Return the full program name of the Python executable; this is
1826computed as a side-effect of deriving the default module search path
Guido van Rossum09270b51997-08-15 18:57:32 +00001827from the program name (set by \code{Py_SetProgramName()} above). The
Guido van Rossum4a944d71997-08-14 20:35:38 +00001828returned string points into static storage; the caller should not
1829modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00001830\code{sys.executable}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00001831\end{cfuncdesc}
1832
1833\begin{cfuncdesc}{char *}{Py_GetPath}{}
1834Return the default module search path; this is computed from the
Guido van Rossum09270b51997-08-15 18:57:32 +00001835program name (set by \code{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00001836environment variables. The returned string consists of a series of
1837directory names separated by a platform dependent delimiter character.
Fred Drakeb0a78731998-01-13 18:51:10 +00001838The delimiter character is \code{':'} on \UNIX{}, \code{';'} on
Guido van Rossum09270b51997-08-15 18:57:32 +00001839DOS/Windows, and \code{'\\n'} (the ASCII newline character) on
Guido van Rossum4a944d71997-08-14 20:35:38 +00001840Macintosh. The returned string points into static storage; the caller
1841should not modify its value. The value is available to Python code
1842as the list \code{sys.path}, which may be modified to change the
1843future search path for loaded modules.
1844
1845% XXX should give the exact rules
1846\end{cfuncdesc}
1847
1848\begin{cfuncdesc}{const char *}{Py_GetVersion}{}
1849Return the version of this Python interpreter. This is a string that
1850looks something like
1851
Guido van Rossum09270b51997-08-15 18:57:32 +00001852\begin{verbatim}
1853"1.5a3 (#67, Aug 1 1997, 22:34:28) [GCC 2.7.2.2]"
1854\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001855
1856The first word (up to the first space character) is the current Python
1857version; the first three characters are the major and minor version
1858separated by a period. The returned string points into static storage;
1859the caller should not modify its value. The value is available to
1860Python code as the list \code{sys.version}.
1861\end{cfuncdesc}
1862
1863\begin{cfuncdesc}{const char *}{Py_GetPlatform}{}
Fred Drakeb0a78731998-01-13 18:51:10 +00001864Return the platform identifier for the current platform. On \UNIX{},
Guido van Rossum4a944d71997-08-14 20:35:38 +00001865this is formed from the ``official'' name of the operating system,
1866converted to lower case, followed by the major revision number; e.g.,
1867for Solaris 2.x, which is also known as SunOS 5.x, the value is
1868\code{"sunos5"}. On Macintosh, it is \code{"mac"}. On Windows, it
1869is \code{"win"}. The returned string points into static storage;
1870the caller should not modify its value. The value is available to
1871Python code as \code{sys.platform}.
1872\end{cfuncdesc}
1873
1874\begin{cfuncdesc}{const char *}{Py_GetCopyright}{}
1875Return the official copyright string for the current Python version,
1876for example
1877
1878\code{"Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam"}
1879
1880The returned string points into static storage; the caller should not
1881modify its value. The value is available to Python code as the list
1882\code{sys.copyright}.
1883\end{cfuncdesc}
1884
1885\begin{cfuncdesc}{const char *}{Py_GetCompiler}{}
1886Return an indication of the compiler used to build the current Python
1887version, in square brackets, for example
1888
1889\code{"[GCC 2.7.2.2]"}
1890
1891The returned string points into static storage; the caller should not
1892modify its value. The value is available to Python code as part of
1893the variable \code{sys.version}.
1894\end{cfuncdesc}
1895
1896\begin{cfuncdesc}{const char *}{Py_GetBuildInfo}{}
1897Return information about the sequence number and build date and time
1898of the current Python interpreter instance, for example
1899
Guido van Rossum09270b51997-08-15 18:57:32 +00001900\begin{verbatim}
1901"#67, Aug 1 1997, 22:34:28"
1902\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001903
1904The returned string points into static storage; the caller should not
1905modify its value. The value is available to Python code as part of
1906the variable \code{sys.version}.
1907\end{cfuncdesc}
1908
1909\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
1910% XXX
1911\end{cfuncdesc}
1912
1913% XXX Other PySys thingies (doesn't really belong in this chapter)
1914
1915\section{Thread State and the Global Interpreter Lock}
1916
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001917The Python interpreter is not fully thread safe. In order to support
1918multi-threaded Python programs, there's a global lock that must be
1919held by the current thread before it can safely access Python objects.
1920Without the lock, even the simplest operations could cause problems in
1921a multi-threaded proram: for example, when two threads simultaneously
1922increment the reference count of the same object, the reference count
1923could end up being incremented only once instead of twice.
1924
1925Therefore, the rule exists that only the thread that has acquired the
1926global interpreter lock may operate on Python objects or call Python/C
1927API functions. In order to support multi-threaded Python programs,
1928the interpreter regularly release and reacquires the lock -- by
1929default, every ten bytecode instructions (this can be changed with
1930\code{sys.setcheckinterval()}). The lock is also released and
1931reacquired around potentially blocking I/O operations like reading or
1932writing a file, so that other threads can run while the thread that
1933requests the I/O is waiting for the I/O operation to complete.
1934
1935The Python interpreter needs to keep some bookkeeping information
1936separate per thread -- for this it uses a data structure called
1937PyThreadState. This is new in Python 1.5; in earlier versions, such
1938state was stored in global variables, and switching threads could
1939cause problems. In particular, exception handling is now thread safe,
1940when the application uses \code{sys.exc_info()} to access the exception
1941last raised in the current thread.
1942
1943There's one global variable left, however: the pointer to the current
1944PyThreadState structure. While most thread packages have a way to
1945store ``per-thread global data'', Python's internal platform
1946independent thread abstraction doesn't support this (yet). Therefore,
1947the current thread state must be manipulated explicitly.
1948
1949This is easy enough in most cases. Most code manipulating the global
1950interpreter lock has the following simple structure:
1951
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001952\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001953Save the thread state in a local variable.
1954Release the interpreter lock.
1955...Do some blocking I/O operation...
1956Reacquire the interpreter lock.
1957Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001958\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001959
1960This is so common that a pair of macros exists to simplify it:
1961
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001962\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001963Py_BEGIN_ALLOW_THREADS
1964...Do some blocking I/O operation...
1965Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001966\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001967
1968The BEGIN macro opens a new block and declares a hidden local
1969variable; the END macro closes the block. Another advantage of using
1970these two macros is that when Python is compiled without thread
1971support, they are defined empty, thus saving the thread state and lock
1972manipulations.
1973
1974When thread support is enabled, the block above expands to the
1975following code:
1976
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001977\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001978{
1979 PyThreadState *_save;
1980 _save = PyEval_SaveThread();
1981 ...Do some blocking I/O operation...
1982 PyEval_RestoreThread(_save);
1983}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001984\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001985
1986Using even lower level primitives, we can get roughly the same effect
1987as follows:
1988
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001989\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001990{
1991 PyThreadState *_save;
1992 _save = PyThreadState_Swap(NULL);
1993 PyEval_ReleaseLock();
1994 ...Do some blocking I/O operation...
1995 PyEval_AcquireLock();
1996 PyThreadState_Swap(_save);
1997}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001998\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001999
2000There are some subtle differences; in particular,
2001\code{PyEval_RestoreThread()} saves and restores the value of the
2002global variable \code{errno}, since the lock manipulation does not
2003guarantee that \code{errno} is left alone. Also, when thread support
2004is disabled, \code{PyEval_SaveThread()} and
2005\code{PyEval_RestoreThread()} don't manipulate the lock; in this case,
2006\code{PyEval_ReleaseLock()} and \code{PyEval_AcquireLock()} are not
2007available. (This is done so that dynamically loaded extensions
2008compiled with thread support enabled can be loaded by an interpreter
2009that was compiled with disabled thread support.)
2010
2011The global interpreter lock is used to protect the pointer to the
2012current thread state. When releasing the lock and saving the thread
2013state, the current thread state pointer must be retrieved before the
2014lock is released (since another thread could immediately acquire the
2015lock and store its own thread state in the global variable).
2016Reversely, when acquiring the lock and restoring the thread state, the
2017lock must be acquired before storing the thread state pointer.
2018
2019Why am I going on with so much detail about this? Because when
Fred Drakeb0a78731998-01-13 18:51:10 +00002020threads are created from \C{}, they don't have the global interpreter
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002021lock, nor is there a thread state data structure for them. Such
2022threads must bootstrap themselves into existence, by first creating a
2023thread state data structure, then acquiring the lock, and finally
2024storing their thread state pointer, before they can start using the
2025Python/C API. When they are done, they should reset the thread state
2026pointer, release the lock, and finally free their thread state data
2027structure.
2028
2029When creating a thread data structure, you need to provide an
2030interpreter state data structure. The interpreter state data
2031structure hold global data that is shared by all threads in an
2032interpreter, for example the module administration
2033(\code{sys.modules}). Depending on your needs, you can either create
2034a new interpreter state data structure, or share the interpreter state
2035data structure used by the Python main thread (to access the latter,
2036you must obtain the thread state and access its \code{interp} member;
2037this must be done by a thread that is created by Python or by the main
2038thread after Python is initialized).
2039
2040XXX More?
2041
2042\begin{ctypedesc}{PyInterpreterState}
2043\strong{(NEW in 1.5a3!)}
2044This data structure represents the state shared by a number of
2045cooperating threads. Threads belonging to the same interpreter
2046share their module administration and a few other internal items.
2047There are no public members in this structure.
2048
2049Threads belonging to different interpreters initially share nothing,
2050except process state like available memory, open file descriptors and
2051such. The global interpreter lock is also shared by all threads,
2052regardless of to which interpreter they belong.
2053\end{ctypedesc}
2054
2055\begin{ctypedesc}{PyThreadState}
2056\strong{(NEW in 1.5a3!)}
2057This data structure represents the state of a single thread. The only
2058public data member is \code{PyInterpreterState *interp}, which points
2059to this thread's interpreter state.
2060\end{ctypedesc}
2061
2062\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
2063Initialize and acquire the global interpreter lock. It should be
2064called in the main thread before creating a second thread or engaging
2065in any other thread operations such as \code{PyEval_ReleaseLock()} or
2066\code{PyEval_ReleaseThread(tstate)}. It is not needed before
2067calling \code{PyEval_SaveThread()} or \code{PyEval_RestoreThread()}.
2068
2069This is a no-op when called for a second time. It is safe to call
2070this function before calling \code{Py_Initialize()}.
2071
2072When only the main thread exists, no lock operations are needed. This
2073is a common situation (most Python programs do not use threads), and
2074the lock operations slow the interpreter down a bit. Therefore, the
2075lock is not created initially. This situation is equivalent to having
2076acquired the lock: when there is only a single thread, all object
2077accesses are safe. Therefore, when this function initializes the
2078lock, it also acquires it. Before the Python \code{thread} module
2079creates a new thread, knowing that either it has the lock or the lock
2080hasn't been created yet, it calls \code{PyEval_InitThreads()}. When
2081this call returns, it is guaranteed that the lock has been created and
2082that it has acquired it.
2083
2084It is \strong{not} safe to call this function when it is unknown which
2085thread (if any) currently has the global interpreter lock.
2086
2087This function is not available when thread support is disabled at
2088compile time.
2089\end{cfuncdesc}
2090
Guido van Rossum4a944d71997-08-14 20:35:38 +00002091\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002092\strong{(NEW in 1.5a3!)}
2093Acquire the global interpreter lock. The lock must have been created
2094earlier. If this thread already has the lock, a deadlock ensues.
2095This function is not available when thread support is disabled at
2096compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002097\end{cfuncdesc}
2098
2099\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002100\strong{(NEW in 1.5a3!)}
2101Release the global interpreter lock. The lock must have been created
2102earlier. This function is not available when thread support is
2103disabled at
2104compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002105\end{cfuncdesc}
2106
2107\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002108\strong{(NEW in 1.5a3!)}
2109Acquire the global interpreter lock and then set the current thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002110state to \var{tstate}, which should not be \NULL{}. The lock must
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002111have been created earlier. If this thread already has the lock,
2112deadlock ensues. This function is not available when thread support
2113is disabled at
2114compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002115\end{cfuncdesc}
2116
2117\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002118\strong{(NEW in 1.5a3!)}
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002119Reset the current thread state to \NULL{} and release the global
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002120interpreter lock. The lock must have been created earlier and must be
2121held by the current thread. The \var{tstate} argument, which must not
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002122be \NULL{}, is only used to check that it represents the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002123thread state -- if it isn't, a fatal error is reported. This function
2124is not available when thread support is disabled at
2125compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002126\end{cfuncdesc}
2127
2128\begin{cfuncdesc}{PyThreadState *}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002129\strong{(Different return type in 1.5a3!)}
2130Release the interpreter lock (if it has been created and thread
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002131support is enabled) and reset the thread state to \NULL{},
2132returning the previous thread state (which is not \NULL{}). If
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002133the lock has been created, the current thread must have acquired it.
2134(This function is available even when thread support is disabled at
2135compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002136\end{cfuncdesc}
2137
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002138\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
2139\strong{(Different argument type in 1.5a3!)}
2140Acquire the interpreter lock (if it has been created and thread
2141support is enabled) and set the thread state to \var{tstate}, which
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002142must not be \NULL{}. If the lock has been created, the current
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002143thread must not have acquired it, otherwise deadlock ensues. (This
2144function is available even when thread support is disabled at compile
2145time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002146\end{cfuncdesc}
2147
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002148% XXX These aren't really C types, but the ctypedesc macro is the simplest!
2149\begin{ctypedesc}{Py_BEGIN_ALLOW_THREADS}
2150This macro expands to
2151\code{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
2152Note that it contains an opening brace; it must be matched with a
2153following \code{Py_END_ALLOW_THREADS} macro. See above for further
2154discussion of this macro. It is a no-op when thread support is
2155disabled at compile time.
2156\end{ctypedesc}
2157
2158\begin{ctypedesc}{Py_END_ALLOW_THREADS}
2159This macro expands to
2160\code{PyEval_RestoreThread(_save); \} }.
2161Note that it contains a closing brace; it must be matched with an
2162earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
2163discussion of this macro. It is a no-op when thread support is
2164disabled at compile time.
2165\end{ctypedesc}
2166
2167\begin{ctypedesc}{Py_BEGIN_BLOCK_THREADS}
2168This macro expands to \code{PyEval_RestoreThread(_save);} i.e. it
2169is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
2170brace. It is a no-op when thread support is disabled at compile
2171time.
2172\end{ctypedesc}
2173
2174\begin{ctypedesc}{Py_BEGIN_UNBLOCK_THREADS}
2175This macro expands to \code{_save = PyEval_SaveThread();} i.e. it is
2176equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
2177and variable declaration. It is a no-op when thread support is
2178disabled at compile time.
2179\end{ctypedesc}
2180
2181All of the following functions are only available when thread support
2182is enabled at compile time, and must be called only when the
2183interpreter lock has been created. They are all new in 1.5a3.
2184
2185\begin{cfuncdesc}{PyInterpreterState *}{PyInterpreterState_New}{}
2186Create a new interpreter state object. The interpreter lock must be
2187held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002188\end{cfuncdesc}
2189
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002190\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
2191Reset all information in an interpreter state object. The interpreter
2192lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002193\end{cfuncdesc}
2194
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002195\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
2196Destroy an interpreter state object. The interpreter lock need not be
2197held. The interpreter state must have been reset with a previous
2198call to \code{PyInterpreterState_Clear()}.
2199\end{cfuncdesc}
2200
2201\begin{cfuncdesc}{PyThreadState *}{PyThreadState_New}{PyInterpreterState *interp}
2202Create a new thread state object belonging to the given interpreter
2203object. The interpreter lock must be held.
2204\end{cfuncdesc}
2205
2206\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
2207Reset all information in a thread state object. The interpreter lock
2208must be held.
2209\end{cfuncdesc}
2210
2211\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
2212Destroy a thread state object. The interpreter lock need not be
2213held. The thread state must have been reset with a previous
2214call to \code{PyThreadState_Clear()}.
2215\end{cfuncdesc}
2216
2217\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Get}{}
2218Return the current thread state. The interpreter lock must be held.
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002219When the current thread state is \NULL{}, this issues a fatal
Guido van Rossum5b8a5231997-12-30 04:38:44 +00002220error (so that the caller needn't check for \NULL{}).
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002221\end{cfuncdesc}
2222
2223\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Swap}{PyThreadState *tstate}
2224Swap the current thread state with the thread state given by the
Guido van Rossum580aa8d1997-11-25 15:34:51 +00002225argument \var{tstate}, which may be \NULL{}. The interpreter lock
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002226must be held.
2227\end{cfuncdesc}
2228
2229
2230\section{Defining New Object Types}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002231
Guido van Rossumae110af1997-05-22 20:11:52 +00002232XXX To be done:
2233
2234PyObject, PyVarObject
2235
2236PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
2237
2238Typedefs:
2239unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
2240intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
2241getreadbufferproc, getwritebufferproc, getsegcountproc,
2242destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
2243setattrofunc, cmpfunc, reprfunc, hashfunc
2244
2245PyNumberMethods
2246
2247PySequenceMethods
2248
2249PyMappingMethods
2250
2251PyBufferProcs
2252
2253PyTypeObject
2254
2255DL_IMPORT
2256
2257PyType_Type
2258
2259Py*_Check
2260
2261Py_None, _Py_NoneStruct
2262
2263_PyObject_New, _PyObject_NewVar
2264
2265PyObject_NEW, PyObject_NEW_VAR
2266
2267
2268\chapter{Specific Data Types}
2269
2270This chapter describes the functions that deal with specific types of
2271Python objects. It is structured like the ``family tree'' of Python
2272object types.
2273
2274
2275\section{Fundamental Objects}
2276
2277This section describes Python type objects and the singleton object
2278\code{None}.
2279
2280
2281\subsection{Type Objects}
2282
2283\begin{ctypedesc}{PyTypeObject}
2284
2285\end{ctypedesc}
2286
2287\begin{cvardesc}{PyObject *}{PyType_Type}
2288
2289\end{cvardesc}
2290
2291
2292\subsection{The None Object}
2293
2294\begin{cvardesc}{PyObject *}{Py_None}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002295XXX macro
Guido van Rossumae110af1997-05-22 20:11:52 +00002296\end{cvardesc}
2297
2298
2299\section{Sequence Objects}
2300
2301Generic operations on sequence objects were discussed in the previous
2302chapter; this section deals with the specific kinds of sequence
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002303objects that are intrinsic to the Python language.
Guido van Rossumae110af1997-05-22 20:11:52 +00002304
2305
2306\subsection{String Objects}
2307
2308\begin{ctypedesc}{PyStringObject}
2309This subtype of \code{PyObject} represents a Python string object.
2310\end{ctypedesc}
2311
2312\begin{cvardesc}{PyTypeObject}{PyString_Type}
2313This instance of \code{PyTypeObject} represents the Python string type.
2314\end{cvardesc}
2315
2316\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
2317
2318\end{cfuncdesc}
2319
2320\begin{cfuncdesc}{PyObject *}{PyString_FromStringAndSize}{const char *, int}
2321
2322\end{cfuncdesc}
2323
2324\begin{cfuncdesc}{PyObject *}{PyString_FromString}{const char *}
2325
2326\end{cfuncdesc}
2327
2328\begin{cfuncdesc}{int}{PyString_Size}{PyObject *}
2329
2330\end{cfuncdesc}
2331
2332\begin{cfuncdesc}{char *}{PyString_AsString}{PyObject *}
2333
2334\end{cfuncdesc}
2335
2336\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **, PyObject *}
2337
2338\end{cfuncdesc}
2339
2340\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **, PyObject *}
2341
2342\end{cfuncdesc}
2343
2344\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **, int}
2345
2346\end{cfuncdesc}
2347
2348\begin{cfuncdesc}{PyObject *}{PyString_Format}{PyObject *, PyObject *}
2349
2350\end{cfuncdesc}
2351
2352\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **}
2353
2354\end{cfuncdesc}
2355
2356\begin{cfuncdesc}{PyObject *}{PyString_InternFromString}{const char *}
2357
2358\end{cfuncdesc}
2359
2360\begin{cfuncdesc}{char *}{PyString_AS_STRING}{PyStringObject *}
2361
2362\end{cfuncdesc}
2363
2364\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyStringObject *}
2365
2366\end{cfuncdesc}
2367
2368
2369\subsection{Tuple Objects}
2370
2371\begin{ctypedesc}{PyTupleObject}
2372This subtype of \code{PyObject} represents a Python tuple object.
2373\end{ctypedesc}
2374
2375\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
2376This instance of \code{PyTypeObject} represents the Python tuple type.
2377\end{cvardesc}
2378
2379\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
2380Return true if the argument is a tuple object.
2381\end{cfuncdesc}
2382
2383\begin{cfuncdesc}{PyTupleObject *}{PyTuple_New}{int s}
2384Return a new tuple object of size \code{s}
2385\end{cfuncdesc}
2386
2387\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
2388akes a pointer to a tuple object, and returns the size
2389of that tuple.
2390\end{cfuncdesc}
2391
2392\begin{cfuncdesc}{PyObject *}{PyTuple_GetItem}{PyTupleObject *p, int pos}
2393returns the object at position \code{pos} in the tuple pointed
2394to by \code{p}.
2395\end{cfuncdesc}
2396
2397\begin{cfuncdesc}{PyObject *}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
2398does the same, but does no checking of it's
2399arguments.
2400\end{cfuncdesc}
2401
2402\begin{cfuncdesc}{PyTupleObject *}{PyTuple_GetSlice}{PyTupleObject *p,
2403 int low,
2404 int high}
2405takes a slice of the tuple pointed to by \code{p} from
2406\code{low} to \code{high} and returns it as a new tuple.
2407\end{cfuncdesc}
2408
2409\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyTupleObject *p,
2410 int pos,
2411 PyObject *o}
2412inserts a reference to object \code{o} at position \code{pos} of
2413the tuple pointed to by \code{p}. It returns 0 on success.
2414\end{cfuncdesc}
2415
2416\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyTupleObject *p,
2417 int pos,
2418 PyObject *o}
2419
2420does the same, but does no error checking, and
2421should \emph{only} be used to fill in brand new tuples.
2422\end{cfuncdesc}
2423
2424\begin{cfuncdesc}{PyTupleObject *}{_PyTuple_Resize}{PyTupleObject *p,
2425 int new,
2426 int last_is_sticky}
2427can be used to resize a tuple. Because tuples are
2428\emph{supposed} to be immutable, this should only be used if there is only
2429one module referencing the object. Do \emph{not} use this if the tuple may
2430already be known to some other part of the code. \code{last_is_sticky} is
2431a flag - if set, the tuple will grow or shrink at the front, otherwise
2432it will grow or shrink at the end. Think of this as destroying the old
2433tuple and creating a new one, only more efficiently.
2434\end{cfuncdesc}
2435
2436
2437\subsection{List Objects}
2438
2439\begin{ctypedesc}{PyListObject}
2440This subtype of \code{PyObject} represents a Python list object.
2441\end{ctypedesc}
2442
2443\begin{cvardesc}{PyTypeObject}{PyList_Type}
2444This instance of \code{PyTypeObject} represents the Python list type.
2445\end{cvardesc}
2446
2447\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
2448returns true if it's argument is a \code{PyListObject}
2449\end{cfuncdesc}
2450
2451\begin{cfuncdesc}{PyObject *}{PyList_New}{int size}
2452
2453\end{cfuncdesc}
2454
2455\begin{cfuncdesc}{int}{PyList_Size}{PyObject *}
2456
2457\end{cfuncdesc}
2458
2459\begin{cfuncdesc}{PyObject *}{PyList_GetItem}{PyObject *, int}
2460
2461\end{cfuncdesc}
2462
2463\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *, int, PyObject *}
2464
2465\end{cfuncdesc}
2466
2467\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *, int, PyObject *}
2468
2469\end{cfuncdesc}
2470
2471\begin{cfuncdesc}{int}{PyList_Append}{PyObject *, PyObject *}
2472
2473\end{cfuncdesc}
2474
2475\begin{cfuncdesc}{PyObject *}{PyList_GetSlice}{PyObject *, int, int}
2476
2477\end{cfuncdesc}
2478
2479\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *, int, int, PyObject *}
2480
2481\end{cfuncdesc}
2482
2483\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *}
2484
2485\end{cfuncdesc}
2486
2487\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *}
2488
2489\end{cfuncdesc}
2490
2491\begin{cfuncdesc}{PyObject *}{PyList_AsTuple}{PyObject *}
2492
2493\end{cfuncdesc}
2494
2495\begin{cfuncdesc}{PyObject *}{PyList_GET_ITEM}{PyObject *list, int i}
2496
2497\end{cfuncdesc}
2498
2499\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
2500
2501\end{cfuncdesc}
2502
2503
2504\section{Mapping Objects}
2505
2506\subsection{Dictionary Objects}
2507
2508\begin{ctypedesc}{PyDictObject}
2509This subtype of \code{PyObject} represents a Python dictionary object.
2510\end{ctypedesc}
2511
2512\begin{cvardesc}{PyTypeObject}{PyDict_Type}
2513This instance of \code{PyTypeObject} represents the Python dictionary type.
2514\end{cvardesc}
2515
2516\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
2517returns true if it's argument is a PyDictObject
2518\end{cfuncdesc}
2519
2520\begin{cfuncdesc}{PyDictObject *}{PyDict_New}{}
2521returns a new empty dictionary.
2522\end{cfuncdesc}
2523
2524\begin{cfuncdesc}{void}{PyDict_Clear}{PyDictObject *p}
2525empties an existing dictionary and deletes it.
2526\end{cfuncdesc}
2527
2528\begin{cfuncdesc}{int}{PyDict_SetItem}{PyDictObject *p,
2529 PyObject *key,
2530 PyObject *val}
2531inserts \code{value} into the dictionary with a key of
2532\code{key}. Both \code{key} and \code{value} should be PyObjects, and \code{key} should
2533be hashable.
2534\end{cfuncdesc}
2535
2536\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
2537 char *key,
2538 PyObject *val}
2539inserts \code{value} into the dictionary using \code{key}
2540as a key. \code{key} should be a char *
2541\end{cfuncdesc}
2542
2543\begin{cfuncdesc}{int}{PyDict_DelItem}{PyDictObject *p, PyObject *key}
2544removes the entry in dictionary \code{p} with key \code{key}.
2545\code{key} is a PyObject.
2546\end{cfuncdesc}
2547
2548\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyDictObject *p, char *key}
2549removes the entry in dictionary \code{p} which has a key
2550specified by the \code{char *}\code{key}.
2551\end{cfuncdesc}
2552
2553\begin{cfuncdesc}{PyObject *}{PyDict_GetItem}{PyDictObject *p, PyObject *key}
2554returns the object from dictionary \code{p} which has a key
2555\code{key}.
2556\end{cfuncdesc}
2557
2558\begin{cfuncdesc}{PyObject *}{PyDict_GetItemString}{PyDictObject *p, char *key}
2559does the same, but \code{key} is specified as a
2560\code{char *}, rather than a \code{PyObject *}.
2561\end{cfuncdesc}
2562
2563\begin{cfuncdesc}{PyListObject *}{PyDict_Items}{PyDictObject *p}
2564returns a PyListObject containing all the items
2565from the dictionary, as in the mapping method \code{items()} (see the Reference
2566Guide)
2567\end{cfuncdesc}
2568
2569\begin{cfuncdesc}{PyListObject *}{PyDict_Keys}{PyDictObject *p}
2570returns a PyListObject containing all the keys
2571from the dictionary, as in the mapping method \code{keys()} (see the Reference Guide)
2572\end{cfuncdesc}
2573
2574\begin{cfuncdesc}{PyListObject *}{PyDict_Values}{PyDictObject *p}
2575returns a PyListObject containing all the values
2576from the dictionary, as in the mapping method \code{values()} (see the Reference Guide)
2577\end{cfuncdesc}
2578
2579\begin{cfuncdesc}{int}{PyDict_Size}{PyDictObject *p}
2580returns the number of items in the dictionary.
2581\end{cfuncdesc}
2582
2583\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p,
2584 int ppos,
2585 PyObject **pkey,
2586 PyObject **pvalue}
2587
2588\end{cfuncdesc}
2589
2590
2591\section{Numeric Objects}
2592
2593\subsection{Plain Integer Objects}
2594
2595\begin{ctypedesc}{PyIntObject}
2596This subtype of \code{PyObject} represents a Python integer object.
2597\end{ctypedesc}
2598
2599\begin{cvardesc}{PyTypeObject}{PyInt_Type}
2600This instance of \code{PyTypeObject} represents the Python plain
2601integer type.
2602\end{cvardesc}
2603
2604\begin{cfuncdesc}{int}{PyInt_Check}{PyObject *}
2605
2606\end{cfuncdesc}
2607
2608\begin{cfuncdesc}{PyIntObject *}{PyInt_FromLong}{long ival}
2609creates a new integer object with a value of \code{ival}.
2610
2611The current implementation keeps an array of integer objects for all
2612integers between -1 and 100, when you create an int in that range you
2613actually just get back a reference to the existing object. So it should
2614be possible to change the value of 1. I suspect the behaviour of python
2615in this case is undefined. :-)
2616\end{cfuncdesc}
2617
2618\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyIntObject *io}
2619returns the value of the object \code{io}.
2620\end{cfuncdesc}
2621
2622\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
2623will first attempt to cast the object to a PyIntObject, if
2624it is not already one, and the return it's value.
2625\end{cfuncdesc}
2626
2627\begin{cfuncdesc}{long}{PyInt_GetMax}{}
2628returns the systems idea of the largest int it can handle
2629(LONG_MAX, as defined in the system header files)
2630\end{cfuncdesc}
2631
2632
2633\subsection{Long Integer Objects}
2634
2635\begin{ctypedesc}{PyLongObject}
2636This subtype of \code{PyObject} represents a Python long integer object.
2637\end{ctypedesc}
2638
2639\begin{cvardesc}{PyTypeObject}{PyLong_Type}
2640This instance of \code{PyTypeObject} represents the Python long integer type.
2641\end{cvardesc}
2642
2643\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
2644returns true if it's argument is a \code{PyLongObject}
2645\end{cfuncdesc}
2646
2647\begin{cfuncdesc}{PyObject *}{PyLong_FromLong}{long}
2648
2649\end{cfuncdesc}
2650
2651\begin{cfuncdesc}{PyObject *}{PyLong_FromUnsignedLong}{unsigned long}
2652
2653\end{cfuncdesc}
2654
2655\begin{cfuncdesc}{PyObject *}{PyLong_FromDouble}{double}
2656
2657\end{cfuncdesc}
2658
2659\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *}
2660
2661\end{cfuncdesc}
2662
2663\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject }
2664
2665\end{cfuncdesc}
2666
2667\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *}
2668
2669\end{cfuncdesc}
2670
Fred Drake85a5c521998-01-02 03:24:19 +00002671\begin{cfuncdesc}{PyObject *}{PyLong_FromString}{char *, char **, int}
Guido van Rossumae110af1997-05-22 20:11:52 +00002672
2673\end{cfuncdesc}
2674
2675
2676\subsection{Floating Point Objects}
2677
2678\begin{ctypedesc}{PyFloatObject}
2679This subtype of \code{PyObject} represents a Python floating point object.
2680\end{ctypedesc}
2681
2682\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2683This instance of \code{PyTypeObject} represents the Python floating
2684point type.
2685\end{cvardesc}
2686
2687\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2688returns true if it's argument is a \code{PyFloatObject}
2689\end{cfuncdesc}
2690
2691\begin{cfuncdesc}{PyObject *}{PyFloat_FromDouble}{double}
2692
2693\end{cfuncdesc}
2694
2695\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *}
2696
2697\end{cfuncdesc}
2698
2699\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyFloatObject *}
2700
2701\end{cfuncdesc}
2702
2703
2704\subsection{Complex Number Objects}
2705
2706\begin{ctypedesc}{Py_complex}
2707typedef struct {
2708 double real;
2709 double imag;
2710}
2711\end{ctypedesc}
2712
2713\begin{ctypedesc}{PyComplexObject}
2714This subtype of \code{PyObject} represents a Python complex number object.
2715\end{ctypedesc}
2716
2717\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2718This instance of \code{PyTypeObject} represents the Python complex
2719number type.
2720\end{cvardesc}
2721
2722\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2723returns true if it's argument is a \code{PyComplexObject}
2724\end{cfuncdesc}
2725
2726\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex, Py_complex}
2727
2728\end{cfuncdesc}
2729
2730\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex, Py_complex}
2731
2732\end{cfuncdesc}
2733
2734\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex}
2735
2736\end{cfuncdesc}
2737
2738\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex, Py_complex}
2739
2740\end{cfuncdesc}
2741
2742\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex, Py_complex}
2743
2744\end{cfuncdesc}
2745
2746\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex, Py_complex}
2747
2748\end{cfuncdesc}
2749
2750\begin{cfuncdesc}{PyObject *}{PyComplex_FromCComplex}{Py_complex}
2751
2752\end{cfuncdesc}
2753
2754\begin{cfuncdesc}{PyObject *}{PyComplex_FromDoubles}{double real, double imag}
2755
2756\end{cfuncdesc}
2757
2758\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2759
2760\end{cfuncdesc}
2761
2762\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2763
2764\end{cfuncdesc}
2765
2766\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2767
2768\end{cfuncdesc}
2769
2770
2771
2772\section{Other Objects}
2773
2774\subsection{File Objects}
2775
2776\begin{ctypedesc}{PyFileObject}
2777This subtype of \code{PyObject} represents a Python file object.
2778\end{ctypedesc}
2779
2780\begin{cvardesc}{PyTypeObject}{PyFile_Type}
2781This instance of \code{PyTypeObject} represents the Python file type.
2782\end{cvardesc}
2783
2784\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2785returns true if it's argument is a \code{PyFileObject}
2786\end{cfuncdesc}
2787
2788\begin{cfuncdesc}{PyObject *}{PyFile_FromString}{char *name, char *mode}
2789creates a new PyFileObject pointing to the file
2790specified in \code{name} with the mode specified in \code{mode}
2791\end{cfuncdesc}
2792
2793\begin{cfuncdesc}{PyObject *}{PyFile_FromFile}{FILE *fp,
2794 char *name, char *mode, int (*close})
2795creates a new PyFileObject from the already-open \code{fp}.
2796The function \code{close} will be called when the file should be closed.
2797\end{cfuncdesc}
2798
2799\begin{cfuncdesc}{FILE *}{PyFile_AsFile}{PyFileObject *p}
2800returns the file object associated with \code{p} as a \code{FILE *}
2801\end{cfuncdesc}
2802
2803\begin{cfuncdesc}{PyStringObject *}{PyFile_GetLine}{PyObject *p, int n}
2804undocumented as yet
2805\end{cfuncdesc}
2806
2807\begin{cfuncdesc}{PyStringObject *}{PyFile_Name}{PyObject *p}
2808returns the name of the file specified by \code{p} as a
2809PyStringObject
2810\end{cfuncdesc}
2811
2812\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2813on systems with \code{setvbuf} only
2814\end{cfuncdesc}
2815
2816\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyFileObject *p, int newflag}
2817same as the file object method \code{softspace}
2818\end{cfuncdesc}
2819
2820\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p}
2821writes object \code{obj} to file object \code{p}
2822\end{cfuncdesc}
2823
2824\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p}
2825writes string \code{s} to file object \code{p}
2826\end{cfuncdesc}
2827
2828
Guido van Rossum5b8a5231997-12-30 04:38:44 +00002829\subsection{CObjects}
2830
2831XXX
2832
2833
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002834\input{api.ind} % Index -- must be last
2835
2836\end{document}