3 \title{Python/C API Reference Manual
}
7 \makeindex % tell \index to actually write the .idx file
15 \chapter*
{Front Matter
\label{front
}}
23 This manual documents the API used by
\C{} (or
\Cpp{}) programmers who
24 want to write extension modules or embed Python. It is a companion to
25 \emph{Extending and Embedding the Python Interpreter
}, which describes
26 the general principles of extension writing but does not
document the
27 API functions in detail.
29 \strong{Warning:
} The current version of this
document is incomplete.
30 I hope that it is nevertheless useful. I will continue to work on it,
31 and release new versions from time to time, independent from Python
38 % XXX Consider moving all this back to ext.tex and giving api.tex
39 % XXX a *really* short intro only.
41 \chapter{Introduction
\label{intro
}}
43 The Application Programmer's Interface to Python gives
\C{} and
\Cpp{}
44 programmers access to the Python interpreter at a variety of levels.
45 The API is equally usable from
\Cpp{}, but for brevity it is generally
46 referred to as the Python/
\C{} API. There are two fundamentally
47 different reasons for using the Python/
\C{} API. The first reason is
48 to write
\emph{extension modules
} for specific purposes; these are
49 \C{} modules that extend the Python interpreter. This is probably the
50 most common use. The second reason is to use Python as a component in
51 a larger application; this technique is generally referred to as
52 \dfn{embedding
} Python in an application.
54 Writing an extension module is a relatively well-understood process,
55 where a ``cookbook'' approach works well. There are several tools
56 that automate the process to some extent. While people have embedded
57 Python in other applications since its early existence, the process of
58 embedding Python is less straightforward that writing an extension.
59 Python
1.5 introduces a number of new API functions as well as some
60 changes to the build process that make embedding much simpler.
61 This manual describes the
\version\ state of affairs.
62 % XXX Eventually, take the historical notes out
64 Many API functions are useful independent of whether you're embedding
65 or extending Python; moreover, most applications that embed Python
66 will need to provide a custom extension as well, so it's probably a
67 good idea to become familiar with writing an extension before
68 attempting to embed Python in a real application.
71 \section{Include Files
\label{includes
}}
73 All function, type and macro definitions needed to use the Python/C
74 API are included in your code by the following line:
80 This implies inclusion of the following standard headers:
81 \code{<stdio.h>
},
\code{<string.h>
},
\code{<errno.h>
}, and
82 \code{<stdlib.h>
} (if available).
84 All user visible names defined by Python.h (except those defined by
85 the included standard headers) have one of the prefixes
\samp{Py
} or
86 \samp{_Py
}. Names beginning with
\samp{_Py
} are for internal use
87 only. Structure member names do not have a reserved prefix.
89 \strong{Important:
} user code should never define names that begin
90 with
\samp{Py
} or
\samp{_Py
}. This confuses the reader, and
91 jeopardizes the portability of the user code to future Python
92 versions, which may define additional names beginning with one of
96 \section{Objects, Types and Reference Counts
\label{objects
}}
98 Most Python/C API functions have one or more arguments as well as a
99 return value of type
\ctype{PyObject *
}. This type is a pointer
100 to an opaque data type representing an arbitrary Python
101 object. Since all Python object types are treated the same way by the
102 Python language in most situations (e.g., assignments, scope rules,
103 and argument passing), it is only fitting that they should be
104 represented by a single
\C{} type. All Python objects live on the heap:
105 you never declare an automatic or static variable of type
106 \ctype{PyObject
}, only pointer variables of type
\ctype{PyObject *
} can
109 All Python objects (even Python integers) have a
\dfn{type
} and a
110 \dfn{reference count
}. An object's type determines what kind of object
111 it is (e.g., an integer, a list, or a user-defined function; there are
112 many more as explained in the
\emph{Python Reference Manual
}). For
113 each of the well-known types there is a macro to check whether an
114 object is of that type; for instance,
\samp{PyList_Check(
\var{a
})
} is
115 true iff the object pointed to by
\var{a
} is a Python list.
118 \subsection{Reference Counts
\label{refcounts
}}
120 The reference count is important because today's computers have a
121 finite (and often severely limited) memory size; it counts how many
122 different places there are that have a reference to an object. Such a
123 place could be another object, or a global (or static)
\C{} variable, or
124 a local variable in some
\C{} function. When an object's reference count
125 becomes zero, the object is deallocated. If it contains references to
126 other objects, their reference count is decremented. Those other
127 objects may be deallocated in turn, if this decrement makes their
128 reference count become zero, and so on. (There's an obvious problem
129 with objects that reference each other here; for now, the solution is
132 Reference counts are always manipulated explicitly. The normal way is
133 to use the macro
\cfunction{Py_INCREF()
} to increment an object's
134 reference count by one, and
\cfunction{Py_DECREF()
} to decrement it by
135 one. The decref macro is considerably more complex than the incref one,
136 since it must check whether the reference count becomes zero and then
137 cause the object's deallocator, which is a function pointer contained
138 in the object's type structure. The type-specific deallocator takes
139 care of decrementing the reference counts for other objects contained
140 in the object, and so on, if this is a compound object type such as a
141 list. There's no chance that the reference count can overflow; at
142 least as many bits are used to hold the reference count as there are
143 distinct memory locations in virtual memory (assuming
144 \code{sizeof(long) >= sizeof(char *)
}). Thus, the reference count
145 increment is a simple operation.
147 It is not necessary to increment an object's reference count for every
148 local variable that contains a pointer to an object. In theory, the
149 object's reference count goes up by one when the variable is made to
150 point to it and it goes down by one when the variable goes out of
151 scope. However, these two cancel each other out, so at the end the
152 reference count hasn't changed. The only real reason to use the
153 reference count is to prevent the object from being deallocated as
154 long as our variable is pointing to it. If we know that there is at
155 least one other reference to the object that lives at least as long as
156 our variable, there is no need to increment the reference count
157 temporarily. An important situation where this arises is in objects
158 that are passed as arguments to
\C{} functions in an extension module
159 that are called from Python; the call mechanism guarantees to hold a
160 reference to every argument for the duration of the call.
162 However, a common pitfall is to extract an object from a list and
163 hold on to it for a while without incrementing its reference count.
164 Some other operation might conceivably remove the object from the
165 list, decrementing its reference count and possible deallocating it.
166 The real danger is that innocent-looking operations may invoke
167 arbitrary Python code which could do this; there is a code path which
168 allows control to flow back to the user from a
\cfunction{Py_DECREF()
},
169 so almost any operation is potentially dangerous.
171 A safe approach is to always use the generic operations (functions
172 whose name begins with
\samp{PyObject_
},
\samp{PyNumber_
},
173 \samp{PySequence_
} or
\samp{PyMapping_
}). These operations always
174 increment the reference count of the object they return. This leaves
175 the caller with the responsibility to call
\cfunction{Py_DECREF()
}
176 when they are done with the result; this soon becomes second nature.
179 \subsubsection{Reference Count Details
\label{refcountDetails
}}
181 The reference count behavior of functions in the Python/C API is best
182 expelained in terms of
\emph{ownership of references
}. Note that we
183 talk of owning references, never of owning objects; objects are always
184 shared! When a function owns a reference, it has to dispose of it
185 properly --- either by passing ownership on (usually to its caller) or
186 by calling
\cfunction{Py_DECREF()
} or
\cfunction{Py_XDECREF()
}. When
187 a function passes ownership of a reference on to its caller, the
188 caller is said to receive a
\emph{new
} reference. When no ownership
189 is transferred, the caller is said to
\emph{borrow
} the reference.
190 Nothing needs to be done for a borrowed reference.
192 Conversely, when calling a function passes it a reference to an
193 object, there are two possibilities: the function
\emph{steals
} a
194 reference to the object, or it does not. Few functions steal
195 references; the two notable exceptions are
196 \cfunction{PyList_SetItem()
} and
\cfunction{PyTuple_SetItem()
}, which
197 steal a reference to the item (but not to the tuple or list into which
198 the item is put!). These functions were designed to steal a reference
199 because of a common idiom for populating a tuple or list with newly
200 created objects; for example, the code to create the tuple
\code{(
1,
201 2, "three")
} could look like this (forgetting about error handling for
202 the moment; a better way to code this is shown below anyway):
208 PyTuple_SetItem(t,
0, PyInt_FromLong(
1L));
209 PyTuple_SetItem(t,
1, PyInt_FromLong(
2L));
210 PyTuple_SetItem(t,
2, PyString_FromString("three"));
213 Incidentally,
\cfunction{PyTuple_SetItem()
} is the
\emph{only
} way to
214 set tuple items;
\cfunction{PySequence_SetItem()
} and
215 \cfunction{PyObject_SetItem()
} refuse to do this since tuples are an
216 immutable data type. You should only use
217 \cfunction{PyTuple_SetItem()
} for tuples that you are creating
220 Equivalent code for populating a list can be written using
221 \cfunction{PyList_New()
} and
\cfunction{PyList_SetItem()
}. Such code
222 can also use
\cfunction{PySequence_SetItem()
}; this illustrates the
223 difference between the two (the extra
\cfunction{Py_DECREF()
} calls):
229 x = PyInt_FromLong(
1L);
230 PySequence_SetItem(l,
0, x); Py_DECREF(x);
231 x = PyInt_FromLong(
2L);
232 PySequence_SetItem(l,
1, x); Py_DECREF(x);
233 x = PyString_FromString("three");
234 PySequence_SetItem(l,
2, x); Py_DECREF(x);
237 You might find it strange that the ``recommended'' approach takes more
238 code. However, in practice, you will rarely use these ways of
239 creating and populating a tuple or list. There's a generic function,
240 \cfunction{Py_BuildValue()
}, that can create most common objects from
241 \C{} values, directed by a
\dfn{format string
}. For example, the
242 above two blocks of code could be replaced by the following (which
243 also takes care of the error checking):
248 t = Py_BuildValue("(iis)",
1,
2, "three");
249 l = Py_BuildValue("
[iis
]",
1,
2, "three");
252 It is much more common to use
\cfunction{PyObject_SetItem()
} and
253 friends with items whose references you are only borrowing, like
254 arguments that were passed in to the function you are writing. In
255 that case, their behaviour regarding reference counts is much saner,
256 since you don't have to increment a reference count so you can give a
257 reference away (``have it be stolen''). For example, this function
258 sets all items of a list (actually, any mutable sequence) to a given
262 int set_all(PyObject *target, PyObject *item)
266 n = PyObject_Length(target);
269 for (i =
0; i < n; i++)
{
270 if (PyObject_SetItem(target, i, item) <
0)
277 The situation is slightly different for function return values.
278 While passing a reference to most functions does not change your
279 ownership responsibilities for that reference, many functions that
280 return a referece to an object give you ownership of the reference.
281 The reason is simple: in many cases, the returned object is created
282 on the fly, and the reference you get is the only reference to the
283 object. Therefore, the generic functions that return object
284 references, like
\cfunction{PyObject_GetItem()
} and
285 \cfunction{PySequence_GetItem()
}, always return a new reference (i.e.,
286 the caller becomes the owner of the reference).
288 It is important to realize that whether you own a reference returned
289 by a function depends on which function you call only ---
\emph{the
290 plumage
} (i.e., the type of the type of the object passed as an
291 argument to the function)
\emph{doesn't enter into it!
} Thus, if you
292 extract an item from a list using
\cfunction{PyList_GetItem()
}, you
293 don't own the reference --- but if you obtain the same item from the
294 same list using
\cfunction{PySequence_GetItem()
} (which happens to
295 take exactly the same arguments), you do own a reference to the
298 Here is an example of how you could write a function that computes the
299 sum of the items in a list of integers; once using
300 \cfunction{PyList_GetItem()
}, once using
301 \cfunction{PySequence_GetItem()
}.
304 long sum_list(PyObject *list)
310 n = PyList_Size(list);
312 return -
1; /* Not a list */
313 for (i =
0; i < n; i++)
{
314 item = PyList_GetItem(list, i); /* Can't fail */
315 if (!PyInt_Check(item)) continue; /* Skip non-integers */
316 total += PyInt_AsLong(item);
323 long sum_sequence(PyObject *sequence)
328 n = PyObject_Size(list);
330 return -
1; /* Has no length */
331 for (i =
0; i < n; i++)
{
332 item = PySequence_GetItem(list, i);
334 return -
1; /* Not a sequence, or other failure */
335 if (PyInt_Check(item))
336 total += PyInt_AsLong(item);
337 Py_DECREF(item); /* Discard reference ownership */
344 \subsection{Types
\label{types
}}
346 There are few other data types that play a significant role in
347 the Python/C API; most are simple
\C{} types such as
\ctype{int
},
348 \ctype{long
},
\ctype{double
} and
\ctype{char *
}. A few structure types
349 are used to describe static tables used to list the functions exported
350 by a module or the data attributes of a new object type. These will
351 be discussed together with the functions that use them.
354 \section{Exceptions
\label{exceptions
}}
356 The Python programmer only needs to deal with exceptions if specific
357 error handling is required; unhandled exceptions are automatically
358 propagated to the caller, then to the caller's caller, and so on, till
359 they reach the top-level interpreter, where they are reported to the
360 user accompanied by a stack traceback.
362 For
\C{} programmers, however, error checking always has to be explicit.
363 All functions in the Python/C API can raise exceptions, unless an
364 explicit claim is made otherwise in a function's documentation. In
365 general, when a function encounters an error, it sets an exception,
366 discards any object references that it owns, and returns an
367 error indicator --- usually
\NULL{} or
\code{-
1}. A few functions
368 return a Boolean true/false result, with false indicating an error.
369 Very few functions return no explicit error indicator or have an
370 ambiguous return value, and require explicit testing for errors with
371 \cfunction{PyErr_Occurred()
}.
373 Exception state is maintained in per-thread storage (this is
374 equivalent to using global storage in an unthreaded application). A
375 thread can be in one of two states: an exception has occurred, or not.
376 The function
\cfunction{PyErr_Occurred()
} can be used to check for
377 this: it returns a borrowed reference to the exception type object
378 when an exception has occurred, and
\NULL{} otherwise. There are a
379 number of functions to set the exception state:
380 \cfunction{PyErr_SetString()
} is the most common (though not the most
381 general) function to set the exception state, and
382 \cfunction{PyErr_Clear()
} clears the exception state.
384 The full exception state consists of three objects (all of which can
385 be
\NULL{}): the exception type, the corresponding exception
386 value, and the traceback. These have the same meanings as the Python
387 object
\code{sys.exc_type
},
\code{sys.exc_value
},
388 \code{sys.exc_traceback
}; however, they are not the same: the Python
389 objects represent the last exception being handled by a Python
390 \keyword{try
} \ldots\
\keyword{except
} statement, while the
\C{} level
391 exception state only exists while an exception is being passed on
392 between
\C{} functions until it reaches the Python interpreter, which
393 takes care of transferring it to
\code{sys.exc_type
} and friends.
395 Note that starting with Python
1.5, the preferred, thread-safe way to
396 access the exception state from Python code is to call the function
397 \function{sys.exc_info()
}, which returns the per-thread exception state
398 for Python code. Also, the semantics of both ways to access the
399 exception state have changed so that a function which catches an
400 exception will save and restore its thread's exception state so as to
401 preserve the exception state of its caller. This prevents common bugs
402 in exception handling code caused by an innocent-looking function
403 overwriting the exception being handled; it also reduces the often
404 unwanted lifetime extension for objects that are referenced by the
405 stack frames in the traceback.
407 As a general principle, a function that calls another function to
408 perform some task should check whether the called function raised an
409 exception, and if so, pass the exception state on to its caller. It
410 should discard any object references that it owns, and returns an
411 error indicator, but it should
\emph{not
} set another exception ---
412 that would overwrite the exception that was just raised, and lose
413 important information about the exact cause of the error.
415 A simple example of detecting exceptions and passing them on is shown
416 in the
\cfunction{sum_sequence()
} example above. It so happens that
417 that example doesn't need to clean up any owned references when it
418 detects an error. The following example function shows some error
419 cleanup. First, to remind you why you like Python, we show the
420 equivalent Python code:
423 def incr_item(dict, key):
431 Here is the corresponding
\C{} code, in all its glory:
434 int incr_item(PyObject *dict, PyObject *key)
436 /* Objects all initialized to NULL for Py_XDECREF */
437 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
438 int rv = -
1; /* Return value initialized to -
1 (failure) */
440 item = PyObject_GetItem(dict, key);
442 /* Handle KeyError only: */
443 if (!PyErr_ExceptionMatches(PyExc_KeyError)) goto error;
445 /* Clear the error and use zero: */
447 item = PyInt_FromLong(
0L);
448 if (item == NULL) goto error;
451 const_one = PyInt_FromLong(
1L);
452 if (const_one == NULL) goto error;
454 incremented_item = PyNumber_Add(item, const_one);
455 if (incremented_item == NULL) goto error;
457 if (PyObject_SetItem(dict, key, incremented_item) <
0) goto error;
458 rv =
0; /* Success */
459 /* Continue with cleanup code */
462 /* Cleanup code, shared by success and failure path */
464 /* Use Py_XDECREF() to ignore NULL references */
466 Py_XDECREF(const_one);
467 Py_XDECREF(incremented_item);
469 return rv; /* -
1 for error,
0 for success */
473 This example represents an endorsed use of the
\keyword{goto
} statement
474 in
\C{}! It illustrates the use of
475 \cfunction{PyErr_ExceptionMatches()
} and
\cfunction{PyErr_Clear()
} to
476 handle specific exceptions, and the use of
\cfunction{Py_XDECREF()
} to
477 dispose of owned references that may be
\NULL{} (note the
\samp{X
} in
478 the name;
\cfunction{Py_DECREF()
} would crash when confronted with a
479 \NULL{} reference). It is important that the variables used to hold
480 owned references are initialized to
\NULL{} for this to work;
481 likewise, the proposed return value is initialized to
\code{-
1}
482 (failure) and only set to success after the final call made is
486 \section{Embedding Python
\label{embedding
}}
488 The one important task that only embedders (as opposed to extension
489 writers) of the Python interpreter have to worry about is the
490 initialization, and possibly the finalization, of the Python
491 interpreter. Most functionality of the interpreter can only be used
492 after the interpreter has been initialized.
494 The basic initialization function is
\cfunction{Py_Initialize()
}.
495 This initializes the table of loaded modules, and creates the
496 fundamental modules
\module{__builtin__
}\refbimodindex{__builtin__
},
497 \module{__main__
}\refbimodindex{__main__
} and
498 \module{sys
}\refbimodindex{sys
}. It also initializes the module
499 search path (
\code{sys.path
}).
%
500 \indexiii{module
}{search
}{path
}
502 \cfunction{Py_Initialize()
} does not set the ``script argument list''
503 (
\code{sys.argv
}). If this variable is needed by Python code that
504 will be executed later, it must be set explicitly with a call to
505 \code{PySys_SetArgv(
\var{argc
},
\var{argv
})
} subsequent to the call
506 to
\cfunction{Py_Initialize()
}.
508 On most systems (in particular, on
\UNIX{} and Windows, although the
509 details are slightly different),
\cfunction{Py_Initialize()
}
510 calculates the module search path based upon its best guess for the
511 location of the standard Python interpreter executable, assuming that
512 the Python library is found in a fixed location relative to the Python
513 interpreter executable. In particular, it looks for a directory named
514 \file{lib/python1.5
} (replacing
\file{1.5} with the current
515 interpreter version) relative to the parent directory where the
516 executable named
\file{python
} is found on the shell command search
517 path (the environment variable
\envvar{PATH
}).
519 For instance, if the Python executable is found in
520 \file{/usr/local/bin/python
}, it will assume that the libraries are in
521 \file{/usr/local/lib/python1.5
}. (In fact, this particular path
522 is also the ``fallback'' location, used when no executable file named
523 \file{python
} is found along
\envvar{PATH
}.) The user can override
524 this behavior by setting the environment variable
\envvar{PYTHONHOME
},
525 or insert additional directories in front of the standard path by
526 setting
\envvar{PYTHONPATH
}.
528 The embedding application can steer the search by calling
529 \code{Py_SetProgramName(
\var{file
})
} \emph{before
} calling
530 \cfunction{Py_Initialize()
}. Note that
\envvar{PYTHONHOME
} still
531 overrides this and
\envvar{PYTHONPATH
} is still inserted in front of
532 the standard path. An application that requires total control has to
533 provide its own implementation of
\cfunction{Py_GetPath()
},
534 \cfunction{Py_GetPrefix()
},
\cfunction{Py_GetExecPrefix()
},
535 \cfunction{Py_GetProgramFullPath()
} (all defined in
536 \file{Modules/getpath.c
}).
538 Sometimes, it is desirable to ``uninitialize'' Python. For instance,
539 the application may want to start over (make another call to
540 \cfunction{Py_Initialize()
}) or the application is simply done with its
541 use of Python and wants to free all memory allocated by Python. This
542 can be accomplished by calling
\cfunction{Py_Finalize()
}. The function
543 \cfunction{Py_IsInitialized()
} returns true iff Python is currently in the
544 initialized state. More information about these functions is given in
548 \chapter{The Very High Level Layer
\label{veryhigh
}}
550 The functions in this chapter will let you execute Python source code
551 given in a file or a buffer, but they will not let you interact in a
552 more detailed way with the interpreter.
554 \begin{cfuncdesc
}{int
}{PyRun_AnyFile
}{FILE *fp, char *filename
}
557 \begin{cfuncdesc
}{int
}{PyRun_SimpleString
}{char *command
}
560 \begin{cfuncdesc
}{int
}{PyRun_SimpleFile
}{FILE *fp, char *filename
}
563 \begin{cfuncdesc
}{int
}{PyRun_InteractiveOne
}{FILE *fp, char *filename
}
566 \begin{cfuncdesc
}{int
}{PyRun_InteractiveLoop
}{FILE *fp, char *filename
}
569 \begin{cfuncdesc
}{struct _node*
}{PyParser_SimpleParseString
}{char *str,
573 \begin{cfuncdesc
}{struct _node*
}{PyParser_SimpleParseFile
}{FILE *fp,
574 char *filename, int start
}
577 \begin{cfuncdesc
}{PyObject*
}{PyRun_String
}{char *str, int start,
582 \begin{cfuncdesc
}{PyObject*
}{PyRun_File
}{FILE *fp, char *filename,
583 int start, PyObject *globals,
587 \begin{cfuncdesc
}{PyObject*
}{Py_CompileString
}{char *str, char *filename,
592 \chapter{Reference Counting
\label{countingRefs
}}
594 The macros in this section are used for managing reference counts
597 \begin{cfuncdesc
}{void
}{Py_INCREF
}{PyObject *o
}
598 Increment the reference count for object
\var{o
}. The object must
599 not be
\NULL{}; if you aren't sure that it isn't
\NULL{}, use
600 \cfunction{Py_XINCREF()
}.
603 \begin{cfuncdesc
}{void
}{Py_XINCREF
}{PyObject *o
}
604 Increment the reference count for object
\var{o
}. The object may be
605 \NULL{}, in which case the macro has no effect.
608 \begin{cfuncdesc
}{void
}{Py_DECREF
}{PyObject *o
}
609 Decrement the reference count for object
\var{o
}. The object must
610 not be
\NULL{}; if you aren't sure that it isn't
\NULL{}, use
611 \cfunction{Py_XDECREF()
}. If the reference count reaches zero, the
612 object's type's deallocation function (which must not be
\NULL{}) is
615 \strong{Warning:
} The deallocation function can cause arbitrary Python
616 code to be invoked (e.g. when a class instance with a
\method{__del__()
}
617 method is deallocated). While exceptions in such code are not
618 propagated, the executed code has free access to all Python global
619 variables. This means that any object that is reachable from a global
620 variable should be in a consistent state before
\cfunction{Py_DECREF()
} is
621 invoked. For example, code to delete an object from a list should
622 copy a reference to the deleted object in a temporary variable, update
623 the list data structure, and then call
\cfunction{Py_DECREF()
} for the
627 \begin{cfuncdesc
}{void
}{Py_XDECREF
}{PyObject *o
}
628 Decrement the reference count for object
\var{o
}. The object may be
629 \NULL{}, in which case the macro has no effect; otherwise the effect
630 is the same as for
\cfunction{Py_DECREF()
}, and the same warning
634 The following functions or macros are only for internal use:
635 \cfunction{_Py_Dealloc()
},
\cfunction{_Py_ForgetReference()
},
636 \cfunction{_Py_NewReference()
}, as well as the global variable
637 \cdata{_Py_RefTotal
}.
639 XXX Should mention Py_Malloc(), Py_Realloc(), Py_Free(),
640 PyMem_Malloc(), PyMem_Realloc(), PyMem_Free(), PyMem_NEW(),
641 PyMem_RESIZE(), PyMem_DEL(), PyMem_XDEL().
644 \chapter{Exception Handling
\label{exceptionHandling
}}
646 The functions in this chapter will let you handle and raise Python
647 exceptions. It is important to understand some of the basics of
648 Python exception handling. It works somewhat like the
\UNIX{}
649 \cdata{errno
} variable: there is a global indicator (per thread) of the
650 last error that occurred. Most functions don't clear this on success,
651 but will set it to indicate the cause of the error on failure. Most
652 functions also return an error indicator, usually
\NULL{} if they are
653 supposed to return a pointer, or
\code{-
1} if they return an integer
654 (exception: the
\cfunction{PyArg_Parse*()
} functions return
\code{1} for
655 success and
\code{0} for failure). When a function must fail because
656 some function it called failed, it generally doesn't set the error
657 indicator; the function it called already set it.
659 The error indicator consists of three Python objects corresponding to
660 the Python variables
\code{sys.exc_type
},
\code{sys.exc_value
} and
661 \code{sys.exc_traceback
}. API functions exist to interact with the
662 error indicator in various ways. There is a separate error indicator
665 % XXX Order of these should be more thoughtful.
666 % Either alphabetical or some kind of structure.
668 \begin{cfuncdesc
}{void
}{PyErr_Print
}{}
669 Print a standard traceback to
\code{sys.stderr
} and clear the error
670 indicator. Call this function only when the error indicator is set.
671 (Otherwise it will cause a fatal error!)
674 \begin{cfuncdesc
}{PyObject*
}{PyErr_Occurred
}{}
675 Test whether the error indicator is set. If set, return the exception
676 \emph{type
} (the first argument to the last call to one of the
677 \cfunction{PyErr_Set*()
} functions or to
\cfunction{PyErr_Restore()
}). If
678 not set, return
\NULL{}. You do not own a reference to the return
679 value, so you do not need to
\cfunction{Py_DECREF()
} it.
680 \strong{Note:
} do not compare the return value to a specific
681 exception; use
\cfunction{PyErr_ExceptionMatches()
} instead, shown
685 \begin{cfuncdesc
}{int
}{PyErr_ExceptionMatches
}{PyObject *exc
}
687 \samp{PyErr_GivenExceptionMatches(PyErr_Occurred(),
\var{exc
})
}.
688 This should only be called when an exception is actually set.
691 \begin{cfuncdesc
}{int
}{PyErr_GivenExceptionMatches
}{PyObject *given, PyObject *exc
}
692 Return true if the
\var{given
} exception matches the exception in
693 \var{exc
}. If
\var{exc
} is a class object, this also returns true
694 when
\var{given
} is a subclass. If
\var{exc
} is a tuple, all
695 exceptions in the tuple (and recursively in subtuples) are searched
696 for a match. This should only be called when an exception is actually
700 \begin{cfuncdesc
}{void
}{PyErr_NormalizeException
}{PyObject**exc, PyObject**val, PyObject**tb
}
701 Under certain circumstances, the values returned by
702 \cfunction{PyErr_Fetch()
} below can be ``unnormalized'', meaning that
703 \code{*
\var{exc
}} is a class object but
\code{*
\var{val
}} is not an
704 instance of the same class. This function can be used to instantiate
705 the class in that case. If the values are already normalized, nothing
709 \begin{cfuncdesc
}{void
}{PyErr_Clear
}{}
710 Clear the error indicator. If the error indicator is not set, there
714 \begin{cfuncdesc
}{void
}{PyErr_Fetch
}{PyObject **ptype, PyObject **pvalue, PyObject **ptraceback
}
715 Retrieve the error indicator into three variables whose addresses are
716 passed. If the error indicator is not set, set all three variables to
717 \NULL{}. If it is set, it will be cleared and you own a reference to
718 each object retrieved. The value and traceback object may be
\NULL{}
719 even when the type object is not.
\strong{Note:
} this function is
720 normally only used by code that needs to handle exceptions or by code
721 that needs to save and restore the error indicator temporarily.
724 \begin{cfuncdesc
}{void
}{PyErr_Restore
}{PyObject *type, PyObject *value, PyObject *traceback
}
725 Set the error indicator from the three objects. If the error
726 indicator is already set, it is cleared first. If the objects are
727 \NULL{}, the error indicator is cleared. Do not pass a
\NULL{} type
728 and non-
\NULL{} value or traceback. The exception type should be a
729 string or class; if it is a class, the value should be an instance of
730 that class. Do not pass an invalid exception type or value.
731 (Violating these rules will cause subtle problems later.) This call
732 takes away a reference to each object, i.e. you must own a reference
733 to each object before the call and after the call you no longer own
734 these references. (If you don't understand this, don't use this
735 function. I warned you.)
\strong{Note:
} this function is normally
736 only used by code that needs to save and restore the error indicator
740 \begin{cfuncdesc
}{void
}{PyErr_SetString
}{PyObject *type, char *message
}
741 This is the most common way to set the error indicator. The first
742 argument specifies the exception type; it is normally one of the
743 standard exceptions, e.g.
\cdata{PyExc_RuntimeError
}. You need not
744 increment its reference count. The second argument is an error
745 message; it is converted to a string object.
748 \begin{cfuncdesc
}{void
}{PyErr_SetObject
}{PyObject *type, PyObject *value
}
749 This function is similar to
\cfunction{PyErr_SetString()
} but lets you
750 specify an arbitrary Python object for the ``value'' of the exception.
751 You need not increment its reference count.
754 \begin{cfuncdesc
}{void
}{PyErr_SetNone
}{PyObject *type
}
755 This is a shorthand for
\samp{PyErr_SetObject(
\var{type
}, Py_None)
}.
758 \begin{cfuncdesc
}{int
}{PyErr_BadArgument
}{}
759 This is a shorthand for
\samp{PyErr_SetString(PyExc_TypeError,
760 \var{message
})
}, where
\var{message
} indicates that a built-in operation
761 was invoked with an illegal argument. It is mostly for internal use.
764 \begin{cfuncdesc
}{PyObject*
}{PyErr_NoMemory
}{}
765 This is a shorthand for
\samp{PyErr_SetNone(PyExc_MemoryError)
}; it
766 returns
\NULL{} so an object allocation function can write
767 \samp{return PyErr_NoMemory();
} when it runs out of memory.
770 \begin{cfuncdesc
}{PyObject*
}{PyErr_SetFromErrno
}{PyObject *type
}
771 This is a convenience function to raise an exception when a
\C{} library
772 function has returned an error and set the
\C{} variable
\cdata{errno
}.
773 It constructs a tuple object whose first item is the integer
774 \cdata{errno
} value and whose second item is the corresponding error
775 message (gotten from
\cfunction{strerror()
}), and then calls
776 \samp{PyErr_SetObject(
\var{type
},
\var{object
})
}. On
\UNIX{}, when
777 the
\cdata{errno
} value is
\constant{EINTR
}, indicating an interrupted
778 system call, this calls
\cfunction{PyErr_CheckSignals()
}, and if that set
779 the error indicator, leaves it set to that. The function always
780 returns
\NULL{}, so a wrapper function around a system call can write
781 \samp{return PyErr_SetFromErrno();
} when the system call returns an
785 \begin{cfuncdesc
}{void
}{PyErr_BadInternalCall
}{}
786 This is a shorthand for
\samp{PyErr_SetString(PyExc_TypeError,
787 \var{message
})
}, where
\var{message
} indicates that an internal
788 operation (e.g. a Python/C API function) was invoked with an illegal
789 argument. It is mostly for internal use.
792 \begin{cfuncdesc
}{int
}{PyErr_CheckSignals
}{}
793 This function interacts with Python's signal handling. It checks
794 whether a signal has been sent to the processes and if so, invokes the
795 corresponding signal handler. If the
796 \module{signal
}\refbimodindex{signal
} module is supported, this can
797 invoke a signal handler written in Python. In all cases, the default
798 effect for
\constant{SIGINT
} is to raise the
799 \exception{KeyboadInterrupt
} exception. If an exception is raised the
800 error indicator is set and the function returns
\code{1}; otherwise
801 the function returns
\code{0}. The error indicator may or may not be
802 cleared if it was previously set.
805 \begin{cfuncdesc
}{void
}{PyErr_SetInterrupt
}{}
806 This function is obsolete (XXX or platform dependent?). It simulates
807 the effect of a
\constant{SIGINT
} signal arriving --- the next time
808 \cfunction{PyErr_CheckSignals()
} is called,
809 \exception{KeyboadInterrupt
} will be raised.
812 \begin{cfuncdesc
}{PyObject*
}{PyErr_NewException
}{char *name,
815 This utility function creates and returns a new exception object. The
816 \var{name
} argument must be the name of the new exception, a
\C{} string
817 of the form
\code{module.class
}. The
\var{base
} and
\var{dict
}
818 arguments are normally
\NULL{}. Normally, this creates a class
819 object derived from the root for all exceptions, the built-in name
820 \exception{Exception
} (accessible in
\C{} as
\cdata{PyExc_Exception
}).
821 In this case the
\member{__module__
} attribute of the new class is set to the
822 first part (up to the last dot) of the
\var{name
} argument, and the
823 class name is set to the last part (after the last dot). When the
824 user has specified the
\code{-X
} command line option to use string
825 exceptions, for backward compatibility, or when the
\var{base
}
826 argument is not a class object (and not
\NULL{}), a string object
827 created from the entire
\var{name
} argument is returned. The
828 \var{base
} argument can be used to specify an alternate base class.
829 The
\var{dict
} argument can be used to specify a dictionary of class
830 variables and methods.
834 \section{Standard Exceptions
\label{standardExceptions
}}
836 All standard Python exceptions are available as global variables whose
837 names are
\samp{PyExc_
} followed by the Python exception name.
838 These have the type
\ctype{PyObject *
}; they are all either class
839 objects or string objects, depending on the use of the
\code{-X
}
840 option to the interpreter. For completeness, here are all the
842 \cdata{PyExc_Exception
},
843 \cdata{PyExc_StandardError
},
844 \cdata{PyExc_ArithmeticError
},
845 \cdata{PyExc_LookupError
},
846 \cdata{PyExc_AssertionError
},
847 \cdata{PyExc_AttributeError
},
848 \cdata{PyExc_EOFError
},
849 \cdata{PyExc_EnvironmentError
},
850 \cdata{PyExc_FloatingPointError
},
851 \cdata{PyExc_IOError
},
852 \cdata{PyExc_ImportError
},
853 \cdata{PyExc_IndexError
},
854 \cdata{PyExc_KeyError
},
855 \cdata{PyExc_KeyboardInterrupt
},
856 \cdata{PyExc_MemoryError
},
857 \cdata{PyExc_NameError
},
858 \cdata{PyExc_NotImplementedError
},
859 \cdata{PyExc_OSError
},
860 \cdata{PyExc_OverflowError
},
861 \cdata{PyExc_RuntimeError
},
862 \cdata{PyExc_SyntaxError
},
863 \cdata{PyExc_SystemError
},
864 \cdata{PyExc_SystemExit
},
865 \cdata{PyExc_TypeError
},
866 \cdata{PyExc_ValueError
},
867 \cdata{PyExc_ZeroDivisionError
}.
870 \chapter{Utilities
\label{utilities
}}
872 The functions in this chapter perform various utility tasks, such as
873 parsing function arguments and constructing Python values from
\C{}
876 \section{OS Utilities
\label{os
}}
878 \begin{cfuncdesc
}{int
}{Py_FdIsInteractive
}{FILE *fp, char *filename
}
879 Return true (nonzero) if the standard I/O file
\var{fp
} with name
880 \var{filename
} is deemed interactive. This is the case for files for
881 which
\samp{isatty(fileno(
\var{fp
}))
} is true. If the global flag
882 \cdata{Py_InteractiveFlag
} is true, this function also returns true if
883 the
\var{name
} pointer is
\NULL{} or if the name is equal to one of
884 the strings
\code{"<stdin>"
} or
\code{"???"
}.
887 \begin{cfuncdesc
}{long
}{PyOS_GetLastModificationTime
}{char *filename
}
888 Return the time of last modification of the file
\var{filename
}.
889 The result is encoded in the same way as the timestamp returned by
890 the standard
\C{} library function
\cfunction{time()
}.
894 \section{Process Control
\label{processControl
}}
896 \begin{cfuncdesc
}{void
}{Py_FatalError
}{char *message
}
897 Print a fatal error message and kill the process. No cleanup is
898 performed. This function should only be invoked when a condition is
899 detected that would make it dangerous to continue using the Python
900 interpreter; e.g., when the object administration appears to be
901 corrupted. On
\UNIX{}, the standard
\C{} library function
902 \cfunction{abort()
} is called which will attempt to produce a
906 \begin{cfuncdesc
}{void
}{Py_Exit
}{int status
}
907 Exit the current process. This calls
\cfunction{Py_Finalize()
} and
908 then calls the standard
\C{} library function
909 \code{exit(
\var{status
})
}.
912 \begin{cfuncdesc
}{int
}{Py_AtExit
}{void
(*func) ()}
913 Register a cleanup function to be called by \cfunction{Py_Finalize()}.
914 The cleanup function will be called with no arguments and should
915 return no value. At most 32 cleanup functions can be registered.
916 When the registration is successful, \cfunction{Py_AtExit()} returns
917 \code{0}; on failure, it returns \code{-1}. The cleanup function
918 registered last is called first. Each cleanup function will be called
919 at most once. Since Python's internal finallization will have
920 completed before the cleanup function, no Python APIs should be called
925 \section{Importing Modules \label{importing}}
927 \begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
928 This is a simplified interface to \cfunction{PyImport_ImportModuleEx()}
929 below, leaving the \var{globals} and \var{locals} arguments set to
930 \NULL{}. When the \var{name} argument contains a dot (i.e., when
931 it specifies a submodule of a package), the \var{fromlist} argument is
932 set to the list \code{['*']} so that the return value is the named
933 module rather than the top-level package containing it as would
934 otherwise be the case. (Unfortunately, this has an additional side
935 effect when \var{name} in fact specifies a subpackage instead of a
936 submodule: the submodules specified in the package's \code{__all__}
937 variable are loaded.) Return a new reference to the imported module,
938 or \NULL{} with an exception set on failure (the module may still
939 be created in this case --- examine \code{sys.modules} to find out).
942 \begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
943 Import a module. This is best described by referring to the built-in
944 Python function \function{__import__()}\bifuncindex{__import__}, as
945 the standard \function{__import__()} function calls this function
948 The return value is a new reference to the imported module or
949 top-level package, or \NULL{} with an exception set on failure
950 (the module may still be created in this case). Like for
951 \function{__import__()}, the return value when a submodule of a
952 package was requested is normally the top-level package, unless a
953 non-empty \var{fromlist} was given.
956 \begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
957 This is a higher-level interface that calls the current ``import hook
958 function''. It invokes the \function{__import__()} function from the
959 \code{__builtins__} of the current globals. This means that the
960 import is done using whatever import hooks are installed in the
961 current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
962 \module{ihooks}\refstmodindex{ihooks}.
965 \begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
966 Reload a module. This is best described by referring to the built-in
967 Python function \function{reload()}\bifuncindex{reload}, as the standard
968 \function{reload()} function calls this function directly. Return a
969 new reference to the reloaded module, or \NULL{} with an exception set
970 on failure (the module still exists in this case).
973 \begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
974 Return the module object corresponding to a module name. The
975 \var{name} argument may be of the form \code{package.module}). First
976 check the modules dictionary if there's one there, and if not, create
977 a new one and insert in in the modules dictionary. Because the former
978 action is most common, this does not return a new reference, and you
979 do not own the returned reference.
980 Warning: this function does not load or import the module; if the
981 module wasn't already loaded, you will get an empty module object.
982 Use \cfunction{PyImport_ImportModule()} or one of its variants to
984 Return \NULL{} with an
985 exception set on failure. \strong{Note:} this function returns
986 a ``borrowed'' reference.
989 \begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
990 Given a module name (possibly of the form \code{package.module}) and a
991 code object read from a Python bytecode file or obtained from the
992 built-in function \function{compile()}\bifuncindex{compile}, load the
993 module. Return a new reference to the module object, or \NULL{} with
994 an exception set if an error occurred (the module may still be created
995 in this case). (This function would reload the module if it was
999 \begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
1000 Return the magic number for Python bytecode files (a.k.a. \file{.pyc}
1001 and \file{.pyo} files). The magic number should be present in the
1002 first four bytes of the bytecode file, in little-endian byte order.
1005 \begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
1006 Return the dictionary used for the module administration
1007 (a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1011 \begin{cfuncdesc}{void}{_PyImport_Init}{}
1012 Initialize the import mechanism. For internal use only.
1015 \begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1016 Empty the module table. For internal use only.
1019 \begin{cfuncdesc}{void}{_PyImport_Fini}{}
1020 Finalize the import mechanism. For internal use only.
1023 \begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
1024 For internal use only.
1027 \begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
1028 For internal use only.
1031 \begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *}
1032 Load a frozen module. Return \code{1} for success, \code{0} if the
1033 module is not found, and \code{-1} with an exception set if the
1034 initialization failed. To access the imported module on a successful
1035 load, use \cfunction{PyImport_ImportModule()}.
1036 (Note the misnomer --- this function would reload the module if it was
1040 \begin{ctypedesc}{struct _frozen}
1041 This is the structure type definition for frozen module descriptors,
1042 as generated by the \program{freeze}\index{freeze utility} utility
1043 (see \file{Tools/freeze/} in the Python source distribution). Its
1049 unsigned char *code;
1055 \begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
1056 This pointer is initialized to point to an array of \ctype{struct
1057 _frozen} records, terminated by one whose members are all \NULL{}
1058 or zero. When a frozen module is imported, it is searched in this
1059 table. Third-party code could play tricks with this to provide a
1060 dynamically created collection of frozen modules.
1064 \chapter{Abstract Objects Layer \label{abstract}}
1066 The functions in this chapter interact with Python objects regardless
1067 of their type, or with wide classes of object types (e.g. all
1068 numerical types, or all sequence types). When used on object types
1069 for which they do not apply, they will flag a Python exception.
1071 \section{Object Protocol \label{object}}
1073 \begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
1074 Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error
1075 The flags argument is used to enable certain printing
1076 options. The only option currently supported is
1077 \constant{Py_PRINT_RAW}.
1080 \begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
1081 Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1082 \code{0} otherwise. This is equivalent to the Python expression
1083 \samp{hasattr(\var{o}, \var{attr_name})}.
1084 This function always succeeds.
1087 \begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o, char *attr_name}
1088 Retrieve an attribute named \var{attr_name} from object \var{o}.
1089 Returns the attribute value on success, or \NULL{} on failure.
1090 This is the equivalent of the Python expression
1091 \samp{\var{o}.\var{attr_name}}.
1095 \begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
1096 Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1097 \code{0} otherwise. This is equivalent to the Python expression
1098 \samp{hasattr(\var{o}, \var{attr_name})}.
1099 This function always succeeds.
1103 \begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o, PyObject *attr_name}
1104 Retrieve an attribute named \var{attr_name} from object \var{o}.
1105 Returns the attribute value on success, or \NULL{} on failure.
1106 This is the equivalent of the Python expression
1107 \samp{\var{o}.\var{attr_name}}.
1111 \begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
1112 Set the value of the attribute named \var{attr_name}, for object
1113 \var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1114 the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1119 \begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
1120 Set the value of the attribute named \var{attr_name}, for
1122 to the value \var{v}. Returns \code{-1} on failure. This is
1123 the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1128 \begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
1129 Delete attribute named \var{attr_name}, for object \var{o}. Returns
1130 \code{-1} on failure. This is the equivalent of the Python
1131 statement: \samp{del \var{o}.\var{attr_name}}.
1135 \begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
1136 Delete attribute named \var{attr_name}, for object \var{o}. Returns
1137 \code{-1} on failure. This is the equivalent of the Python
1138 statement \samp{del \var{o}.\var{attr_name}}.
1142 \begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
1143 Compare the values of \var{o1} and \var{o2} using a routine provided
1144 by \var{o1}, if one exists, otherwise with a routine provided by
1145 \var{o2}. The result of the comparison is returned in \var{result}.
1146 Returns \code{-1} on failure. This is the equivalent of the Python
1147 statement \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
1151 \begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
1152 Compare the values of \var{o1} and \var{o2} using a routine provided
1153 by \var{o1}, if one exists, otherwise with a routine provided by
1154 \var{o2}. Returns the result of the comparison on success. On error,
1155 the value returned is undefined; use \cfunction{PyErr_Occurred()} to
1156 detect an error. This is equivalent to the
1157 Python expression \samp{cmp(\var{o1}, \var{o2})}.
1161 \begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
1162 Compute the string representation of object, \var{o}. Returns the
1163 string representation on success, \NULL{} on failure. This is
1164 the equivalent of the Python expression \samp{repr(\var{o})}.
1165 Called by the \function{repr()}\bifuncindex{repr} built-in function
1166 and by reverse quotes.
1170 \begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
1171 Compute the string representation of object \var{o}. Returns the
1172 string representation on success, \NULL{} on failure. This is
1173 the equivalent of the Python expression \samp{str(\var{o})}.
1174 Called by the \function{str()}\bifuncindex{str} built-in function and
1175 by the \keyword{print} statement.
1179 \begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
1180 Determine if the object \var{o}, is callable. Return \code{1} if the
1181 object is callable and \code{0} otherwise.
1182 This function always succeeds.
1186 \begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object, PyObject *args}
1187 Call a callable Python object \var{callable_object}, with
1188 arguments given by the tuple \var{args}. If no arguments are
1189 needed, then args may be \NULL{}. Returns the result of the
1190 call on success, or \NULL{} on failure. This is the equivalent
1191 of the Python expression \samp{apply(\var{o}, \var{args})}.
1194 \begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
1195 Call a callable Python object \var{callable_object}, with a
1196 variable number of \C{} arguments. The \C{} arguments are described
1197 using a \cfunction{Py_BuildValue()} style format string. The format may
1198 be \NULL{}, indicating that no arguments are provided. Returns the
1199 result of the call on success, or \NULL{} on failure. This is
1200 the equivalent of the Python expression \samp{apply(\var{o},
1205 \begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
1206 Call the method named \var{m} of object \var{o} with a variable number
1207 of C arguments. The \C{} arguments are described by a
1208 \cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1209 indicating that no arguments are provided. Returns the result of the
1210 call on success, or \NULL{} on failure. This is the equivalent of the
1211 Python expression \samp{\var{o}.\var{method}(\var{args})}.
1212 Note that Special method names, such as \method{__add__()},
1213 \method{__getitem__()}, and so on are not supported. The specific
1214 abstract-object routines for these must be used.
1218 \begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
1219 Compute and return the hash value of an object \var{o}. On
1220 failure, return \code{-1}. This is the equivalent of the Python
1221 expression \samp{hash(\var{o})}.
1225 \begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
1226 Returns \code{1} if the object \var{o} is considered to be true, and
1227 \code{0} otherwise. This is equivalent to the Python expression
1228 \samp{not not \var{o}}.
1229 This function always succeeds.
1233 \begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1234 On success, returns a type object corresponding to the object
1235 type of object \var{o}. On failure, returns \NULL{}. This is
1236 equivalent to the Python expression \samp{type(\var{o})}.
1240 \begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
1241 Return the length of object \var{o}. If the object \var{o} provides
1242 both sequence and mapping protocols, the sequence length is
1243 returned. On error, \code{-1} is returned. This is the equivalent
1244 to the Python expression \samp{len(\var{o})}.
1248 \begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
1249 Return element of \var{o} corresponding to the object \var{key} or
1250 \NULL{} on failure. This is the equivalent of the Python expression
1251 \samp{\var{o}[\var{key}]}.
1255 \begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
1256 Map the object \var{key} to the value \var{v}.
1257 Returns \code{-1} on failure. This is the equivalent
1258 of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
1262 \begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
1263 Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1264 failure. This is the equivalent of the Python statement \samp{del
1265 \var{o}[\var{key}]}.
1269 \section{Number Protocol \label{number}}
1271 \begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
1272 Returns \code{1} if the object \var{o} provides numeric protocols, and
1274 This function always succeeds.
1278 \begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
1279 Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1280 failure. This is the equivalent of the Python expression
1281 \samp{\var{o1} + \var{o2}}.
1285 \begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
1286 Returns the result of subtracting \var{o2} from \var{o1}, or \NULL{}
1287 on failure. This is the equivalent of the Python expression
1288 \samp{\var{o1} - \var{o2}}.
1292 \begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
1293 Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1294 failure. This is the equivalent of the Python expression
1295 \samp{\var{o1} * \var{o2}}.
1299 \begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
1300 Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1302 This is the equivalent of the Python expression \samp{\var{o1} /
1307 \begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
1308 Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1309 failure. This is the equivalent of the Python expression
1310 \samp{\var{o1} \% \var{o2}}.
1314 \begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
1315 See the built-in function \function{divmod()}\bifuncindex{divmod}.
1316 Returns \NULL{} on failure. This is the equivalent of the Python
1317 expression \samp{divmod(\var{o1}, \var{o2})}.
1321 \begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
1322 See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1323 \NULL{} on failure. This is the equivalent of the Python expression
1324 \samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
1325 If \var{o3} is to be ignored, pass \cdata{Py_None} in its place.
1329 \begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
1330 Returns the negation of \var{o} on success, or \NULL{} on failure.
1331 This is the equivalent of the Python expression \samp{-\var{o}}.
1335 \begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
1336 Returns \var{o} on success, or \NULL{} on failure.
1337 This is the equivalent of the Python expression \samp{+\var{o}}.
1341 \begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
1342 Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1343 the equivalent of the Python expression \samp{abs(\var{o})}.
1347 \begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
1348 Returns the bitwise negation of \var{o} on success, or \NULL{} on
1349 failure. This is the equivalent of the Python expression
1354 \begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
1355 Returns the result of left shifting \var{o1} by \var{o2} on success,
1356 or \NULL{} on failure. This is the equivalent of the Python
1357 expression \samp{\var{o1} << \var{o2}}.
1361 \begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
1362 Returns the result of right shifting \var{o1} by \var{o2} on success,
1363 or \NULL{} on failure. This is the equivalent of the Python
1364 expression \samp{\var{o1} >> \var{o2}}.
1368 \begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
1369 Returns the result of ``anding'' \var{o2} and \var{o2} on success and
1370 \NULL{} on failure. This is the equivalent of the Python
1371 expression \samp{\var{o1} and \var{o2}}.
1375 \begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
1376 Returns the bitwise exclusive or of \var{o1} by \var{o2} on success,
1377 or \NULL{} on failure. This is the equivalent of the Python
1378 expression \samp{\var{o1} \^{ }\var{o2}}.
1381 \begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
1382 Returns the result of \var{o1} and \var{o2} on success, or \NULL{} on
1383 failure. This is the equivalent of the Python expression
1384 \samp{\var{o1} or \var{o2}}.
1388 \begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
1389 This function takes the addresses of two variables of type
1392 If the objects pointed to by \code{*\var{p1}} and \code{*\var{p2}}
1393 have the same type, increment their reference count and return
1394 \code{0} (success). If the objects can be converted to a common
1395 numeric type, replace \code{*p1} and \code{*p2} by their converted
1396 value (with 'new' reference counts), and return \code{0}.
1397 If no conversion is possible, or if some other error occurs,
1398 return \code{-1} (failure) and don't increment the reference counts.
1399 The call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the
1400 Python statement \samp{\var{o1}, \var{o2} = coerce(\var{o1},
1405 \begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
1406 Returns the \var{o} converted to an integer object on success, or
1407 \NULL{} on failure. This is the equivalent of the Python
1408 expression \samp{int(\var{o})}.
1412 \begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
1413 Returns the \var{o} converted to a long integer object on success,
1414 or \NULL{} on failure. This is the equivalent of the Python
1415 expression \samp{long(\var{o})}.
1419 \begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
1420 Returns the \var{o} converted to a float object on success, or \NULL{}
1421 on failure. This is the equivalent of the Python expression
1422 \samp{float(\var{o})}.
1426 \section{Sequence Protocol \label{sequence}}
1428 \begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
1429 Return \code{1} if the object provides sequence protocol, and \code{0}
1431 This function always succeeds.
1435 \begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
1436 Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
1437 failure. This is the equivalent of the Python
1438 expression \samp{\var{o1} + \var{o2}}.
1442 \begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
1443 Return the result of repeating sequence object \var{o} \var{count}
1444 times, or \NULL{} on failure. This is the equivalent of the Python
1445 expression \samp{\var{o} * \var{count}}.
1449 \begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
1450 Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
1451 is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
1455 \begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
1456 Return the slice of sequence object \var{o} between \var{i1} and
1457 \var{i2}, or \NULL{} on failure. This is the equivalent of the Python
1458 expression \samp{\var{o}[\var{i1}:\var{i2}]}.
1462 \begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
1463 Assign object \var{v} to the \var{i}th element of \var{o}.
1464 Returns \code{-1} on failure. This is the equivalent of the Python
1465 statement \samp{\var{o}[\var{i}] = \var{v}}.
1468 \begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
1469 Delete the \var{i}th element of object \var{v}. Returns
1470 \code{-1} on failure. This is the equivalent of the Python
1471 statement \samp{del \var{o}[\var{i}]}.
1474 \begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1, int i2, PyObject *v}
1475 Assign the sequence object \var{v} to the slice in sequence
1476 object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
1477 the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
1480 \begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
1481 Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
1482 Returns \code{-1} on failure. This is the equivalent of the Python
1483 statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
1486 \begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1487 Returns the \var{o} as a tuple on success, and \NULL{} on failure.
1488 This is equivalent to the Python expression \code{tuple(\var{o})}.
1491 \begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
1492 Return the number of occurrences of \var{value} in \var{o}, that is,
1493 return the number of keys for which \code{\var{o}[\var{key}] ==
1494 \var{value}}. On failure, return \code{-1}. This is equivalent to
1495 the Python expression \samp{\var{o}.count(\var{value})}.
1498 \begin{cfuncdesc}{int}{PySequence_In}{PyObject *o, PyObject *value}
1499 Determine if \var{o} contains \var{value}. If an item in \var{o} is
1500 equal to \var{value}, return \code{1}, otherwise return \code{0}. On
1501 error, return \code{-1}. This is equivalent to the Python expression
1502 \samp{\var{value} in \var{o}}.
1505 \begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
1506 Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
1507 \var{value}}. On error, return \code{-1}. This is equivalent to
1508 the Python expression \samp{\var{o}.index(\var{value})}.
1512 \section{Mapping Protocol \label{mapping}}
1514 \begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
1515 Return \code{1} if the object provides mapping protocol, and \code{0}
1517 This function always succeeds.
1521 \begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
1522 Returns the number of keys in object \var{o} on success, and \code{-1}
1523 on failure. For objects that do not provide sequence protocol,
1524 this is equivalent to the Python expression \samp{len(\var{o})}.
1528 \begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
1529 Remove the mapping for object \var{key} from the object \var{o}.
1530 Return \code{-1} on failure. This is equivalent to
1531 the Python statement \samp{del \var{o}[\var{key}]}.
1535 \begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
1536 Remove the mapping for object \var{key} from the object \var{o}.
1537 Return \code{-1} on failure. This is equivalent to
1538 the Python statement \samp{del \var{o}[\var{key}]}.
1542 \begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
1543 On success, return \code{1} if the mapping object has the key \var{key}
1544 and \code{0} otherwise. This is equivalent to the Python expression
1545 \samp{\var{o}.has_key(\var{key})}.
1546 This function always succeeds.
1550 \begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
1551 Return \code{1} if the mapping object has the key \var{key} and
1552 \code{0} otherwise. This is equivalent to the Python expression
1553 \samp{\var{o}.has_key(\var{key})}.
1554 This function always succeeds.
1558 \begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
1559 On success, return a list of the keys in object \var{o}. On
1560 failure, return \NULL{}. This is equivalent to the Python
1561 expression \samp{\var{o}.keys()}.
1565 \begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
1566 On success, return a list of the values in object \var{o}. On
1567 failure, return \NULL{}. This is equivalent to the Python
1568 expression \samp{\var{o}.values()}.
1572 \begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
1573 On success, return a list of the items in object \var{o}, where
1574 each item is a tuple containing a key-value pair. On
1575 failure, return \NULL{}. This is equivalent to the Python
1576 expression \samp{\var{o}.items()}.
1579 \begin{cfuncdesc}{int}{PyMapping_Clear}{PyObject *o}
1580 Make object \var{o} empty. Returns \code{1} on success and \code{0}
1581 on failure. This is equivalent to the Python statement
1582 \samp{for key in \var{o}.keys(): del \var{o}[key]}.
1586 \begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
1587 Return element of \var{o} corresponding to the object \var{key} or
1588 \NULL{} on failure. This is the equivalent of the Python expression
1589 \samp{\var{o}[\var{key}]}.
1592 \begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
1593 Map the object \var{key} to the value \var{v} in object \var{o}.
1594 Returns \code{-1} on failure. This is the equivalent of the Python
1595 statement \samp{\var{o}[\var{key}] = \var{v}}.
1599 \section{Constructors}
1601 \begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *file_name, char *mode}
1602 On success, returns a new file object that is opened on the
1603 file given by \var{file_name}, with a file mode given by \var{mode},
1604 where \var{mode} has the same semantics as the standard \C{} routine
1605 \cfunction{fopen()}. On failure, return \code{-1}.
1608 \begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp, char *file_name, char *mode, int close_on_del}
1609 Return a new file object for an already opened standard \C{} file
1610 pointer, \var{fp}. A file name, \var{file_name}, and open mode,
1611 \var{mode}, must be provided as well as a flag, \var{close_on_del},
1612 that indicates whether the file is to be closed when the file object
1613 is destroyed. On failure, return \code{-1}.
1616 \begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
1617 Returns a new float object with the value \var{v} on success, and
1621 \begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long v}
1622 Returns a new int object with the value \var{v} on success, and
1626 \begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
1627 Returns a new list of length \var{len} on success, and \NULL{} on
1631 \begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
1632 Returns a new long object with the value \var{v} on success, and
1636 \begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
1637 Returns a new long object with the value \var{v} on success, and
1641 \begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1642 Returns a new empty dictionary on success, and \NULL{} on
1646 \begin{cfuncdesc}{PyObject*}{PyString_FromString}{char *v}
1647 Returns a new string object with the value \var{v} on success, and
1651 \begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{char *v, int len}
1652 Returns a new string object with the value \var{v} and length
1653 \var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
1654 the contents of the string are uninitialized.
1657 \begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
1658 Returns a new tuple of length \var{len} on success, and \NULL{} on
1663 \chapter{Concrete Objects Layer \label{concrete}}
1665 The functions in this chapter are specific to certain Python object
1666 types. Passing them an object of the wrong type is not a good idea;
1667 if you receive an object from a Python program and you are not sure
1668 that it has the right type, you must perform a type check first;
1669 e.g. to check that an object is a dictionary, use
1670 \cfunction{PyDict_Check()}. The chapter is structured like the
1671 ``family tree'' of Python object types.
1674 \section{Fundamental Objects \label{fundamental}}
1676 This section describes Python type objects and the singleton object
1680 \subsection{Type Objects \label{typeObjects}}
1682 \begin{ctypedesc}{PyTypeObject}
1686 \begin{cvardesc}{PyObject *}{PyType_Type}
1687 This is the type object for type objects; it is the same object as
1688 \code{types.TypeType} in the Python layer.
1692 \subsection{The None Object \label{noneObject}}
1694 \begin{cvardesc}{PyObject *}{Py_None}
1695 The Python \code{None} object, denoting lack of value. This object has
1700 \section{Sequence Objects \label{sequenceObjects}}
1702 Generic operations on sequence objects were discussed in the previous
1703 chapter; this section deals with the specific kinds of sequence
1704 objects that are intrinsic to the Python language.
1707 \subsection{String Objects \label{stringObjects}}
1709 \begin{ctypedesc}{PyStringObject}
1710 This subtype of \ctype{PyObject} represents a Python string object.
1713 \begin{cvardesc}{PyTypeObject}{PyString_Type}
1714 This instance of \ctype{PyTypeObject} represents the Python string type.
1717 \begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
1718 Returns true if the object \var{o} is a string object.
1721 \begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
1723 Returns a new string object with the value \var{v} and length
1724 \var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
1725 the contents of the string are uninitialized.
1728 \begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
1729 Returns a new string object with the value \var{v} on success, and
1733 \begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
1734 Returns the length of the string in string object \var{string}.
1737 \begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
1738 Resturns a \NULL{} terminated representation of the contents of \var{string}.
1741 \begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
1743 Creates a new string object in \var{*string} containing the
1744 contents of \var{newpart} appended to \var{string}. The old value of
1745 \var{string} have its reference count decremented. If the new string
1746 cannot be created, the old reference to \var{string} will still be
1747 discarded and the value of \var{*string} will be set to
1748 \NULL{}; the appropriate exception will be set.
1751 \begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
1753 Creates a new string object in \var{*string} containing the contents
1754 of \var{newpart} appended to \var{string}. This version decrements
1755 the reference count of \var{newpart}.
1758 \begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
1759 A way to resize a string object even though it is ``immutable''.
1760 Only use this to build up a brand new string object; don't use this if
1761 the string may already be known in other parts of the code.
1764 \begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
1766 Returns a new string object from \var{format} and \var{args}. Analogous
1767 to \code{\var{format} \% \var{args}}. The \var{args} argument must be
1771 \begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
1772 Intern the argument \var{*string} in place. The argument must be the
1773 address of a pointer variable pointing to a Python string object.
1774 If there is an existing interned string that is the same as
1775 \var{*string}, it sets \var{*string} to it (decrementing the reference
1776 count of the old string object and incrementing the reference count of
1777 the interned string object), otherwise it leaves \var{*string} alone
1778 and interns it (incrementing its reference count). (Clarification:
1779 even though there is a lot of talk about reference counts, think of
1780 this function as reference-count-neutral; you own the object after
1781 the call if and only if you owned it before the call.)
1784 \begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
1785 A combination of \cfunction{PyString_FromString()} and
1786 \cfunction{PyString_InternInPlace()}, returning either a new string object
1787 that has been interned, or a new (``owned'') reference to an earlier
1788 interned string object with the same value.
1791 \begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
1792 Macro form of \cfunction{PyString_AsString()} but without error checking.
1795 \begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
1796 Macro form of \cfunction{PyString_GetSize()} but without error checking.
1801 \subsection{Tuple Objects \label{tupleObjects}}
1803 \begin{ctypedesc}{PyTupleObject}
1804 This subtype of \ctype{PyObject} represents a Python tuple object.
1807 \begin{cvardesc}{PyTypeObject}{PyTuple_Type}
1808 This instance of \ctype{PyTypeObject} represents the Python tuple type.
1811 \begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
1812 Return true if the argument is a tuple object.
1815 \begin{cfuncdesc}{PyObject*}{PyTuple_New}{int s}
1816 Return a new tuple object of size \var{s}.
1819 \begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
1820 Takes a pointer to a tuple object, and returns the size
1824 \begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyTupleObject *p, int pos}
1825 Returns the object at position \var{pos} in the tuple pointed
1826 to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
1827 sets an \exception{IndexError} exception. \strong{Note:} this
1828 function returns a ``borrowed'' reference.
1831 \begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
1832 Does the same, but does no checking of its arguments.
1835 \begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyTupleObject *p,
1838 Takes a slice of the tuple pointed to by \var{p} from
1839 \var{low} to \var{high} and returns it as a new tuple.
1842 \begin{cfuncdesc}{int}{PyTuple_SetItem}{PyTupleObject *p,
1845 Inserts a reference to object \var{o} at position \var{pos} of
1846 the tuple pointed to by \var{p}. It returns \code{0} on success.
1849 \begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyTupleObject *p,
1853 Does the same, but does no error checking, and
1854 should \emph{only} be used to fill in brand new tuples.
1857 \begin{cfuncdesc}{int}{_PyTuple_Resize}{PyTupleObject *p,
1860 Can be used to resize a tuple. Because tuples are
1861 \emph{supposed} to be immutable, this should only be used if there is only
1862 one module referencing the object. Do \emph{not} use this if the tuple may
1863 already be known to some other part of the code. \var{last_is_sticky} is
1864 a flag --- if set, the tuple will grow or shrink at the front, otherwise
1865 it will grow or shrink at the end. Think of this as destroying the old
1866 tuple and creating a new one, only more efficiently.
1870 \subsection{List Objects \label{listObjects}}
1872 \begin{ctypedesc}{PyListObject}
1873 This subtype of \ctype{PyObject} represents a Python list object.
1876 \begin{cvardesc}{PyTypeObject}{PyList_Type}
1877 This instance of \ctype{PyTypeObject} represents the Python list type.
1880 \begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
1881 Returns true if its argument is a \ctype{PyListObject}.
1884 \begin{cfuncdesc}{PyObject*}{PyList_New}{int size}
1885 Returns a new list of length \var{len} on success, and \NULL{} on
1889 \begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
1890 Returns the length of the list object in \var{list}.
1893 \begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
1894 Returns the object at position \var{pos} in the list pointed
1895 to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
1896 sets an \exception{IndexError} exception. \strong{Note:} this
1897 function returns a ``borrowed'' reference.
1900 \begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
1902 Sets the item at index \var{index} in list to \var{item}.
1905 \begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
1907 Inserts the item \var{item} into list \var{list} in front of index
1908 \var{index}. Returns 0 if successful; returns -1 and sets an
1909 exception if unsuccessful. Analogous to \code{list.insert(index, item)}.
1912 \begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
1913 Appends the object \var{item} at the end of list \var{list}. Returns
1914 0 if successful; returns -1 and sets an exception if unsuccessful.
1915 Analogous to \code{list.append(item)}.
1918 \begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
1920 Returns a list of the objects in \var{list} containing the objects
1921 \emph{between} \var{low} and \var{high}. Returns NULL and sets an
1922 exception if unsuccessful.
1923 Analogous to \code{list[low:high]}.
1926 \begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
1929 Sets the slice of \var{list} between \var{low} and \var{high} to the contents
1930 of \var{itemlist}. Analogous to \code{list[low:high]=itemlist}. Returns 0
1931 on success, -1 on failure.
1934 \begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
1935 Sorts the items of \var{list} in place. Returns 0 on success, -1 on failure.
1938 \begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
1939 Reverses the items of \var{list} in place. Returns 0 on success, -1 on failure.
1942 \begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
1943 Returns a new tuple object containing the contents of \var{list}.
1946 \begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
1947 Macro form of \cfunction{PyList_GetItem()} without error checking.
1950 \begin{cfuncdesc}{PyObject*}{PyList_SET_ITEM}{PyObject *list, int i,
1952 Macro form of \cfunction{PyList_SetItem()} without error checking.
1955 \begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
1956 Macro form of \cfunction{PyList_GetSize()} without error checking.
1960 \section{Mapping Objects \label{mapObjects}}
1962 \subsection{Dictionary Objects \label{dictObjects}}
1964 \begin{ctypedesc}{PyDictObject}
1965 This subtype of \ctype{PyObject} represents a Python dictionary object.
1968 \begin{cvardesc}{PyTypeObject}{PyDict_Type}
1969 This instance of \ctype{PyTypeObject} represents the Python dictionary type.
1972 \begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
1973 Returns true if its argument is a \ctype{PyDictObject}.
1976 \begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1977 Returns a new empty dictionary.
1980 \begin{cfuncdesc}{void}{PyDict_Clear}{PyDictObject *p}
1981 Empties an existing dictionary of all key/value pairs.
1984 \begin{cfuncdesc}{int}{PyDict_SetItem}{PyDictObject *p,
1987 Inserts \var{value} into the dictionary with a key of \var{key}. Both
1988 \var{key} and \var{value} should be PyObjects, and \var{key} should be
1992 \begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
1995 Inserts \var{value} into the dictionary using \var{key}
1996 as a key. \var{key} should be a \ctype{char *}. The key object is
1997 created using \code{PyString_FromString(\var{key})}.
2000 \begin{cfuncdesc}{int}{PyDict_DelItem}{PyDictObject *p, PyObject *key}
2001 Removes the entry in dictionary \var{p} with key \var{key}.
2002 \var{key} is a PyObject.
2005 \begin{cfuncdesc}{int}{PyDict_DelItemString}{PyDictObject *p, char *key}
2006 Removes the entry in dictionary \var{p} which has a key
2007 specified by the \ctype{char *}\var{key}.
2010 \begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyDictObject *p, PyObject *key}
2011 Returns the object from dictionary \var{p} which has a key
2012 \var{key}. Returns \NULL{} if the key \var{key} is not present, but
2013 without (!) setting an exception. \strong{Note:} this function
2014 returns a ``borrowed'' reference.
2017 \begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyDictObject *p, char *key}
2018 This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
2019 specified as a \ctype{char *}, rather than a \ctype{PyObject *}.
2022 \begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyDictObject *p}
2023 Returns a \ctype{PyListObject} containing all the items
2024 from the dictionary, as in the dictinoary method \method{items()} (see
2025 the \emph{Python Library Reference}).
2028 \begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyDictObject *p}
2029 Returns a \ctype{PyListObject} containing all the keys
2030 from the dictionary, as in the dictionary method \method{keys()} (see the
2031 \emph{Python Library Reference}).
2034 \begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyDictObject *p}
2035 Returns a \ctype{PyListObject} containing all the values
2036 from the dictionary \var{p}, as in the dictionary method
2037 \method{values()} (see the \emph{Python Library Reference}).
2040 \begin{cfuncdesc}{int}{PyDict_Size}{PyDictObject *p}
2041 Returns the number of items in the dictionary.
2044 \begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p,
2052 \section{Numeric Objects \label{numericObjects}}
2054 \subsection{Plain Integer Objects \label{intObjects}}
2056 \begin{ctypedesc}{PyIntObject}
2057 This subtype of \ctype{PyObject} represents a Python integer object.
2060 \begin{cvardesc}{PyTypeObject}{PyInt_Type}
2061 This instance of \ctype{PyTypeObject} represents the Python plain
2065 \begin{cfuncdesc}{int}{PyInt_Check}{PyObject *}
2069 \begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
2070 Creates a new integer object with a value of \var{ival}.
2072 The current implementation keeps an array of integer objects for all
2073 integers between \code{-1} and \code{100}, when you create an int in
2074 that range you actually just get back a reference to the existing
2075 object. So it should be possible to change the value of \code{1}. I
2076 suspect the behaviour of Python in this case is undefined. :-)
2079 \begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyIntObject *io}
2080 Returns the value of the object \var{io}. No error checking is
2084 \begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
2085 Will first attempt to cast the object to a \ctype{PyIntObject}, if
2086 it is not already one, and then return its value.
2089 \begin{cfuncdesc}{long}{PyInt_GetMax}{}
2090 Returns the systems idea of the largest integer it can handle
2091 (\constant{LONG_MAX}, as defined in the system header files).
2095 \subsection{Long Integer Objects \label{longObjects}}
2097 \begin{ctypedesc}{PyLongObject}
2098 This subtype of \ctype{PyObject} represents a Python long integer
2102 \begin{cvardesc}{PyTypeObject}{PyLong_Type}
2103 This instance of \ctype{PyTypeObject} represents the Python long
2107 \begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
2108 Returns true if its argument is a \ctype{PyLongObject}.
2111 \begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
2112 Returns a new \ctype{PyLongObject} object from \var{v}.
2115 \begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
2116 Returns a new \ctype{PyLongObject} object from an unsigned \C{} long.
2119 \begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
2120 Returns a new \ctype{PyLongObject} object from the integer part of \var{v}.
2123 \begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
2124 Returns a \C{} \ctype{long} representation of the contents of \var{pylong}.
2125 WHAT HAPPENS IF \var{pylong} is greater than \constant{LONG_MAX}?
2128 \begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
2129 Returns a \C{} \ctype{unsigned long} representation of the contents of
2130 \var{pylong}. WHAT HAPPENS IF \var{pylong} is greater than
2131 \constant{ULONG_MAX}?
2134 \begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
2135 Returns a \C{} \ctype{double} representation of the contents of \var{pylong}.
2138 \begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
2143 \subsection{Floating Point Objects \label{floatObjects}}
2145 \begin{ctypedesc}{PyFloatObject}
2146 This subtype of \ctype{PyObject} represents a Python floating point
2150 \begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2151 This instance of \ctype{PyTypeObject} represents the Python floating
2155 \begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2156 Returns true if its argument is a \ctype{PyFloatObject}.
2159 \begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
2160 Creates a \ctype{PyFloatObject} object from \var{v}.
2163 \begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
2164 Returns a \C{} \ctype{double} representation of the contents of \var{pyfloat}.
2167 \begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
2168 Returns a \C{} \ctype{double} representation of the contents of
2169 \var{pyfloat}, but without error checking.
2173 \subsection{Complex Number Objects \label{complexObjects}}
2175 \begin{ctypedesc}{Py_complex}
2176 The \C{} structure which corresponds to the value portion of a Python
2177 complex number object. Most of the functions for dealing with complex
2178 number objects use structures of this type as input or output values,
2179 as appropriate. It is defined as:
2189 \begin{ctypedesc}{PyComplexObject}
2190 This subtype of \ctype{PyObject} represents a Python complex number object.
2193 \begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2194 This instance of \ctype{PyTypeObject} represents the Python complex
2198 \begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2199 Returns true if its argument is a \ctype{PyComplexObject}.
2202 \begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
2205 \begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
2208 \begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
2211 \begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
2214 \begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
2218 \begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
2221 \begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
2224 \begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
2225 Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}.
2228 \begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2229 Returns the real part of \var{op} as a \C{} \ctype{double}.
2232 \begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2233 Returns the imaginary part of \var{op} as a \C{} \ctype{double}.
2236 \begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2241 \section{Other Objects \label{otherObjects}}
2243 \subsection{File Objects \label{fileObjects}}
2245 \begin{ctypedesc}{PyFileObject}
2246 This subtype of \ctype{PyObject} represents a Python file object.
2249 \begin{cvardesc}{PyTypeObject}{PyFile_Type}
2250 This instance of \ctype{PyTypeObject} represents the Python file type.
2253 \begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2254 Returns true if its argument is a \ctype{PyFileObject}.
2257 \begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *name, char *mode}
2258 Creates a new \ctype{PyFileObject} pointing to the file
2259 specified in \var{name} with the mode specified in \var{mode}.
2262 \begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
2263 char *name, char *mode, int (*close)}
2264 Creates a new \ctype{PyFileObject} from the already-open \var{fp}.
2265 The function \var{close} will be called when the file should be
2269 \begin{cfuncdesc}{FILE *}{PyFile_AsFile}{PyFileObject *p}
2270 Returns the file object associated with \var{p} as a \ctype{FILE *}.
2273 \begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
2277 \begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
2278 Returns the name of the file specified by \var{p} as a
2279 \ctype{PyStringObject}.
2282 \begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2283 Available on systems with \cfunction{setvbuf()} only. This should
2284 only be called immediately after file object creation.
2287 \begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyFileObject *p, int newflag}
2288 Sets the \member{softspace} attribute of \var{p} to \var{newflag}.
2289 Returns the previous value. This function clears any errors, and will
2290 return \code{0} as the previous value if the attribute either does not
2291 exist or if there were errors in retrieving it. There is no way to
2292 detect errors from this function, but doing so should not be needed.
2295 \begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
2297 Writes object \var{obj} to file object \var{p}.
2300 \begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p,
2302 Writes string \var{s} to file object \var{p}.
2306 \subsection{Module Objects \label{moduleObjects}}
2309 There are only a few functions special to module objects.
2311 \begin{cfuncdesc}{PyObject *}{PyModule_New}{char *name}
2312 Return a new module object with the \member{__name__} attribute set to
2313 \var{name}. Only the module's \member{__doc__} and \member{__name__}
2314 attributes are filled in; the caller is responsible for providing a
2315 \member{__file__} attribute.
2318 \begin{cfuncdesc}{PyObject *}{PyModule_GetDict}{PyObject *module}
2319 Return the dictionary object that implements \var{module}'s namespace;
2320 this object is the same as the \member{__dict__} attribute of the
2321 module object. This function never fails.
2324 \begin{cfuncdesc}{char *}{PyModule_GetName}{PyObject *module}
2325 Return \var{module}'s \member{__name__} value. If the module does not
2326 provide one, \exception{SystemError} is raised.
2329 \begin{cfuncdesc}{char *}{PyModule_GetFilename}{PyObject *module}
2330 Return the name of the file from which \var{module} was loaded using
2331 \var{module}'s \member{__file__} attribute. If this is not defined,
2332 raise \exception{SystemError}.
2336 \subsection{CObjects \label{cObjects}}
2338 \begin{ctypedesc}{PyCObject}
2339 This subtype of \ctype{PyObject} represents an opaque value, useful for
2340 \C{} extension modules who need to pass an opaque value (as a
2341 \ctype{void *} pointer) through Python code to other \C{} code. It is
2342 often used to make a C function pointer defined in one module
2343 available to other modules, so the regular import mechanism can be
2344 used to access C APIs defined in dynamically loaded modules.
2347 \begin{cfuncdesc}{PyObject *}{PyCObject_FromVoidPtr}{void* cobj,
2348 void (*destr)(void *)}
2349 Creates a
\ctype{PyCObject
} from the
\code{void *
} \var{cobj
}. The
2350 \var{destr
} function will be called when the object is reclaimed.
2353 \begin{cfuncdesc
}{PyObject *
}{PyCObject_FromVoidPtrAndDesc
}{void* cobj,
2354 void* desc, void
(*destr)(void *, void *) }
2355 Creates a
\ctype{PyCObject
} from the
\ctype{void *
}\var{cobj
}. The
2356 \var{destr
} function will be called when the object is reclaimed. The
2357 \var{desc
} argument can be used to pass extra callback data for the
2358 destructor function.
2361 \begin{cfuncdesc
}{void *
}{PyCObject_AsVoidPtr
}{PyObject* self
}
2362 Returns the object
\ctype{void *
} that the
\ctype{PyCObject
} \var{self
}
2366 \begin{cfuncdesc
}{void *
}{PyCObject_GetDesc
}{PyObject* self
}
2367 Returns the description
\ctype{void *
} that the
\ctype{PyCObject
}
2368 \var{self
} was created with.
2371 \chapter{Initialization, Finalization, and Threads
2372 \label{initialization
}}
2374 \begin{cfuncdesc
}{void
}{Py_Initialize
}{}
2375 Initialize the Python interpreter. In an application embedding
2376 Python, this should be called before using any other Python/C API
2377 functions; with the exception of
\cfunction{Py_SetProgramName()
},
2378 \cfunction{PyEval_InitThreads()
},
\cfunction{PyEval_ReleaseLock()
},
2379 and
\cfunction{PyEval_AcquireLock()
}. This initializes the table of
2380 loaded modules (
\code{sys.modules
}), and creates the fundamental
2381 modules
\module{__builtin__
}\refbimodindex{__builtin__
},
2382 \module{__main__
}\refbimodindex{__main__
} and
2383 \module{sys
}\refbimodindex{sys
}. It also initializes the module
2384 search path (
\code{sys.path
}).
%
2385 \indexiii{module
}{search
}{path
}
2386 It does not set
\code{sys.argv
}; use
\cfunction{PySys_SetArgv()
} for
2387 that. This is a no-op when called for a second time (without calling
2388 \cfunction{Py_Finalize()
} first). There is no return value; it is a
2389 fatal error if the initialization fails.
2392 \begin{cfuncdesc
}{int
}{Py_IsInitialized
}{}
2393 Return true (nonzero) when the Python interpreter has been
2394 initialized, false (zero) if not. After
\cfunction{Py_Finalize()
} is
2395 called, this returns false until
\cfunction{Py_Initialize()
} is called
2399 \begin{cfuncdesc
}{void
}{Py_Finalize
}{}
2400 Undo all initializations made by
\cfunction{Py_Initialize()
} and
2401 subsequent use of Python/C API functions, and destroy all
2402 sub-interpreters (see
\cfunction{Py_NewInterpreter()
} below) that were
2403 created and not yet destroyed since the last call to
2404 \cfunction{Py_Initialize()
}. Ideally, this frees all memory allocated
2405 by the Python interpreter. This is a no-op when called for a second
2406 time (without calling
\cfunction{Py_Initialize()
} again first). There
2407 is no return value; errors during finalization are ignored.
2409 This function is provided for a number of reasons. An embedding
2410 application might want to restart Python without having to restart the
2411 application itself. An application that has loaded the Python
2412 interpreter from a dynamically loadable library (or DLL) might want to
2413 free all memory allocated by Python before unloading the DLL. During a
2414 hunt for memory leaks in an application a developer might want to free
2415 all memory allocated by Python before exiting from the application.
2417 \strong{Bugs and caveats:
} The destruction of modules and objects in
2418 modules is done in random order; this may cause destructors
2419 (
\method{__del__()
} methods) to fail when they depend on other objects
2420 (even functions) or modules. Dynamically loaded extension modules
2421 loaded by Python are not unloaded. Small amounts of memory allocated
2422 by the Python interpreter may not be freed (if you find a leak, please
2423 report it). Memory tied up in circular references between objects is
2424 not freed. Some memory allocated by extension modules may not be
2425 freed. Some extension may not work properly if their initialization
2426 routine is called more than once; this can happen if an applcation
2427 calls
\cfunction{Py_Initialize()
} and
\cfunction{Py_Finalize()
} more
2431 \begin{cfuncdesc
}{PyThreadState*
}{Py_NewInterpreter
}{}
2432 Create a new sub-interpreter. This is an (almost) totally separate
2433 environment for the execution of Python code. In particular, the new
2434 interpreter has separate, independent versions of all imported
2435 modules, including the fundamental modules
2436 \module{__builtin__
}\refbimodindex{__builtin__
},
2437 \module{__main__
}\refbimodindex{__main__
} and
2438 \module{sys
}\refbimodindex{sys
}. The table of loaded modules
2439 (
\code{sys.modules
}) and the module search path (
\code{sys.path
}) are
2440 also separate. The new environment has no
\code{sys.argv
} variable.
2441 It has new standard I/O stream file objects
\code{sys.stdin
},
2442 \code{sys.stdout
} and
\code{sys.stderr
} (however these refer to the
2443 same underlying
\ctype{FILE
} structures in the
\C{} library).
2445 The return value points to the first thread state created in the new
2446 sub-interpreter. This thread state is made the current thread state.
2447 Note that no actual thread is created; see the discussion of thread
2448 states below. If creation of the new interpreter is unsuccessful,
2449 \NULL{} is returned; no exception is set since the exception state
2450 is stored in the current thread state and there may not be a current
2451 thread state. (Like all other Python/C API functions, the global
2452 interpreter lock must be held before calling this function and is
2453 still held when it returns; however, unlike most other Python/C API
2454 functions, there needn't be a current thread state on entry.)
2456 Extension modules are shared between (sub-)interpreters as follows:
2457 the first time a particular extension is imported, it is initialized
2458 normally, and a (shallow) copy of its module's dictionary is
2459 squirreled away. When the same extension is imported by another
2460 (sub-)interpreter, a new module is initialized and filled with the
2461 contents of this copy; the extension's
\code{init
} function is not
2462 called. Note that this is different from what happens when an
2463 extension is imported after the interpreter has been completely
2464 re-initialized by calling
\cfunction{Py_Finalize()
} and
2465 \cfunction{Py_Initialize()
}; in that case, the extension's
\code{init
}
2466 function
\emph{is
} called again.
2468 \strong{Bugs and caveats:
} Because sub-interpreters (and the main
2469 interpreter) are part of the same process, the insulation between them
2470 isn't perfect --- for example, using low-level file operations like
2471 \function{os.close()
} they can (accidentally or maliciously) affect each
2472 other's open files. Because of the way extensions are shared between
2473 (sub-)interpreters, some extensions may not work properly; this is
2474 especially likely when the extension makes use of (static) global
2475 variables, or when the extension manipulates its module's dictionary
2476 after its initialization. It is possible to insert objects created in
2477 one sub-interpreter into a namespace of another sub-interpreter; this
2478 should be done with great care to avoid sharing user-defined
2479 functions, methods, instances or classes between sub-interpreters,
2480 since import operations executed by such objects may affect the
2481 wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
2482 a hard-to-fix bug that will be addressed in a future release.)
2485 \begin{cfuncdesc
}{void
}{Py_EndInterpreter
}{PyThreadState *tstate
}
2486 Destroy the (sub-)interpreter represented by the given thread state.
2487 The given thread state must be the current thread state. See the
2488 discussion of thread states below. When the call returns, the current
2489 thread state is
\NULL{}. All thread states associated with this
2490 interpreted are destroyed. (The global interpreter lock must be held
2491 before calling this function and is still held when it returns.)
2492 \cfunction{Py_Finalize()
} will destroy all sub-interpreters that haven't
2493 been explicitly destroyed at that point.
2496 \begin{cfuncdesc
}{void
}{Py_SetProgramName
}{char *name
}
2497 This function should be called before
\cfunction{Py_Initialize()
} is called
2498 for the first time, if it is called at all. It tells the interpreter
2499 the value of the
\code{argv
[0]} argument to the
\cfunction{main()
} function
2500 of the program. This is used by
\cfunction{Py_GetPath()
} and some other
2501 functions below to find the Python run-time libraries relative to the
2502 interpreter executable. The default value is
\code{"python"
}. The
2503 argument should point to a zero-terminated character string in static
2504 storage whose contents will not change for the duration of the
2505 program's execution. No code in the Python interpreter will change
2506 the contents of this storage.
2509 \begin{cfuncdesc
}{char*
}{Py_GetProgramName
}{}
2510 Return the program name set with
\cfunction{Py_SetProgramName()
}, or the
2511 default. The returned string points into static storage; the caller
2512 should not modify its value.
2515 \begin{cfuncdesc
}{char*
}{Py_GetPrefix
}{}
2516 Return the
\emph{prefix
} for installed platform-independent files. This
2517 is derived through a number of complicated rules from the program name
2518 set with
\cfunction{Py_SetProgramName()
} and some environment variables;
2519 for example, if the program name is
\code{"/usr/local/bin/python"
},
2520 the prefix is
\code{"/usr/local"
}. The returned string points into
2521 static storage; the caller should not modify its value. This
2522 corresponds to the
\makevar{prefix
} variable in the top-level
2523 \file{Makefile
} and the
\code{-
}\code{-prefix
} argument to the
2524 \program{configure
} script at build time. The value is available to
2525 Python code as
\code{sys.prefix
}. It is only useful on
\UNIX{}. See
2526 also the next function.
2529 \begin{cfuncdesc
}{char*
}{Py_GetExecPrefix
}{}
2530 Return the
\emph{exec-prefix
} for installed platform-
\emph{de
}pendent
2531 files. This is derived through a number of complicated rules from the
2532 program name set with
\cfunction{Py_SetProgramName()
} and some environment
2533 variables; for example, if the program name is
2534 \code{"/usr/local/bin/python"
}, the exec-prefix is
2535 \code{"/usr/local"
}. The returned string points into static storage;
2536 the caller should not modify its value. This corresponds to the
2537 \makevar{exec_prefix
} variable in the top-level
\file{Makefile
} and the
2538 \code{-
}\code{-exec_prefix
} argument to the
\program{configure
} script
2539 at build time. The value is available to Python code as
2540 \code{sys.exec_prefix
}. It is only useful on
\UNIX{}.
2542 Background: The exec-prefix differs from the prefix when platform
2543 dependent files (such as executables and shared libraries) are
2544 installed in a different directory tree. In a typical installation,
2545 platform dependent files may be installed in the
2546 \code{"/usr/local/plat"
} subtree while platform independent may be
2547 installed in
\code{"/usr/local"
}.
2549 Generally speaking, a platform is a combination of hardware and
2550 software families, e.g. Sparc machines running the Solaris
2.x
2551 operating system are considered the same platform, but Intel machines
2552 running Solaris
2.x are another platform, and Intel machines running
2553 Linux are yet another platform. Different major revisions of the same
2554 operating system generally also form different platforms. Non-
\UNIX{}
2555 operating systems are a different story; the installation strategies
2556 on those systems are so different that the prefix and exec-prefix are
2557 meaningless, and set to the empty string. Note that compiled Python
2558 bytecode files are platform independent (but not independent from the
2559 Python version by which they were compiled!).
2561 System administrators will know how to configure the
\program{mount
} or
2562 \program{automount
} programs to share
\code{"/usr/local"
} between platforms
2563 while having
\code{"/usr/local/plat"
} be a different filesystem for each
2567 \begin{cfuncdesc
}{char*
}{Py_GetProgramFullPath
}{}
2568 Return the full program name of the Python executable; this is
2569 computed as a side-effect of deriving the default module search path
2570 from the program name (set by
\cfunction{Py_SetProgramName()
} above). The
2571 returned string points into static storage; the caller should not
2572 modify its value. The value is available to Python code as
2573 \code{sys.executable
}.
2576 \begin{cfuncdesc
}{char*
}{Py_GetPath
}{}
2577 \indexiii{module
}{search
}{path
}
2578 Return the default module search path; this is computed from the
2579 program name (set by
\cfunction{Py_SetProgramName()
} above) and some
2580 environment variables. The returned string consists of a series of
2581 directory names separated by a platform dependent delimiter character.
2582 The delimiter character is
\character{:
} on
\UNIX{},
\character{;
} on
2583 DOS/Windows, and
\character{\
\n} (the
\ASCII{} newline character) on
2584 Macintosh. The returned string points into static storage; the caller
2585 should not modify its value. The value is available to Python code
2586 as the list
\code{sys.path
}, which may be modified to change the
2587 future search path for loaded modules.
2589 % XXX should give the exact rules
2592 \begin{cfuncdesc
}{const char*
}{Py_GetVersion
}{}
2593 Return the version of this Python interpreter. This is a string that
2594 looks something like
2597 "
1.5 (
#67, Dec
31 1997,
22:
34:
28)
[GCC
2.7.2.2]"
2600 The first word (up to the first space character) is the current Python
2601 version; the first three characters are the major and minor version
2602 separated by a period. The returned string points into static storage;
2603 the caller should not modify its value. The value is available to
2604 Python code as the list
\code{sys.version
}.
2607 \begin{cfuncdesc
}{const char*
}{Py_GetPlatform
}{}
2608 Return the platform identifier for the current platform. On
\UNIX{},
2609 this is formed from the ``official'' name of the operating system,
2610 converted to lower case, followed by the major revision number; e.g.,
2611 for Solaris
2.x, which is also known as SunOS
5.x, the value is
2612 \code{"sunos5"
}. On Macintosh, it is
\code{"mac"
}. On Windows, it
2613 is
\code{"win"
}. The returned string points into static storage;
2614 the caller should not modify its value. The value is available to
2615 Python code as
\code{sys.platform
}.
2618 \begin{cfuncdesc
}{const char*
}{Py_GetCopyright
}{}
2619 Return the official copyright string for the current Python version,
2622 \code{"Copyright
1991-
1995 Stichting Mathematisch Centrum, Amsterdam"
}
2624 The returned string points into static storage; the caller should not
2625 modify its value. The value is available to Python code as the list
2626 \code{sys.copyright
}.
2629 \begin{cfuncdesc
}{const char*
}{Py_GetCompiler
}{}
2630 Return an indication of the compiler used to build the current Python
2631 version, in square brackets, for example:
2637 The returned string points into static storage; the caller should not
2638 modify its value. The value is available to Python code as part of
2639 the variable
\code{sys.version
}.
2642 \begin{cfuncdesc
}{const char*
}{Py_GetBuildInfo
}{}
2643 Return information about the sequence number and build date and time
2644 of the current Python interpreter instance, for example
2647 "
#67, Aug
1 1997,
22:
34:
28"
2650 The returned string points into static storage; the caller should not
2651 modify its value. The value is available to Python code as part of
2652 the variable
\code{sys.version
}.
2655 \begin{cfuncdesc
}{int
}{PySys_SetArgv
}{int argc, char **argv
}
2659 % XXX Other PySys thingies (doesn't really belong in this chapter)
2661 \section{Thread State and the Global Interpreter Lock
2664 The Python interpreter is not fully thread safe. In order to support
2665 multi-threaded Python programs, there's a global lock that must be
2666 held by the current thread before it can safely access Python objects.
2667 Without the lock, even the simplest operations could cause problems in
2668 a multi-threaded program: for example, when two threads simultaneously
2669 increment the reference count of the same object, the reference count
2670 could end up being incremented only once instead of twice.
2672 Therefore, the rule exists that only the thread that has acquired the
2673 global interpreter lock may operate on Python objects or call Python/C
2674 API functions. In order to support multi-threaded Python programs,
2675 the interpreter regularly release and reacquires the lock --- by
2676 default, every ten bytecode instructions (this can be changed with
2677 \function{sys.setcheckinterval()
}). The lock is also released and
2678 reacquired around potentially blocking I/O operations like reading or
2679 writing a file, so that other threads can run while the thread that
2680 requests the I/O is waiting for the I/O operation to complete.
2682 The Python interpreter needs to keep some bookkeeping information
2683 separate per thread --- for this it uses a data structure called
2684 \ctype{PyThreadState
}. This is new in Python
1.5; in earlier versions,
2685 such state was stored in global variables, and switching threads could
2686 cause problems. In particular, exception handling is now thread safe,
2687 when the application uses
\function{sys.exc_info()
} to access the
2688 exception last raised in the current thread.
2690 There's one global variable left, however: the pointer to the current
2691 \ctype{PyThreadState
} structure. While most thread packages have a way
2692 to store ``per-thread global data,'' Python's internal platform
2693 independent thread abstraction doesn't support this yet. Therefore,
2694 the current thread state must be manipulated explicitly.
2696 This is easy enough in most cases. Most code manipulating the global
2697 interpreter lock has the following simple structure:
2700 Save the thread state in a local variable.
2701 Release the interpreter lock.
2702 ...Do some blocking I/O operation...
2703 Reacquire the interpreter lock.
2704 Restore the thread state from the local variable.
2707 This is so common that a pair of macros exists to simplify it:
2710 Py_BEGIN_ALLOW_THREADS
2711 ...Do some blocking I/O operation...
2712 Py_END_ALLOW_THREADS
2715 The
\code{Py_BEGIN_ALLOW_THREADS
} macro opens a new block and declares
2716 a hidden local variable; the
\code{Py_END_ALLOW_THREADS
} macro closes
2717 the block. Another advantage of using these two macros is that when
2718 Python is compiled without thread support, they are defined empty,
2719 thus saving the thread state and lock manipulations.
2721 When thread support is enabled, the block above expands to the
2726 PyThreadState *_save;
2727 _save = PyEval_SaveThread();
2728 ...Do some blocking I/O operation...
2729 PyEval_RestoreThread(_save);
2733 Using even lower level primitives, we can get roughly the same effect
2738 PyThreadState *_save;
2739 _save = PyThreadState_Swap(NULL);
2740 PyEval_ReleaseLock();
2741 ...Do some blocking I/O operation...
2742 PyEval_AcquireLock();
2743 PyThreadState_Swap(_save);
2747 There are some subtle differences; in particular,
2748 \cfunction{PyEval_RestoreThread()
} saves and restores the value of the
2749 global variable
\cdata{errno
}, since the lock manipulation does not
2750 guarantee that
\cdata{errno
} is left alone. Also, when thread support
2751 is disabled,
\cfunction{PyEval_SaveThread()
} and
2752 \cfunction{PyEval_RestoreThread()
} don't manipulate the lock; in this
2753 case,
\cfunction{PyEval_ReleaseLock()
} and
2754 \cfunction{PyEval_AcquireLock()
} are not available. This is done so
2755 that dynamically loaded extensions compiled with thread support
2756 enabled can be loaded by an interpreter that was compiled with
2757 disabled thread support.
2759 The global interpreter lock is used to protect the pointer to the
2760 current thread state. When releasing the lock and saving the thread
2761 state, the current thread state pointer must be retrieved before the
2762 lock is released (since another thread could immediately acquire the
2763 lock and store its own thread state in the global variable).
2764 Reversely, when acquiring the lock and restoring the thread state, the
2765 lock must be acquired before storing the thread state pointer.
2767 Why am I going on with so much detail about this? Because when
2768 threads are created from
\C{}, they don't have the global interpreter
2769 lock, nor is there a thread state data structure for them. Such
2770 threads must bootstrap themselves into existence, by first creating a
2771 thread state data structure, then acquiring the lock, and finally
2772 storing their thread state pointer, before they can start using the
2773 Python/C API. When they are done, they should reset the thread state
2774 pointer, release the lock, and finally free their thread state data
2777 When creating a thread data structure, you need to provide an
2778 interpreter state data structure. The interpreter state data
2779 structure hold global data that is shared by all threads in an
2780 interpreter, for example the module administration
2781 (
\code{sys.modules
}). Depending on your needs, you can either create
2782 a new interpreter state data structure, or share the interpreter state
2783 data structure used by the Python main thread (to access the latter,
2784 you must obtain the thread state and access its
\member{interp
} member;
2785 this must be done by a thread that is created by Python or by the main
2786 thread after Python is initialized).
2790 \begin{ctypedesc
}{PyInterpreterState
}
2791 This data structure represents the state shared by a number of
2792 cooperating threads. Threads belonging to the same interpreter
2793 share their module administration and a few other internal items.
2794 There are no public members in this structure.
2796 Threads belonging to different interpreters initially share nothing,
2797 except process state like available memory, open file descriptors and
2798 such. The global interpreter lock is also shared by all threads,
2799 regardless of to which interpreter they belong.
2802 \begin{ctypedesc
}{PyThreadState
}
2803 This data structure represents the state of a single thread. The only
2804 public data member is
\ctype{PyInterpreterState *
}\member{interp
},
2805 which points to this thread's interpreter state.
2808 \begin{cfuncdesc
}{void
}{PyEval_InitThreads
}{}
2809 Initialize and acquire the global interpreter lock. It should be
2810 called in the main thread before creating a second thread or engaging
2811 in any other thread operations such as
2812 \cfunction{PyEval_ReleaseLock()
} or
2813 \code{PyEval_ReleaseThread(
\var{tstate
})
}. It is not needed before
2814 calling
\cfunction{PyEval_SaveThread()
} or
2815 \cfunction{PyEval_RestoreThread()
}.
2817 This is a no-op when called for a second time. It is safe to call
2818 this function before calling
\cfunction{Py_Initialize()
}.
2820 When only the main thread exists, no lock operations are needed. This
2821 is a common situation (most Python programs do not use threads), and
2822 the lock operations slow the interpreter down a bit. Therefore, the
2823 lock is not created initially. This situation is equivalent to having
2824 acquired the lock: when there is only a single thread, all object
2825 accesses are safe. Therefore, when this function initializes the
2826 lock, it also acquires it. Before the Python
2827 \module{thread
}\refbimodindex{thread
} module creates a new thread,
2828 knowing that either it has the lock or the lock hasn't been created
2829 yet, it calls
\cfunction{PyEval_InitThreads()
}. When this call
2830 returns, it is guaranteed that the lock has been created and that it
2833 It is
\strong{not
} safe to call this function when it is unknown which
2834 thread (if any) currently has the global interpreter lock.
2836 This function is not available when thread support is disabled at
2840 \begin{cfuncdesc
}{void
}{PyEval_AcquireLock
}{}
2841 Acquire the global interpreter lock. The lock must have been created
2842 earlier. If this thread already has the lock, a deadlock ensues.
2843 This function is not available when thread support is disabled at
2847 \begin{cfuncdesc
}{void
}{PyEval_ReleaseLock
}{}
2848 Release the global interpreter lock. The lock must have been created
2849 earlier. This function is not available when thread support is
2850 disabled at compile time.
2853 \begin{cfuncdesc
}{void
}{PyEval_AcquireThread
}{PyThreadState *tstate
}
2854 Acquire the global interpreter lock and then set the current thread
2855 state to
\var{tstate
}, which should not be
\NULL{}. The lock must
2856 have been created earlier. If this thread already has the lock,
2857 deadlock ensues. This function is not available when thread support
2858 is disabled at compile time.
2861 \begin{cfuncdesc
}{void
}{PyEval_ReleaseThread
}{PyThreadState *tstate
}
2862 Reset the current thread state to
\NULL{} and release the global
2863 interpreter lock. The lock must have been created earlier and must be
2864 held by the current thread. The
\var{tstate
} argument, which must not
2865 be
\NULL{}, is only used to check that it represents the current
2866 thread state --- if it isn't, a fatal error is reported. This
2867 function is not available when thread support is disabled at compile
2871 \begin{cfuncdesc
}{PyThreadState*
}{PyEval_SaveThread
}{}
2872 Release the interpreter lock (if it has been created and thread
2873 support is enabled) and reset the thread state to
\NULL{},
2874 returning the previous thread state (which is not
\NULL{}). If
2875 the lock has been created, the current thread must have acquired it.
2876 (This function is available even when thread support is disabled at
2880 \begin{cfuncdesc
}{void
}{PyEval_RestoreThread
}{PyThreadState *tstate
}
2881 Acquire the interpreter lock (if it has been created and thread
2882 support is enabled) and set the thread state to
\var{tstate
}, which
2883 must not be
\NULL{}. If the lock has been created, the current
2884 thread must not have acquired it, otherwise deadlock ensues. (This
2885 function is available even when thread support is disabled at compile
2889 % XXX These aren't really C types, but the ctypedesc macro is the simplest!
2890 \begin{ctypedesc
}{Py_BEGIN_ALLOW_THREADS
}
2891 This macro expands to
2892 \samp{\
{ PyThreadState *_save; _save = PyEval_SaveThread();
}.
2893 Note that it contains an opening brace; it must be matched with a
2894 following
\code{Py_END_ALLOW_THREADS
} macro. See above for further
2895 discussion of this macro. It is a no-op when thread support is
2896 disabled at compile time.
2899 \begin{ctypedesc
}{Py_END_ALLOW_THREADS
}
2900 This macro expands to
2901 \samp{PyEval_RestoreThread(_save); \
}}.
2902 Note that it contains a closing brace; it must be matched with an
2903 earlier
\code{Py_BEGIN_ALLOW_THREADS
} macro. See above for further
2904 discussion of this macro. It is a no-op when thread support is
2905 disabled at compile time.
2908 \begin{ctypedesc
}{Py_BEGIN_BLOCK_THREADS
}
2909 This macro expands to
\samp{PyEval_RestoreThread(_save);
} i.e. it
2910 is equivalent to
\code{Py_END_ALLOW_THREADS
} without the closing
2911 brace. It is a no-op when thread support is disabled at compile
2915 \begin{ctypedesc
}{Py_BEGIN_UNBLOCK_THREADS
}
2916 This macro expands to
\samp{_save = PyEval_SaveThread();
} i.e. it is
2917 equivalent to
\code{Py_BEGIN_ALLOW_THREADS
} without the opening brace
2918 and variable declaration. It is a no-op when thread support is
2919 disabled at compile time.
2922 All of the following functions are only available when thread support
2923 is enabled at compile time, and must be called only when the
2924 interpreter lock has been created.
2926 \begin{cfuncdesc
}{PyInterpreterState*
}{PyInterpreterState_New
}{}
2927 Create a new interpreter state object. The interpreter lock need not
2928 be held, but may be held if it is necessary to serialize calls to this
2932 \begin{cfuncdesc
}{void
}{PyInterpreterState_Clear
}{PyInterpreterState *interp
}
2933 Reset all information in an interpreter state object. The interpreter
2937 \begin{cfuncdesc
}{void
}{PyInterpreterState_Delete
}{PyInterpreterState *interp
}
2938 Destroy an interpreter state object. The interpreter lock need not be
2939 held. The interpreter state must have been reset with a previous
2940 call to
\cfunction{PyInterpreterState_Clear()
}.
2943 \begin{cfuncdesc
}{PyThreadState*
}{PyThreadState_New
}{PyInterpreterState *interp
}
2944 Create a new thread state object belonging to the given interpreter
2945 object. The interpreter lock need not be held, but may be held if it
2946 is necessary to serialize calls to this function.
2949 \begin{cfuncdesc
}{void
}{PyThreadState_Clear
}{PyThreadState *tstate
}
2950 Reset all information in a thread state object. The interpreter lock
2954 \begin{cfuncdesc
}{void
}{PyThreadState_Delete
}{PyThreadState *tstate
}
2955 Destroy a thread state object. The interpreter lock need not be
2956 held. The thread state must have been reset with a previous
2957 call to
\cfunction{PyThreadState_Clear()
}.
2960 \begin{cfuncdesc
}{PyThreadState*
}{PyThreadState_Get
}{}
2961 Return the current thread state. The interpreter lock must be held.
2962 When the current thread state is
\NULL{}, this issues a fatal
2963 error (so that the caller needn't check for
\NULL{}).
2966 \begin{cfuncdesc
}{PyThreadState*
}{PyThreadState_Swap
}{PyThreadState *tstate
}
2967 Swap the current thread state with the thread state given by the
2968 argument
\var{tstate
}, which may be
\NULL{}. The interpreter lock
2973 \chapter{Defining New Object Types
\label{newTypes
}}
2975 \begin{cfuncdesc
}{PyObject*
}{_PyObject_New
}{PyTypeObject *type
}
2978 \begin{cfuncdesc
}{PyObject*
}{_PyObject_NewVar
}{PyTypeObject *type, int size
}
2981 \begin{cfuncdesc
}{TYPE
}{_PyObject_NEW
}{TYPE, PyTypeObject *
}
2984 \begin{cfuncdesc
}{TYPE
}{_PyObject_NEW_VAR
}{TYPE, PyTypeObject *, int size
}
2989 PyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse
2993 PyObject, PyVarObject
2995 PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
2998 unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
2999 intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
3000 getreadbufferproc, getwritebufferproc, getsegcountproc,
3001 destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
3002 setattrofunc, cmpfunc, reprfunc, hashfunc
3020 Py_None, _Py_NoneStruct
3023 \chapter{Debugging
\label{debugging
}}
3025 XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
3028 \input{api.ind
} % Index -- must be last