blob: 494eb416455bcee7ce936a7fc343dbcd6c64c4fa [file] [log] [blame]
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001\documentstyle[twoside,11pt,myformat]{report}
2
Guido van Rossum9faf4c51997-10-07 14:38:54 +00003\title{Python/C API Reference Manual}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00004
5\input{boilerplate}
6
7\makeindex % tell \index to actually write the .idx file
8
9
10\begin{document}
11
12\pagenumbering{roman}
13
14\maketitle
15
16\input{copyright}
17
18\begin{abstract}
19
20\noindent
21This manual documents the API used by C (or C++) programmers who want
22to write extension modules or embed Python. It is a companion to
23``Extending and Embedding the Python Interpreter'', which describes
24the general principles of extension writing but does not document the
25API functions in detail.
26
27\end{abstract}
28
29\pagebreak
30
31{
32\parskip = 0mm
33\tableofcontents
34}
35
36\pagebreak
37
38\pagenumbering{arabic}
39
Guido van Rossum5060b3b1997-08-17 18:02:23 +000040% XXX Consider moving all this back to ext.tex and giving api.tex
41% XXX a *really* short intro only.
Guido van Rossum9231c8f1997-05-15 21:43:21 +000042
43\chapter{Introduction}
44
Guido van Rossum59a61351997-08-14 20:34:33 +000045The Application Programmer's Interface to Python gives C and C++
46programmers access to the Python interpreter at a variety of levels.
Guido van Rossum4a944d71997-08-14 20:35:38 +000047There are two fundamentally different reasons for using the Python/C
48API. (The API is equally usable from C++, but for brevity it is
49generally referred to as the Python/C API.) The first reason is to
50write ``extension modules'' for specific purposes; these are C modules
51that extend the Python interpreter. This is probably the most common
52use. The second reason is to use Python as a component in a larger
53application; this technique is generally referred to as ``embedding''
Guido van Rossum59a61351997-08-14 20:34:33 +000054Python in an application.
55
Guido van Rossum4a944d71997-08-14 20:35:38 +000056Writing an extension module is a relatively well-understood process,
57where a ``cookbook'' approach works well. There are several tools
58that automate the process to some extent. While people have embedded
59Python in other applications since its early existence, the process of
60embedding Python is less straightforward that writing an extension.
61Python 1.5 introduces a number of new API functions as well as some
62changes to the build process that make embedding much simpler.
Guido van Rossum59a61351997-08-14 20:34:33 +000063This manual describes the 1.5 state of affair (as of Python 1.5a3).
64% 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
72\section{Objects, Types and Reference Counts}
73
Guido van Rossum4a944d71997-08-14 20:35:38 +000074Most Python/C API functions have one or more arguments as well as a
75return value of type \code{PyObject *}. This type is a pointer
76(obviously!) to an opaque data type representing an arbitrary Python
77object. Since all Python object types are treated the same way by the
78Python language in most situations (e.g., assignments, scope rules,
79and argument passing), it is only fitting that they should be
Guido van Rossum59a61351997-08-14 20:34:33 +000080represented by a single C type. All Python objects live on the heap:
Guido van Rossum4a944d71997-08-14 20:35:38 +000081you never declare an automatic or static variable of type
82\code{PyObject}, only pointer variables of type \code{PyObject *} can
Guido van Rossum59a61351997-08-14 20:34:33 +000083be declared.
84
Guido van Rossum4a944d71997-08-14 20:35:38 +000085All Python objects (even Python integers) have a ``type'' and a
86``reference count''. An object's type determines what kind of object
87it is (e.g., an integer, a list, or a user-defined function; there are
88many more as explained in the Python Language Reference Manual). For
89each of the well-known types there is a macro to check whether an
90object is of that type; for instance, \code{PyList_Check(a)} is true
Guido van Rossum59a61351997-08-14 20:34:33 +000091iff the object pointed to by \code{a} is a Python list.
92
Guido van Rossum5060b3b1997-08-17 18:02:23 +000093\subsection{Reference Counts}
94
Guido van Rossum4a944d71997-08-14 20:35:38 +000095The reference count is important only because today's computers have a
96finite (and often severly limited) memory size; it counts how many
97different places there are that have a reference to an object. Such a
98place could be another object, or a global (or static) C variable, or
99a local variable in some C function. When an object's reference count
100becomes zero, the object is deallocated. If it contains references to
101other objects, their reference count is decremented. Those other
102objects may be deallocated in turn, if this decrement makes their
103reference count become zero, and so on. (There's an obvious problem
104with objects that reference each other here; for now, the solution is
Guido van Rossum59a61351997-08-14 20:34:33 +0000105``don't do that''.)
106
Guido van Rossum4a944d71997-08-14 20:35:38 +0000107Reference counts are always manipulated explicitly. The normal way is
108to use the macro \code{Py_INCREF(a)} to increment an object's
109reference count by one, and \code{Py_DECREF(a)} to decrement it by
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000110one. The decref macro is considerably more complex than the incref one,
Guido van Rossum4a944d71997-08-14 20:35:38 +0000111since it must check whether the reference count becomes zero and then
112cause the object's deallocator, which is a function pointer contained
113in the object's type structure. The type-specific deallocator takes
114care of decrementing the reference counts for other objects contained
115in the object, and so on, if this is a compound object type such as a
116list. There's no chance that the reference count can overflow; at
117least as many bits are used to hold the reference count as there are
118distinct memory locations in virtual memory (assuming
119\code{sizeof(long) >= sizeof(char *)}). Thus, the reference count
Guido van Rossum59a61351997-08-14 20:34:33 +0000120increment is a simple operation.
121
Guido van Rossum4a944d71997-08-14 20:35:38 +0000122It is not necessary to increment an object's reference count for every
123local variable that contains a pointer to an object. In theory, the
124oject's reference count goes up by one when the variable is made to
125point to it and it goes down by one when the variable goes out of
126scope. However, these two cancel each other out, so at the end the
127reference count hasn't changed. The only real reason to use the
128reference count is to prevent the object from being deallocated as
129long as our variable is pointing to it. If we know that there is at
130least one other reference to the object that lives at least as long as
131our variable, there is no need to increment the reference count
132temporarily. An important situation where this arises is in objects
133that are passed as arguments to C functions in an extension module
134that are called from Python; the call mechanism guarantees to hold a
Guido van Rossum59a61351997-08-14 20:34:33 +0000135reference to every argument for the duration of the call.
136
Guido van Rossum4a944d71997-08-14 20:35:38 +0000137However, a common pitfall is to extract an object from a list and
138holding on to it for a while without incrementing its reference count.
139Some other operation might conceivably remove the object from the
140list, decrementing its reference count and possible deallocating it.
141The real danger is that innocent-looking operations may invoke
142arbitrary Python code which could do this; there is a code path which
143allows control to flow back to the user from a \code{Py_DECREF()}, so
Guido van Rossum59a61351997-08-14 20:34:33 +0000144almost any operation is potentially dangerous.
145
Guido van Rossum4a944d71997-08-14 20:35:38 +0000146A safe approach is to always use the generic operations (functions
147whose name begins with \code{PyObject_}, \code{PyNumber_},
148\code{PySequence_} or \code{PyMapping_}). These operations always
149increment the reference count of the object they return. This leaves
150the caller with the responsibility to call \code{Py_DECREF()} when
Guido van Rossum59a61351997-08-14 20:34:33 +0000151they are done with the result; this soon becomes second nature.
152
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000153\subsubsection{Reference Count Details}
154
155The reference count behavior of functions in the Python/C API is best
156expelained in terms of \emph{ownership of references}. Note that we
157talk of owning reference, never of owning objects; objects are always
158shared! When a function owns a reference, it has to dispose of it
159properly -- either by passing ownership on (usually to its caller) or
160by calling \code{Py_DECREF()} or \code{Py_XDECREF()}. When a function
161passes ownership of a reference on to its caller, the caller is said
162to receive a \emph{new} reference. When to ownership is transferred,
163the caller is said to \emph{borrow} the reference. Nothing needs to
164be done for a borrowed reference.
165
166Conversely, when calling a function while passing it a reference to an
167object, there are two possibilities: the function \emph{steals} a
168reference to the object, or it does not. Few functions steal
169references; the two notable exceptions are \code{PyList_SetItem()} and
170\code{PyTuple_SetItem()}, which steal a reference to the item (but not to
171the tuple or list into which the item it put!). These functions were
172designed to steal a reference because of a common idiom for
173populating a tuple or list with newly created objects; e.g., the code
174to create the tuple \code{(1, 2, "three")} could look like this
175(forgetting about error handling for the moment):
176
177\begin{verbatim}
178PyObject *t;
179t = PyTuple_New(3);
180PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
181PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
182PyTuple_SetItem(t, 2, PyString_FromString("three"));
183\end{verbatim}
184
185Incidentally, \code{PyTuple_SetItem()} is the \emph{only} way to set
186tuple items; \code{PyObject_SetItem()} refuses to do this since tuples
187are an immutable data type. You should only use
188\code{PyTuple_SetItem()} for tuples that you are creating yourself.
189
190Equivalent code for populating a list can be written using
191\code{PyList_New()} and \code{PyList_SetItem()}. Such code can also
192use \code{PySequence_SetItem()}; this illustrates the difference
193between the two:
194
195\begin{verbatim}
196PyObject *l, *x;
197l = PyList_New(3);
198x = PyInt_FromLong(1L);
199PyObject_SetItem(l, 0, x); Py_DECREF(x);
200x = PyInt_FromLong(2L);
201PyObject_SetItem(l, 1, x); Py_DECREF(x);
202x = PyString_FromString("three");
203PyObject_SetItem(l, 2, x); Py_DECREF(x);
204\end{verbatim}
205
206You might find it strange that the ``recommended'' approach takes
207more code. in practice, you will rarely use these ways of creating
208and populating a tuple or list, however; there's a generic function,
209\code{Py_BuildValue()} that can create most common objects from C
210values, directed by a ``format string''. For example, the above two
211blocks of code could be replaced by the following (which also takes
212care of the error checking!):
213
214\begin{verbatim}
215PyObject *t, *l;
216t = Py_BuildValue("(iis)", 1, 2, "three");
217l = Py_BuildValue("[iis]", 1, 2, "three");
218\end{verbatim}
219
220It is much more common to use \code{PyObject_SetItem()} and friends
221with items whose references you are only borrowing, like arguments
222that were passed in to the function you are writing. In that case,
223their behaviour regarding reference counts is much saner, since you
224don't have to increment a reference count so you can give a reference
225away (``have it be stolen''). For example, this function sets all
226items of a list (actually, any mutable sequence) to a given item:
227
228\begin{verbatim}
229int set_all(PyObject *target, PyObject *item)
230{
231 int i, n;
232 n = PyObject_Length(target);
233 if (n < 0)
234 return -1;
235 for (i = 0; i < n; i++) {
236 if (PyObject_SetItem(target, i, item) < 0)
237 return -1;
238 }
239 return 0;
240}
241\end{verbatim}
242
243The situation is slightly different for function return values.
244While passing a reference to most functions does not change your
245ownership responsibilities for that reference, many functions that
246return a referece to an object give you ownership of the reference.
247The reason is simple: in many cases, the returned object is created
248on the fly, and the reference you get is the only reference to the
249object! Therefore, the generic functions that return object
250references, like \code{PyObject_GetItem()} and
251\code{PySequence_GetItem()}, always return a new reference (i.e., the
252caller becomes the owner of the reference).
253
254It is important to realize that whether you own a reference returned
255by a function depends on which function you call only -- \emph{the
256plumage} (i.e., the type of the type of the object passed as an
257argument to the function) \emph{don't enter into it!} Thus, if you
258extract an item from a list using \code{PyList_GetItem()}, yo don't
259own the reference -- but if you obtain the same item from the same
260list using \code{PySequence_GetItem()} (which happens to take exactly
261the same arguments), you do own a reference to the returned object.
262
263Here is an example of how you could write a function that computes the
264sum of the items in a list of integers; once using
265\code{PyList_GetItem()}, once using \code{PySequence_GetItem()}.
266
267\begin{verbatim}
268long sum_list(PyObject *list)
269{
270 int i, n;
271 long total = 0;
272 PyObject *item;
273 n = PyList_Size(list);
274 if (n < 0)
275 return -1; /* Not a list */
276 for (i = 0; i < n; i++) {
277 item = PyList_GetItem(list, i); /* Can't fail */
278 if (!PyInt_Check(item)) continue; /* Skip non-integers */
279 total += PyInt_AsLong(item);
280 }
281 return total;
282}
283\end{verbatim}
284
285\begin{verbatim}
286long sum_sequence(PyObject *sequence)
287{
288 int i, n;
289 long total = 0;
290 PyObject *item;
291 n = PyObject_Size(list);
292 if (n < 0)
293 return -1; /* Has no length */
294 for (i = 0; i < n; i++) {
295 item = PySequence_GetItem(list, i);
296 if (item == NULL)
297 return -1; /* Not a sequence, or other failure */
298 if (PyInt_Check(item))
299 total += PyInt_AsLong(item);
300 Py_DECREF(item); /* Discared reference ownership */
301 }
302 return total;
303}
304\end{verbatim}
305
306\subsection{Types}
307
308There are few other data types that play a significant role in
Guido van Rossum4a944d71997-08-14 20:35:38 +0000309the Python/C API; most are all simple C types such as \code{int},
310\code{long}, \code{double} and \code{char *}. A few structure types
311are used to describe static tables used to list the functions exported
312by a module or the data attributes of a new object type. These will
Guido van Rossum59a61351997-08-14 20:34:33 +0000313be discussed together with the functions that use them.
314
315\section{Exceptions}
316
Guido van Rossum4a944d71997-08-14 20:35:38 +0000317The Python programmer only needs to deal with exceptions if specific
318error handling is required; unhandled exceptions are automatically
319propagated to the caller, then to the caller's caller, and so on, till
320they reach the top-level interpreter, where they are reported to the
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000321user accompanied by a stack traceback.
Guido van Rossum59a61351997-08-14 20:34:33 +0000322
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000323For C programmers, however, error checking always has to be explicit.
324All functions in the Python/C API can raise exceptions, unless an
325explicit claim is made otherwise in a function's documentation. In
326general, when a function encounters an error, it sets an exception,
327discards any object references that it owns, and returns an
328error indicator -- usually \code{NULL} or \code{-1}. A few functions
329return a Boolean true/false result, with false indicating an error.
330Very few functions return no explicit error indicator or have an
331ambiguous return value, and require explicit testing for errors with
332\code{PyErr_Occurred()}.
333
334Exception state is maintained in per-thread storage (this is
335equivalent to using global storage in an unthreaded application). A
336thread can be on one of two states: an exception has occurred, or not.
337The function \code{PyErr_Occurred()} can be used to check for this: it
338returns a borrowed reference to the exception type object when an
339exception has occurred, and \code{NULL} otherwise. There are a number
340of functions to set the exception state: \code{PyErr_SetString()} is
341the most common (though not the most general) function to set the
342exception state, and \code{PyErr_Clear()} clears the exception state.
343
344The full exception state consists of three objects (all of which can
345be \code{NULL} ): the exception type, the corresponding exception
346value, and the traceback. These have the same meanings as the Python
347object \code{sys.exc_type}, \code{sys.exc_value},
348\code{sys.exc_traceback}; however, they are not the same: the Python
349objects represent the last exception being handled by a Python
350\code{try...except} statement, while the C level exception state only
351exists while an exception is being passed on between C functions until
352it reaches the Python interpreter, which takes care of transferring it
353to \code{sys.exc_type} and friends.
354
355(Note that starting with Python 1.5, the preferred, thread-safe way to
356access the exception state from Python code is to call the function
357\code{sys.exc_info()}, which returns the per-thread exception state
358for Python code. Also, the semantics of both ways to access the
359exception state have changed so that a function which catches an
360exception will save and restore its thread's exception state so as to
361preserve the exception state of its caller. This prevents common bugs
362in exception handling code caused by an innocent-looking function
363overwriting the exception being handled; it also reduces the often
364unwanted lifetime extension for objects that are referenced by the
365stack frames in the traceback.)
366
367As a general principle, a function that calls another function to
368perform some task should check whether the called function raised an
369exception, and if so, pass the exception state on to its caller. It
370should discards any object references that it owns, and returns an
371error indicator, but it should \emph{not} set another exception --
372that would overwrite the exception that was just raised, and lose
373important reason about the exact cause of the error.
374
375A simple example of detecting exceptions and passing them on is shown
376in the \code{sum_sequence()} example above. It so happens that that
377example doesn't need to clean up any owned references when it detects
378an error. The following example function shows some error cleanup.
379First we show the equivalent Python code (to remind you why you like
380Python):
381
382\begin{verbatim}
383def incr_item(seq, i):
384 try:
385 item = seq[i]
386 except IndexError:
387 item = 0
388 seq[i] = item + 1
389\end{verbatim}
390
391Here is the corresponding C code, in all its glory:
392
393% XXX Is it better to have fewer comments in the code?
394
395\begin{verbatim}
396int incr_item(PyObject *seq, int i)
397{
398 /* Objects all initialized to NULL for Py_XDECREF */
399 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
400 int rv = -1; /* Return value initialized to -1 (faulure) */
401
402 item = PySequence_GetItem(seq, i);
403 if (item == NULL) {
404 /* Handle IndexError only: */
405 if (PyErr_Occurred() != PyExc_IndexError) goto error;
406
407 /* Clear the error and use zero: */
408 PyErr_Clear();
409 item = PyInt_FromLong(1L);
410 if (item == NULL) goto error;
411 }
412
413 const_one = PyInt_FromLong(1L);
414 if (const_one == NULL) goto error;
415
416 incremented_item = PyNumber_Add(item, const_one);
417 if (incremented_item == NULL) goto error;
418
419 if (PyObject_SetItem(seq, i, incremented_item) < 0) goto error;
420 rv = 0; /* Success */
421 /* Continue with cleanup code */
422
423 error:
424 /* Cleanup code, shared by success and failure path */
425
426 /* Use Py_XDECREF() to ignore NULL references */
427 Py_XDECREF(item);
428 Py_XDECREF(const_one);
429 Py_XDECREF(incremented_item);
430
431 return rv; /* -1 for error, 0 for success */
432}
433\end{verbatim}
434
435This example represents an endorsed use of the \code{goto} statement
436in C! It illustrates the use of \code{PyErr_Occurred()} and
437\code{PyErr_Clear()} to handle specific exceptions, and the use of
438\code{Py_XDECREF()} to dispose of owned references that may be
439\code{NULL} (note the `X' in the name; \code{Py_DECREF()} would crash
440when confronted with a \code{NULL} reference). It is important that
441the variables used to hold owned references are initialized to
442\code{NULL} for this to work; likewise, the proposed return value is
443initialized to \code{-1} (failure) and only set to success after
444the final call made is succesful.
445
Guido van Rossum59a61351997-08-14 20:34:33 +0000446
447\section{Embedding Python}
448
Guido van Rossum4a944d71997-08-14 20:35:38 +0000449The one important task that only embedders of the Python interpreter
450have to worry about is the initialization (and possibly the
451finalization) of the Python interpreter. Most functionality of the
452interpreter can only be used after the interpreter has been
Guido van Rossum59a61351997-08-14 20:34:33 +0000453initialized.
454
Guido van Rossum4a944d71997-08-14 20:35:38 +0000455The basic initialization function is \code{Py_Initialize()}. This
456initializes the table of loaded modules, and creates the fundamental
457modules \code{__builtin__}, \code{__main__} and \code{sys}. It also
Guido van Rossum59a61351997-08-14 20:34:33 +0000458initializes the module search path (\code{sys.path}).
459
Guido van Rossum4a944d71997-08-14 20:35:38 +0000460\code{Py_Initialize()} does not set the ``script argument list''
461(\code{sys.argv}). If this variable is needed by Python code that
462will be executed later, it must be set explicitly with a call to
463\code{PySys_SetArgv(\var{argc}, \var{argv})} subsequent to the call
Guido van Rossum59a61351997-08-14 20:34:33 +0000464to \code{Py_Initialize()}.
465
Guido van Rossum42cefd01997-10-05 15:27:29 +0000466On most systems (in particular, on Unix and Windows, although the
467details are slightly different), \code{Py_Initialize()} calculates the
468module search path based upon its best guess for the location of the
469standard Python interpreter executable, assuming that the Python
470library is found in a fixed location relative to the Python
471interpreter executable. In particular, it looks for a directory named
472\code{lib/python1.5} (replacing \code{1.5} with the current
473interpreter version) relative to the parent directory where the
474executable named \code{python} is found on the shell command search
475path (the environment variable \code{\$PATH}).
476
477For instance, if the Python executable is found in
478\code{/usr/local/bin/python}, it will assume that the libraries are in
479\code{/usr/local/lib/python1.5}. In fact, this also the ``fallback''
480location, used when no executable file named \code{python} is found
481along \code{\$PATH}. The user can change this behavior by setting the
482environment variable \code{\$PYTHONHOME}, and can insert additional
483directories in front of the standard path by setting
Guido van Rossum59a61351997-08-14 20:34:33 +0000484\code{\$PYTHONPATH}.
485
Guido van Rossum4a944d71997-08-14 20:35:38 +0000486The embedding application can steer the search by calling
487\code{Py_SetProgramName(\var{file})} \emph{before} calling
Guido van Rossum09270b51997-08-15 18:57:32 +0000488\code{Py_Initialize()}. Note that \code{\$PYTHONHOME} still overrides
Guido van Rossum4a944d71997-08-14 20:35:38 +0000489this and \code{\$PYTHONPATH} is still inserted in front of the
Guido van Rossum59a61351997-08-14 20:34:33 +0000490standard path.
491
Guido van Rossum4a944d71997-08-14 20:35:38 +0000492Sometimes, it is desirable to ``uninitialize'' Python. For instance,
493the application may want to start over (make another call to
494\code{Py_Initialize()}) or the application is simply done with its
495use of Python and wants to free all memory allocated by Python. This
Guido van Rossum59a61351997-08-14 20:34:33 +0000496can be accomplished by calling \code{Py_Finalize()}.
497% XXX More...
498
499\section{Embedding Python in Threaded Applications}
500
Guido van Rossum4a944d71997-08-14 20:35:38 +0000501
502
503
504
505
506
507
508
Guido van Rossum59a61351997-08-14 20:34:33 +0000509
510\chapter{Old Introduction}
511
Guido van Rossumae110af1997-05-22 20:11:52 +0000512(XXX This is the old introduction, mostly by Jim Fulton -- should be
513rewritten.)
514
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000515From the viewpoint of of C access to Python services, we have:
516
517\begin{enumerate}
518
519\item "Very high level layer": two or three functions that let you
520exec or eval arbitrary Python code given as a string in a module whose
521name is given, passing C values in and getting C values out using
522mkvalue/getargs style format strings. This does not require the user
523to declare any variables of type \code{PyObject *}. This should be
524enough to write a simple application that gets Python code from the
525user, execs it, and returns the output or errors.
526
527\item "Abstract objects layer": which is the subject of this chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000528It has many functions operating on objects, and lets you do many
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000529things from C that you can also write in Python, without going through
530the Python parser.
531
532\item "Concrete objects layer": This is the public type-dependent
533interface provided by the standard built-in types, such as floats,
534strings, and lists. This interface exists and is currently documented
535by the collection of include files provides with the Python
536distributions.
537
Guido van Rossumae110af1997-05-22 20:11:52 +0000538\end{enumerate}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000539
540From the point of view of Python accessing services provided by C
541modules:
542
Guido van Rossumae110af1997-05-22 20:11:52 +0000543\begin{enumerate}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000544
Guido van Rossumae110af1997-05-22 20:11:52 +0000545\item[4.] "Python module interface": this interface consist of the basic
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000546routines used to define modules and their members. Most of the
547current extensions-writing guide deals with this interface.
548
Guido van Rossumae110af1997-05-22 20:11:52 +0000549\item[5.] "Built-in object interface": this is the interface that a new
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000550built-in type must provide and the mechanisms and rules that a
551developer of a new built-in type must use and follow.
552
553\end{enumerate}
554
555The Python C API provides four groups of operations on objects,
556corresponding to the same operations in the Python language: object,
557numeric, sequence, and mapping. Each protocol consists of a
558collection of related operations. If an operation that is not
559provided by a particular type is invoked, then the standard exception
560\code{TypeError} is raised with a operation name as an argument.
561
562In addition, for convenience this interface defines a set of
563constructors for building objects of built-in types. This is needed
564so new objects can be returned from C functions that otherwise treat
565objects generically.
566
567\section{Reference Counting}
568
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000569For most of the functions in the Python/C API, if a function retains a
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000570reference to a Python object passed as an argument, then the function
571will increase the reference count of the object. It is unnecessary
572for the caller to increase the reference count of an argument in
573anticipation of the object's retention.
574
575Usually, Python objects returned from functions should be treated as
576new objects. Functions that return objects assume that the caller
577will retain a reference and the reference count of the object has
578already been incremented to account for this fact. A caller that does
579not retain a reference to an object that is returned from a function
580must decrement the reference count of the object (using
581\code{Py_DECREF()}) to prevent memory leaks.
582
583Exceptions to these rules will be noted with the individual functions.
584
585\section{Include Files}
586
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000587All function, type and macro definitions needed to use the Python/C
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000588API are included in your code by the following line:
589
590\code{\#include "Python.h"}
591
592This implies inclusion of the following standard header files:
593stdio.h, string.h, errno.h, and stdlib.h (if available).
594
595All user visible names defined by Python.h (except those defined by
596the included standard headers) have one of the prefixes \code{Py} or
597\code{_Py}. Names beginning with \code{_Py} are for internal use
598only.
599
600
601\chapter{Initialization and Shutdown of an Embedded Python Interpreter}
602
603When embedding the Python interpreter in a C or C++ program, the
604interpreter must be initialized.
605
606\begin{cfuncdesc}{void}{PyInitialize}{}
607This function initializes the interpreter. It must be called before
608any interaction with the interpreter takes place. If it is called
609more than once, the second and further calls have no effect.
610
611The function performs the following tasks: create an environment in
612which modules can be imported and Python code can be executed;
613initialize the \code{__builtin__} module; initialize the \code{sys}
614module; initialize \code{sys.path}; initialize signal handling; and
615create the empty \code{__main__} module.
616
617In the current system, there is no way to undo all these
618initializations or to create additional interpreter environments.
619\end{cfuncdesc}
620
621\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
622Register a cleanup function to be called when Python exits. The
623cleanup function will be called with no arguments and should return no
624value. At most 32 cleanup functions can be registered. When the
625registration is successful, \code{Py_AtExit} returns 0; on failure, it
626returns -1. Each cleanup function will be called t most once. The
627cleanup function registered last is called first.
628\end{cfuncdesc}
629
630\begin{cfuncdesc}{void}{Py_Exit}{int status}
631Exit the current process. This calls \code{Py_Cleanup()} (see next
632item) and performs additional cleanup (under some circumstances it
633will attempt to delete all modules), and then calls the standard C
634library function \code{exit(status)}.
635\end{cfuncdesc}
636
637\begin{cfuncdesc}{void}{Py_Cleanup}{}
638Perform some of the cleanup that \code{Py_Exit} performs, but don't
639exit the process. In particular, this invokes the user's
640\code{sys.exitfunc} function (if defined at all), and it invokes the
641cleanup functions registered with \code{Py_AtExit()}, in reverse order
642of their registration.
643\end{cfuncdesc}
644
645\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
646Print a fatal error message and die. No cleanup is performed. This
647function should only be invoked when a condition is detected that
648would make it dangerous to continue using the Python interpreter;
649e.g., when the object administration appears to be corrupted.
650\end{cfuncdesc}
651
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000652\begin{cfuncdesc}{void}{PyBuiltin_Init}{}
653Initialize the \code{__builtin__} module. For internal use only.
654\end{cfuncdesc}
655
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000656XXX Other init functions: PyOS_InitInterrupts,
Guido van Rossumae110af1997-05-22 20:11:52 +0000657PyMarshal_Init, PySys_Init.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000658
659\chapter{Reference Counting}
660
661The functions in this chapter are used for managing reference counts
662of Python objects.
663
664\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
665Increment the reference count for object \code{o}. The object must
666not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
667\code{Py_XINCREF()}.
668\end{cfuncdesc}
669
670\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
671Increment the reference count for object \code{o}. The object may be
672\NULL{}, in which case the function has no effect.
673\end{cfuncdesc}
674
675\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
676Decrement the reference count for object \code{o}. The object must
677not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
678\code{Py_XDECREF()}. If the reference count reaches zero, the object's
679type's deallocation function (which must not be \NULL{}) is invoked.
680
681\strong{Warning:} The deallocation function can cause arbitrary Python
682code to be invoked (e.g. when a class instance with a \code{__del__()}
683method is deallocated). While exceptions in such code are not
684propagated, the executed code has free access to all Python global
685variables. This means that any object that is reachable from a global
686variable should be in a consistent state before \code{Py_DECREF()} is
687invoked. For example, code to delete an object from a list should
688copy a reference to the deleted object in a temporary variable, update
689the list data structure, and then call \code{Py_DECREF()} for the
690temporary variable.
691\end{cfuncdesc}
692
693\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
694Decrement the reference count for object \code{o}.The object may be
695\NULL{}, in which case the function has no effect; otherwise the
696effect is the same as for \code{Py_DECREF()}, and the same warning
697applies.
698\end{cfuncdesc}
699
Guido van Rossumae110af1997-05-22 20:11:52 +0000700The following functions are only for internal use:
701\code{_Py_Dealloc}, \code{_Py_ForgetReference}, \code{_Py_NewReference},
702as well as the global variable \code{_Py_RefTotal}.
703
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000704
705\chapter{Exception Handling}
706
707The functions in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000708exceptions. It is important to understand some of the basics of
709Python exception handling. It works somewhat like the Unix
710\code{errno} variable: there is a global indicator (per thread) of the
711last error that occurred. Most functions don't clear this on success,
712but will set it to indicate the cause of the error on failure. Most
713functions also return an error indicator, usually \NULL{} if they are
714supposed to return a pointer, or -1 if they return an integer
715(exception: the \code{PyArg_Parse*()} functions return 1 for success and
7160 for failure). When a function must fail because of some function it
717called failed, it generally doesn't set the error indicator; the
718function it called already set it.
719
720The error indicator consists of three Python objects corresponding to
721the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
722\code{sys.exc_traceback}. API functions exist to interact with the
723error indicator in various ways. There is a separate error indicator
724for each thread.
725
726% XXX Order of these should be more thoughtful.
727% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000728
729\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000730Print a standard traceback to \code{sys.stderr} and clear the error
731indicator. Call this function only when the error indicator is set.
732(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000733\end{cfuncdesc}
734
Guido van Rossumae110af1997-05-22 20:11:52 +0000735\begin{cfuncdesc}{PyObject *}{PyErr_Occurred}{}
736Test whether the error indicator is set. If set, return the exception
737\code{type} (the first argument to the last call to one of the
738\code{PyErr_Set*()} functions or to \code{PyErr_Restore()}). If not
739set, return \NULL{}. You do not own a reference to the return value,
Guido van Rossum42cefd01997-10-05 15:27:29 +0000740so you do not need to \code{Py_DECREF()} it. Note: do not compare the
741return value to a specific exception; use
742\code{PyErr_ExceptionMatches} instead, shown below.
743\end{cfuncdesc}
744
745\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000746\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000747Equivalent to
748\code{PyErr_GivenExceptionMatches(PyErr_Occurred(), \var{exc})}.
749This should only be called when an exception is actually set.
750\end{cfuncdesc}
751
752\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000753\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000754Return true if the \var{given} exception matches the exception in
755\var{exc}. If \var{exc} is a class object, this also returns true
756when \var{given} is a subclass. If \var{exc} is a tuple, all
757exceptions in the tuple (and recursively in subtuples) are searched
758for a match. This should only be called when an exception is actually
759set.
760\end{cfuncdesc}
761
762\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000763\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000764Under certain circumstances, the values returned by
765\code{PyErr_Fetch()} below can be ``unnormalized'', meaning that
766\var{*exc} is a class object but \var{*val} is not an instance of the
767same class. This function can be used to instantiate the class in
768that case. If the values are already normalized, nothing happens.
Guido van Rossumae110af1997-05-22 20:11:52 +0000769\end{cfuncdesc}
770
771\begin{cfuncdesc}{void}{PyErr_Clear}{}
772Clear the error indicator. If the error indicator is not set, there
773is no effect.
774\end{cfuncdesc}
775
776\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue, PyObject **ptraceback}
777Retrieve the error indicator into three variables whose addresses are
778passed. If the error indicator is not set, set all three variables to
779\NULL{}. If it is set, it will be cleared and you own a reference to
780each object retrieved. The value and traceback object may be \NULL{}
781even when the type object is not. \strong{Note:} this function is
782normally only used by code that needs to handle exceptions or by code
783that needs to save and restore the error indicator temporarily.
784\end{cfuncdesc}
785
786\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value, PyObject *traceback}
787Set the error indicator from the three objects. If the error
788indicator is already set, it is cleared first. If the objects are
789\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
790and non-\NULL{} value or traceback. The exception type should be a
791string or class; if it is a class, the value should be an instance of
792that class. Do not pass an invalid exception type or value.
793(Violating these rules will cause subtle problems later.) This call
794takes away a reference to each object, i.e. you must own a reference
795to each object before the call and after the call you no longer own
796these references. (If you don't understand this, don't use this
797function. I warned you.) \strong{Note:} this function is normally
798only used by code that needs to save and restore the error indicator
799temporarily.
800\end{cfuncdesc}
801
802\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
803This is the most common way to set the error indicator. The first
804argument specifies the exception type; it is normally one of the
805standard exceptions, e.g. \code{PyExc_RuntimeError}. You need not
806increment its reference count. The second argument is an error
807message; it is converted to a string object.
808\end{cfuncdesc}
809
810\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
811This function is similar to \code{PyErr_SetString()} but lets you
812specify an arbitrary Python object for the ``value'' of the exception.
813You need not increment its reference count.
814\end{cfuncdesc}
815
816\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
817This is a shorthand for \code{PyErr_SetString(\var{type}, Py_None}.
818\end{cfuncdesc}
819
820\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
821This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
822\var{message})}, where \var{message} indicates that a built-in operation
823was invoked with an illegal argument. It is mostly for internal use.
824\end{cfuncdesc}
825
826\begin{cfuncdesc}{PyObject *}{PyErr_NoMemory}{}
827This is a shorthand for \code{PyErr_SetNone(PyExc_MemoryError)}; it
828returns \NULL{} so an object allocation function can write
829\code{return PyErr_NoMemory();} when it runs out of memory.
830\end{cfuncdesc}
831
832\begin{cfuncdesc}{PyObject *}{PyErr_SetFromErrno}{PyObject *type}
833This is a convenience function to raise an exception when a C library
834function has returned an error and set the C variable \code{errno}.
835It constructs a tuple object whose first item is the integer
836\code{errno} value and whose second item is the corresponding error
837message (gotten from \code{strerror()}), and then calls
838\code{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
839the \code{errno} value is \code{EINTR}, indicating an interrupted
840system call, this calls \code{PyErr_CheckSignals()}, and if that set
841the error indicator, leaves it set to that. The function always
842returns \NULL{}, so a wrapper function around a system call can write
843\code{return PyErr_NoMemory();} when the system call returns an error.
844\end{cfuncdesc}
845
846\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
847This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
848\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000849operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000850argument. It is mostly for internal use.
851\end{cfuncdesc}
852
853\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
854This function interacts with Python's signal handling. It checks
855whether a signal has been sent to the processes and if so, invokes the
856corresponding signal handler. If the \code{signal} module is
857supported, this can invoke a signal handler written in Python. In all
858cases, the default effect for \code{SIGINT} is to raise the
859\code{KeyboadInterrupt} exception. If an exception is raised the
860error indicator is set and the function returns 1; otherwise the
861function returns 0. The error indicator may or may not be cleared if
862it was previously set.
863\end{cfuncdesc}
864
865\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
866This function is obsolete (XXX or platform dependent?). It simulates
867the effect of a \code{SIGINT} signal arriving -- the next time
868\code{PyErr_CheckSignals()} is called, \code{KeyboadInterrupt} will be
869raised.
870\end{cfuncdesc}
871
Guido van Rossum42cefd01997-10-05 15:27:29 +0000872\begin{cfuncdesc}{PyObject *}{PyErr_NewException}{char *name,
873PyObject *base, PyObject *dict}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000874\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000875This utility function creates and returns a new exception object. The
876\var{name} argument must be the name of the new exception, a C string
877of the form \code{module.class}. The \var{base} and \var{dict}
878arguments are normally \code{NULL}. Normally, this creates a class
879object derived from the root for all exceptions, the built-in name
880\code{Exception} (accessible in C as \code{PyExc_Exception}). In this
881case the \code{__module__} attribute of the new class is set to the
882first part (up to the last dot) of the \var{name} argument, and the
883class name is set to the last part (after the last dot). When the
884user has specified the \code{-X} command line option to use string
885exceptions, for backward compatibility, or when the \var{base}
886argument is not a class object (and not \code{NULL}), a string object
887created from the entire \var{name} argument is returned. The
888\var{base} argument can be used to specify an alternate base class.
889The \var{dict} argument can be used to specify a dictionary of class
890variables and methods.
891\end{cfuncdesc}
892
893
Guido van Rossumae110af1997-05-22 20:11:52 +0000894\section{Standard Exceptions}
895
896All standard Python exceptions are available as global variables whose
897names are \code{PyExc_} followed by the Python exception name.
898These have the type \code{PyObject *}; they are all string objects.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000899For completeness, here are all the variables (the first four are new
900in Python 1.5a4):
901\code{PyExc_Exception},
902\code{PyExc_StandardError},
903\code{PyExc_ArithmeticError},
904\code{PyExc_LookupError},
Guido van Rossumae110af1997-05-22 20:11:52 +0000905\code{PyExc_AssertionError},
906\code{PyExc_AttributeError},
907\code{PyExc_EOFError},
908\code{PyExc_FloatingPointError},
909\code{PyExc_IOError},
910\code{PyExc_ImportError},
911\code{PyExc_IndexError},
912\code{PyExc_KeyError},
913\code{PyExc_KeyboardInterrupt},
914\code{PyExc_MemoryError},
915\code{PyExc_NameError},
916\code{PyExc_OverflowError},
917\code{PyExc_RuntimeError},
918\code{PyExc_SyntaxError},
919\code{PyExc_SystemError},
920\code{PyExc_SystemExit},
921\code{PyExc_TypeError},
922\code{PyExc_ValueError},
923\code{PyExc_ZeroDivisionError}.
924
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000925
926\chapter{Utilities}
927
928The functions in this chapter perform various utility tasks, such as
929parsing function arguments and constructing Python values from C
930values.
931
Guido van Rossum42cefd01997-10-05 15:27:29 +0000932\section{OS Utilities}
933
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000934\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
935Return true (nonzero) if the standard I/O file \code{fp} with name
936\code{filename} is deemed interactive. This is the case for files for
937which \code{isatty(fileno(fp))} is true. If the global flag
938\code{Py_InteractiveFlag} is true, this function also returns true if
939the \code{name} pointer is \NULL{} or if the name is equal to one of
940the strings \code{"<stdin>"} or \code{"???"}.
941\end{cfuncdesc}
942
943\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
944Return the time of last modification of the file \code{filename}.
945The result is encoded in the same way as the timestamp returned by
946the standard C library function \code{time()}.
947\end{cfuncdesc}
948
949
Guido van Rossum42cefd01997-10-05 15:27:29 +0000950\section{Importing modules}
951
952\begin{cfuncdesc}{PyObject *}{PyImport_ImportModule}{char *name}
953This is a simplified interface to \code{PyImport_ImportModuleEx}
954below, leaving the \var{globals} and \var{locals} arguments set to
955\code{NULL}. When the \var{name} argument contains a dot (i.e., when
956it specifies a submodule of a package), the \var{fromlist} argument is
957set to the list \code{['*']} so that the return value is the named
958module rather than the top-level package containing it as would
959otherwise be the case. (Unfortunately, this has an additional side
960effect when \var{name} in fact specifies a subpackage instead of a
961submodule: the submodules specified in the package's \code{__all__}
962variable are loaded.) Return a new reference to the imported module,
963or \code{NULL} with an exception set on failure (the module may still
964be created in this case).
965\end{cfuncdesc}
966
967\begin{cfuncdesc}{PyObject *}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000968\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +0000969Import a module. This is best described by referring to the built-in
970Python function \code{__import()__}, as the standard
971\code{__import__()} function calls this function directly.
972
Guido van Rossum42cefd01997-10-05 15:27:29 +0000973The return value is a new reference to the imported module or
974top-level package, or \code{NULL} with an exception set on failure
Guido van Rossumc44d3d61997-10-06 05:10:47 +0000975(the module may still be created in this case). Like for
976\code{__import__()}, the return value when a submodule of a package
977was requested is normally the top-level package, unless a non-empty
978\var{fromlist} was given.
Guido van Rossum42cefd01997-10-05 15:27:29 +0000979\end{cfuncdesc}
980
981\begin{cfuncdesc}{PyObject *}{PyImport_Import}{PyObject *name}
982This is a higher-level interface that calls the current ``import hook
983function''. It invokes the \code{__import__()} function from the
984\code{__builtins__} of the current globals. This means that the
985import is done using whatever import hooks are installed in the
986current environment, e.g. by \code{rexec} or \code{ihooks}.
987\end{cfuncdesc}
988
989\begin{cfuncdesc}{PyObject *}{PyImport_ReloadModule}{PyObject *m}
990Reload a module. This is best described by referring to the built-in
991Python function \code{reload()}, as the standard \code{reload()}
992function calls this function directly. Return a new reference to the
993reloaded module, or \code{NULL} with an exception set on failure (the
994module still exists in this case).
995\end{cfuncdesc}
996
997\begin{cfuncdesc}{PyObject *}{PyImport_AddModule}{char *name}
998Return the module object corresponding to a module name. The
999\var{name} argument may be of the form \code{package.module}). First
1000check the modules dictionary if there's one there, and if not, create
1001a new one and insert in in the modules dictionary. Because the former
1002action is most common, this does not return a new reference, and you
1003do not own the returned reference. Return \code{NULL} with an
1004exception set on failure.
1005\end{cfuncdesc}
1006
1007\begin{cfuncdesc}{PyObject *}{PyImport_ExecCodeModule}{char *name, PyObject *co}
1008Given a module name (possibly of the form \code{package.module}) and a
1009code object read from a Python bytecode file or obtained from the
1010built-in function \code{compile()}, load the module. Return a new
1011reference to the module object, or \code{NULL} with an exception set
1012if an error occurred (the module may still be created in this case).
1013(This function would reload the module if it was already imported.)
1014\end{cfuncdesc}
1015
1016\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
1017Return the magic number for Python bytecode files (a.k.a. \code{.pyc}
1018and \code{.pyo} files). The magic number should be present in the
1019first four bytes of the bytecode file, in little-endian byte order.
1020\end{cfuncdesc}
1021
1022\begin{cfuncdesc}{PyObject *}{PyImport_GetModuleDict}{}
1023Return the dictionary used for the module administration
1024(a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1025variable.
1026\end{cfuncdesc}
1027
1028\begin{cfuncdesc}{void}{_PyImport_Init}{}
1029Initialize the import mechanism. For internal use only.
1030\end{cfuncdesc}
1031
1032\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1033Empty the module table. For internal use only.
1034\end{cfuncdesc}
1035
1036\begin{cfuncdesc}{void}{_PyImport_Fini}{}
1037Finalize the import mechanism. For internal use only.
1038\end{cfuncdesc}
1039
1040\begin{cvardesc}{extern PyObject *}{_PyImport_FindExtension}{char *, char *}
1041For internal use only.
1042\end{cvardesc}
1043
1044\begin{cvardesc}{extern PyObject *}{_PyImport_FixupExtension}{char *, char *}
1045For internal use only.
1046\end{cvardesc}
1047
1048\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *}
1049Load a frozen module. Return \code{1} for success, \code{0} if the
1050module is not found, and \code{-1} with an exception set if the
1051initialization failed. To access the imported module on a successful
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001052load, use \code{PyImport_ImportModule())}.
Guido van Rossum42cefd01997-10-05 15:27:29 +00001053(Note the misnomer -- this function would reload the module if it was
1054already imported.)
1055\end{cfuncdesc}
1056
1057\begin{ctypedesc}{struct _frozen}
1058This is the structure type definition for frozen module descriptors,
1059as generated by the \code{freeze} utility (see \file{Tools/freeze/} in
1060the Python source distribution). Its definition is:
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001061\begin{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001062struct _frozen {
Fred Drake36fbe761997-10-13 18:18:33 +00001063 char *name;
1064 unsigned char *code;
1065 int size;
Guido van Rossum42cefd01997-10-05 15:27:29 +00001066};
Guido van Rossum9faf4c51997-10-07 14:38:54 +00001067\end{verbatim}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001068\end{ctypedesc}
1069
1070\begin{cvardesc}{struct _frozen *}{PyImport_FrozenModules}
1071This pointer is initialized to point to an array of \code{struct
Fred Drake36fbe761997-10-13 18:18:33 +00001072_frozen} records, terminated by one whose members are all \code{NULL}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001073or zero. When a frozen module is imported, it is searched in this
1074table. Third party code could play tricks with this to provide a
1075dynamically created collection of frozen modules.
1076\end{cvardesc}
1077
1078
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001079\chapter{Debugging}
1080
1081XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
1082
1083
1084\chapter{The Very High Level Layer}
1085
1086The functions in this chapter will let you execute Python source code
1087given in a file or a buffer, but they will not let you interact in a
1088more detailed way with the interpreter.
1089
Guido van Rossumae110af1997-05-22 20:11:52 +00001090\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *, char *}
1091\end{cfuncdesc}
1092
1093\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *}
1094\end{cfuncdesc}
1095
1096\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *, char *}
1097\end{cfuncdesc}
1098
1099\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *, char *}
1100\end{cfuncdesc}
1101
1102\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *, char *}
1103\end{cfuncdesc}
1104
1105\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseString}{char *, int}
1106\end{cfuncdesc}
1107
1108\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseFile}{FILE *, char *, int}
1109\end{cfuncdesc}
1110
Guido van Rossumb9046291997-08-21 02:28:57 +00001111\begin{cfuncdesc}{}{PyObject *PyRun_String}{char *, int, PyObject *, PyObject *}
Guido van Rossumae110af1997-05-22 20:11:52 +00001112\end{cfuncdesc}
1113
Guido van Rossumb9046291997-08-21 02:28:57 +00001114\begin{cfuncdesc}{}{PyObject *PyRun_File}{FILE *, char *, int, PyObject *, PyObject *}
Guido van Rossumae110af1997-05-22 20:11:52 +00001115\end{cfuncdesc}
1116
Guido van Rossumb9046291997-08-21 02:28:57 +00001117\begin{cfuncdesc}{}{PyObject *Py_CompileString}{char *, char *, int}
Guido van Rossumae110af1997-05-22 20:11:52 +00001118\end{cfuncdesc}
1119
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001120
1121\chapter{Abstract Objects Layer}
1122
1123The functions in this chapter interact with Python objects regardless
1124of their type, or with wide classes of object types (e.g. all
1125numerical types, or all sequence types). When used on object types
1126for which they do not apply, they will flag a Python exception.
1127
1128\section{Object Protocol}
1129
1130\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
1131Print an object \code{o}, on file \code{fp}. Returns -1 on error
1132The flags argument is used to enable certain printing
1133options. The only option currently supported is \code{Py_Print_RAW}.
1134\end{cfuncdesc}
1135
1136\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
1137Returns 1 if o has the attribute attr_name, and 0 otherwise.
1138This is equivalent to the Python expression:
1139\code{hasattr(o,attr_name)}.
1140This function always succeeds.
1141\end{cfuncdesc}
1142
1143\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o, char *attr_name}
Guido van Rossum59a61351997-08-14 20:34:33 +00001144Retrieve an attributed named attr_name from object o.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001145Returns the attribute value on success, or \NULL{} on failure.
1146This is the equivalent of the Python expression: \code{o.attr_name}.
1147\end{cfuncdesc}
1148
1149
1150\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
1151Returns 1 if o has the attribute attr_name, and 0 otherwise.
1152This is equivalent to the Python expression:
1153\code{hasattr(o,attr_name)}.
1154This function always succeeds.
1155\end{cfuncdesc}
1156
1157
1158\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o, PyObject *attr_name}
1159Retrieve an attributed named attr_name form object o.
1160Returns the attribute value on success, or \NULL{} on failure.
1161This is the equivalent of the Python expression: o.attr_name.
1162\end{cfuncdesc}
1163
1164
1165\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
1166Set the value of the attribute named \code{attr_name}, for object \code{o},
1167to the value \code{v}. Returns -1 on failure. This is
1168the equivalent of the Python statement: \code{o.attr_name=v}.
1169\end{cfuncdesc}
1170
1171
1172\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
1173Set the value of the attribute named \code{attr_name}, for
1174object \code{o},
1175to the value \code{v}. Returns -1 on failure. This is
1176the equivalent of the Python statement: \code{o.attr_name=v}.
1177\end{cfuncdesc}
1178
1179
1180\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
1181Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1182failure. This is the equivalent of the Python
1183statement: \code{del o.attr_name}.
1184\end{cfuncdesc}
1185
1186
1187\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
1188Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1189failure. This is the equivalent of the Python
1190statement: \code{del o.attr_name}.
1191\end{cfuncdesc}
1192
1193
1194\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
1195Compare the values of \code{o1} and \code{o2} using a routine provided by
1196\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1197The result of the comparison is returned in \code{result}. Returns
1198-1 on failure. This is the equivalent of the Python
1199statement: \code{result=cmp(o1,o2)}.
1200\end{cfuncdesc}
1201
1202
1203\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
1204Compare the values of \code{o1} and \code{o2} using a routine provided by
1205\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1206Returns the result of the comparison on success. On error,
1207the value returned is undefined. This is equivalent to the
1208Python expression: \code{cmp(o1,o2)}.
1209\end{cfuncdesc}
1210
1211
1212\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
1213Compute the string representation of object, \code{o}. Returns the
1214string representation on success, \NULL{} on failure. This is
1215the equivalent of the Python expression: \code{repr(o)}.
1216Called by the \code{repr()} built-in function and by reverse quotes.
1217\end{cfuncdesc}
1218
1219
1220\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
1221Compute the string representation of object, \code{o}. Returns the
1222string representation on success, \NULL{} on failure. This is
1223the equivalent of the Python expression: \code{str(o)}.
1224Called by the \code{str()} built-in function and by the \code{print}
1225statement.
1226\end{cfuncdesc}
1227
1228
1229\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
1230Determine if the object \code{o}, is callable. Return 1 if the
1231object is callable and 0 otherwise.
1232This function always succeeds.
1233\end{cfuncdesc}
1234
1235
1236\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object, PyObject *args}
1237Call a callable Python object \code{callable_object}, with
1238arguments given by the tuple \code{args}. If no arguments are
1239needed, then args may be \NULL{}. Returns the result of the
1240call on success, or \NULL{} on failure. This is the equivalent
1241of the Python expression: \code{apply(o, args)}.
1242\end{cfuncdesc}
1243
1244\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
1245Call a callable Python object \code{callable_object}, with a
1246variable number of C arguments. The C arguments are described
1247using a mkvalue-style format string. The format may be \NULL{},
1248indicating that no arguments are provided. Returns the
1249result of the call on success, or \NULL{} on failure. This is
1250the equivalent of the Python expression: \code{apply(o,args)}.
1251\end{cfuncdesc}
1252
1253
1254\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
1255Call the method named \code{m} of object \code{o} with a variable number of
1256C arguments. The C arguments are described by a mkvalue
1257format string. The format may be \NULL{}, indicating that no
1258arguments are provided. Returns the result of the call on
1259success, or \NULL{} on failure. This is the equivalent of the
1260Python expression: \code{o.method(args)}.
1261Note that Special method names, such as "\code{__add__}",
1262"\code{__getitem__}", and so on are not supported. The specific
1263abstract-object routines for these must be used.
1264\end{cfuncdesc}
1265
1266
1267\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
1268Compute and return the hash value of an object \code{o}. On
1269failure, return -1. This is the equivalent of the Python
1270expression: \code{hash(o)}.
1271\end{cfuncdesc}
1272
1273
1274\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
1275Returns 1 if the object \code{o} is considered to be true, and
12760 otherwise. This is equivalent to the Python expression:
1277\code{not not o}.
1278This function always succeeds.
1279\end{cfuncdesc}
1280
1281
1282\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1283On success, returns a type object corresponding to the object
1284type of object \code{o}. On failure, returns \NULL{}. This is
1285equivalent to the Python expression: \code{type(o)}.
1286\end{cfuncdesc}
1287
1288\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
1289Return the length of object \code{o}. If the object \code{o} provides
1290both sequence and mapping protocols, the sequence length is
1291returned. On error, -1 is returned. This is the equivalent
1292to the Python expression: \code{len(o)}.
1293\end{cfuncdesc}
1294
1295
1296\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
1297Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1298on failure. This is the equivalent of the Python expression:
1299\code{o[key]}.
1300\end{cfuncdesc}
1301
1302
1303\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
1304Map the object \code{key} to the value \code{v}.
1305Returns -1 on failure. This is the equivalent
1306of the Python statement: \code{o[key]=v}.
1307\end{cfuncdesc}
1308
1309
1310\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key, PyObject *v}
1311Delete the mapping for \code{key} from \code{*o}. Returns -1
1312on failure.
Guido van Rossum59a61351997-08-14 20:34:33 +00001313This is the equivalent of the Python statement: \code{del o[key]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001314\end{cfuncdesc}
1315
1316
1317\section{Number Protocol}
1318
1319\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
1320Returns 1 if the object \code{o} provides numeric protocols, and
1321false otherwise.
1322This function always succeeds.
1323\end{cfuncdesc}
1324
1325
1326\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
1327Returns the result of adding \code{o1} and \code{o2}, or null on failure.
1328This is the equivalent of the Python expression: \code{o1+o2}.
1329\end{cfuncdesc}
1330
1331
1332\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
1333Returns the result of subtracting \code{o2} from \code{o1}, or null on
1334failure. This is the equivalent of the Python expression:
1335\code{o1-o2}.
1336\end{cfuncdesc}
1337
1338
1339\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
1340Returns the result of multiplying \code{o1} and \code{o2}, or null on
1341failure. This is the equivalent of the Python expression:
1342\code{o1*o2}.
1343\end{cfuncdesc}
1344
1345
1346\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
1347Returns the result of dividing \code{o1} by \code{o2}, or null on failure.
1348This is the equivalent of the Python expression: \code{o1/o2}.
1349\end{cfuncdesc}
1350
1351
1352\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
1353Returns the remainder of dividing \code{o1} by \code{o2}, or null on
1354failure. This is the equivalent of the Python expression:
1355\code{o1\%o2}.
1356\end{cfuncdesc}
1357
1358
1359\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
1360See the built-in function divmod. Returns \NULL{} on failure.
1361This is the equivalent of the Python expression:
1362\code{divmod(o1,o2)}.
1363\end{cfuncdesc}
1364
1365
1366\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
1367See the built-in function pow. Returns \NULL{} on failure.
1368This is the equivalent of the Python expression:
1369\code{pow(o1,o2,o3)}, where \code{o3} is optional.
1370\end{cfuncdesc}
1371
1372
1373\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
1374Returns the negation of \code{o} on success, or null on failure.
1375This is the equivalent of the Python expression: \code{-o}.
1376\end{cfuncdesc}
1377
1378
1379\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
1380Returns \code{o} on success, or \NULL{} on failure.
1381This is the equivalent of the Python expression: \code{+o}.
1382\end{cfuncdesc}
1383
1384
1385\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
1386Returns the absolute value of \code{o}, or null on failure. This is
1387the equivalent of the Python expression: \code{abs(o)}.
1388\end{cfuncdesc}
1389
1390
1391\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
1392Returns the bitwise negation of \code{o} on success, or \NULL{} on
1393failure. This is the equivalent of the Python expression:
Guido van Rossum59a61351997-08-14 20:34:33 +00001394\code{\~o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001395\end{cfuncdesc}
1396
1397
1398\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
1399Returns the result of left shifting \code{o1} by \code{o2} on success, or
1400\NULL{} on failure. This is the equivalent of the Python
1401expression: \code{o1 << o2}.
1402\end{cfuncdesc}
1403
1404
1405\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
1406Returns the result of right shifting \code{o1} by \code{o2} on success, or
1407\NULL{} on failure. This is the equivalent of the Python
1408expression: \code{o1 >> o2}.
1409\end{cfuncdesc}
1410
1411
1412\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
1413Returns the result of "anding" \code{o2} and \code{o2} on success and \NULL{}
1414on failure. This is the equivalent of the Python
1415expression: \code{o1 and o2}.
1416\end{cfuncdesc}
1417
1418
1419\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
1420Returns the bitwise exclusive or of \code{o1} by \code{o2} on success, or
1421\NULL{} on failure. This is the equivalent of the Python
1422expression: \code{o1\^{ }o2}.
1423\end{cfuncdesc}
1424
1425\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Guido van Rossum59a61351997-08-14 20:34:33 +00001426Returns the result of \code{o1} and \code{o2} on success, or \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001427failure. This is the equivalent of the Python expression:
1428\code{o1 or o2}.
1429\end{cfuncdesc}
1430
1431
1432\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject *o1, PyObject *o2}
1433This function takes the addresses of two variables of type
1434\code{PyObject*}.
1435
1436If the objects pointed to by \code{*p1} and \code{*p2} have the same type,
1437increment their reference count and return 0 (success).
1438If the objects can be converted to a common numeric type,
1439replace \code{*p1} and \code{*p2} by their converted value (with 'new'
1440reference counts), and return 0.
1441If no conversion is possible, or if some other error occurs,
1442return -1 (failure) and don't increment the reference counts.
1443The call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1444statement \code{o1, o2 = coerce(o1, o2)}.
1445\end{cfuncdesc}
1446
1447
1448\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
1449Returns the \code{o} converted to an integer object on success, or
1450\NULL{} on failure. This is the equivalent of the Python
1451expression: \code{int(o)}.
1452\end{cfuncdesc}
1453
1454
1455\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
1456Returns the \code{o} converted to a long integer object on success,
1457or \NULL{} on failure. This is the equivalent of the Python
1458expression: \code{long(o)}.
1459\end{cfuncdesc}
1460
1461
1462\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
1463Returns the \code{o} converted to a float object on success, or \NULL{}
1464on failure. This is the equivalent of the Python expression:
1465\code{float(o)}.
1466\end{cfuncdesc}
1467
1468
1469\section{Sequence protocol}
1470
1471\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
1472Return 1 if the object provides sequence protocol, and 0
1473otherwise.
1474This function always succeeds.
1475\end{cfuncdesc}
1476
1477
1478\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
1479Return the concatination of \code{o1} and \code{o2} on success, and \NULL{} on
1480failure. This is the equivalent of the Python
1481expression: \code{o1+o2}.
1482\end{cfuncdesc}
1483
1484
1485\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Guido van Rossum59a61351997-08-14 20:34:33 +00001486Return the result of repeating sequence object \code{o} \code{count} times,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001487or \NULL{} on failure. This is the equivalent of the Python
1488expression: \code{o*count}.
1489\end{cfuncdesc}
1490
1491
1492\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
1493Return the ith element of \code{o}, or \NULL{} on failure. This is the
1494equivalent of the Python expression: \code{o[i]}.
1495\end{cfuncdesc}
1496
1497
1498\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
1499Return the slice of sequence object \code{o} between \code{i1} and \code{i2}, or
1500\NULL{} on failure. This is the equivalent of the Python
1501expression, \code{o[i1:i2]}.
1502\end{cfuncdesc}
1503
1504
1505\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
1506Assign object \code{v} to the \code{i}th element of \code{o}.
1507Returns -1 on failure. This is the equivalent of the Python
1508statement, \code{o[i]=v}.
1509\end{cfuncdesc}
1510
1511\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
1512Delete the \code{i}th element of object \code{v}. Returns
1513-1 on failure. This is the equivalent of the Python
1514statement: \code{del o[i]}.
1515\end{cfuncdesc}
1516
1517\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1, int i2, PyObject *v}
1518Assign the sequence object \code{v} to the slice in sequence
1519object \code{o} from \code{i1} to \code{i2}. This is the equivalent of the Python
1520statement, \code{o[i1:i2]=v}.
1521\end{cfuncdesc}
1522
1523\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
1524Delete the slice in sequence object, \code{o}, from \code{i1} to \code{i2}.
1525Returns -1 on failure. This is the equivalent of the Python
1526statement: \code{del o[i1:i2]}.
1527\end{cfuncdesc}
1528
1529\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1530Returns the \code{o} as a tuple on success, and \NULL{} on failure.
1531This is equivalent to the Python expression: \code{tuple(o)}.
1532\end{cfuncdesc}
1533
1534\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
1535Return the number of occurrences of \code{value} on \code{o}, that is,
1536return the number of keys for which \code{o[key]==value}. On
1537failure, return -1. This is equivalent to the Python
1538expression: \code{o.count(value)}.
1539\end{cfuncdesc}
1540
1541\begin{cfuncdesc}{int}{PySequence_In}{PyObject *o, PyObject *value}
1542Determine if \code{o} contains \code{value}. If an item in \code{o} is equal to
1543\code{value}, return 1, otherwise return 0. On error, return -1. This
1544is equivalent to the Python expression: \code{value in o}.
1545\end{cfuncdesc}
1546
1547\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Guido van Rossum59a61351997-08-14 20:34:33 +00001548Return the first index for which \code{o[i]==value}. On error,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001549return -1. This is equivalent to the Python
1550expression: \code{o.index(value)}.
1551\end{cfuncdesc}
1552
1553\section{Mapping protocol}
1554
1555\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
1556Return 1 if the object provides mapping protocol, and 0
1557otherwise.
1558This function always succeeds.
1559\end{cfuncdesc}
1560
1561
1562\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
1563Returns the number of keys in object \code{o} on success, and -1 on
1564failure. For objects that do not provide sequence protocol,
1565this is equivalent to the Python expression: \code{len(o)}.
1566\end{cfuncdesc}
1567
1568
1569\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
1570Remove the mapping for object \code{key} from the object \code{o}.
1571Return -1 on failure. This is equivalent to
1572the Python statement: \code{del o[key]}.
1573\end{cfuncdesc}
1574
1575
1576\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
1577Remove the mapping for object \code{key} from the object \code{o}.
1578Return -1 on failure. This is equivalent to
1579the Python statement: \code{del o[key]}.
1580\end{cfuncdesc}
1581
1582
1583\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
1584On success, return 1 if the mapping object has the key \code{key}
1585and 0 otherwise. This is equivalent to the Python expression:
1586\code{o.has_key(key)}.
1587This function always succeeds.
1588\end{cfuncdesc}
1589
1590
1591\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
1592Return 1 if the mapping object has the key \code{key}
1593and 0 otherwise. This is equivalent to the Python expression:
1594\code{o.has_key(key)}.
1595This function always succeeds.
1596\end{cfuncdesc}
1597
1598
1599\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
1600On success, return a list of the keys in object \code{o}. On
1601failure, return \NULL{}. This is equivalent to the Python
1602expression: \code{o.keys()}.
1603\end{cfuncdesc}
1604
1605
1606\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
1607On success, return a list of the values in object \code{o}. On
1608failure, return \NULL{}. This is equivalent to the Python
1609expression: \code{o.values()}.
1610\end{cfuncdesc}
1611
1612
1613\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
1614On success, return a list of the items in object \code{o}, where
1615each item is a tuple containing a key-value pair. On
1616failure, return \NULL{}. This is equivalent to the Python
1617expression: \code{o.items()}.
1618\end{cfuncdesc}
1619
1620\begin{cfuncdesc}{int}{PyMapping_Clear}{PyObject *o}
1621Make object \code{o} empty. Returns 1 on success and 0 on failure.
1622This is equivalent to the Python statement:
1623\code{for key in o.keys(): del o[key]}
1624\end{cfuncdesc}
1625
1626
1627\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
1628Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1629on failure. This is the equivalent of the Python expression:
1630\code{o[key]}.
1631\end{cfuncdesc}
1632
1633\begin{cfuncdesc}{PyObject*}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
1634Map the object \code{key} to the value \code{v} in object \code{o}. Returns
1635-1 on failure. This is the equivalent of the Python
1636statement: \code{o[key]=v}.
1637\end{cfuncdesc}
1638
1639
1640\section{Constructors}
1641
1642\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *file_name, char *mode}
1643On success, returns a new file object that is opened on the
1644file given by \code{file_name}, with a file mode given by \code{mode},
1645where \code{mode} has the same semantics as the standard C routine,
1646fopen. On failure, return -1.
1647\end{cfuncdesc}
1648
1649\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp, char *file_name, char *mode, int close_on_del}
1650Return a new file object for an already opened standard C
1651file pointer, \code{fp}. A file name, \code{file_name}, and open mode,
1652\code{mode}, must be provided as well as a flag, \code{close_on_del}, that
1653indicates whether the file is to be closed when the file
1654object is destroyed. On failure, return -1.
1655\end{cfuncdesc}
1656
1657\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
1658Returns a new float object with the value \code{v} on success, and
1659\NULL{} on failure.
1660\end{cfuncdesc}
1661
1662\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long v}
1663Returns a new int object with the value \code{v} on success, and
1664\NULL{} on failure.
1665\end{cfuncdesc}
1666
1667\begin{cfuncdesc}{PyObject*}{PyList_New}{int l}
1668Returns a new list of length \code{l} on success, and \NULL{} on
1669failure.
1670\end{cfuncdesc}
1671
1672\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
1673Returns a new long object with the value \code{v} on success, and
1674\NULL{} on failure.
1675\end{cfuncdesc}
1676
1677\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
1678Returns a new long object with the value \code{v} on success, and
1679\NULL{} on failure.
1680\end{cfuncdesc}
1681
1682\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1683Returns a new empty dictionary on success, and \NULL{} on
1684failure.
1685\end{cfuncdesc}
1686
1687\begin{cfuncdesc}{PyObject*}{PyString_FromString}{char *v}
1688Returns a new string object with the value \code{v} on success, and
1689\NULL{} on failure.
1690\end{cfuncdesc}
1691
1692\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{char *v, int l}
1693Returns a new string object with the value \code{v} and length \code{l}
1694on success, and \NULL{} on failure.
1695\end{cfuncdesc}
1696
1697\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int l}
1698Returns a new tuple of length \code{l} on success, and \NULL{} on
1699failure.
1700\end{cfuncdesc}
1701
1702
1703\chapter{Concrete Objects Layer}
1704
1705The functions in this chapter are specific to certain Python object
1706types. Passing them an object of the wrong type is not a good idea;
1707if you receive an object from a Python program and you are not sure
1708that it has the right type, you must perform a type check first;
1709e.g. to check that an object is a dictionary, use
1710\code{PyDict_Check()}.
1711
1712
1713\chapter{Defining New Object Types}
1714
1715\begin{cfuncdesc}{PyObject *}{_PyObject_New}{PyTypeObject *type}
1716\end{cfuncdesc}
1717
Guido van Rossumae110af1997-05-22 20:11:52 +00001718\begin{cfuncdesc}{PyObject *}{_PyObject_NewVar}{PyTypeObject *type, int size}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001719\end{cfuncdesc}
1720
Guido van Rossumae110af1997-05-22 20:11:52 +00001721\begin{cfuncdesc}{TYPE}{_PyObject_NEW}{TYPE, PyTypeObject *}
1722\end{cfuncdesc}
1723
1724\begin{cfuncdesc}{TYPE}{_PyObject_NEW_VAR}{TYPE, PyTypeObject *, int size}
1725\end{cfuncdesc}
1726
Guido van Rossum4a944d71997-08-14 20:35:38 +00001727\chapter{Initialization, Finalization, and Threads}
1728
Guido van Rossum4a944d71997-08-14 20:35:38 +00001729\begin{cfuncdesc}{void}{Py_Initialize}{}
1730Initialize the Python interpreter. In an application embedding
1731Python, this should be called before using any other Python/C API
1732functions; with the exception of \code{Py_SetProgramName()},
1733\code{PyEval_InitThreads()}, \code{PyEval_ReleaseLock()}, and
1734\code{PyEval_AcquireLock()}. This initializes the table of loaded
1735modules (\code{sys.modules}), and creates the fundamental modules
1736\code{__builtin__}, \code{__main__} and \code{sys}. It also
1737initializes the module search path (\code{sys.path}). It does not set
Guido van Rossum42cefd01997-10-05 15:27:29 +00001738\code{sys.argv}; use \code{PySys_SetArgv()} for that. This is a no-op
1739when called for a second time (without calling \code{Py_Finalize()}
1740first). There is no return value; it is a fatal error if the
1741initialization fails.
1742\end{cfuncdesc}
1743
1744\begin{cfuncdesc}{int}{Py_IsInitialized}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001745\strong{(NEW in 1.5a4!)}
Guido van Rossum42cefd01997-10-05 15:27:29 +00001746Return true (nonzero) when the Python interpreter has been
1747initialized, false (zero) if not. After \code{Py_Finalize()} is
1748called, this returns false until \code{Py_Initialize()} is called
1749again.
Guido van Rossum4a944d71997-08-14 20:35:38 +00001750\end{cfuncdesc}
1751
1752\begin{cfuncdesc}{void}{Py_Finalize}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001753\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001754Undo all initializations made by \code{Py_Initialize()} and subsequent
1755use of Python/C API functions, and destroy all sub-interpreters (see
1756\code{Py_NewInterpreter()} below) that were created and not yet
Guido van Rossum42cefd01997-10-05 15:27:29 +00001757destroyed since the last call to \code{Py_Initialize()}. Ideally,
1758this frees all memory allocated by the Python interpreter. This is a
1759no-op when called for a second time (without calling
1760\code{Py_Initialize()} again first). There is no return value; errors
Guido van Rossum4a944d71997-08-14 20:35:38 +00001761during finalization are ignored.
1762
1763This function is provided for a number of reasons. An embedding
1764application might want to restart Python without having to restart the
1765application itself. An application that has loaded the Python
1766interpreter from a dynamically loadable library (or DLL) might want to
1767free all memory allocated by Python before unloading the DLL. During a
1768hunt for memory leaks in an application a developer might want to free
1769all memory allocated by Python before exiting from the application.
1770
1771\emph{Bugs and caveats:} The destruction of modules and objects in
1772modules is done in random order; this may cause destructors
1773(\code{__del__} methods) to fail when they depend on other objects
1774(even functions) or modules. Dynamically loaded extension modules
1775loaded by Python are not unloaded. Small amounts of memory allocated
1776by the Python interpreter may not be freed (if you find a leak, please
1777report it). Memory tied up in circular references between objects is
1778not freed. Some memory allocated by extension modules may not be
1779freed. Some extension may not work properly if their initialization
1780routine is called more than once; this can happen if an applcation
1781calls \code{Py_Initialize()} and \code{Py_Finalize()} more than once.
1782\end{cfuncdesc}
1783
1784\begin{cfuncdesc}{PyThreadState *}{Py_NewInterpreter}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001785\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001786Create a new sub-interpreter. This is an (almost) totally separate
1787environment for the execution of Python code. In particular, the new
1788interpreter has separate, independent versions of all imported
1789modules, including the fundamental modules \code{__builtin__},
1790\code{__main__} and \code{sys}. The table of loaded modules
1791(\code{sys.modules}) and the module search path (\code{sys.path}) are
1792also separate. The new environment has no \code{sys.argv} variable.
1793It has new standard I/O stream file objects \code{sys.stdin},
1794\code{sys.stdout} and \code{sys.stderr} (however these refer to the
1795same underlying \code{FILE} structures in the C library).
1796
1797The return value points to the first thread state created in the new
1798sub-interpreter. This thread state is made the current thread state.
1799Note that no actual thread is created; see the discussion of thread
1800states below. If creation of the new interpreter is unsuccessful,
1801\code{NULL} is returned; no exception is set since the exception state
1802is stored in the current thread state and there may not be a current
1803thread state. (Like all other Python/C API functions, the global
1804interpreter lock must be held before calling this function and is
1805still held when it returns; however, unlike most other Python/C API
1806functions, there needn't be a current thread state on entry.)
1807
1808Extension modules are shared between (sub-)interpreters as follows:
1809the first time a particular extension is imported, it is initialized
1810normally, and a (shallow) copy of its module's dictionary is
1811squirreled away. When the same extension is imported by another
1812(sub-)interpreter, a new module is initialized and filled with the
1813contents of this copy; the extension's \code{init} function is not
1814called. Note that this is different from what happens when as
1815extension is imported after the interpreter has been completely
1816re-initialized by calling \code{Py_Finalize()} and
1817\code{Py_Initialize()}; in that case, the extension's \code{init}
1818function \emph{is} called again.
1819
1820\emph{Bugs and caveats:} Because sub-interpreters (and the main
1821interpreter) are part of the same process, the insulation between them
1822isn't perfect -- for example, using low-level file operations like
1823\code{os.close()} they can (accidentally or maliciously) affect each
1824other's open files. Because of the way extensions are shared between
1825(sub-)interpreters, some extensions may not work properly; this is
1826especially likely when the extension makes use of (static) global
1827variables, or when the extension manipulates its module's dictionary
1828after its initialization. It is possible to insert objects created in
1829one sub-interpreter into a namespace of another sub-interpreter; this
1830should be done with great care to avoid sharing user-defined
1831functions, methods, instances or classes between sub-interpreters,
1832since import operations executed by such objects may affect the
1833wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
1834a hard-to-fix bug that will be addressed in a future release.)
1835\end{cfuncdesc}
1836
1837\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001838\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001839Destroy the (sub-)interpreter represented by the given thread state.
1840The given thread state must be the current thread state. See the
1841discussion of thread states below. When the call returns, the current
1842thread state is \code{NULL}. All thread states associated with this
1843interpreted are destroyed. (The global interpreter lock must be held
1844before calling this function and is still held when it returns.)
1845\code{Py_Finalize()} will destroy all sub-interpreters that haven't
1846been explicitly destroyed at that point.
1847\end{cfuncdesc}
1848
1849\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001850\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001851This function should be called before \code{Py_Initialize()} is called
1852for the first time, if it is called at all. It tells the interpreter
1853the value of the \code{argv[0]} argument to the \code{main()} function
1854of the program. This is used by \code{Py_GetPath()} and some other
1855functions below to find the Python run-time libraries relative to the
1856interpreter executable. The default value is \code{"python"}. The
1857argument should point to a zero-terminated character string in static
1858storage whose contents will not change for the duration of the
1859program's execution. No code in the Python interpreter will change
1860the contents of this storage.
1861\end{cfuncdesc}
1862
1863\begin{cfuncdesc}{char *}{Py_GetProgramName}{}
1864Return the program name set with \code{Py_SetProgramName()}, or the
1865default. The returned string points into static storage; the caller
1866should not modify its value.
1867\end{cfuncdesc}
1868
1869\begin{cfuncdesc}{char *}{Py_GetPrefix}{}
1870Return the ``prefix'' for installed platform-independent files. This
1871is derived through a number of complicated rules from the program name
1872set with \code{Py_SetProgramName()} and some environment variables;
1873for example, if the program name is \code{"/usr/local/bin/python"},
1874the prefix is \code{"/usr/local"}. The returned string points into
1875static storage; the caller should not modify its value. This
1876corresponds to the \code{prefix} variable in the top-level
1877\code{Makefile} and the \code{--prefix} argument to the
1878\code{configure} script at build time. The value is available to
1879Python code as \code{sys.prefix}. It is only useful on Unix. See
1880also the next function.
1881\end{cfuncdesc}
1882
1883\begin{cfuncdesc}{char *}{Py_GetExecPrefix}{}
1884Return the ``exec-prefix'' for installed platform-\emph{de}pendent
1885files. This is derived through a number of complicated rules from the
1886program name set with \code{Py_SetProgramName()} and some environment
1887variables; for example, if the program name is
1888\code{"/usr/local/bin/python"}, the exec-prefix is
1889\code{"/usr/local"}. The returned string points into static storage;
1890the caller should not modify its value. This corresponds to the
1891\code{exec_prefix} variable in the top-level \code{Makefile} and the
1892\code{--exec_prefix} argument to the \code{configure} script at build
1893time. The value is available to Python code as
1894\code{sys.exec_prefix}. It is only useful on Unix.
1895
1896Background: The exec-prefix differs from the prefix when platform
1897dependent files (such as executables and shared libraries) are
1898installed in a different directory tree. In a typical installation,
1899platform dependent files may be installed in the
1900\code{"/usr/local/plat"} subtree while platform independent may be
1901installed in \code{"/usr/local"}.
1902
1903Generally speaking, a platform is a combination of hardware and
1904software families, e.g. Sparc machines running the Solaris 2.x
1905operating system are considered the same platform, but Intel machines
1906running Solaris 2.x are another platform, and Intel machines running
1907Linux are yet another platform. Different major revisions of the same
1908operating system generally also form different platforms. Non-Unix
1909operating systems are a different story; the installation strategies
1910on those systems are so different that the prefix and exec-prefix are
1911meaningless, and set to the empty string. Note that compiled Python
1912bytecode files are platform independent (but not independent from the
1913Python version by which they were compiled!).
1914
1915System administrators will know how to configure the \code{mount} or
1916\code{automount} programs to share \code{"/usr/local"} between platforms
1917while having \code{"/usr/local/plat"} be a different filesystem for each
1918platform.
1919\end{cfuncdesc}
1920
1921\begin{cfuncdesc}{char *}{Py_GetProgramFullPath}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00001922\strong{(NEW in 1.5a3!)}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001923Return the full program name of the Python executable; this is
1924computed as a side-effect of deriving the default module search path
Guido van Rossum09270b51997-08-15 18:57:32 +00001925from the program name (set by \code{Py_SetProgramName()} above). The
Guido van Rossum4a944d71997-08-14 20:35:38 +00001926returned string points into static storage; the caller should not
1927modify its value. The value is available to Python code as
Guido van Rossum42cefd01997-10-05 15:27:29 +00001928\code{sys.executable}.
Guido van Rossum4a944d71997-08-14 20:35:38 +00001929\end{cfuncdesc}
1930
1931\begin{cfuncdesc}{char *}{Py_GetPath}{}
1932Return the default module search path; this is computed from the
Guido van Rossum09270b51997-08-15 18:57:32 +00001933program name (set by \code{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00001934environment variables. The returned string consists of a series of
1935directory names separated by a platform dependent delimiter character.
1936The delimiter character is \code{':'} on Unix, \code{';'} on
Guido van Rossum09270b51997-08-15 18:57:32 +00001937DOS/Windows, and \code{'\\n'} (the ASCII newline character) on
Guido van Rossum4a944d71997-08-14 20:35:38 +00001938Macintosh. The returned string points into static storage; the caller
1939should not modify its value. The value is available to Python code
1940as the list \code{sys.path}, which may be modified to change the
1941future search path for loaded modules.
1942
1943% XXX should give the exact rules
1944\end{cfuncdesc}
1945
1946\begin{cfuncdesc}{const char *}{Py_GetVersion}{}
1947Return the version of this Python interpreter. This is a string that
1948looks something like
1949
Guido van Rossum09270b51997-08-15 18:57:32 +00001950\begin{verbatim}
1951"1.5a3 (#67, Aug 1 1997, 22:34:28) [GCC 2.7.2.2]"
1952\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001953
1954The first word (up to the first space character) is the current Python
1955version; the first three characters are the major and minor version
1956separated by a period. The returned string points into static storage;
1957the caller should not modify its value. The value is available to
1958Python code as the list \code{sys.version}.
1959\end{cfuncdesc}
1960
1961\begin{cfuncdesc}{const char *}{Py_GetPlatform}{}
1962Return the platform identifier for the current platform. On Unix,
1963this is formed from the ``official'' name of the operating system,
1964converted to lower case, followed by the major revision number; e.g.,
1965for Solaris 2.x, which is also known as SunOS 5.x, the value is
1966\code{"sunos5"}. On Macintosh, it is \code{"mac"}. On Windows, it
1967is \code{"win"}. The returned string points into static storage;
1968the caller should not modify its value. The value is available to
1969Python code as \code{sys.platform}.
1970\end{cfuncdesc}
1971
1972\begin{cfuncdesc}{const char *}{Py_GetCopyright}{}
1973Return the official copyright string for the current Python version,
1974for example
1975
1976\code{"Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam"}
1977
1978The returned string points into static storage; the caller should not
1979modify its value. The value is available to Python code as the list
1980\code{sys.copyright}.
1981\end{cfuncdesc}
1982
1983\begin{cfuncdesc}{const char *}{Py_GetCompiler}{}
1984Return an indication of the compiler used to build the current Python
1985version, in square brackets, for example
1986
1987\code{"[GCC 2.7.2.2]"}
1988
1989The returned string points into static storage; the caller should not
1990modify its value. The value is available to Python code as part of
1991the variable \code{sys.version}.
1992\end{cfuncdesc}
1993
1994\begin{cfuncdesc}{const char *}{Py_GetBuildInfo}{}
1995Return information about the sequence number and build date and time
1996of the current Python interpreter instance, for example
1997
Guido van Rossum09270b51997-08-15 18:57:32 +00001998\begin{verbatim}
1999"#67, Aug 1 1997, 22:34:28"
2000\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002001
2002The returned string points into static storage; the caller should not
2003modify its value. The value is available to Python code as part of
2004the variable \code{sys.version}.
2005\end{cfuncdesc}
2006
2007\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
2008% XXX
2009\end{cfuncdesc}
2010
2011% XXX Other PySys thingies (doesn't really belong in this chapter)
2012
2013\section{Thread State and the Global Interpreter Lock}
2014
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002015The Python interpreter is not fully thread safe. In order to support
2016multi-threaded Python programs, there's a global lock that must be
2017held by the current thread before it can safely access Python objects.
2018Without the lock, even the simplest operations could cause problems in
2019a multi-threaded proram: for example, when two threads simultaneously
2020increment the reference count of the same object, the reference count
2021could end up being incremented only once instead of twice.
2022
2023Therefore, the rule exists that only the thread that has acquired the
2024global interpreter lock may operate on Python objects or call Python/C
2025API functions. In order to support multi-threaded Python programs,
2026the interpreter regularly release and reacquires the lock -- by
2027default, every ten bytecode instructions (this can be changed with
2028\code{sys.setcheckinterval()}). The lock is also released and
2029reacquired around potentially blocking I/O operations like reading or
2030writing a file, so that other threads can run while the thread that
2031requests the I/O is waiting for the I/O operation to complete.
2032
2033The Python interpreter needs to keep some bookkeeping information
2034separate per thread -- for this it uses a data structure called
2035PyThreadState. This is new in Python 1.5; in earlier versions, such
2036state was stored in global variables, and switching threads could
2037cause problems. In particular, exception handling is now thread safe,
2038when the application uses \code{sys.exc_info()} to access the exception
2039last raised in the current thread.
2040
2041There's one global variable left, however: the pointer to the current
2042PyThreadState structure. While most thread packages have a way to
2043store ``per-thread global data'', Python's internal platform
2044independent thread abstraction doesn't support this (yet). Therefore,
2045the current thread state must be manipulated explicitly.
2046
2047This is easy enough in most cases. Most code manipulating the global
2048interpreter lock has the following simple structure:
2049
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002050\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002051Save the thread state in a local variable.
2052Release the interpreter lock.
2053...Do some blocking I/O operation...
2054Reacquire the interpreter lock.
2055Restore the thread state from the local variable.
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002056\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002057
2058This is so common that a pair of macros exists to simplify it:
2059
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002060\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002061Py_BEGIN_ALLOW_THREADS
2062...Do some blocking I/O operation...
2063Py_END_ALLOW_THREADS
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002064\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002065
2066The BEGIN macro opens a new block and declares a hidden local
2067variable; the END macro closes the block. Another advantage of using
2068these two macros is that when Python is compiled without thread
2069support, they are defined empty, thus saving the thread state and lock
2070manipulations.
2071
2072When thread support is enabled, the block above expands to the
2073following code:
2074
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002075\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002076{
2077 PyThreadState *_save;
2078 _save = PyEval_SaveThread();
2079 ...Do some blocking I/O operation...
2080 PyEval_RestoreThread(_save);
2081}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002082\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002083
2084Using even lower level primitives, we can get roughly the same effect
2085as follows:
2086
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002087\begin{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002088{
2089 PyThreadState *_save;
2090 _save = PyThreadState_Swap(NULL);
2091 PyEval_ReleaseLock();
2092 ...Do some blocking I/O operation...
2093 PyEval_AcquireLock();
2094 PyThreadState_Swap(_save);
2095}
Guido van Rossum9faf4c51997-10-07 14:38:54 +00002096\end{verbatim}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002097
2098There are some subtle differences; in particular,
2099\code{PyEval_RestoreThread()} saves and restores the value of the
2100global variable \code{errno}, since the lock manipulation does not
2101guarantee that \code{errno} is left alone. Also, when thread support
2102is disabled, \code{PyEval_SaveThread()} and
2103\code{PyEval_RestoreThread()} don't manipulate the lock; in this case,
2104\code{PyEval_ReleaseLock()} and \code{PyEval_AcquireLock()} are not
2105available. (This is done so that dynamically loaded extensions
2106compiled with thread support enabled can be loaded by an interpreter
2107that was compiled with disabled thread support.)
2108
2109The global interpreter lock is used to protect the pointer to the
2110current thread state. When releasing the lock and saving the thread
2111state, the current thread state pointer must be retrieved before the
2112lock is released (since another thread could immediately acquire the
2113lock and store its own thread state in the global variable).
2114Reversely, when acquiring the lock and restoring the thread state, the
2115lock must be acquired before storing the thread state pointer.
2116
2117Why am I going on with so much detail about this? Because when
2118threads are created from C, they don't have the global interpreter
2119lock, nor is there a thread state data structure for them. Such
2120threads must bootstrap themselves into existence, by first creating a
2121thread state data structure, then acquiring the lock, and finally
2122storing their thread state pointer, before they can start using the
2123Python/C API. When they are done, they should reset the thread state
2124pointer, release the lock, and finally free their thread state data
2125structure.
2126
2127When creating a thread data structure, you need to provide an
2128interpreter state data structure. The interpreter state data
2129structure hold global data that is shared by all threads in an
2130interpreter, for example the module administration
2131(\code{sys.modules}). Depending on your needs, you can either create
2132a new interpreter state data structure, or share the interpreter state
2133data structure used by the Python main thread (to access the latter,
2134you must obtain the thread state and access its \code{interp} member;
2135this must be done by a thread that is created by Python or by the main
2136thread after Python is initialized).
2137
2138XXX More?
2139
2140\begin{ctypedesc}{PyInterpreterState}
2141\strong{(NEW in 1.5a3!)}
2142This data structure represents the state shared by a number of
2143cooperating threads. Threads belonging to the same interpreter
2144share their module administration and a few other internal items.
2145There are no public members in this structure.
2146
2147Threads belonging to different interpreters initially share nothing,
2148except process state like available memory, open file descriptors and
2149such. The global interpreter lock is also shared by all threads,
2150regardless of to which interpreter they belong.
2151\end{ctypedesc}
2152
2153\begin{ctypedesc}{PyThreadState}
2154\strong{(NEW in 1.5a3!)}
2155This data structure represents the state of a single thread. The only
2156public data member is \code{PyInterpreterState *interp}, which points
2157to this thread's interpreter state.
2158\end{ctypedesc}
2159
2160\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
2161Initialize and acquire the global interpreter lock. It should be
2162called in the main thread before creating a second thread or engaging
2163in any other thread operations such as \code{PyEval_ReleaseLock()} or
2164\code{PyEval_ReleaseThread(tstate)}. It is not needed before
2165calling \code{PyEval_SaveThread()} or \code{PyEval_RestoreThread()}.
2166
2167This is a no-op when called for a second time. It is safe to call
2168this function before calling \code{Py_Initialize()}.
2169
2170When only the main thread exists, no lock operations are needed. This
2171is a common situation (most Python programs do not use threads), and
2172the lock operations slow the interpreter down a bit. Therefore, the
2173lock is not created initially. This situation is equivalent to having
2174acquired the lock: when there is only a single thread, all object
2175accesses are safe. Therefore, when this function initializes the
2176lock, it also acquires it. Before the Python \code{thread} module
2177creates a new thread, knowing that either it has the lock or the lock
2178hasn't been created yet, it calls \code{PyEval_InitThreads()}. When
2179this call returns, it is guaranteed that the lock has been created and
2180that it has acquired it.
2181
2182It is \strong{not} safe to call this function when it is unknown which
2183thread (if any) currently has the global interpreter lock.
2184
2185This function is not available when thread support is disabled at
2186compile time.
2187\end{cfuncdesc}
2188
Guido van Rossum4a944d71997-08-14 20:35:38 +00002189\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002190\strong{(NEW in 1.5a3!)}
2191Acquire the global interpreter lock. The lock must have been created
2192earlier. If this thread already has the lock, a deadlock ensues.
2193This function is not available when thread support is disabled at
2194compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002195\end{cfuncdesc}
2196
2197\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002198\strong{(NEW in 1.5a3!)}
2199Release the global interpreter lock. The lock must have been created
2200earlier. This function is not available when thread support is
2201disabled at
2202compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002203\end{cfuncdesc}
2204
2205\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002206\strong{(NEW in 1.5a3!)}
2207Acquire the global interpreter lock and then set the current thread
2208state to \var{tstate}, which should not be \code{NULL}. The lock must
2209have been created earlier. If this thread already has the lock,
2210deadlock ensues. This function is not available when thread support
2211is disabled at
2212compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002213\end{cfuncdesc}
2214
2215\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002216\strong{(NEW in 1.5a3!)}
2217Reset the current thread state to \code{NULL} and release the global
2218interpreter lock. The lock must have been created earlier and must be
2219held by the current thread. The \var{tstate} argument, which must not
2220be \code{NULL}, is only used to check that it represents the current
2221thread state -- if it isn't, a fatal error is reported. This function
2222is not available when thread support is disabled at
2223compile time.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002224\end{cfuncdesc}
2225
2226\begin{cfuncdesc}{PyThreadState *}{PyEval_SaveThread}{}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002227\strong{(Different return type in 1.5a3!)}
2228Release the interpreter lock (if it has been created and thread
2229support is enabled) and reset the thread state to \code{NULL},
2230returning the previous thread state (which is not \code{NULL}). If
2231the lock has been created, the current thread must have acquired it.
2232(This function is available even when thread support is disabled at
2233compile time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002234\end{cfuncdesc}
2235
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002236\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
2237\strong{(Different argument type in 1.5a3!)}
2238Acquire the interpreter lock (if it has been created and thread
2239support is enabled) and set the thread state to \var{tstate}, which
2240must not be \code{NULL}. If the lock has been created, the current
2241thread must not have acquired it, otherwise deadlock ensues. (This
2242function is available even when thread support is disabled at compile
2243time.)
Guido van Rossum4a944d71997-08-14 20:35:38 +00002244\end{cfuncdesc}
2245
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002246% XXX These aren't really C types, but the ctypedesc macro is the simplest!
2247\begin{ctypedesc}{Py_BEGIN_ALLOW_THREADS}
2248This macro expands to
2249\code{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
2250Note that it contains an opening brace; it must be matched with a
2251following \code{Py_END_ALLOW_THREADS} macro. See above for further
2252discussion of this macro. It is a no-op when thread support is
2253disabled at compile time.
2254\end{ctypedesc}
2255
2256\begin{ctypedesc}{Py_END_ALLOW_THREADS}
2257This macro expands to
2258\code{PyEval_RestoreThread(_save); \} }.
2259Note that it contains a closing brace; it must be matched with an
2260earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
2261discussion of this macro. It is a no-op when thread support is
2262disabled at compile time.
2263\end{ctypedesc}
2264
2265\begin{ctypedesc}{Py_BEGIN_BLOCK_THREADS}
2266This macro expands to \code{PyEval_RestoreThread(_save);} i.e. it
2267is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
2268brace. It is a no-op when thread support is disabled at compile
2269time.
2270\end{ctypedesc}
2271
2272\begin{ctypedesc}{Py_BEGIN_UNBLOCK_THREADS}
2273This macro expands to \code{_save = PyEval_SaveThread();} i.e. it is
2274equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
2275and variable declaration. It is a no-op when thread support is
2276disabled at compile time.
2277\end{ctypedesc}
2278
2279All of the following functions are only available when thread support
2280is enabled at compile time, and must be called only when the
2281interpreter lock has been created. They are all new in 1.5a3.
2282
2283\begin{cfuncdesc}{PyInterpreterState *}{PyInterpreterState_New}{}
2284Create a new interpreter state object. The interpreter lock must be
2285held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002286\end{cfuncdesc}
2287
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002288\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
2289Reset all information in an interpreter state object. The interpreter
2290lock must be held.
Guido van Rossum4a944d71997-08-14 20:35:38 +00002291\end{cfuncdesc}
2292
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002293\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
2294Destroy an interpreter state object. The interpreter lock need not be
2295held. The interpreter state must have been reset with a previous
2296call to \code{PyInterpreterState_Clear()}.
2297\end{cfuncdesc}
2298
2299\begin{cfuncdesc}{PyThreadState *}{PyThreadState_New}{PyInterpreterState *interp}
2300Create a new thread state object belonging to the given interpreter
2301object. The interpreter lock must be held.
2302\end{cfuncdesc}
2303
2304\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
2305Reset all information in a thread state object. The interpreter lock
2306must be held.
2307\end{cfuncdesc}
2308
2309\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
2310Destroy a thread state object. The interpreter lock need not be
2311held. The thread state must have been reset with a previous
2312call to \code{PyThreadState_Clear()}.
2313\end{cfuncdesc}
2314
2315\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Get}{}
2316Return the current thread state. The interpreter lock must be held.
2317When the current thread state is \code{NULL}, this issues a fatal
2318error (so that the caller needn't check for \code{NULL}.
2319\end{cfuncdesc}
2320
2321\begin{cfuncdesc}{PyThreadState *}{PyThreadState_Swap}{PyThreadState *tstate}
2322Swap the current thread state with the thread state given by the
2323argument \var{tstate}, which may be \code{NULL}. The interpreter lock
2324must be held.
2325\end{cfuncdesc}
2326
2327
2328\section{Defining New Object Types}
Guido van Rossum4a944d71997-08-14 20:35:38 +00002329
Guido van Rossumae110af1997-05-22 20:11:52 +00002330XXX To be done:
2331
2332PyObject, PyVarObject
2333
2334PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
2335
2336Typedefs:
2337unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
2338intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
2339getreadbufferproc, getwritebufferproc, getsegcountproc,
2340destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
2341setattrofunc, cmpfunc, reprfunc, hashfunc
2342
2343PyNumberMethods
2344
2345PySequenceMethods
2346
2347PyMappingMethods
2348
2349PyBufferProcs
2350
2351PyTypeObject
2352
2353DL_IMPORT
2354
2355PyType_Type
2356
2357Py*_Check
2358
2359Py_None, _Py_NoneStruct
2360
2361_PyObject_New, _PyObject_NewVar
2362
2363PyObject_NEW, PyObject_NEW_VAR
2364
2365
2366\chapter{Specific Data Types}
2367
2368This chapter describes the functions that deal with specific types of
2369Python objects. It is structured like the ``family tree'' of Python
2370object types.
2371
2372
2373\section{Fundamental Objects}
2374
2375This section describes Python type objects and the singleton object
2376\code{None}.
2377
2378
2379\subsection{Type Objects}
2380
2381\begin{ctypedesc}{PyTypeObject}
2382
2383\end{ctypedesc}
2384
2385\begin{cvardesc}{PyObject *}{PyType_Type}
2386
2387\end{cvardesc}
2388
2389
2390\subsection{The None Object}
2391
2392\begin{cvardesc}{PyObject *}{Py_None}
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002393XXX macro
Guido van Rossumae110af1997-05-22 20:11:52 +00002394\end{cvardesc}
2395
2396
2397\section{Sequence Objects}
2398
2399Generic operations on sequence objects were discussed in the previous
2400chapter; this section deals with the specific kinds of sequence
Guido van Rossumc44d3d61997-10-06 05:10:47 +00002401objects that are intrinsic to the Python language.
Guido van Rossumae110af1997-05-22 20:11:52 +00002402
2403
2404\subsection{String Objects}
2405
2406\begin{ctypedesc}{PyStringObject}
2407This subtype of \code{PyObject} represents a Python string object.
2408\end{ctypedesc}
2409
2410\begin{cvardesc}{PyTypeObject}{PyString_Type}
2411This instance of \code{PyTypeObject} represents the Python string type.
2412\end{cvardesc}
2413
2414\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
2415
2416\end{cfuncdesc}
2417
2418\begin{cfuncdesc}{PyObject *}{PyString_FromStringAndSize}{const char *, int}
2419
2420\end{cfuncdesc}
2421
2422\begin{cfuncdesc}{PyObject *}{PyString_FromString}{const char *}
2423
2424\end{cfuncdesc}
2425
2426\begin{cfuncdesc}{int}{PyString_Size}{PyObject *}
2427
2428\end{cfuncdesc}
2429
2430\begin{cfuncdesc}{char *}{PyString_AsString}{PyObject *}
2431
2432\end{cfuncdesc}
2433
2434\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **, PyObject *}
2435
2436\end{cfuncdesc}
2437
2438\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **, PyObject *}
2439
2440\end{cfuncdesc}
2441
2442\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **, int}
2443
2444\end{cfuncdesc}
2445
2446\begin{cfuncdesc}{PyObject *}{PyString_Format}{PyObject *, PyObject *}
2447
2448\end{cfuncdesc}
2449
2450\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **}
2451
2452\end{cfuncdesc}
2453
2454\begin{cfuncdesc}{PyObject *}{PyString_InternFromString}{const char *}
2455
2456\end{cfuncdesc}
2457
2458\begin{cfuncdesc}{char *}{PyString_AS_STRING}{PyStringObject *}
2459
2460\end{cfuncdesc}
2461
2462\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyStringObject *}
2463
2464\end{cfuncdesc}
2465
2466
2467\subsection{Tuple Objects}
2468
2469\begin{ctypedesc}{PyTupleObject}
2470This subtype of \code{PyObject} represents a Python tuple object.
2471\end{ctypedesc}
2472
2473\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
2474This instance of \code{PyTypeObject} represents the Python tuple type.
2475\end{cvardesc}
2476
2477\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
2478Return true if the argument is a tuple object.
2479\end{cfuncdesc}
2480
2481\begin{cfuncdesc}{PyTupleObject *}{PyTuple_New}{int s}
2482Return a new tuple object of size \code{s}
2483\end{cfuncdesc}
2484
2485\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
2486akes a pointer to a tuple object, and returns the size
2487of that tuple.
2488\end{cfuncdesc}
2489
2490\begin{cfuncdesc}{PyObject *}{PyTuple_GetItem}{PyTupleObject *p, int pos}
2491returns the object at position \code{pos} in the tuple pointed
2492to by \code{p}.
2493\end{cfuncdesc}
2494
2495\begin{cfuncdesc}{PyObject *}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
2496does the same, but does no checking of it's
2497arguments.
2498\end{cfuncdesc}
2499
2500\begin{cfuncdesc}{PyTupleObject *}{PyTuple_GetSlice}{PyTupleObject *p,
2501 int low,
2502 int high}
2503takes a slice of the tuple pointed to by \code{p} from
2504\code{low} to \code{high} and returns it as a new tuple.
2505\end{cfuncdesc}
2506
2507\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyTupleObject *p,
2508 int pos,
2509 PyObject *o}
2510inserts a reference to object \code{o} at position \code{pos} of
2511the tuple pointed to by \code{p}. It returns 0 on success.
2512\end{cfuncdesc}
2513
2514\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyTupleObject *p,
2515 int pos,
2516 PyObject *o}
2517
2518does the same, but does no error checking, and
2519should \emph{only} be used to fill in brand new tuples.
2520\end{cfuncdesc}
2521
2522\begin{cfuncdesc}{PyTupleObject *}{_PyTuple_Resize}{PyTupleObject *p,
2523 int new,
2524 int last_is_sticky}
2525can be used to resize a tuple. Because tuples are
2526\emph{supposed} to be immutable, this should only be used if there is only
2527one module referencing the object. Do \emph{not} use this if the tuple may
2528already be known to some other part of the code. \code{last_is_sticky} is
2529a flag - if set, the tuple will grow or shrink at the front, otherwise
2530it will grow or shrink at the end. Think of this as destroying the old
2531tuple and creating a new one, only more efficiently.
2532\end{cfuncdesc}
2533
2534
2535\subsection{List Objects}
2536
2537\begin{ctypedesc}{PyListObject}
2538This subtype of \code{PyObject} represents a Python list object.
2539\end{ctypedesc}
2540
2541\begin{cvardesc}{PyTypeObject}{PyList_Type}
2542This instance of \code{PyTypeObject} represents the Python list type.
2543\end{cvardesc}
2544
2545\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
2546returns true if it's argument is a \code{PyListObject}
2547\end{cfuncdesc}
2548
2549\begin{cfuncdesc}{PyObject *}{PyList_New}{int size}
2550
2551\end{cfuncdesc}
2552
2553\begin{cfuncdesc}{int}{PyList_Size}{PyObject *}
2554
2555\end{cfuncdesc}
2556
2557\begin{cfuncdesc}{PyObject *}{PyList_GetItem}{PyObject *, int}
2558
2559\end{cfuncdesc}
2560
2561\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *, int, PyObject *}
2562
2563\end{cfuncdesc}
2564
2565\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *, int, PyObject *}
2566
2567\end{cfuncdesc}
2568
2569\begin{cfuncdesc}{int}{PyList_Append}{PyObject *, PyObject *}
2570
2571\end{cfuncdesc}
2572
2573\begin{cfuncdesc}{PyObject *}{PyList_GetSlice}{PyObject *, int, int}
2574
2575\end{cfuncdesc}
2576
2577\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *, int, int, PyObject *}
2578
2579\end{cfuncdesc}
2580
2581\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *}
2582
2583\end{cfuncdesc}
2584
2585\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *}
2586
2587\end{cfuncdesc}
2588
2589\begin{cfuncdesc}{PyObject *}{PyList_AsTuple}{PyObject *}
2590
2591\end{cfuncdesc}
2592
2593\begin{cfuncdesc}{PyObject *}{PyList_GET_ITEM}{PyObject *list, int i}
2594
2595\end{cfuncdesc}
2596
2597\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
2598
2599\end{cfuncdesc}
2600
2601
2602\section{Mapping Objects}
2603
2604\subsection{Dictionary Objects}
2605
2606\begin{ctypedesc}{PyDictObject}
2607This subtype of \code{PyObject} represents a Python dictionary object.
2608\end{ctypedesc}
2609
2610\begin{cvardesc}{PyTypeObject}{PyDict_Type}
2611This instance of \code{PyTypeObject} represents the Python dictionary type.
2612\end{cvardesc}
2613
2614\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
2615returns true if it's argument is a PyDictObject
2616\end{cfuncdesc}
2617
2618\begin{cfuncdesc}{PyDictObject *}{PyDict_New}{}
2619returns a new empty dictionary.
2620\end{cfuncdesc}
2621
2622\begin{cfuncdesc}{void}{PyDict_Clear}{PyDictObject *p}
2623empties an existing dictionary and deletes it.
2624\end{cfuncdesc}
2625
2626\begin{cfuncdesc}{int}{PyDict_SetItem}{PyDictObject *p,
2627 PyObject *key,
2628 PyObject *val}
2629inserts \code{value} into the dictionary with a key of
2630\code{key}. Both \code{key} and \code{value} should be PyObjects, and \code{key} should
2631be hashable.
2632\end{cfuncdesc}
2633
2634\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
2635 char *key,
2636 PyObject *val}
2637inserts \code{value} into the dictionary using \code{key}
2638as a key. \code{key} should be a char *
2639\end{cfuncdesc}
2640
2641\begin{cfuncdesc}{int}{PyDict_DelItem}{PyDictObject *p, PyObject *key}
2642removes the entry in dictionary \code{p} with key \code{key}.
2643\code{key} is a PyObject.
2644\end{cfuncdesc}
2645
2646\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyDictObject *p, char *key}
2647removes the entry in dictionary \code{p} which has a key
2648specified by the \code{char *}\code{key}.
2649\end{cfuncdesc}
2650
2651\begin{cfuncdesc}{PyObject *}{PyDict_GetItem}{PyDictObject *p, PyObject *key}
2652returns the object from dictionary \code{p} which has a key
2653\code{key}.
2654\end{cfuncdesc}
2655
2656\begin{cfuncdesc}{PyObject *}{PyDict_GetItemString}{PyDictObject *p, char *key}
2657does the same, but \code{key} is specified as a
2658\code{char *}, rather than a \code{PyObject *}.
2659\end{cfuncdesc}
2660
2661\begin{cfuncdesc}{PyListObject *}{PyDict_Items}{PyDictObject *p}
2662returns a PyListObject containing all the items
2663from the dictionary, as in the mapping method \code{items()} (see the Reference
2664Guide)
2665\end{cfuncdesc}
2666
2667\begin{cfuncdesc}{PyListObject *}{PyDict_Keys}{PyDictObject *p}
2668returns a PyListObject containing all the keys
2669from the dictionary, as in the mapping method \code{keys()} (see the Reference Guide)
2670\end{cfuncdesc}
2671
2672\begin{cfuncdesc}{PyListObject *}{PyDict_Values}{PyDictObject *p}
2673returns a PyListObject containing all the values
2674from the dictionary, as in the mapping method \code{values()} (see the Reference Guide)
2675\end{cfuncdesc}
2676
2677\begin{cfuncdesc}{int}{PyDict_Size}{PyDictObject *p}
2678returns the number of items in the dictionary.
2679\end{cfuncdesc}
2680
2681\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p,
2682 int ppos,
2683 PyObject **pkey,
2684 PyObject **pvalue}
2685
2686\end{cfuncdesc}
2687
2688
2689\section{Numeric Objects}
2690
2691\subsection{Plain Integer Objects}
2692
2693\begin{ctypedesc}{PyIntObject}
2694This subtype of \code{PyObject} represents a Python integer object.
2695\end{ctypedesc}
2696
2697\begin{cvardesc}{PyTypeObject}{PyInt_Type}
2698This instance of \code{PyTypeObject} represents the Python plain
2699integer type.
2700\end{cvardesc}
2701
2702\begin{cfuncdesc}{int}{PyInt_Check}{PyObject *}
2703
2704\end{cfuncdesc}
2705
2706\begin{cfuncdesc}{PyIntObject *}{PyInt_FromLong}{long ival}
2707creates a new integer object with a value of \code{ival}.
2708
2709The current implementation keeps an array of integer objects for all
2710integers between -1 and 100, when you create an int in that range you
2711actually just get back a reference to the existing object. So it should
2712be possible to change the value of 1. I suspect the behaviour of python
2713in this case is undefined. :-)
2714\end{cfuncdesc}
2715
2716\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyIntObject *io}
2717returns the value of the object \code{io}.
2718\end{cfuncdesc}
2719
2720\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
2721will first attempt to cast the object to a PyIntObject, if
2722it is not already one, and the return it's value.
2723\end{cfuncdesc}
2724
2725\begin{cfuncdesc}{long}{PyInt_GetMax}{}
2726returns the systems idea of the largest int it can handle
2727(LONG_MAX, as defined in the system header files)
2728\end{cfuncdesc}
2729
2730
2731\subsection{Long Integer Objects}
2732
2733\begin{ctypedesc}{PyLongObject}
2734This subtype of \code{PyObject} represents a Python long integer object.
2735\end{ctypedesc}
2736
2737\begin{cvardesc}{PyTypeObject}{PyLong_Type}
2738This instance of \code{PyTypeObject} represents the Python long integer type.
2739\end{cvardesc}
2740
2741\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
2742returns true if it's argument is a \code{PyLongObject}
2743\end{cfuncdesc}
2744
2745\begin{cfuncdesc}{PyObject *}{PyLong_FromLong}{long}
2746
2747\end{cfuncdesc}
2748
2749\begin{cfuncdesc}{PyObject *}{PyLong_FromUnsignedLong}{unsigned long}
2750
2751\end{cfuncdesc}
2752
2753\begin{cfuncdesc}{PyObject *}{PyLong_FromDouble}{double}
2754
2755\end{cfuncdesc}
2756
2757\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *}
2758
2759\end{cfuncdesc}
2760
2761\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject }
2762
2763\end{cfuncdesc}
2764
2765\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *}
2766
2767\end{cfuncdesc}
2768
2769\begin{cfuncdesc}{PyObject *}{*PyLong_FromString}{char *, char **, int}
2770
2771\end{cfuncdesc}
2772
2773
2774\subsection{Floating Point Objects}
2775
2776\begin{ctypedesc}{PyFloatObject}
2777This subtype of \code{PyObject} represents a Python floating point object.
2778\end{ctypedesc}
2779
2780\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2781This instance of \code{PyTypeObject} represents the Python floating
2782point type.
2783\end{cvardesc}
2784
2785\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2786returns true if it's argument is a \code{PyFloatObject}
2787\end{cfuncdesc}
2788
2789\begin{cfuncdesc}{PyObject *}{PyFloat_FromDouble}{double}
2790
2791\end{cfuncdesc}
2792
2793\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *}
2794
2795\end{cfuncdesc}
2796
2797\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyFloatObject *}
2798
2799\end{cfuncdesc}
2800
2801
2802\subsection{Complex Number Objects}
2803
2804\begin{ctypedesc}{Py_complex}
2805typedef struct {
2806 double real;
2807 double imag;
2808}
2809\end{ctypedesc}
2810
2811\begin{ctypedesc}{PyComplexObject}
2812This subtype of \code{PyObject} represents a Python complex number object.
2813\end{ctypedesc}
2814
2815\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2816This instance of \code{PyTypeObject} represents the Python complex
2817number type.
2818\end{cvardesc}
2819
2820\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2821returns true if it's argument is a \code{PyComplexObject}
2822\end{cfuncdesc}
2823
2824\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex, Py_complex}
2825
2826\end{cfuncdesc}
2827
2828\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex, Py_complex}
2829
2830\end{cfuncdesc}
2831
2832\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex}
2833
2834\end{cfuncdesc}
2835
2836\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex, Py_complex}
2837
2838\end{cfuncdesc}
2839
2840\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex, Py_complex}
2841
2842\end{cfuncdesc}
2843
2844\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex, Py_complex}
2845
2846\end{cfuncdesc}
2847
2848\begin{cfuncdesc}{PyObject *}{PyComplex_FromCComplex}{Py_complex}
2849
2850\end{cfuncdesc}
2851
2852\begin{cfuncdesc}{PyObject *}{PyComplex_FromDoubles}{double real, double imag}
2853
2854\end{cfuncdesc}
2855
2856\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2857
2858\end{cfuncdesc}
2859
2860\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2861
2862\end{cfuncdesc}
2863
2864\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2865
2866\end{cfuncdesc}
2867
2868
2869
2870\section{Other Objects}
2871
2872\subsection{File Objects}
2873
2874\begin{ctypedesc}{PyFileObject}
2875This subtype of \code{PyObject} represents a Python file object.
2876\end{ctypedesc}
2877
2878\begin{cvardesc}{PyTypeObject}{PyFile_Type}
2879This instance of \code{PyTypeObject} represents the Python file type.
2880\end{cvardesc}
2881
2882\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2883returns true if it's argument is a \code{PyFileObject}
2884\end{cfuncdesc}
2885
2886\begin{cfuncdesc}{PyObject *}{PyFile_FromString}{char *name, char *mode}
2887creates a new PyFileObject pointing to the file
2888specified in \code{name} with the mode specified in \code{mode}
2889\end{cfuncdesc}
2890
2891\begin{cfuncdesc}{PyObject *}{PyFile_FromFile}{FILE *fp,
2892 char *name, char *mode, int (*close})
2893creates a new PyFileObject from the already-open \code{fp}.
2894The function \code{close} will be called when the file should be closed.
2895\end{cfuncdesc}
2896
2897\begin{cfuncdesc}{FILE *}{PyFile_AsFile}{PyFileObject *p}
2898returns the file object associated with \code{p} as a \code{FILE *}
2899\end{cfuncdesc}
2900
2901\begin{cfuncdesc}{PyStringObject *}{PyFile_GetLine}{PyObject *p, int n}
2902undocumented as yet
2903\end{cfuncdesc}
2904
2905\begin{cfuncdesc}{PyStringObject *}{PyFile_Name}{PyObject *p}
2906returns the name of the file specified by \code{p} as a
2907PyStringObject
2908\end{cfuncdesc}
2909
2910\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2911on systems with \code{setvbuf} only
2912\end{cfuncdesc}
2913
2914\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyFileObject *p, int newflag}
2915same as the file object method \code{softspace}
2916\end{cfuncdesc}
2917
2918\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p}
2919writes object \code{obj} to file object \code{p}
2920\end{cfuncdesc}
2921
2922\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p}
2923writes string \code{s} to file object \code{p}
2924\end{cfuncdesc}
2925
2926
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002927\input{api.ind} % Index -- must be last
2928
2929\end{document}