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