blob: 2935c7be005f05c422f1122df101fc7e465da83b [file] [log] [blame]
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001\documentstyle[twoside,11pt,myformat]{report}
2
Guido van Rossum5060b3b1997-08-17 18:02:23 +00003\title{Python/C API Reference}
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 Rossum4a944d71997-08-14 20:35:38 +0000466On Unix, \code{Py_Initialize()} calculates the module search path
467based upon its best guess for the location of the standard Python
468interpreter executable, assuming that the Python library is found in a
469fixed location relative to the Python interpreter executable. In
470particular, it looks for a directory named \code{lib/python1.5}
471(replacing \code{1.5} with the current interpreter version) relative
472to the parent directory where the executable named \code{python} is
473found on the shell command search path (the environment variable
Guido van Rossum09270b51997-08-15 18:57:32 +0000474\code{\$PATH}). For instance, if the Python executable is found in
Guido van Rossum4a944d71997-08-14 20:35:38 +0000475\code{/usr/local/bin/python}, it will assume that the libraries are in
476\code{/usr/local/lib/python1.5}. In fact, this also the ``fallback''
477location, used when no executable file named \code{python} is found
478along \code{\$PATH}. The user can change this behavior by setting the
479environment variable \code{\$PYTHONHOME}, and can insert additional
480directories in front of the standard path by setting
Guido van Rossum59a61351997-08-14 20:34:33 +0000481\code{\$PYTHONPATH}.
482
Guido van Rossum4a944d71997-08-14 20:35:38 +0000483The embedding application can steer the search by calling
484\code{Py_SetProgramName(\var{file})} \emph{before} calling
Guido van Rossum09270b51997-08-15 18:57:32 +0000485\code{Py_Initialize()}. Note that \code{\$PYTHONHOME} still overrides
Guido van Rossum4a944d71997-08-14 20:35:38 +0000486this and \code{\$PYTHONPATH} is still inserted in front of the
Guido van Rossum59a61351997-08-14 20:34:33 +0000487standard path.
488
Guido van Rossum4a944d71997-08-14 20:35:38 +0000489Sometimes, it is desirable to ``uninitialize'' Python. For instance,
490the application may want to start over (make another call to
491\code{Py_Initialize()}) or the application is simply done with its
492use of Python and wants to free all memory allocated by Python. This
Guido van Rossum59a61351997-08-14 20:34:33 +0000493can be accomplished by calling \code{Py_Finalize()}.
494% XXX More...
495
496\section{Embedding Python in Threaded Applications}
497
Guido van Rossum4a944d71997-08-14 20:35:38 +0000498
499
500
501
502
503
504
505
Guido van Rossum59a61351997-08-14 20:34:33 +0000506
507\chapter{Old Introduction}
508
Guido van Rossumae110af1997-05-22 20:11:52 +0000509(XXX This is the old introduction, mostly by Jim Fulton -- should be
510rewritten.)
511
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000512From the viewpoint of of C access to Python services, we have:
513
514\begin{enumerate}
515
516\item "Very high level layer": two or three functions that let you
517exec or eval arbitrary Python code given as a string in a module whose
518name is given, passing C values in and getting C values out using
519mkvalue/getargs style format strings. This does not require the user
520to declare any variables of type \code{PyObject *}. This should be
521enough to write a simple application that gets Python code from the
522user, execs it, and returns the output or errors.
523
524\item "Abstract objects layer": which is the subject of this chapter.
Guido van Rossum59a61351997-08-14 20:34:33 +0000525It has many functions operating on objects, and lets you do many
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000526things from C that you can also write in Python, without going through
527the Python parser.
528
529\item "Concrete objects layer": This is the public type-dependent
530interface provided by the standard built-in types, such as floats,
531strings, and lists. This interface exists and is currently documented
532by the collection of include files provides with the Python
533distributions.
534
Guido van Rossumae110af1997-05-22 20:11:52 +0000535\end{enumerate}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000536
537From the point of view of Python accessing services provided by C
538modules:
539
Guido van Rossumae110af1997-05-22 20:11:52 +0000540\begin{enumerate}
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000541
Guido van Rossumae110af1997-05-22 20:11:52 +0000542\item[4.] "Python module interface": this interface consist of the basic
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000543routines used to define modules and their members. Most of the
544current extensions-writing guide deals with this interface.
545
Guido van Rossumae110af1997-05-22 20:11:52 +0000546\item[5.] "Built-in object interface": this is the interface that a new
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000547built-in type must provide and the mechanisms and rules that a
548developer of a new built-in type must use and follow.
549
550\end{enumerate}
551
552The Python C API provides four groups of operations on objects,
553corresponding to the same operations in the Python language: object,
554numeric, sequence, and mapping. Each protocol consists of a
555collection of related operations. If an operation that is not
556provided by a particular type is invoked, then the standard exception
557\code{TypeError} is raised with a operation name as an argument.
558
559In addition, for convenience this interface defines a set of
560constructors for building objects of built-in types. This is needed
561so new objects can be returned from C functions that otherwise treat
562objects generically.
563
564\section{Reference Counting}
565
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000566For most of the functions in the Python/C API, if a function retains a
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000567reference to a Python object passed as an argument, then the function
568will increase the reference count of the object. It is unnecessary
569for the caller to increase the reference count of an argument in
570anticipation of the object's retention.
571
572Usually, Python objects returned from functions should be treated as
573new objects. Functions that return objects assume that the caller
574will retain a reference and the reference count of the object has
575already been incremented to account for this fact. A caller that does
576not retain a reference to an object that is returned from a function
577must decrement the reference count of the object (using
578\code{Py_DECREF()}) to prevent memory leaks.
579
580Exceptions to these rules will be noted with the individual functions.
581
582\section{Include Files}
583
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000584All function, type and macro definitions needed to use the Python/C
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000585API are included in your code by the following line:
586
587\code{\#include "Python.h"}
588
589This implies inclusion of the following standard header files:
590stdio.h, string.h, errno.h, and stdlib.h (if available).
591
592All user visible names defined by Python.h (except those defined by
593the included standard headers) have one of the prefixes \code{Py} or
594\code{_Py}. Names beginning with \code{_Py} are for internal use
595only.
596
597
598\chapter{Initialization and Shutdown of an Embedded Python Interpreter}
599
600When embedding the Python interpreter in a C or C++ program, the
601interpreter must be initialized.
602
603\begin{cfuncdesc}{void}{PyInitialize}{}
604This function initializes the interpreter. It must be called before
605any interaction with the interpreter takes place. If it is called
606more than once, the second and further calls have no effect.
607
608The function performs the following tasks: create an environment in
609which modules can be imported and Python code can be executed;
610initialize the \code{__builtin__} module; initialize the \code{sys}
611module; initialize \code{sys.path}; initialize signal handling; and
612create the empty \code{__main__} module.
613
614In the current system, there is no way to undo all these
615initializations or to create additional interpreter environments.
616\end{cfuncdesc}
617
618\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
619Register a cleanup function to be called when Python exits. The
620cleanup function will be called with no arguments and should return no
621value. At most 32 cleanup functions can be registered. When the
622registration is successful, \code{Py_AtExit} returns 0; on failure, it
623returns -1. Each cleanup function will be called t most once. The
624cleanup function registered last is called first.
625\end{cfuncdesc}
626
627\begin{cfuncdesc}{void}{Py_Exit}{int status}
628Exit the current process. This calls \code{Py_Cleanup()} (see next
629item) and performs additional cleanup (under some circumstances it
630will attempt to delete all modules), and then calls the standard C
631library function \code{exit(status)}.
632\end{cfuncdesc}
633
634\begin{cfuncdesc}{void}{Py_Cleanup}{}
635Perform some of the cleanup that \code{Py_Exit} performs, but don't
636exit the process. In particular, this invokes the user's
637\code{sys.exitfunc} function (if defined at all), and it invokes the
638cleanup functions registered with \code{Py_AtExit()}, in reverse order
639of their registration.
640\end{cfuncdesc}
641
642\begin{cfuncdesc}{void}{Py_FatalError}{char *message}
643Print a fatal error message and die. No cleanup is performed. This
644function should only be invoked when a condition is detected that
645would make it dangerous to continue using the Python interpreter;
646e.g., when the object administration appears to be corrupted.
647\end{cfuncdesc}
648
649\begin{cfuncdesc}{void}{PyImport_Init}{}
650Initialize the module table. For internal use only.
651\end{cfuncdesc}
652
653\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
654Empty the module table. For internal use only.
655\end{cfuncdesc}
656
657\begin{cfuncdesc}{void}{PyBuiltin_Init}{}
658Initialize the \code{__builtin__} module. For internal use only.
659\end{cfuncdesc}
660
Guido van Rossumae110af1997-05-22 20:11:52 +0000661XXX Other init functions: PyEval_InitThreads, PyOS_InitInterrupts,
662PyMarshal_Init, PySys_Init.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000663
664\chapter{Reference Counting}
665
666The functions in this chapter are used for managing reference counts
667of Python objects.
668
669\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
670Increment the reference count for object \code{o}. The object must
671not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
672\code{Py_XINCREF()}.
673\end{cfuncdesc}
674
675\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
676Increment the reference count for object \code{o}. The object may be
677\NULL{}, in which case the function has no effect.
678\end{cfuncdesc}
679
680\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
681Decrement the reference count for object \code{o}. The object must
682not be \NULL{}; if you aren't sure that it isn't \NULL{}, use
683\code{Py_XDECREF()}. If the reference count reaches zero, the object's
684type's deallocation function (which must not be \NULL{}) is invoked.
685
686\strong{Warning:} The deallocation function can cause arbitrary Python
687code to be invoked (e.g. when a class instance with a \code{__del__()}
688method is deallocated). While exceptions in such code are not
689propagated, the executed code has free access to all Python global
690variables. This means that any object that is reachable from a global
691variable should be in a consistent state before \code{Py_DECREF()} is
692invoked. For example, code to delete an object from a list should
693copy a reference to the deleted object in a temporary variable, update
694the list data structure, and then call \code{Py_DECREF()} for the
695temporary variable.
696\end{cfuncdesc}
697
698\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
699Decrement the reference count for object \code{o}.The object may be
700\NULL{}, in which case the function has no effect; otherwise the
701effect is the same as for \code{Py_DECREF()}, and the same warning
702applies.
703\end{cfuncdesc}
704
Guido van Rossumae110af1997-05-22 20:11:52 +0000705The following functions are only for internal use:
706\code{_Py_Dealloc}, \code{_Py_ForgetReference}, \code{_Py_NewReference},
707as well as the global variable \code{_Py_RefTotal}.
708
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000709
710\chapter{Exception Handling}
711
712The functions in this chapter will let you handle and raise Python
Guido van Rossumae110af1997-05-22 20:11:52 +0000713exceptions. It is important to understand some of the basics of
714Python exception handling. It works somewhat like the Unix
715\code{errno} variable: there is a global indicator (per thread) of the
716last error that occurred. Most functions don't clear this on success,
717but will set it to indicate the cause of the error on failure. Most
718functions also return an error indicator, usually \NULL{} if they are
719supposed to return a pointer, or -1 if they return an integer
720(exception: the \code{PyArg_Parse*()} functions return 1 for success and
7210 for failure). When a function must fail because of some function it
722called failed, it generally doesn't set the error indicator; the
723function it called already set it.
724
725The error indicator consists of three Python objects corresponding to
726the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
727\code{sys.exc_traceback}. API functions exist to interact with the
728error indicator in various ways. There is a separate error indicator
729for each thread.
730
731% XXX Order of these should be more thoughtful.
732% Either alphabetical or some kind of structure.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000733
734\begin{cfuncdesc}{void}{PyErr_Print}{}
Guido van Rossumae110af1997-05-22 20:11:52 +0000735Print a standard traceback to \code{sys.stderr} and clear the error
736indicator. Call this function only when the error indicator is set.
737(Otherwise it will cause a fatal error!)
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000738\end{cfuncdesc}
739
Guido van Rossumae110af1997-05-22 20:11:52 +0000740\begin{cfuncdesc}{PyObject *}{PyErr_Occurred}{}
741Test whether the error indicator is set. If set, return the exception
742\code{type} (the first argument to the last call to one of the
743\code{PyErr_Set*()} functions or to \code{PyErr_Restore()}). If not
744set, return \NULL{}. You do not own a reference to the return value,
745so you do not need to \code{Py_DECREF()} it.
746\end{cfuncdesc}
747
748\begin{cfuncdesc}{void}{PyErr_Clear}{}
749Clear the error indicator. If the error indicator is not set, there
750is no effect.
751\end{cfuncdesc}
752
753\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue, PyObject **ptraceback}
754Retrieve the error indicator into three variables whose addresses are
755passed. If the error indicator is not set, set all three variables to
756\NULL{}. If it is set, it will be cleared and you own a reference to
757each object retrieved. The value and traceback object may be \NULL{}
758even when the type object is not. \strong{Note:} this function is
759normally only used by code that needs to handle exceptions or by code
760that needs to save and restore the error indicator temporarily.
761\end{cfuncdesc}
762
763\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value, PyObject *traceback}
764Set the error indicator from the three objects. If the error
765indicator is already set, it is cleared first. If the objects are
766\NULL{}, the error indicator is cleared. Do not pass a \NULL{} type
767and non-\NULL{} value or traceback. The exception type should be a
768string or class; if it is a class, the value should be an instance of
769that class. Do not pass an invalid exception type or value.
770(Violating these rules will cause subtle problems later.) This call
771takes away a reference to each object, i.e. you must own a reference
772to each object before the call and after the call you no longer own
773these references. (If you don't understand this, don't use this
774function. I warned you.) \strong{Note:} this function is normally
775only used by code that needs to save and restore the error indicator
776temporarily.
777\end{cfuncdesc}
778
779\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
780This is the most common way to set the error indicator. The first
781argument specifies the exception type; it is normally one of the
782standard exceptions, e.g. \code{PyExc_RuntimeError}. You need not
783increment its reference count. The second argument is an error
784message; it is converted to a string object.
785\end{cfuncdesc}
786
787\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
788This function is similar to \code{PyErr_SetString()} but lets you
789specify an arbitrary Python object for the ``value'' of the exception.
790You need not increment its reference count.
791\end{cfuncdesc}
792
793\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
794This is a shorthand for \code{PyErr_SetString(\var{type}, Py_None}.
795\end{cfuncdesc}
796
797\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
798This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
799\var{message})}, where \var{message} indicates that a built-in operation
800was invoked with an illegal argument. It is mostly for internal use.
801\end{cfuncdesc}
802
803\begin{cfuncdesc}{PyObject *}{PyErr_NoMemory}{}
804This is a shorthand for \code{PyErr_SetNone(PyExc_MemoryError)}; it
805returns \NULL{} so an object allocation function can write
806\code{return PyErr_NoMemory();} when it runs out of memory.
807\end{cfuncdesc}
808
809\begin{cfuncdesc}{PyObject *}{PyErr_SetFromErrno}{PyObject *type}
810This is a convenience function to raise an exception when a C library
811function has returned an error and set the C variable \code{errno}.
812It constructs a tuple object whose first item is the integer
813\code{errno} value and whose second item is the corresponding error
814message (gotten from \code{strerror()}), and then calls
815\code{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX{}, when
816the \code{errno} value is \code{EINTR}, indicating an interrupted
817system call, this calls \code{PyErr_CheckSignals()}, and if that set
818the error indicator, leaves it set to that. The function always
819returns \NULL{}, so a wrapper function around a system call can write
820\code{return PyErr_NoMemory();} when the system call returns an error.
821\end{cfuncdesc}
822
823\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
824This is a shorthand for \code{PyErr_SetString(PyExc_TypeError,
825\var{message})}, where \var{message} indicates that an internal
Guido van Rossum5060b3b1997-08-17 18:02:23 +0000826operation (e.g. a Python/C API function) was invoked with an illegal
Guido van Rossumae110af1997-05-22 20:11:52 +0000827argument. It is mostly for internal use.
828\end{cfuncdesc}
829
830\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
831This function interacts with Python's signal handling. It checks
832whether a signal has been sent to the processes and if so, invokes the
833corresponding signal handler. If the \code{signal} module is
834supported, this can invoke a signal handler written in Python. In all
835cases, the default effect for \code{SIGINT} is to raise the
836\code{KeyboadInterrupt} exception. If an exception is raised the
837error indicator is set and the function returns 1; otherwise the
838function returns 0. The error indicator may or may not be cleared if
839it was previously set.
840\end{cfuncdesc}
841
842\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
843This function is obsolete (XXX or platform dependent?). It simulates
844the effect of a \code{SIGINT} signal arriving -- the next time
845\code{PyErr_CheckSignals()} is called, \code{KeyboadInterrupt} will be
846raised.
847\end{cfuncdesc}
848
849\section{Standard Exceptions}
850
851All standard Python exceptions are available as global variables whose
852names are \code{PyExc_} followed by the Python exception name.
853These have the type \code{PyObject *}; they are all string objects.
854For completion, here are all the variables:
855\code{PyExc_AccessError},
856\code{PyExc_AssertionError},
857\code{PyExc_AttributeError},
858\code{PyExc_EOFError},
859\code{PyExc_FloatingPointError},
860\code{PyExc_IOError},
861\code{PyExc_ImportError},
862\code{PyExc_IndexError},
863\code{PyExc_KeyError},
864\code{PyExc_KeyboardInterrupt},
865\code{PyExc_MemoryError},
866\code{PyExc_NameError},
867\code{PyExc_OverflowError},
868\code{PyExc_RuntimeError},
869\code{PyExc_SyntaxError},
870\code{PyExc_SystemError},
871\code{PyExc_SystemExit},
872\code{PyExc_TypeError},
873\code{PyExc_ValueError},
874\code{PyExc_ZeroDivisionError}.
875
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000876
877\chapter{Utilities}
878
879The functions in this chapter perform various utility tasks, such as
880parsing function arguments and constructing Python values from C
881values.
882
883\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
884Return true (nonzero) if the standard I/O file \code{fp} with name
885\code{filename} is deemed interactive. This is the case for files for
886which \code{isatty(fileno(fp))} is true. If the global flag
887\code{Py_InteractiveFlag} is true, this function also returns true if
888the \code{name} pointer is \NULL{} or if the name is equal to one of
889the strings \code{"<stdin>"} or \code{"???"}.
890\end{cfuncdesc}
891
892\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
893Return the time of last modification of the file \code{filename}.
894The result is encoded in the same way as the timestamp returned by
895the standard C library function \code{time()}.
896\end{cfuncdesc}
897
898
899\chapter{Debugging}
900
901XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
902
903
904\chapter{The Very High Level Layer}
905
906The functions in this chapter will let you execute Python source code
907given in a file or a buffer, but they will not let you interact in a
908more detailed way with the interpreter.
909
Guido van Rossumae110af1997-05-22 20:11:52 +0000910\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *, char *}
911\end{cfuncdesc}
912
913\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *}
914\end{cfuncdesc}
915
916\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *, char *}
917\end{cfuncdesc}
918
919\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *, char *}
920\end{cfuncdesc}
921
922\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *, char *}
923\end{cfuncdesc}
924
925\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseString}{char *, int}
926\end{cfuncdesc}
927
928\begin{cfuncdesc}{struct _node *}{PyParser_SimpleParseFile}{FILE *, char *, int}
929\end{cfuncdesc}
930
931\begin{cfuncdesc}{}{PyObject *PyRun}{ROTO((char *, int, PyObject *, PyObject *}
932\end{cfuncdesc}
933
934\begin{cfuncdesc}{}{PyObject *PyRun}{ROTO((FILE *, char *, int, PyObject *, PyObject *}
935\end{cfuncdesc}
936
937\begin{cfuncdesc}{}{PyObject *Py}{ROTO((char *, char *, int}
938\end{cfuncdesc}
939
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000940
941\chapter{Abstract Objects Layer}
942
943The functions in this chapter interact with Python objects regardless
944of their type, or with wide classes of object types (e.g. all
945numerical types, or all sequence types). When used on object types
946for which they do not apply, they will flag a Python exception.
947
948\section{Object Protocol}
949
950\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
951Print an object \code{o}, on file \code{fp}. Returns -1 on error
952The flags argument is used to enable certain printing
953options. The only option currently supported is \code{Py_Print_RAW}.
954\end{cfuncdesc}
955
956\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
957Returns 1 if o has the attribute attr_name, and 0 otherwise.
958This is equivalent to the Python expression:
959\code{hasattr(o,attr_name)}.
960This function always succeeds.
961\end{cfuncdesc}
962
963\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o, char *attr_name}
Guido van Rossum59a61351997-08-14 20:34:33 +0000964Retrieve an attributed named attr_name from object o.
Guido van Rossum9231c8f1997-05-15 21:43:21 +0000965Returns the attribute value on success, or \NULL{} on failure.
966This is the equivalent of the Python expression: \code{o.attr_name}.
967\end{cfuncdesc}
968
969
970\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
971Returns 1 if o has the attribute attr_name, and 0 otherwise.
972This is equivalent to the Python expression:
973\code{hasattr(o,attr_name)}.
974This function always succeeds.
975\end{cfuncdesc}
976
977
978\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o, PyObject *attr_name}
979Retrieve an attributed named attr_name form object o.
980Returns the attribute value on success, or \NULL{} on failure.
981This is the equivalent of the Python expression: o.attr_name.
982\end{cfuncdesc}
983
984
985\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
986Set the value of the attribute named \code{attr_name}, for object \code{o},
987to the value \code{v}. Returns -1 on failure. This is
988the equivalent of the Python statement: \code{o.attr_name=v}.
989\end{cfuncdesc}
990
991
992\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
993Set the value of the attribute named \code{attr_name}, for
994object \code{o},
995to the value \code{v}. Returns -1 on failure. This is
996the equivalent of the Python statement: \code{o.attr_name=v}.
997\end{cfuncdesc}
998
999
1000\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
1001Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1002failure. This is the equivalent of the Python
1003statement: \code{del o.attr_name}.
1004\end{cfuncdesc}
1005
1006
1007\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
1008Delete attribute named \code{attr_name}, for object \code{o}. Returns -1 on
1009failure. This is the equivalent of the Python
1010statement: \code{del o.attr_name}.
1011\end{cfuncdesc}
1012
1013
1014\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
1015Compare the values of \code{o1} and \code{o2} using a routine provided by
1016\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1017The result of the comparison is returned in \code{result}. Returns
1018-1 on failure. This is the equivalent of the Python
1019statement: \code{result=cmp(o1,o2)}.
1020\end{cfuncdesc}
1021
1022
1023\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
1024Compare the values of \code{o1} and \code{o2} using a routine provided by
1025\code{o1}, if one exists, otherwise with a routine provided by \code{o2}.
1026Returns the result of the comparison on success. On error,
1027the value returned is undefined. This is equivalent to the
1028Python expression: \code{cmp(o1,o2)}.
1029\end{cfuncdesc}
1030
1031
1032\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
1033Compute the string representation of object, \code{o}. Returns the
1034string representation on success, \NULL{} on failure. This is
1035the equivalent of the Python expression: \code{repr(o)}.
1036Called by the \code{repr()} built-in function and by reverse quotes.
1037\end{cfuncdesc}
1038
1039
1040\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
1041Compute the string representation of object, \code{o}. Returns the
1042string representation on success, \NULL{} on failure. This is
1043the equivalent of the Python expression: \code{str(o)}.
1044Called by the \code{str()} built-in function and by the \code{print}
1045statement.
1046\end{cfuncdesc}
1047
1048
1049\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
1050Determine if the object \code{o}, is callable. Return 1 if the
1051object is callable and 0 otherwise.
1052This function always succeeds.
1053\end{cfuncdesc}
1054
1055
1056\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object, PyObject *args}
1057Call a callable Python object \code{callable_object}, with
1058arguments given by the tuple \code{args}. If no arguments are
1059needed, then args may be \NULL{}. Returns the result of the
1060call on success, or \NULL{} on failure. This is the equivalent
1061of the Python expression: \code{apply(o, args)}.
1062\end{cfuncdesc}
1063
1064\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
1065Call a callable Python object \code{callable_object}, with a
1066variable number of C arguments. The C arguments are described
1067using a mkvalue-style format string. The format may be \NULL{},
1068indicating that no arguments are provided. Returns the
1069result of the call on success, or \NULL{} on failure. This is
1070the equivalent of the Python expression: \code{apply(o,args)}.
1071\end{cfuncdesc}
1072
1073
1074\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
1075Call the method named \code{m} of object \code{o} with a variable number of
1076C arguments. The C arguments are described by a mkvalue
1077format string. The format may be \NULL{}, indicating that no
1078arguments are provided. Returns the result of the call on
1079success, or \NULL{} on failure. This is the equivalent of the
1080Python expression: \code{o.method(args)}.
1081Note that Special method names, such as "\code{__add__}",
1082"\code{__getitem__}", and so on are not supported. The specific
1083abstract-object routines for these must be used.
1084\end{cfuncdesc}
1085
1086
1087\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
1088Compute and return the hash value of an object \code{o}. On
1089failure, return -1. This is the equivalent of the Python
1090expression: \code{hash(o)}.
1091\end{cfuncdesc}
1092
1093
1094\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
1095Returns 1 if the object \code{o} is considered to be true, and
10960 otherwise. This is equivalent to the Python expression:
1097\code{not not o}.
1098This function always succeeds.
1099\end{cfuncdesc}
1100
1101
1102\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1103On success, returns a type object corresponding to the object
1104type of object \code{o}. On failure, returns \NULL{}. This is
1105equivalent to the Python expression: \code{type(o)}.
1106\end{cfuncdesc}
1107
1108\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
1109Return the length of object \code{o}. If the object \code{o} provides
1110both sequence and mapping protocols, the sequence length is
1111returned. On error, -1 is returned. This is the equivalent
1112to the Python expression: \code{len(o)}.
1113\end{cfuncdesc}
1114
1115
1116\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
1117Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1118on failure. This is the equivalent of the Python expression:
1119\code{o[key]}.
1120\end{cfuncdesc}
1121
1122
1123\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
1124Map the object \code{key} to the value \code{v}.
1125Returns -1 on failure. This is the equivalent
1126of the Python statement: \code{o[key]=v}.
1127\end{cfuncdesc}
1128
1129
1130\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key, PyObject *v}
1131Delete the mapping for \code{key} from \code{*o}. Returns -1
1132on failure.
Guido van Rossum59a61351997-08-14 20:34:33 +00001133This is the equivalent of the Python statement: \code{del o[key]}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001134\end{cfuncdesc}
1135
1136
1137\section{Number Protocol}
1138
1139\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
1140Returns 1 if the object \code{o} provides numeric protocols, and
1141false otherwise.
1142This function always succeeds.
1143\end{cfuncdesc}
1144
1145
1146\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
1147Returns the result of adding \code{o1} and \code{o2}, or null on failure.
1148This is the equivalent of the Python expression: \code{o1+o2}.
1149\end{cfuncdesc}
1150
1151
1152\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
1153Returns the result of subtracting \code{o2} from \code{o1}, or null on
1154failure. This is the equivalent of the Python expression:
1155\code{o1-o2}.
1156\end{cfuncdesc}
1157
1158
1159\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
1160Returns the result of multiplying \code{o1} and \code{o2}, or null on
1161failure. This is the equivalent of the Python expression:
1162\code{o1*o2}.
1163\end{cfuncdesc}
1164
1165
1166\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
1167Returns the result of dividing \code{o1} by \code{o2}, or null on failure.
1168This is the equivalent of the Python expression: \code{o1/o2}.
1169\end{cfuncdesc}
1170
1171
1172\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
1173Returns the remainder of dividing \code{o1} by \code{o2}, or null on
1174failure. This is the equivalent of the Python expression:
1175\code{o1\%o2}.
1176\end{cfuncdesc}
1177
1178
1179\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
1180See the built-in function divmod. Returns \NULL{} on failure.
1181This is the equivalent of the Python expression:
1182\code{divmod(o1,o2)}.
1183\end{cfuncdesc}
1184
1185
1186\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
1187See the built-in function pow. Returns \NULL{} on failure.
1188This is the equivalent of the Python expression:
1189\code{pow(o1,o2,o3)}, where \code{o3} is optional.
1190\end{cfuncdesc}
1191
1192
1193\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
1194Returns the negation of \code{o} on success, or null on failure.
1195This is the equivalent of the Python expression: \code{-o}.
1196\end{cfuncdesc}
1197
1198
1199\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
1200Returns \code{o} on success, or \NULL{} on failure.
1201This is the equivalent of the Python expression: \code{+o}.
1202\end{cfuncdesc}
1203
1204
1205\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
1206Returns the absolute value of \code{o}, or null on failure. This is
1207the equivalent of the Python expression: \code{abs(o)}.
1208\end{cfuncdesc}
1209
1210
1211\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
1212Returns the bitwise negation of \code{o} on success, or \NULL{} on
1213failure. This is the equivalent of the Python expression:
Guido van Rossum59a61351997-08-14 20:34:33 +00001214\code{\~o}.
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001215\end{cfuncdesc}
1216
1217
1218\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
1219Returns the result of left shifting \code{o1} by \code{o2} on success, or
1220\NULL{} on failure. This is the equivalent of the Python
1221expression: \code{o1 << o2}.
1222\end{cfuncdesc}
1223
1224
1225\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
1226Returns the result of right shifting \code{o1} by \code{o2} on success, or
1227\NULL{} on failure. This is the equivalent of the Python
1228expression: \code{o1 >> o2}.
1229\end{cfuncdesc}
1230
1231
1232\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
1233Returns the result of "anding" \code{o2} and \code{o2} on success and \NULL{}
1234on failure. This is the equivalent of the Python
1235expression: \code{o1 and o2}.
1236\end{cfuncdesc}
1237
1238
1239\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
1240Returns the bitwise exclusive or of \code{o1} by \code{o2} on success, or
1241\NULL{} on failure. This is the equivalent of the Python
1242expression: \code{o1\^{ }o2}.
1243\end{cfuncdesc}
1244
1245\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
Guido van Rossum59a61351997-08-14 20:34:33 +00001246Returns the result of \code{o1} and \code{o2} on success, or \NULL{} on
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001247failure. This is the equivalent of the Python expression:
1248\code{o1 or o2}.
1249\end{cfuncdesc}
1250
1251
1252\begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject *o1, PyObject *o2}
1253This function takes the addresses of two variables of type
1254\code{PyObject*}.
1255
1256If the objects pointed to by \code{*p1} and \code{*p2} have the same type,
1257increment their reference count and return 0 (success).
1258If the objects can be converted to a common numeric type,
1259replace \code{*p1} and \code{*p2} by their converted value (with 'new'
1260reference counts), and return 0.
1261If no conversion is possible, or if some other error occurs,
1262return -1 (failure) and don't increment the reference counts.
1263The call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
1264statement \code{o1, o2 = coerce(o1, o2)}.
1265\end{cfuncdesc}
1266
1267
1268\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
1269Returns the \code{o} converted to an integer object on success, or
1270\NULL{} on failure. This is the equivalent of the Python
1271expression: \code{int(o)}.
1272\end{cfuncdesc}
1273
1274
1275\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
1276Returns the \code{o} converted to a long integer object on success,
1277or \NULL{} on failure. This is the equivalent of the Python
1278expression: \code{long(o)}.
1279\end{cfuncdesc}
1280
1281
1282\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
1283Returns the \code{o} converted to a float object on success, or \NULL{}
1284on failure. This is the equivalent of the Python expression:
1285\code{float(o)}.
1286\end{cfuncdesc}
1287
1288
1289\section{Sequence protocol}
1290
1291\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
1292Return 1 if the object provides sequence protocol, and 0
1293otherwise.
1294This function always succeeds.
1295\end{cfuncdesc}
1296
1297
1298\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
1299Return the concatination of \code{o1} and \code{o2} on success, and \NULL{} on
1300failure. This is the equivalent of the Python
1301expression: \code{o1+o2}.
1302\end{cfuncdesc}
1303
1304
1305\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
Guido van Rossum59a61351997-08-14 20:34:33 +00001306Return the result of repeating sequence object \code{o} \code{count} times,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001307or \NULL{} on failure. This is the equivalent of the Python
1308expression: \code{o*count}.
1309\end{cfuncdesc}
1310
1311
1312\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
1313Return the ith element of \code{o}, or \NULL{} on failure. This is the
1314equivalent of the Python expression: \code{o[i]}.
1315\end{cfuncdesc}
1316
1317
1318\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
1319Return the slice of sequence object \code{o} between \code{i1} and \code{i2}, or
1320\NULL{} on failure. This is the equivalent of the Python
1321expression, \code{o[i1:i2]}.
1322\end{cfuncdesc}
1323
1324
1325\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
1326Assign object \code{v} to the \code{i}th element of \code{o}.
1327Returns -1 on failure. This is the equivalent of the Python
1328statement, \code{o[i]=v}.
1329\end{cfuncdesc}
1330
1331\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
1332Delete the \code{i}th element of object \code{v}. Returns
1333-1 on failure. This is the equivalent of the Python
1334statement: \code{del o[i]}.
1335\end{cfuncdesc}
1336
1337\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1, int i2, PyObject *v}
1338Assign the sequence object \code{v} to the slice in sequence
1339object \code{o} from \code{i1} to \code{i2}. This is the equivalent of the Python
1340statement, \code{o[i1:i2]=v}.
1341\end{cfuncdesc}
1342
1343\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
1344Delete the slice in sequence object, \code{o}, from \code{i1} to \code{i2}.
1345Returns -1 on failure. This is the equivalent of the Python
1346statement: \code{del o[i1:i2]}.
1347\end{cfuncdesc}
1348
1349\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1350Returns the \code{o} as a tuple on success, and \NULL{} on failure.
1351This is equivalent to the Python expression: \code{tuple(o)}.
1352\end{cfuncdesc}
1353
1354\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
1355Return the number of occurrences of \code{value} on \code{o}, that is,
1356return the number of keys for which \code{o[key]==value}. On
1357failure, return -1. This is equivalent to the Python
1358expression: \code{o.count(value)}.
1359\end{cfuncdesc}
1360
1361\begin{cfuncdesc}{int}{PySequence_In}{PyObject *o, PyObject *value}
1362Determine if \code{o} contains \code{value}. If an item in \code{o} is equal to
1363\code{value}, return 1, otherwise return 0. On error, return -1. This
1364is equivalent to the Python expression: \code{value in o}.
1365\end{cfuncdesc}
1366
1367\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
Guido van Rossum59a61351997-08-14 20:34:33 +00001368Return the first index for which \code{o[i]==value}. On error,
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001369return -1. This is equivalent to the Python
1370expression: \code{o.index(value)}.
1371\end{cfuncdesc}
1372
1373\section{Mapping protocol}
1374
1375\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
1376Return 1 if the object provides mapping protocol, and 0
1377otherwise.
1378This function always succeeds.
1379\end{cfuncdesc}
1380
1381
1382\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
1383Returns the number of keys in object \code{o} on success, and -1 on
1384failure. For objects that do not provide sequence protocol,
1385this is equivalent to the Python expression: \code{len(o)}.
1386\end{cfuncdesc}
1387
1388
1389\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
1390Remove the mapping for object \code{key} from the object \code{o}.
1391Return -1 on failure. This is equivalent to
1392the Python statement: \code{del o[key]}.
1393\end{cfuncdesc}
1394
1395
1396\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
1397Remove the mapping for object \code{key} from the object \code{o}.
1398Return -1 on failure. This is equivalent to
1399the Python statement: \code{del o[key]}.
1400\end{cfuncdesc}
1401
1402
1403\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
1404On success, return 1 if the mapping object has the key \code{key}
1405and 0 otherwise. This is equivalent to the Python expression:
1406\code{o.has_key(key)}.
1407This function always succeeds.
1408\end{cfuncdesc}
1409
1410
1411\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
1412Return 1 if the mapping object has the key \code{key}
1413and 0 otherwise. This is equivalent to the Python expression:
1414\code{o.has_key(key)}.
1415This function always succeeds.
1416\end{cfuncdesc}
1417
1418
1419\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
1420On success, return a list of the keys in object \code{o}. On
1421failure, return \NULL{}. This is equivalent to the Python
1422expression: \code{o.keys()}.
1423\end{cfuncdesc}
1424
1425
1426\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
1427On success, return a list of the values in object \code{o}. On
1428failure, return \NULL{}. This is equivalent to the Python
1429expression: \code{o.values()}.
1430\end{cfuncdesc}
1431
1432
1433\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
1434On success, return a list of the items in object \code{o}, where
1435each item is a tuple containing a key-value pair. On
1436failure, return \NULL{}. This is equivalent to the Python
1437expression: \code{o.items()}.
1438\end{cfuncdesc}
1439
1440\begin{cfuncdesc}{int}{PyMapping_Clear}{PyObject *o}
1441Make object \code{o} empty. Returns 1 on success and 0 on failure.
1442This is equivalent to the Python statement:
1443\code{for key in o.keys(): del o[key]}
1444\end{cfuncdesc}
1445
1446
1447\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
1448Return element of \code{o} corresponding to the object \code{key} or \NULL{}
1449on failure. This is the equivalent of the Python expression:
1450\code{o[key]}.
1451\end{cfuncdesc}
1452
1453\begin{cfuncdesc}{PyObject*}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
1454Map the object \code{key} to the value \code{v} in object \code{o}. Returns
1455-1 on failure. This is the equivalent of the Python
1456statement: \code{o[key]=v}.
1457\end{cfuncdesc}
1458
1459
1460\section{Constructors}
1461
1462\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *file_name, char *mode}
1463On success, returns a new file object that is opened on the
1464file given by \code{file_name}, with a file mode given by \code{mode},
1465where \code{mode} has the same semantics as the standard C routine,
1466fopen. On failure, return -1.
1467\end{cfuncdesc}
1468
1469\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp, char *file_name, char *mode, int close_on_del}
1470Return a new file object for an already opened standard C
1471file pointer, \code{fp}. A file name, \code{file_name}, and open mode,
1472\code{mode}, must be provided as well as a flag, \code{close_on_del}, that
1473indicates whether the file is to be closed when the file
1474object is destroyed. On failure, return -1.
1475\end{cfuncdesc}
1476
1477\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
1478Returns a new float object with the value \code{v} on success, and
1479\NULL{} on failure.
1480\end{cfuncdesc}
1481
1482\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long v}
1483Returns a new int object with the value \code{v} on success, and
1484\NULL{} on failure.
1485\end{cfuncdesc}
1486
1487\begin{cfuncdesc}{PyObject*}{PyList_New}{int l}
1488Returns a new list of length \code{l} on success, and \NULL{} on
1489failure.
1490\end{cfuncdesc}
1491
1492\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
1493Returns a new long object with the value \code{v} on success, and
1494\NULL{} on failure.
1495\end{cfuncdesc}
1496
1497\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
1498Returns a new long object with the value \code{v} on success, and
1499\NULL{} on failure.
1500\end{cfuncdesc}
1501
1502\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1503Returns a new empty dictionary on success, and \NULL{} on
1504failure.
1505\end{cfuncdesc}
1506
1507\begin{cfuncdesc}{PyObject*}{PyString_FromString}{char *v}
1508Returns a new string object with the value \code{v} on success, and
1509\NULL{} on failure.
1510\end{cfuncdesc}
1511
1512\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{char *v, int l}
1513Returns a new string object with the value \code{v} and length \code{l}
1514on success, and \NULL{} on failure.
1515\end{cfuncdesc}
1516
1517\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int l}
1518Returns a new tuple of length \code{l} on success, and \NULL{} on
1519failure.
1520\end{cfuncdesc}
1521
1522
1523\chapter{Concrete Objects Layer}
1524
1525The functions in this chapter are specific to certain Python object
1526types. Passing them an object of the wrong type is not a good idea;
1527if you receive an object from a Python program and you are not sure
1528that it has the right type, you must perform a type check first;
1529e.g. to check that an object is a dictionary, use
1530\code{PyDict_Check()}.
1531
1532
1533\chapter{Defining New Object Types}
1534
1535\begin{cfuncdesc}{PyObject *}{_PyObject_New}{PyTypeObject *type}
1536\end{cfuncdesc}
1537
Guido van Rossumae110af1997-05-22 20:11:52 +00001538\begin{cfuncdesc}{PyObject *}{_PyObject_NewVar}{PyTypeObject *type, int size}
Guido van Rossum9231c8f1997-05-15 21:43:21 +00001539\end{cfuncdesc}
1540
Guido van Rossumae110af1997-05-22 20:11:52 +00001541\begin{cfuncdesc}{TYPE}{_PyObject_NEW}{TYPE, PyTypeObject *}
1542\end{cfuncdesc}
1543
1544\begin{cfuncdesc}{TYPE}{_PyObject_NEW_VAR}{TYPE, PyTypeObject *, int size}
1545\end{cfuncdesc}
1546
Guido van Rossum4a944d71997-08-14 20:35:38 +00001547\chapter{Initialization, Finalization, and Threads}
1548
1549% XXX Check argument/return type of all these
1550
1551\begin{cfuncdesc}{void}{Py_Initialize}{}
1552Initialize the Python interpreter. In an application embedding
1553Python, this should be called before using any other Python/C API
1554functions; with the exception of \code{Py_SetProgramName()},
1555\code{PyEval_InitThreads()}, \code{PyEval_ReleaseLock()}, and
1556\code{PyEval_AcquireLock()}. This initializes the table of loaded
1557modules (\code{sys.modules}), and creates the fundamental modules
1558\code{__builtin__}, \code{__main__} and \code{sys}. It also
1559initializes the module search path (\code{sys.path}). It does not set
1560\code{sys.argv}; use \code{PySys_SetArgv()} for that. It is a fatal
1561error to call it for a second time without calling
1562\code{Py_Finalize()} first. There is no return value; it is a fatal
1563error if the initialization fails.
1564\end{cfuncdesc}
1565
1566\begin{cfuncdesc}{void}{Py_Finalize}{}
1567Undo all initializations made by \code{Py_Initialize()} and subsequent
1568use of Python/C API functions, and destroy all sub-interpreters (see
1569\code{Py_NewInterpreter()} below) that were created and not yet
1570destroyed since the last call to \code{Py_Initialize()}. Ideally,
1571this frees all memory allocated by the Python interpreter. It is a
1572fatal error to call it for a second time without calling
1573\code{Py_Initialize()} again first. There is no return value; errors
1574during finalization are ignored.
1575
1576This function is provided for a number of reasons. An embedding
1577application might want to restart Python without having to restart the
1578application itself. An application that has loaded the Python
1579interpreter from a dynamically loadable library (or DLL) might want to
1580free all memory allocated by Python before unloading the DLL. During a
1581hunt for memory leaks in an application a developer might want to free
1582all memory allocated by Python before exiting from the application.
1583
1584\emph{Bugs and caveats:} The destruction of modules and objects in
1585modules is done in random order; this may cause destructors
1586(\code{__del__} methods) to fail when they depend on other objects
1587(even functions) or modules. Dynamically loaded extension modules
1588loaded by Python are not unloaded. Small amounts of memory allocated
1589by the Python interpreter may not be freed (if you find a leak, please
1590report it). Memory tied up in circular references between objects is
1591not freed. Some memory allocated by extension modules may not be
1592freed. Some extension may not work properly if their initialization
1593routine is called more than once; this can happen if an applcation
1594calls \code{Py_Initialize()} and \code{Py_Finalize()} more than once.
1595\end{cfuncdesc}
1596
1597\begin{cfuncdesc}{PyThreadState *}{Py_NewInterpreter}{}
1598Create a new sub-interpreter. This is an (almost) totally separate
1599environment for the execution of Python code. In particular, the new
1600interpreter has separate, independent versions of all imported
1601modules, including the fundamental modules \code{__builtin__},
1602\code{__main__} and \code{sys}. The table of loaded modules
1603(\code{sys.modules}) and the module search path (\code{sys.path}) are
1604also separate. The new environment has no \code{sys.argv} variable.
1605It has new standard I/O stream file objects \code{sys.stdin},
1606\code{sys.stdout} and \code{sys.stderr} (however these refer to the
1607same underlying \code{FILE} structures in the C library).
1608
1609The return value points to the first thread state created in the new
1610sub-interpreter. This thread state is made the current thread state.
1611Note that no actual thread is created; see the discussion of thread
1612states below. If creation of the new interpreter is unsuccessful,
1613\code{NULL} is returned; no exception is set since the exception state
1614is stored in the current thread state and there may not be a current
1615thread state. (Like all other Python/C API functions, the global
1616interpreter lock must be held before calling this function and is
1617still held when it returns; however, unlike most other Python/C API
1618functions, there needn't be a current thread state on entry.)
1619
1620Extension modules are shared between (sub-)interpreters as follows:
1621the first time a particular extension is imported, it is initialized
1622normally, and a (shallow) copy of its module's dictionary is
1623squirreled away. When the same extension is imported by another
1624(sub-)interpreter, a new module is initialized and filled with the
1625contents of this copy; the extension's \code{init} function is not
1626called. Note that this is different from what happens when as
1627extension is imported after the interpreter has been completely
1628re-initialized by calling \code{Py_Finalize()} and
1629\code{Py_Initialize()}; in that case, the extension's \code{init}
1630function \emph{is} called again.
1631
1632\emph{Bugs and caveats:} Because sub-interpreters (and the main
1633interpreter) are part of the same process, the insulation between them
1634isn't perfect -- for example, using low-level file operations like
1635\code{os.close()} they can (accidentally or maliciously) affect each
1636other's open files. Because of the way extensions are shared between
1637(sub-)interpreters, some extensions may not work properly; this is
1638especially likely when the extension makes use of (static) global
1639variables, or when the extension manipulates its module's dictionary
1640after its initialization. It is possible to insert objects created in
1641one sub-interpreter into a namespace of another sub-interpreter; this
1642should be done with great care to avoid sharing user-defined
1643functions, methods, instances or classes between sub-interpreters,
1644since import operations executed by such objects may affect the
1645wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
1646a hard-to-fix bug that will be addressed in a future release.)
1647\end{cfuncdesc}
1648
1649\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
1650Destroy the (sub-)interpreter represented by the given thread state.
1651The given thread state must be the current thread state. See the
1652discussion of thread states below. When the call returns, the current
1653thread state is \code{NULL}. All thread states associated with this
1654interpreted are destroyed. (The global interpreter lock must be held
1655before calling this function and is still held when it returns.)
1656\code{Py_Finalize()} will destroy all sub-interpreters that haven't
1657been explicitly destroyed at that point.
1658\end{cfuncdesc}
1659
1660\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
1661This function should be called before \code{Py_Initialize()} is called
1662for the first time, if it is called at all. It tells the interpreter
1663the value of the \code{argv[0]} argument to the \code{main()} function
1664of the program. This is used by \code{Py_GetPath()} and some other
1665functions below to find the Python run-time libraries relative to the
1666interpreter executable. The default value is \code{"python"}. The
1667argument should point to a zero-terminated character string in static
1668storage whose contents will not change for the duration of the
1669program's execution. No code in the Python interpreter will change
1670the contents of this storage.
1671\end{cfuncdesc}
1672
1673\begin{cfuncdesc}{char *}{Py_GetProgramName}{}
1674Return the program name set with \code{Py_SetProgramName()}, or the
1675default. The returned string points into static storage; the caller
1676should not modify its value.
1677\end{cfuncdesc}
1678
1679\begin{cfuncdesc}{char *}{Py_GetPrefix}{}
1680Return the ``prefix'' for installed platform-independent files. This
1681is derived through a number of complicated rules from the program name
1682set with \code{Py_SetProgramName()} and some environment variables;
1683for example, if the program name is \code{"/usr/local/bin/python"},
1684the prefix is \code{"/usr/local"}. The returned string points into
1685static storage; the caller should not modify its value. This
1686corresponds to the \code{prefix} variable in the top-level
1687\code{Makefile} and the \code{--prefix} argument to the
1688\code{configure} script at build time. The value is available to
1689Python code as \code{sys.prefix}. It is only useful on Unix. See
1690also the next function.
1691\end{cfuncdesc}
1692
1693\begin{cfuncdesc}{char *}{Py_GetExecPrefix}{}
1694Return the ``exec-prefix'' for installed platform-\emph{de}pendent
1695files. This is derived through a number of complicated rules from the
1696program name set with \code{Py_SetProgramName()} and some environment
1697variables; for example, if the program name is
1698\code{"/usr/local/bin/python"}, the exec-prefix is
1699\code{"/usr/local"}. The returned string points into static storage;
1700the caller should not modify its value. This corresponds to the
1701\code{exec_prefix} variable in the top-level \code{Makefile} and the
1702\code{--exec_prefix} argument to the \code{configure} script at build
1703time. The value is available to Python code as
1704\code{sys.exec_prefix}. It is only useful on Unix.
1705
1706Background: The exec-prefix differs from the prefix when platform
1707dependent files (such as executables and shared libraries) are
1708installed in a different directory tree. In a typical installation,
1709platform dependent files may be installed in the
1710\code{"/usr/local/plat"} subtree while platform independent may be
1711installed in \code{"/usr/local"}.
1712
1713Generally speaking, a platform is a combination of hardware and
1714software families, e.g. Sparc machines running the Solaris 2.x
1715operating system are considered the same platform, but Intel machines
1716running Solaris 2.x are another platform, and Intel machines running
1717Linux are yet another platform. Different major revisions of the same
1718operating system generally also form different platforms. Non-Unix
1719operating systems are a different story; the installation strategies
1720on those systems are so different that the prefix and exec-prefix are
1721meaningless, and set to the empty string. Note that compiled Python
1722bytecode files are platform independent (but not independent from the
1723Python version by which they were compiled!).
1724
1725System administrators will know how to configure the \code{mount} or
1726\code{automount} programs to share \code{"/usr/local"} between platforms
1727while having \code{"/usr/local/plat"} be a different filesystem for each
1728platform.
1729\end{cfuncdesc}
1730
1731\begin{cfuncdesc}{char *}{Py_GetProgramFullPath}{}
1732Return the full program name of the Python executable; this is
1733computed as a side-effect of deriving the default module search path
Guido van Rossum09270b51997-08-15 18:57:32 +00001734from the program name (set by \code{Py_SetProgramName()} above). The
Guido van Rossum4a944d71997-08-14 20:35:38 +00001735returned string points into static storage; the caller should not
1736modify its value. The value is available to Python code as
1737\code{sys.executable}. % XXX is that the right sys.name?
1738\end{cfuncdesc}
1739
1740\begin{cfuncdesc}{char *}{Py_GetPath}{}
1741Return the default module search path; this is computed from the
Guido van Rossum09270b51997-08-15 18:57:32 +00001742program name (set by \code{Py_SetProgramName()} above) and some
Guido van Rossum4a944d71997-08-14 20:35:38 +00001743environment variables. The returned string consists of a series of
1744directory names separated by a platform dependent delimiter character.
1745The delimiter character is \code{':'} on Unix, \code{';'} on
Guido van Rossum09270b51997-08-15 18:57:32 +00001746DOS/Windows, and \code{'\\n'} (the ASCII newline character) on
Guido van Rossum4a944d71997-08-14 20:35:38 +00001747Macintosh. The returned string points into static storage; the caller
1748should not modify its value. The value is available to Python code
1749as the list \code{sys.path}, which may be modified to change the
1750future search path for loaded modules.
1751
1752% XXX should give the exact rules
1753\end{cfuncdesc}
1754
1755\begin{cfuncdesc}{const char *}{Py_GetVersion}{}
1756Return the version of this Python interpreter. This is a string that
1757looks something like
1758
Guido van Rossum09270b51997-08-15 18:57:32 +00001759\begin{verbatim}
1760"1.5a3 (#67, Aug 1 1997, 22:34:28) [GCC 2.7.2.2]"
1761\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001762
1763The first word (up to the first space character) is the current Python
1764version; the first three characters are the major and minor version
1765separated by a period. The returned string points into static storage;
1766the caller should not modify its value. The value is available to
1767Python code as the list \code{sys.version}.
1768\end{cfuncdesc}
1769
1770\begin{cfuncdesc}{const char *}{Py_GetPlatform}{}
1771Return the platform identifier for the current platform. On Unix,
1772this is formed from the ``official'' name of the operating system,
1773converted to lower case, followed by the major revision number; e.g.,
1774for Solaris 2.x, which is also known as SunOS 5.x, the value is
1775\code{"sunos5"}. On Macintosh, it is \code{"mac"}. On Windows, it
1776is \code{"win"}. The returned string points into static storage;
1777the caller should not modify its value. The value is available to
1778Python code as \code{sys.platform}.
1779\end{cfuncdesc}
1780
1781\begin{cfuncdesc}{const char *}{Py_GetCopyright}{}
1782Return the official copyright string for the current Python version,
1783for example
1784
1785\code{"Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam"}
1786
1787The returned string points into static storage; the caller should not
1788modify its value. The value is available to Python code as the list
1789\code{sys.copyright}.
1790\end{cfuncdesc}
1791
1792\begin{cfuncdesc}{const char *}{Py_GetCompiler}{}
1793Return an indication of the compiler used to build the current Python
1794version, in square brackets, for example
1795
1796\code{"[GCC 2.7.2.2]"}
1797
1798The returned string points into static storage; the caller should not
1799modify its value. The value is available to Python code as part of
1800the variable \code{sys.version}.
1801\end{cfuncdesc}
1802
1803\begin{cfuncdesc}{const char *}{Py_GetBuildInfo}{}
1804Return information about the sequence number and build date and time
1805of the current Python interpreter instance, for example
1806
Guido van Rossum09270b51997-08-15 18:57:32 +00001807\begin{verbatim}
1808"#67, Aug 1 1997, 22:34:28"
1809\end{verbatim}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001810
1811The returned string points into static storage; the caller should not
1812modify its value. The value is available to Python code as part of
1813the variable \code{sys.version}.
1814\end{cfuncdesc}
1815
1816\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
1817% XXX
1818\end{cfuncdesc}
1819
1820% XXX Other PySys thingies (doesn't really belong in this chapter)
1821
1822\section{Thread State and the Global Interpreter Lock}
1823
1824\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
1825\end{cfuncdesc}
1826
1827\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
1828\end{cfuncdesc}
1829
1830\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
1831\end{cfuncdesc}
1832
1833\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
1834\end{cfuncdesc}
1835
1836\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
1837\end{cfuncdesc}
1838
1839\begin{cfuncdesc}{PyThreadState *}{PyEval_SaveThread}{}
1840\end{cfuncdesc}
1841
1842% XXX These aren't really C functions!
Guido van Rossum09270b51997-08-15 18:57:32 +00001843\begin{cfuncdesc}{}{Py_BEGIN_ALLOW_THREADS}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001844\end{cfuncdesc}
1845
Guido van Rossum09270b51997-08-15 18:57:32 +00001846\begin{cfuncdesc}{}{Py_BEGIN_END_THREADS}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001847\end{cfuncdesc}
1848
Guido van Rossum09270b51997-08-15 18:57:32 +00001849\begin{cfuncdesc}{}{Py_BEGIN_XXX_THREADS}{}
Guido van Rossum4a944d71997-08-14 20:35:38 +00001850\end{cfuncdesc}
1851
1852
Guido van Rossumae110af1997-05-22 20:11:52 +00001853XXX To be done:
1854
1855PyObject, PyVarObject
1856
1857PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
1858
1859Typedefs:
1860unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
1861intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
1862getreadbufferproc, getwritebufferproc, getsegcountproc,
1863destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
1864setattrofunc, cmpfunc, reprfunc, hashfunc
1865
1866PyNumberMethods
1867
1868PySequenceMethods
1869
1870PyMappingMethods
1871
1872PyBufferProcs
1873
1874PyTypeObject
1875
1876DL_IMPORT
1877
1878PyType_Type
1879
1880Py*_Check
1881
1882Py_None, _Py_NoneStruct
1883
1884_PyObject_New, _PyObject_NewVar
1885
1886PyObject_NEW, PyObject_NEW_VAR
1887
1888
1889\chapter{Specific Data Types}
1890
1891This chapter describes the functions that deal with specific types of
1892Python objects. It is structured like the ``family tree'' of Python
1893object types.
1894
1895
1896\section{Fundamental Objects}
1897
1898This section describes Python type objects and the singleton object
1899\code{None}.
1900
1901
1902\subsection{Type Objects}
1903
1904\begin{ctypedesc}{PyTypeObject}
1905
1906\end{ctypedesc}
1907
1908\begin{cvardesc}{PyObject *}{PyType_Type}
1909
1910\end{cvardesc}
1911
1912
1913\subsection{The None Object}
1914
1915\begin{cvardesc}{PyObject *}{Py_None}
1916macro
1917\end{cvardesc}
1918
1919
1920\section{Sequence Objects}
1921
1922Generic operations on sequence objects were discussed in the previous
1923chapter; this section deals with the specific kinds of sequence
1924objects that are intrinsuc to the Python language.
1925
1926
1927\subsection{String Objects}
1928
1929\begin{ctypedesc}{PyStringObject}
1930This subtype of \code{PyObject} represents a Python string object.
1931\end{ctypedesc}
1932
1933\begin{cvardesc}{PyTypeObject}{PyString_Type}
1934This instance of \code{PyTypeObject} represents the Python string type.
1935\end{cvardesc}
1936
1937\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
1938
1939\end{cfuncdesc}
1940
1941\begin{cfuncdesc}{PyObject *}{PyString_FromStringAndSize}{const char *, int}
1942
1943\end{cfuncdesc}
1944
1945\begin{cfuncdesc}{PyObject *}{PyString_FromString}{const char *}
1946
1947\end{cfuncdesc}
1948
1949\begin{cfuncdesc}{int}{PyString_Size}{PyObject *}
1950
1951\end{cfuncdesc}
1952
1953\begin{cfuncdesc}{char *}{PyString_AsString}{PyObject *}
1954
1955\end{cfuncdesc}
1956
1957\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **, PyObject *}
1958
1959\end{cfuncdesc}
1960
1961\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **, PyObject *}
1962
1963\end{cfuncdesc}
1964
1965\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **, int}
1966
1967\end{cfuncdesc}
1968
1969\begin{cfuncdesc}{PyObject *}{PyString_Format}{PyObject *, PyObject *}
1970
1971\end{cfuncdesc}
1972
1973\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **}
1974
1975\end{cfuncdesc}
1976
1977\begin{cfuncdesc}{PyObject *}{PyString_InternFromString}{const char *}
1978
1979\end{cfuncdesc}
1980
1981\begin{cfuncdesc}{char *}{PyString_AS_STRING}{PyStringObject *}
1982
1983\end{cfuncdesc}
1984
1985\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyStringObject *}
1986
1987\end{cfuncdesc}
1988
1989
1990\subsection{Tuple Objects}
1991
1992\begin{ctypedesc}{PyTupleObject}
1993This subtype of \code{PyObject} represents a Python tuple object.
1994\end{ctypedesc}
1995
1996\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
1997This instance of \code{PyTypeObject} represents the Python tuple type.
1998\end{cvardesc}
1999
2000\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
2001Return true if the argument is a tuple object.
2002\end{cfuncdesc}
2003
2004\begin{cfuncdesc}{PyTupleObject *}{PyTuple_New}{int s}
2005Return a new tuple object of size \code{s}
2006\end{cfuncdesc}
2007
2008\begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
2009akes a pointer to a tuple object, and returns the size
2010of that tuple.
2011\end{cfuncdesc}
2012
2013\begin{cfuncdesc}{PyObject *}{PyTuple_GetItem}{PyTupleObject *p, int pos}
2014returns the object at position \code{pos} in the tuple pointed
2015to by \code{p}.
2016\end{cfuncdesc}
2017
2018\begin{cfuncdesc}{PyObject *}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
2019does the same, but does no checking of it's
2020arguments.
2021\end{cfuncdesc}
2022
2023\begin{cfuncdesc}{PyTupleObject *}{PyTuple_GetSlice}{PyTupleObject *p,
2024 int low,
2025 int high}
2026takes a slice of the tuple pointed to by \code{p} from
2027\code{low} to \code{high} and returns it as a new tuple.
2028\end{cfuncdesc}
2029
2030\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyTupleObject *p,
2031 int pos,
2032 PyObject *o}
2033inserts a reference to object \code{o} at position \code{pos} of
2034the tuple pointed to by \code{p}. It returns 0 on success.
2035\end{cfuncdesc}
2036
2037\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyTupleObject *p,
2038 int pos,
2039 PyObject *o}
2040
2041does the same, but does no error checking, and
2042should \emph{only} be used to fill in brand new tuples.
2043\end{cfuncdesc}
2044
2045\begin{cfuncdesc}{PyTupleObject *}{_PyTuple_Resize}{PyTupleObject *p,
2046 int new,
2047 int last_is_sticky}
2048can be used to resize a tuple. Because tuples are
2049\emph{supposed} to be immutable, this should only be used if there is only
2050one module referencing the object. Do \emph{not} use this if the tuple may
2051already be known to some other part of the code. \code{last_is_sticky} is
2052a flag - if set, the tuple will grow or shrink at the front, otherwise
2053it will grow or shrink at the end. Think of this as destroying the old
2054tuple and creating a new one, only more efficiently.
2055\end{cfuncdesc}
2056
2057
2058\subsection{List Objects}
2059
2060\begin{ctypedesc}{PyListObject}
2061This subtype of \code{PyObject} represents a Python list object.
2062\end{ctypedesc}
2063
2064\begin{cvardesc}{PyTypeObject}{PyList_Type}
2065This instance of \code{PyTypeObject} represents the Python list type.
2066\end{cvardesc}
2067
2068\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
2069returns true if it's argument is a \code{PyListObject}
2070\end{cfuncdesc}
2071
2072\begin{cfuncdesc}{PyObject *}{PyList_New}{int size}
2073
2074\end{cfuncdesc}
2075
2076\begin{cfuncdesc}{int}{PyList_Size}{PyObject *}
2077
2078\end{cfuncdesc}
2079
2080\begin{cfuncdesc}{PyObject *}{PyList_GetItem}{PyObject *, int}
2081
2082\end{cfuncdesc}
2083
2084\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *, int, PyObject *}
2085
2086\end{cfuncdesc}
2087
2088\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *, int, PyObject *}
2089
2090\end{cfuncdesc}
2091
2092\begin{cfuncdesc}{int}{PyList_Append}{PyObject *, PyObject *}
2093
2094\end{cfuncdesc}
2095
2096\begin{cfuncdesc}{PyObject *}{PyList_GetSlice}{PyObject *, int, int}
2097
2098\end{cfuncdesc}
2099
2100\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *, int, int, PyObject *}
2101
2102\end{cfuncdesc}
2103
2104\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *}
2105
2106\end{cfuncdesc}
2107
2108\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *}
2109
2110\end{cfuncdesc}
2111
2112\begin{cfuncdesc}{PyObject *}{PyList_AsTuple}{PyObject *}
2113
2114\end{cfuncdesc}
2115
2116\begin{cfuncdesc}{PyObject *}{PyList_GET_ITEM}{PyObject *list, int i}
2117
2118\end{cfuncdesc}
2119
2120\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
2121
2122\end{cfuncdesc}
2123
2124
2125\section{Mapping Objects}
2126
2127\subsection{Dictionary Objects}
2128
2129\begin{ctypedesc}{PyDictObject}
2130This subtype of \code{PyObject} represents a Python dictionary object.
2131\end{ctypedesc}
2132
2133\begin{cvardesc}{PyTypeObject}{PyDict_Type}
2134This instance of \code{PyTypeObject} represents the Python dictionary type.
2135\end{cvardesc}
2136
2137\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
2138returns true if it's argument is a PyDictObject
2139\end{cfuncdesc}
2140
2141\begin{cfuncdesc}{PyDictObject *}{PyDict_New}{}
2142returns a new empty dictionary.
2143\end{cfuncdesc}
2144
2145\begin{cfuncdesc}{void}{PyDict_Clear}{PyDictObject *p}
2146empties an existing dictionary and deletes it.
2147\end{cfuncdesc}
2148
2149\begin{cfuncdesc}{int}{PyDict_SetItem}{PyDictObject *p,
2150 PyObject *key,
2151 PyObject *val}
2152inserts \code{value} into the dictionary with a key of
2153\code{key}. Both \code{key} and \code{value} should be PyObjects, and \code{key} should
2154be hashable.
2155\end{cfuncdesc}
2156
2157\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
2158 char *key,
2159 PyObject *val}
2160inserts \code{value} into the dictionary using \code{key}
2161as a key. \code{key} should be a char *
2162\end{cfuncdesc}
2163
2164\begin{cfuncdesc}{int}{PyDict_DelItem}{PyDictObject *p, PyObject *key}
2165removes the entry in dictionary \code{p} with key \code{key}.
2166\code{key} is a PyObject.
2167\end{cfuncdesc}
2168
2169\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyDictObject *p, char *key}
2170removes the entry in dictionary \code{p} which has a key
2171specified by the \code{char *}\code{key}.
2172\end{cfuncdesc}
2173
2174\begin{cfuncdesc}{PyObject *}{PyDict_GetItem}{PyDictObject *p, PyObject *key}
2175returns the object from dictionary \code{p} which has a key
2176\code{key}.
2177\end{cfuncdesc}
2178
2179\begin{cfuncdesc}{PyObject *}{PyDict_GetItemString}{PyDictObject *p, char *key}
2180does the same, but \code{key} is specified as a
2181\code{char *}, rather than a \code{PyObject *}.
2182\end{cfuncdesc}
2183
2184\begin{cfuncdesc}{PyListObject *}{PyDict_Items}{PyDictObject *p}
2185returns a PyListObject containing all the items
2186from the dictionary, as in the mapping method \code{items()} (see the Reference
2187Guide)
2188\end{cfuncdesc}
2189
2190\begin{cfuncdesc}{PyListObject *}{PyDict_Keys}{PyDictObject *p}
2191returns a PyListObject containing all the keys
2192from the dictionary, as in the mapping method \code{keys()} (see the Reference Guide)
2193\end{cfuncdesc}
2194
2195\begin{cfuncdesc}{PyListObject *}{PyDict_Values}{PyDictObject *p}
2196returns a PyListObject containing all the values
2197from the dictionary, as in the mapping method \code{values()} (see the Reference Guide)
2198\end{cfuncdesc}
2199
2200\begin{cfuncdesc}{int}{PyDict_Size}{PyDictObject *p}
2201returns the number of items in the dictionary.
2202\end{cfuncdesc}
2203
2204\begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p,
2205 int ppos,
2206 PyObject **pkey,
2207 PyObject **pvalue}
2208
2209\end{cfuncdesc}
2210
2211
2212\section{Numeric Objects}
2213
2214\subsection{Plain Integer Objects}
2215
2216\begin{ctypedesc}{PyIntObject}
2217This subtype of \code{PyObject} represents a Python integer object.
2218\end{ctypedesc}
2219
2220\begin{cvardesc}{PyTypeObject}{PyInt_Type}
2221This instance of \code{PyTypeObject} represents the Python plain
2222integer type.
2223\end{cvardesc}
2224
2225\begin{cfuncdesc}{int}{PyInt_Check}{PyObject *}
2226
2227\end{cfuncdesc}
2228
2229\begin{cfuncdesc}{PyIntObject *}{PyInt_FromLong}{long ival}
2230creates a new integer object with a value of \code{ival}.
2231
2232The current implementation keeps an array of integer objects for all
2233integers between -1 and 100, when you create an int in that range you
2234actually just get back a reference to the existing object. So it should
2235be possible to change the value of 1. I suspect the behaviour of python
2236in this case is undefined. :-)
2237\end{cfuncdesc}
2238
2239\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyIntObject *io}
2240returns the value of the object \code{io}.
2241\end{cfuncdesc}
2242
2243\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
2244will first attempt to cast the object to a PyIntObject, if
2245it is not already one, and the return it's value.
2246\end{cfuncdesc}
2247
2248\begin{cfuncdesc}{long}{PyInt_GetMax}{}
2249returns the systems idea of the largest int it can handle
2250(LONG_MAX, as defined in the system header files)
2251\end{cfuncdesc}
2252
2253
2254\subsection{Long Integer Objects}
2255
2256\begin{ctypedesc}{PyLongObject}
2257This subtype of \code{PyObject} represents a Python long integer object.
2258\end{ctypedesc}
2259
2260\begin{cvardesc}{PyTypeObject}{PyLong_Type}
2261This instance of \code{PyTypeObject} represents the Python long integer type.
2262\end{cvardesc}
2263
2264\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
2265returns true if it's argument is a \code{PyLongObject}
2266\end{cfuncdesc}
2267
2268\begin{cfuncdesc}{PyObject *}{PyLong_FromLong}{long}
2269
2270\end{cfuncdesc}
2271
2272\begin{cfuncdesc}{PyObject *}{PyLong_FromUnsignedLong}{unsigned long}
2273
2274\end{cfuncdesc}
2275
2276\begin{cfuncdesc}{PyObject *}{PyLong_FromDouble}{double}
2277
2278\end{cfuncdesc}
2279
2280\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *}
2281
2282\end{cfuncdesc}
2283
2284\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject }
2285
2286\end{cfuncdesc}
2287
2288\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *}
2289
2290\end{cfuncdesc}
2291
2292\begin{cfuncdesc}{PyObject *}{*PyLong_FromString}{char *, char **, int}
2293
2294\end{cfuncdesc}
2295
2296
2297\subsection{Floating Point Objects}
2298
2299\begin{ctypedesc}{PyFloatObject}
2300This subtype of \code{PyObject} represents a Python floating point object.
2301\end{ctypedesc}
2302
2303\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2304This instance of \code{PyTypeObject} represents the Python floating
2305point type.
2306\end{cvardesc}
2307
2308\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2309returns true if it's argument is a \code{PyFloatObject}
2310\end{cfuncdesc}
2311
2312\begin{cfuncdesc}{PyObject *}{PyFloat_FromDouble}{double}
2313
2314\end{cfuncdesc}
2315
2316\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *}
2317
2318\end{cfuncdesc}
2319
2320\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyFloatObject *}
2321
2322\end{cfuncdesc}
2323
2324
2325\subsection{Complex Number Objects}
2326
2327\begin{ctypedesc}{Py_complex}
2328typedef struct {
2329 double real;
2330 double imag;
2331}
2332\end{ctypedesc}
2333
2334\begin{ctypedesc}{PyComplexObject}
2335This subtype of \code{PyObject} represents a Python complex number object.
2336\end{ctypedesc}
2337
2338\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2339This instance of \code{PyTypeObject} represents the Python complex
2340number type.
2341\end{cvardesc}
2342
2343\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2344returns true if it's argument is a \code{PyComplexObject}
2345\end{cfuncdesc}
2346
2347\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex, Py_complex}
2348
2349\end{cfuncdesc}
2350
2351\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex, Py_complex}
2352
2353\end{cfuncdesc}
2354
2355\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex}
2356
2357\end{cfuncdesc}
2358
2359\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex, Py_complex}
2360
2361\end{cfuncdesc}
2362
2363\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex, Py_complex}
2364
2365\end{cfuncdesc}
2366
2367\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex, Py_complex}
2368
2369\end{cfuncdesc}
2370
2371\begin{cfuncdesc}{PyObject *}{PyComplex_FromCComplex}{Py_complex}
2372
2373\end{cfuncdesc}
2374
2375\begin{cfuncdesc}{PyObject *}{PyComplex_FromDoubles}{double real, double imag}
2376
2377\end{cfuncdesc}
2378
2379\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2380
2381\end{cfuncdesc}
2382
2383\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2384
2385\end{cfuncdesc}
2386
2387\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2388
2389\end{cfuncdesc}
2390
2391
2392
2393\section{Other Objects}
2394
2395\subsection{File Objects}
2396
2397\begin{ctypedesc}{PyFileObject}
2398This subtype of \code{PyObject} represents a Python file object.
2399\end{ctypedesc}
2400
2401\begin{cvardesc}{PyTypeObject}{PyFile_Type}
2402This instance of \code{PyTypeObject} represents the Python file type.
2403\end{cvardesc}
2404
2405\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2406returns true if it's argument is a \code{PyFileObject}
2407\end{cfuncdesc}
2408
2409\begin{cfuncdesc}{PyObject *}{PyFile_FromString}{char *name, char *mode}
2410creates a new PyFileObject pointing to the file
2411specified in \code{name} with the mode specified in \code{mode}
2412\end{cfuncdesc}
2413
2414\begin{cfuncdesc}{PyObject *}{PyFile_FromFile}{FILE *fp,
2415 char *name, char *mode, int (*close})
2416creates a new PyFileObject from the already-open \code{fp}.
2417The function \code{close} will be called when the file should be closed.
2418\end{cfuncdesc}
2419
2420\begin{cfuncdesc}{FILE *}{PyFile_AsFile}{PyFileObject *p}
2421returns the file object associated with \code{p} as a \code{FILE *}
2422\end{cfuncdesc}
2423
2424\begin{cfuncdesc}{PyStringObject *}{PyFile_GetLine}{PyObject *p, int n}
2425undocumented as yet
2426\end{cfuncdesc}
2427
2428\begin{cfuncdesc}{PyStringObject *}{PyFile_Name}{PyObject *p}
2429returns the name of the file specified by \code{p} as a
2430PyStringObject
2431\end{cfuncdesc}
2432
2433\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2434on systems with \code{setvbuf} only
2435\end{cfuncdesc}
2436
2437\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyFileObject *p, int newflag}
2438same as the file object method \code{softspace}
2439\end{cfuncdesc}
2440
2441\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p}
2442writes object \code{obj} to file object \code{p}
2443\end{cfuncdesc}
2444
2445\begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p}
2446writes string \code{s} to file object \code{p}
2447\end{cfuncdesc}
2448
2449
Guido van Rossum9231c8f1997-05-15 21:43:21 +00002450\input{api.ind} % Index -- must be last
2451
2452\end{document}