Python Api Manual PDF
Python Api Manual PDF
Python Api Manual PDF
Release 2.2.1
PythonLabs
Email: [email protected]
Copyright
c 2001 Python Software Foundation. All rights reserved.
Copyright
c 2000 BeOpen.com. All rights reserved.
Copyright
c 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright
c 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See the end of this document for complete license and permissions information.
Abstract
This manual documents the API used by C and C++ programmers who want to write extension modules
or embed Python. It is a companion to Extending and Embedding the Python Interpreter, which describes
the general principles of extension writing but does not document the API functions in detail.
Warning: The current version of this document is incomplete. I hope that it is nevertheless useful. I
will continue to work on it, and release new versions from time to time, independent from Python source
code releases.
CONTENTS
1 Introduction 1
1.1 Include Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Objects, Types and Reference Counts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Embedding Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3 Reference Counting 11
4 Exception Handling 13
4.1 Standard Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4.2 Deprecation of String Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5 Utilities 19
5.1 Operating System Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.2 Process Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.3 Importing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.4 Data marshalling support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.5 Parsing arguments and building values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
9 Memory Management 69
9.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
9.2 Memory Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
i
9.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
A Reporting Bugs 81
Index 87
ii
CHAPTER
ONE
Introduction
The Application Programmer’s Interface to Python gives C and C++ programmers access to the Python
interpreter at a variety of levels. The API is equally usable from C++, but for brevity it is generally
referred to as the Python/C API. There are two fundamentally different reasons for using the Python/C
API. The first reason is to write extension modules for specific purposes; these are C modules that extend
the Python interpreter. This is probably the most common use. The second reason is to use Python as
a component in a larger application; this technique is generally referred to as embedding Python in an
application.
Writing an extension module is a relatively well-understood process, where a “cookbook” approach
works well. There are several tools that automate the process to some extent. While people have
embedded Python in other applications since its early existence, the process of embedding Python is less
straightforward than writing an extension.
Many API functions are useful independent of whether you’re embedding or extending Python; moreover,
most applications that embed Python will need to provide a custom extension as well, so it’s probably
a good idea to become familiar with writing an extension before attempting to embed Python in a real
application.
#include "Python.h"
This implies inclusion of the following standard headers: <stdio.h>, <string.h>, <errno.h>,
<limits.h>, and <stdlib.h> (if available). Since Python may define some pre-processor definitions
which affect the standard headers on some systems, you must include ‘Python.h’ before any standard
headers are included.
All user visible names defined by Python.h (except those defined by the included standard headers)
have one of the prefixes ‘Py’ or ‘ Py’. Names beginning with ‘ Py’ are for internal use by the Python
implementation and should not be used by extension writers. Structure member names do not have a
reserved prefix.
Important: user code should never define names that begin with ‘Py’ or ‘ Py’. This confuses the reader,
and jeopardizes the portability of the user code to future Python versions, which may define additional
names beginning with one of these prefixes.
The header files are typically installed with Python. On Unix, these are located in the directories
‘prefix/include/pythonversion/’ and ‘exec prefix/include/pythonversion/’, where prefix and exec prefix are
defined by the corresponding parameters to Python’s configure script and version is sys.version[:3].
On Windows, the headers are installed in ‘prefix/include’, where prefix is the installation directory specified
to the installer.
To include the headers, place both directories (if different) on your compiler’s search path for includes.
1
Do not place the parent directories on the search path and then use ‘#include <python2.2/Python.h>’;
this will break on multi-platform builds since the platform independent headers under prefix include the
platform specific headers from exec prefix.
C++ users should note that though the API is defined entirely using C, the header files do properly
declare the entry points to be extern "C", so there is no need to do anything special to use the API
from C++.
The reference count is important because today’s computers have a finite (and often severely limited)
memory size; it counts how many different places there are that have a reference to an object. Such a
place could be another object, or a global (or static) C variable, or a local variable in some C function.
When an object’s reference count becomes zero, the object is deallocated. If it contains references to
other objects, their reference count is decremented. Those other objects may be deallocated in turn, if
this decrement makes their reference count become zero, and so on. (There’s an obvious problem with
objects that reference each other here; for now, the solution is “don’t do that.”)
Reference counts are always manipulated explicitly. The normal way is to use the macro Py INCREF()
to increment an object’s reference count by one, and Py DECREF() to decrement it by one. The
Py DECREF() macro is considerably more complex than the incref one, since it must check whether
the reference count becomes zero and then cause the object’s deallocator to be called. The deallocator
is a function pointer contained in the object’s type structure. The type-specific deallocator takes care of
decrementing the reference counts for other objects contained in the object if this is a compound object
type, such as a list, as well as performing any additional finalization that’s needed. There’s no chance
that the reference count can overflow; at least as many bits are used to hold the reference count as there
are distinct memory locations in virtual memory (assuming sizeof(long) >= sizeof(char*)). Thus,
the reference count increment is a simple operation.
It is not necessary to increment an object’s reference count for every local variable that contains a pointer
to an object. In theory, the object’s reference count goes up by one when the variable is made to point
to it and it goes down by one when the variable goes out of scope. However, these two cancel each other
out, so at the end the reference count hasn’t changed. The only real reason to use the reference count
is to prevent the object from being deallocated as long as our variable is pointing to it. If we know that
there is at least one other reference to the object that lives at least as long as our variable, there is no
need to increment the reference count temporarily. An important situation where this arises is in objects
that are passed as arguments to C functions in an extension module that are called from Python; the
call mechanism guarantees to hold a reference to every argument for the duration of the call.
However, a common pitfall is to extract an object from a list and hold on to it for a while without
incrementing its reference count. Some other operation might conceivably remove the object from the
list, decrementing its reference count and possible deallocating it. The real danger is that innocent-
2 Chapter 1. Introduction
looking operations may invoke arbitrary Python code which could do this; there is a code path which
allows control to flow back to the user from a Py DECREF(), so almost any operation is potentially
dangerous.
A safe approach is to always use the generic operations (functions whose name begins with ‘PyObject ’,
‘PyNumber ’, ‘PySequence ’ or ‘PyMapping ’). These operations always increment the reference count
of the object they return. This leaves the caller with the responsibility to call Py DECREF() when they
are done with the result; this soon becomes second nature.
The reference count behavior of functions in the Python/C API is best explained in terms of ownership
of references. Note that we talk of owning references, never of owning objects; objects are always shared!
When a function owns a reference, it has to dispose of it properly — either by passing ownership on
(usually to its caller) or by calling Py DECREF() or Py XDECREF(). When a function passes ownership of
a reference on to its caller, the caller is said to receive a new reference. When no ownership is transferred,
the caller is said to borrow the reference. Nothing needs to be done for a borrowed reference.
Conversely, when a calling function passes it a reference to an object, there are two possibilities: the
function steals a reference to the object, or it does not. Few functions steal references; the two notable
exceptions are PyList SetItem() and PyTuple SetItem(), which steal a reference to the item (but
not to the tuple or list into which the item is put!). These functions were designed to steal a reference
because of a common idiom for populating a tuple or list with newly created objects; for example, the
code to create the tuple (1, 2, "three") could look like this (forgetting about error handling for the
moment; a better way to code this is shown below):
PyObject *t;
t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
PyTuple_SetItem(t, 2, PyString_FromString("three"));
Incidentally, PyTuple SetItem() is the only way to set tuple items; PySequence SetItem() and
PyObject SetItem() refuse to do this since tuples are an immutable data type. You should only
use PyTuple SetItem() for tuples that you are creating yourself.
Equivalent code for populating a list can be written using PyList New() and PyList SetItem(). Such
code can also use PySequence SetItem(); this illustrates the difference between the two (the extra
Py DECREF() calls):
l = PyList_New(3);
x = PyInt_FromLong(1L);
PySequence_SetItem(l, 0, x); Py_DECREF(x);
x = PyInt_FromLong(2L);
PySequence_SetItem(l, 1, x); Py_DECREF(x);
x = PyString_FromString("three");
PySequence_SetItem(l, 2, x); Py_DECREF(x);
You might find it strange that the “recommended” approach takes more code. However, in practice,
you will rarely use these ways of creating and populating a tuple or list. There’s a generic function,
Py BuildValue(), that can create most common objects from C values, directed by a format string.
For example, the above two blocks of code could be replaced by the following (which also takes care of
the error checking):
t = Py_BuildValue("(iis)", 1, 2, "three");
int
set_all(PyObject *target, PyObject *item)
{
int i, n;
n = PyObject_Length(target);
if (n < 0)
return -1;
for (i = 0; i < n; i++) {
if (PyObject_SetItem(target, i, item) < 0)
return -1;
}
return 0;
}
The situation is slightly different for function return values. While passing a reference to most functions
does not change your ownership responsibilities for that reference, many functions that return a referece
to an object give you ownership of the reference. The reason is simple: in many cases, the returned
object is created on the fly, and the reference you get is the only reference to the object. Therefore, the
generic functions that return object references, like PyObject GetItem() and PySequence GetItem(),
always return a new reference (the caller becomes the owner of the reference).
It is important to realize that whether you own a reference returned by a function depends on which
function you call only — the plumage (the type of the type of the object passed as an argument to the func-
tion) doesn’t enter into it! Thus, if you extract an item from a list using PyList GetItem(), you don’t
own the reference — but if you obtain the same item from the same list using PySequence GetItem()
(which happens to take exactly the same arguments), you do own a reference to the returned object.
Here is an example of how you could write a function that computes the sum of the items in a list of
integers; once using PyList GetItem(), and once using PySequence GetItem().
long
sum_list(PyObject *list)
{
int i, n;
long total = 0;
PyObject *item;
n = PyList_Size(list);
if (n < 0)
return -1; /* Not a list */
for (i = 0; i < n; i++) {
item = PyList_GetItem(list, i); /* Can’t fail */
if (!PyInt_Check(item)) continue; /* Skip non-integers */
total += PyInt_AsLong(item);
}
return total;
}
long
sum_sequence(PyObject *sequence)
{
int i, n;
4 Chapter 1. Introduction
long total = 0;
PyObject *item;
n = PySequence_Length(sequence);
if (n < 0)
return -1; /* Has no length */
for (i = 0; i < n; i++) {
item = PySequence_GetItem(sequence, i);
if (item == NULL)
return -1; /* Not a sequence, or other failure */
if (PyInt_Check(item))
total += PyInt_AsLong(item);
Py_DECREF(item); /* Discard reference ownership */
}
return total;
}
1.2.2 Types
There are few other data types that play a significant role in the Python/C API; most are simple C types
such as int, long, double and char*. A few structure types are used to describe static tables used to
list the functions exported by a module or the data attributes of a new object type, and another is used
to describe the value of a complex number. These will be discussed together with the functions that use
them.
1.3 Exceptions
The Python programmer only needs to deal with exceptions if specific error handling is required; un-
handled exceptions are automatically propagated to the caller, then to the caller’s caller, and so on,
until they reach the top-level interpreter, where they are reported to the user accompanied by a stack
traceback.
For C programmers, however, error checking always has to be explicit. All functions in the Python/C
API can raise exceptions, unless an explicit claim is made otherwise in a function’s documentation. In
general, when a function encounters an error, it sets an exception, discards any object references that it
owns, and returns an error indicator — usually NULL or -1. A few functions return a Boolean true/false
result, with false indicating an error. Very few functions return no explicit error indicator or have an
ambiguous return value, and require explicit testing for errors with PyErr Occurred().
Exception state is maintained in per-thread storage (this is equivalent to using global storage in an
unthreaded application). A thread can be in one of two states: an exception has occurred, or not.
The function PyErr Occurred() can be used to check for this: it returns a borrowed reference to the
exception type object when an exception has occurred, and NULL otherwise. There are a number of
functions to set the exception state: PyErr SetString() is the most common (though not the most
general) function to set the exception state, and PyErr Clear() clears the exception state.
The full exception state consists of three objects (all of which can be NULL): the exception type, the
corresponding exception value, and the traceback. These have the same meanings as the Python
objects sys.exc type, sys.exc value, and sys.exc traceback; however, they are not the same: the
Python objects represent the last exception being handled by a Python try . . . except statement, while
the C level exception state only exists while an exception is being passed on between C functions until it
reaches the Python bytecode interpreter’s main loop, which takes care of transferring it to sys.exc type
and friends.
Note that starting with Python 1.5, the preferred, thread-safe way to access the exception state from
Python code is to call the function sys.exc info(), which returns the per-thread exception state for
Python code. Also, the semantics of both ways to access the exception state have changed so that a
function which catches an exception will save and restore its thread’s exception state so as to preserve
the exception state of its caller. This prevents common bugs in exception handling code caused by an
innocent-looking function overwriting the exception being handled; it also reduces the often unwanted
1.3. Exceptions 5
lifetime extension for objects that are referenced by the stack frames in the traceback.
As a general principle, a function that calls another function to perform some task should check whether
the called function raised an exception, and if so, pass the exception state on to its caller. It should
discard any object references that it owns, and return an error indicator, but it should not set another
exception — that would overwrite the exception that was just raised, and lose important information
about the exact cause of the error.
A simple example of detecting exceptions and passing them on is shown in the sum sequence() example
above. It so happens that that example doesn’t need to clean up any owned references when it detects
an error. The following example function shows some error cleanup. First, to remind you why you like
Python, we show the equivalent Python code:
int
incr_item(PyObject *dict, PyObject *key)
{
/* Objects all initialized to NULL for Py_XDECREF */
PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
int rv = -1; /* Return value initialized to -1 (failure) */
error:
/* Cleanup code, shared by success and failure path */
6 Chapter 1. Introduction
return rv; /* -1 for error, 0 for success */
}
This example represents an endorsed use of the goto statement in C! It illustrates the use of
PyErr ExceptionMatches() and PyErr Clear() to handle specific exceptions, and the use of
Py XDECREF() to dispose of owned references that may be NULL (note the ‘X’ in the name; Py DECREF()
would crash when confronted with a NULL reference). It is important that the variables used to hold
owned references are initialized to NULL for this to work; likewise, the proposed return value is initialized
to -1 (failure) and only set to success after the final call made is successful.
TWO
The functions in this chapter will let you execute Python source code given in a file or a buffer, but they
will not let you interact in a more detailed way with the interpreter.
Several of these functions accept a start symbol from the grammar as a parameter. The available start
symbols are Py eval input, Py file input, and Py single input. These are described following
the functions which accept them as parameters.
Note also that several of these functions take FILE* parameters. On particular issue which needs to be
handled carefully is that the FILE structure for different C libraries can be different and incompatible.
Under Windows (at least), it is possible for dynamically linked extensions to actually use different
libraries, so care should be taken that FILE* parameters are only passed to these functions if it is certain
that they were created by the same library that the Python runtime is using.
int Py Main(int argc, char **argv )
The main program for the standard interpreter. This is made available for programs which embed
Python. The argc and argv parameters should be prepared exactly as those which are passed to
a C program’s main() function. It is important to note that the argument list may be modified
(but the contents of the strings pointed to by the argument list are not). The return value will be
the integer passed to the sys.exit() function, 1 if the interpreter exits due to an exception, or 2
if the parameter list does not represent a valid Python command line.
int PyRun AnyFile(FILE *fp, char *filename)
If fp refers to a file associated with an interactive device (console or terminal input or Unix
pseudo-terminal), return the value of PyRun InteractiveLoop(), otherwise return the result of
PyRun SimpleFile(). If filename is NULL, this function uses "???" as the filename.
int PyRun SimpleString(char *command )
Executes the Python source code from command in the main module. If main does not
already exist, it is created. Returns 0 on success or -1 if an exception was raised. If there was an
error, there is no way to get the exception information.
int PyRun SimpleFile(FILE *fp, char *filename)
Similar to PyRun SimpleString(), but the Python source code is read from fp instead of an
in-memory string. filename should be the name of the file.
int PyRun InteractiveOne(FILE *fp, char *filename)
Read and execute a single statement from a file associated with an interactive device. If filename
is NULL, "???" is used instead. The user will be prompted using sys.ps1 and sys.ps2. Returns 0
when the input was executed successfully, -1 if there was an exception, or an error code from the
‘errcode.h’ include file distributed as part of Python if there was a parse error. (Note that ‘errcode.h’
is not included by ‘Python.h’, so must be included specifically if needed.)
int PyRun InteractiveLoop(FILE *fp, char *filename)
Read and execute statements from a file associated with an interactive device until eof is reached.
If filename is NULL, "???" is used instead. The user will be prompted using sys.ps1 and sys.ps2.
Returns 0 at eof.
struct node* PyParser SimpleParseString(char *str, int start)
Parse Python source code from str using the start token start. The result can be used to create a
9
code object which can be evaluated efficiently. This is useful if a code fragment must be evaluated
many times.
struct node* PyParser SimpleParseFile(FILE *fp, char *filename, int start)
Similar to PyParser SimpleParseString(), but the Python source code is read from fp instead
of an in-memory string. filename should be the name of the file.
PyObject* PyRun String(char *str, int start, PyObject *globals, PyObject *locals)
Return value: New reference.
Execute Python source code from str in the context specified by the dictionaries globals and locals.
The parameter start specifies the start token that should be used to parse the source code.
Returns the result of executing the code as a Python object, or NULL if an exception was raised.
PyObject* PyRun File(FILE *fp, char *filename, int start, PyObject *globals, PyObject *locals)
Return value: New reference.
Similar to PyRun String(), but the Python source code is read from fp instead of an in-memory
string. filename should be the name of the file.
PyObject* Py CompileString(char *str, char *filename, int start)
Return value: New reference.
Parse and compile the Python source code in str , returning the resulting code object. The start
token is given by start; this can be used to constrain the code which can be compiled and should
be Py eval input, Py file input, or Py single input. The filename specified by filename
is used to construct the code object and may appear in tracebacks or SyntaxError exception
messages. This returns NULL if the code cannot be parsed or compiled.
int Py eval input
The start symbol from the Python grammar for isolated expressions; for use with
Py CompileString().
int Py file input
The start symbol from the Python grammar for sequences of statements as read from a file or other
source; for use with Py CompileString(). This is the symbol to use when compiling arbitrarily
long Python source code.
int Py single input
The start symbol from the Python grammar for a single statement; for use with
Py CompileString(). This is the symbol used for the interactive interpreter loop.
THREE
Reference Counting
The macros in this section are used for managing reference counts of Python objects.
void Py INCREF(PyObject *o)
Increment the reference count for object o. The object must not be NULL; if you aren’t sure that
it isn’t NULL, use Py XINCREF().
void Py XINCREF(PyObject *o)
Increment the reference count for object o. The object may be NULL, in which case the macro has
no effect.
void Py DECREF(PyObject *o)
Decrement the reference count for object o. The object must not be NULL; if you aren’t sure that it
isn’t NULL, use Py XDECREF(). If the reference count reaches zero, the object’s type’s deallocation
function (which must not be NULL) is invoked.
Warning: The deallocation function can cause arbitrary Python code to be invoked (e.g. when a
class instance with a del () method is deallocated). While exceptions in such code are not
propagated, the executed code has free access to all Python global variables. This means that any
object that is reachable from a global variable should be in a consistent state before Py DECREF()
is invoked. For example, code to delete an object from a list should copy a reference to the deleted
object in a temporary variable, update the list data structure, and then call Py DECREF() for the
temporary variable.
void Py XDECREF(PyObject *o)
Decrement the reference count for object o. The object may be NULL, in which case the macro has
no effect; otherwise the effect is the same as for Py DECREF(), and the same warning applies.
The following functions or macros are only for use within the interpreter core: Py Dealloc(),
Py ForgetReference(), Py NewReference(), as well as the global variable Py RefTotal.
11
12
CHAPTER
FOUR
Exception Handling
The functions described in this chapter will let you handle and raise Python exceptions. It is important
to understand some of the basics of Python exception handling. It works somewhat like the Unix errno
variable: there is a global indicator (per thread) of the last error that occurred. Most functions don’t
clear this on success, but will set it to indicate the cause of the error on failure. Most functions also
return an error indicator, usually NULL if they are supposed to return a pointer, or -1 if they return an
integer (exception: the PyArg *() functions return 1 for success and 0 for failure).
When a function must fail because some function it called failed, it generally doesn’t set the error
indicator; the function it called already set it. It is responsible for either handling the error and clearing
the exception or returning after cleaning up any resources it holds (such as object references or memory
allocations); it should not continue normally if it is not prepared to handle the error. If returning due to
an error, it is important to indicate to the caller that an error has been set. If the error is not handled
or carefully propogated, additional calls into the Python/C API may not behave as intended and may
fail in mysterious ways.
The error indicator consists of three Python objects corresponding to the Python variables
sys.exc type, sys.exc value and sys.exc traceback. API functions exist to interact with the
error indicator in various ways. There is a separate error indicator for each thread.
void PyErr Print()
Print a standard traceback to sys.stderr and clear the error indicator. Call this function only
when the error indicator is set. (Otherwise it will cause a fatal error!)
PyObject* PyErr Occurred()
Return value: Borrowed reference.
Test whether the error indicator is set. If set, return the exception type (the first argument to the
last call to one of the PyErr Set*() functions or to PyErr Restore()). If not set, return NULL.
You do not own a reference to the return value, so you do not need to Py DECREF() it. Note:
Do not compare the return value to a specific exception; use PyErr ExceptionMatches() instead,
shown below. (The comparison could easily fail since the exception may be an instance instead of
a class, in the case of a class exception, or it may the a subclass of the expected exception.)
int PyErr ExceptionMatches(PyObject *exc)
Equivalent to ‘PyErr GivenExceptionMatches(PyErr Occurred(), exc)’. This should only be
called when an exception is actually set; a memory access violation will occur if no exception has
been raised.
int PyErr GivenExceptionMatches(PyObject *given, PyObject *exc)
Return true if the given exception matches the exception in exc. If exc is a class object, this also
returns true when given is an instance of a subclass. If exc is a tuple, all exceptions in the tuple
(and recursively in subtuples) are searched for a match. If given is NULL, a memory access violation
will occur.
void PyErr NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)
Under certain circumstances, the values returned by PyErr Fetch() below can be “unnormalized”,
meaning that *exc is a class object but *val is not an instance of the same class. This function can
be used to instantiate the class in that case. If the values are already normalized, nothing happens.
The delayed normalization is implemented to improve performance.
13
void PyErr Clear()
Clear the error indicator. If the error indicator is not set, there is no effect.
void PyErr Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback )
Retrieve the error indicator into three variables whose addresses are passed. If the error indicator
is not set, set all three variables to NULL. If it is set, it will be cleared and you own a reference
to each object retrieved. The value and traceback object may be NULL even when the type object
is not. Note: This function is normally only used by code that needs to handle exceptions or by
code that needs to save and restore the error indicator temporarily.
void PyErr Restore(PyObject *type, PyObject *value, PyObject *traceback )
Set the error indicator from the three objects. If the error indicator is already set, it is cleared
first. If the objects are NULL, the error indicator is cleared. Do not pass a NULL type and non-NULL
value or traceback. The exception type should be a string or class; if it is a class, the value should
be an instance of that class. Do not pass an invalid exception type or value. (Violating these rules
will cause subtle problems later.) This call takes away a reference to each object: you must own a
reference to each object before the call and after the call you no longer own these references. (If
you don’t understand this, don’t use this function. I warned you.) Note: This function is normally
only used by code that needs to save and restore the error indicator temporarily.
void PyErr SetString(PyObject *type, char *message)
This is the most common way to set the error indicator. The first argument specifies the exception
type; it is normally one of the standard exceptions, e.g. PyExc RuntimeError. You need not
increment its reference count. The second argument is an error message; it is converted to a string
object.
void PyErr SetObject(PyObject *type, PyObject *value)
This function is similar to PyErr SetString() but lets you specify an arbitrary Python object for
the “value” of the exception. You need not increment its reference count.
PyObject* PyErr Format(PyObject *exception, const char *format, ...)
Return value: Always NULL.
This function sets the error indicator and returns NULL.. exception should be a Python exception
(string or class, not an instance). format should be a string, containing format codes, similar to
printf(). The width.precision before a format code is parsed, but the width part is ignored.
Character Meaning
‘c’ Character, as an int parameter
‘d’ Number in decimal, as an int parameter
‘x’ Number in hexadecimal, as an int parameter
‘s’ A string, as a char * parameter
‘p’ A hex pointer, as a void * parameter
An unrecognized format character causes all the rest of the format string to be copied as-is to the
result string, and any extra arguments discarded.
void PyErr SetNone(PyObject *type)
This is a shorthand for ‘PyErr SetObject(type, Py None)’.
int PyErr BadArgument()
This is a shorthand for ‘PyErr SetString(PyExc TypeError, message)’, where message indi-
cates that a built-in operation was invoked with an illegal argument. It is mostly for internal
use.
PyObject* PyErr NoMemory()
Return value: Always NULL.
This is a shorthand for ‘PyErr SetNone(PyExc MemoryError)’; it returns NULL so an object allo-
cation function can write ‘return PyErr NoMemory();’ when it runs out of memory.
PyObject* PyErr SetFromErrno(PyObject *type)
Return value: Always NULL.
This is a convenience function to raise an exception when a C library function has returned an error
and set the C variable errno. It constructs a tuple object whose first item is the integer errno
value and whose second item is the corresponding error message (gotten from strerror()), and
15
class is set to the first part (up to the last dot) of the name argument, and the class name is set
to the last part (after the last dot). The base argument can be used to specify an alternate base
class. The dict argument can be used to specify a dictionary of class variables and methods.
void PyErr WriteUnraisable(PyObject *obj )
This utility function prints a warning message to sys.stderr when an exception has been set but
it is impossible for the interpreter to actually raise the exception. It is used, for example, when an
exception occurs in an del () method.
The function is called with a single argument obj that identifies where the context in which the
unraisable exception occurred. The repr of obj will be printed in the warning message.
Notes:
FIVE
Utilities
The functions in this chapter perform various utility tasks, ranging from helping C code be more portable
across platforms, using Python modules from C, and parsing function arguments and constructing Python
values from C values.
19
void Py Exit(int status)
Exit the current process. This calls Py Finalize() and then calls the standard C library function
exit(status).
int Py AtExit(void (*func) ())
Register a cleanup function to be called by Py Finalize(). The cleanup function will be called
with no arguments and should return no value. At most 32 cleanup functions can be registered.
When the registration is successful, Py AtExit() returns 0; on failure, it returns -1. The cleanup
function registered last is called first. Each cleanup function will be called at most once. Since
Python’s internal finallization will have completed before the cleanup function, no Python APIs
should be called by func.
20 Chapter 5. Utilities
reference to the module object, or NULL with an exception set if an error occurred (the module may
still be created in this case). (This function would reload the module if it was already imported.)
long PyImport GetMagicNumber()
Return the magic number for Python bytecode files (a.k.a. ‘.pyc’ and ‘.pyo’ files). The magic number
should be present in the first four bytes of the bytecode file, in little-endian byte order.
PyObject* PyImport GetModuleDict()
Return value: Borrowed reference.
Return the dictionary used for the module administration (a.k.a. sys.modules). Note that this is
a per-interpreter variable.
void PyImport Init()
Initialize the import mechanism. For internal use only.
void PyImport Cleanup()
Empty the module table. For internal use only.
void PyImport Fini()
Finalize the import mechanism. For internal use only.
PyObject* PyImport FindExtension(char *, char * )
For internal use only.
PyObject* PyImport FixupExtension(char *, char * )
For internal use only.
int PyImport ImportFrozenModule(char *name)
Load a frozen module named name. Return 1 for success, 0 if the module is not found, and -1 with
an exception set if the initialization failed. To access the imported module on a successful load,
use PyImport ImportModule(). (Note the misnomer — this function would reload the module if
it was already imported.)
struct frozen
This is the structure type definition for frozen module descriptors, as generated by the freeze utility
(see ‘Tools/freeze/’ in the Python source distribution). Its definition, found in ‘Include/import.h’, is:
struct _frozen {
char *name;
unsigned char *code;
int size;
};
struct frozen* PyImport FrozenModules
This pointer is initialized to point to an array of struct frozen records, terminated by one
whose members are all NULL or zero. When a frozen module is imported, it is searched in this
table. Third-party code could play tricks with this to provide a dynamically created collection of
frozen modules.
int PyImport AppendInittab(char *name, void (*initfunc)(void))
Add a single module to the existing table of built-in modules. This is a convenience wrapper around
PyImport ExtendInittab(), returning -1 if the table could not be extended. The new module
can be imported by the name name, and uses the function initfunc as the initialization function
called on the first attempted import. This should be called before Py Initialize().
struct inittab
Structure describing a single entry in the list of built-in modules. Each of these structures gives the
name and initialization function for a module built into the interpreter. Programs which embed
Python may use an array of these structures in conjunction with PyImport ExtendInittab() to
provide additional built-in modules. The structure is defined in ‘Include/import.h’ as:
struct _inittab {
char *name;
void (*initfunc)(void);
22 Chapter 5. Utilities
Return a Python object from the data stream in a character buffer containing len bytes pointed to
by string. On error, sets the appropriate exception (EOFError or TypeError) and returns NULL.
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
PyObject *result = NULL;
24 Chapter 5. Utilities
CHAPTER
SIX
The functions in this chapter interact with Python objects regardless of their type, or with wide classes
of object types (e.g. all numerical types, or all sequence types). When used on object types for which
they do not apply, they will raise a Python exception.
25
This is the equivalent of the Python statement ‘result = cmp(o1 , o2 )’.
int PyObject Compare(PyObject *o1, PyObject *o2 )
Compare the values of o1 and o2 using a routine provided by o1 , if one exists, otherwise with
a routine provided by o2 . Returns the result of the comparison on success. On error, the value
returned is undefined; use PyErr Occurred() to detect an error. This is equivalent to the Python
expression ‘cmp(o1 , o2 )’.
PyObject* PyObject Repr(PyObject *o)
Return value: New reference.
Compute a string representation of object o. Returns the string representation on success, NULL on
failure. This is the equivalent of the Python expression ‘repr(o)’. Called by the repr() built-in
function and by reverse quotes.
PyObject* PyObject Str(PyObject *o)
Return value: New reference.
Compute a string representation of object o. Returns the string representation on success, NULL
on failure. This is the equivalent of the Python expression ‘str(o)’. Called by the str() built-in
function and by the print statement.
PyObject* PyObject Unicode(PyObject *o)
Return value: New reference.
Compute a Unicode string representation of object o. Returns the Unicode string representation
on success, NULL on failure. This is the equivalent of the Python expression ‘unistr(o)’. Called
by the unistr() built-in function.
int PyObject IsInstance(PyObject *inst, PyObject *cls)
Return 1 if inst is an instance of the class cls or a subclass of cls. If cls is a type object rather
than a class object, PyObject IsInstance() returns 1 if inst is of type cls. If inst is not a class
instance and cls is neither a type object or class object, inst must have a class attribute —
the class relationship of the value of that attribute with cls will be used to determine the result of
this function. New in version 2.1.
Subclass determination is done in a fairly straightforward way, but includes a wrinkle that implementors
of extensions to the class system may want to be aware of. If A and B are class objects, B is a subclass of A
if it inherits from A either directly or indirectly. If either is not a class object, a more general mechanism
is used to determine the class relationship of the two objects. When testing if B is a subclass of A, if A is
B , PyObject IsSubclass() returns true. If A and B are different objects, B ’s bases attribute is
searched in a depth-first fashion for A — the presence of the bases attribute is considered sufficient
for this determination.
int PyObject IsSubclass(PyObject *derived, PyObject *cls)
Returns 1 if the class derived is identical to or derived from the class cls, otherwise returns 0. In
case of an error, returns -1. If either derived or cls is not an actual class object, this function uses
the generic algorithm described above. New in version 2.1.
int PyCallable Check(PyObject *o)
Determine if the object o is callable. Return 1 if the object is callable and 0 otherwise. This
function always succeeds.
PyObject* PyObject CallObject(PyObject *callable object, PyObject *args)
Return value: New reference.
Call a callable Python object callable object, with arguments given by the tuple args. If no argu-
ments are needed, then args may be NULL. Returns the result of the call on success, or NULL
on failure. This is the equivalent of the Python expression ‘apply(callable object, args)’ or
‘callable object(*args)’.
PyObject* PyObject CallFunction(PyObject *callable, char *format, ...)
Return value: New reference.
Call a callable Python object callable, with a variable number of C arguments. The C arguments
are described using a Py BuildValue() style format string. The format may be NULL, indicating
that no arguments are provided. Returns the result of the call on success, or NULL on failure. This
is the equivalent of the Python expression ‘apply(callable, args)’ or ‘callable(*args)’.
if (iterator == NULL) {
/* propagate error */
}
Py_DECREF(iterator);
if (PyErr_Occurred()) {
/* propagate error */
}
else {
/* continue doing useful work */
}
SEVEN
The functions in this chapter are specific to certain Python object types. Passing them an object of the
wrong type is not a good idea; if you receive an object from a Python program and you are not sure
that it has the right type, you must perform a type check first; for example, to check that an object is
a dictionary, use PyDict Check(). The chapter is structured like the “family tree” of Python object
types.
Warning: While the functions described in this chapter carefully check the type of the objects which
are passed in, many of them do not check for NULL being passed instead of a valid object. Allowing NULL
to be passed in can cause memory access violations and immediate termination of the interpreter.
PyTypeObject
The C structure of the objects used to describe built-in types.
PyObject* PyType Type
This is the type object for type objects; it is the same object as types.TypeType in the Python
layer.
int PyType Check(PyObject *o)
Returns true is the object o is a type object.
int PyType HasFeature(PyObject *o, int feature)
Returns true if the type object o sets the feature feature. Type features are denoted by single bit
flags.
int PyType IsSubtype(PyTypeObject *a, PyTypeObject *b)
Returns true if a is a subtype of b. New in version 2.2.
PyObject* PyType GenericAlloc(PyTypeObject *type, int nitems)
Return value: New reference.
New in version 2.2.
PyObject* PyType GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
Return value: New reference.
New in version 2.2.
int PyType Ready(PyTypeObject *type)
New in version 2.2.
35
7.1.2 The None Object
Note that the PyTypeObject for None is not directly exposed in the Python/C API. Since None is a
singleton, testing for object identity (using ‘==’ in C) is sufficient. There is no PyNone Check() function
for the same reason.
PyObject* Py None
The Python None object, denoting lack of value. This object has no methods. It needs to be
treated just like any other object with respect to reference counts.
PyIntObject
This subtype of PyObject represents a Python integer object.
PyTypeObject PyInt Type
This instance of PyTypeObject represents the Python plain integer type. This is the same object
as types.IntType.
int PyInt Check(PyObject* o)
Returns true if o is of type PyInt Type or a subtype of PyInt Type. Changed in version 2.2:
Allowed subtypes to be accepted.
int PyInt CheckExact(PyObject* o)
Returns true if o is of type PyInt Type, but not a subtype of PyInt Type. New in version 2.2.
PyObject* PyInt FromLong(long ival )
Return value: New reference.
Creates a new integer object with a value of ival .
The current implementation keeps an array of integer objects for all integers between -1 and 100,
when you create an int in that range you actually just get back a reference to the existing object.
So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is
undefined. :-)
long PyInt AsLong(PyObject *io)
Will first attempt to cast the object to a PyIntObject, if it is not already one, and then return its
value.
long PyInt AS LONG(PyObject *io)
Returns the value of the object io. No error checking is performed.
long PyInt GetMax()
Returns the system’s idea of the largest integer it can handle (LONG MAX, as defined in the system
header files).
PyLongObject
This subtype of PyObject represents a Python long integer object.
PyTypeObject PyLong Type
This instance of PyTypeObject represents the Python long integer type. This is the same object
as types.LongType.
int PyLong Check(PyObject *p)
Returns true if its argument is a PyLongObject or a subtype of PyLongObject. Changed in
version 2.2: Allowed subtypes to be accepted.
int PyLong CheckExact(PyObject *p)
PyFloatObject
This subtype of PyObject represents a Python floating point object.
PyTypeObject PyFloat Type
This instance of PyTypeObject represents the Python floating point type. This is the same object
as types.FloatType.
int PyFloat Check(PyObject *p)
Returns true if its argument is a PyFloatObject or a subtype of PyFloatObject. Changed in
version 2.2: Allowed subtypes to be accepted.
int PyFloat CheckExact(PyObject *p)
Returns true if its argument is a PyFloatObject, but not a subtype of PyFloatObject. New in
version 2.2.
PyObject* PyFloat FromDouble(double v )
Return value: New reference.
Creates a PyFloatObject object from v , or NULL on failure.
double PyFloat AsDouble(PyObject *pyfloat)
Returns a C double representation of the contents of pyfloat.
double PyFloat AS DOUBLE(PyObject *pyfloat)
Returns a C double representation of the contents of pyfloat, but without error checking.
Python’s complex number objects are implemented as two distinct types when viewed from the C API:
one is the Python object exposed to Python programs, and the other is a C structure which represents
the actual complex number value. The API provides functions for working with both.
Note that the functions which accept these structures as parameters and return them as results do so by
value rather than dereferencing them through pointers. This is consistent throughout the API.
Py complex
The C structure which corresponds to the value portion of a Python complex number object. Most
of the functions for dealing with complex number objects use structures of this type as input or
output values, as appropriate. It is defined as:
typedef struct {
double real;
double imag;
} Py_complex;
Py complex Py c sum(Py complex left, Py complex right)
Return the sum of two complex numbers, using the C Py complex representation.
Py complex Py c diff(Py complex left, Py complex right)
Return the difference between two complex numbers, using the C Py complex representation.
Py complex Py c neg(Py complex complex )
Return the negation of the complex number complex , using the C Py complex representation.
PyComplexObject
This subtype of PyObject represents a Python complex number object.
PyTypeObject PyComplex Type
This instance of PyTypeObject represents the Python complex number type.
int PyComplex Check(PyObject *p)
Returns true if its argument is a PyComplexObject or a subtype of PyComplexObject. Changed
in version 2.2: Allowed subtypes to be accepted.
int PyComplex CheckExact(PyObject *p)
Returns true if its argument is a PyComplexObject, but not a subtype of PyComplexObject. New
in version 2.2.
PyObject* PyComplex FromCComplex(Py complex v )
Return value: New reference.
Create a new Python complex number object from a C Py complex value.
PyObject* PyComplex FromDoubles(double real, double imag)
Return value: New reference.
Returns a new PyComplexObject object from real and imag.
double PyComplex RealAsDouble(PyObject *op)
Returns the real part of op as a C double.
double PyComplex ImagAsDouble(PyObject *op)
Returns the imaginary part of op as a C double.
Py complex PyComplex AsCComplex(PyObject *op)
Returns the Py complex value of the complex number op.
These functions raise TypeError when expecting a string parameter and are called with a non-string
parameter.
PyStringObject
This subtype of PyObject represents a Python string object.
PyTypeObject PyString Type
This instance of PyTypeObject represents the Python string type; it is the same object as
types.TypeType in the Python layer. .
int PyString Check(PyObject *o)
Returns true if the object o is a string object or an instance of a subtype of the string type.
Changed in version 2.2: Allowed subtypes to be accepted.
These are the basic Unicode object types used for the Unicode implementation in Python:
Py UNICODE
1.Unicode objects are passed back as-is with incremented refcount. Note: These cannot be
decoded; passing a non-NULL value for encoding will result in a TypeError.
2.String and other char buffer compatible objects are decoded according to the given encoding
and using the error handling defined by errors. Both can be NULL to have the interface use
the default values (see the next section for details).
3.All other objects cause an exception.
The API returns NULL if there was an error. The caller is responsible for decref’ing the returned
objects.
PyObject* PyUnicode FromObject(PyObject *obj )
Return value: New reference.
Shortcut for PyUnicode FromEncodedObject(obj, NULL, "strict") which is used throughout
the interpreter whenever coercion to Unicode is needed.
If the platform supports wchar t and provides a header file wchar.h, Python can interface directly to this
type using the following functions. Support is optimized if Python’s own Py UNICODE type is identical
to the system’s wchar t.
Built-in Codecs
Python provides a set of builtin codecs which are written in C for speed. All of these codecs are directly
usable via the following functions.
Many of the following APIs take two arguments encoding and errors. These parameters encoding and
errors have the same semantics as the ones of the builtin unicode() Unicode object constructor.
Setting encoding to NULL causes the default encoding to be used which is ascii. The file system calls
should use Py FileSystemDefaultEncoding as the encoding for file names. This variable should be
treated as read-only: On some systems, it will be a pointer to a static string, on others, it will change
at run-time, e.g. when the application invokes setlocale.
Error handling is set by errors which may also be set to NULL meaning to use the default handling defined
for the codec. Default error handling for all builtin codecs is “strict” (ValueError is raised).
The codecs all use a similar interface. Only deviation from the following generic ones are documented
for simplicity.
These are the generic codec APIs:
PyObject* PyUnicode Decode(const char *s, int size, const char *encoding, const char *errors)
Return value: New reference.
Create a Unicode object by decoding size bytes of the encoded string s. encoding and errors have
the same meaning as the parameters of the same name in the unicode() builtin function. The
codec to be used is looked up using the Python codec registry. Returns NULL if an exception was
raised by the codec.
PyObject* PyUnicode Encode(const Py UNICODE *s, int size, const char *encoding, const char *errors)
Return value: New reference.
Encodes the Py UNICODE buffer of the given size and returns a Python string object. encoding
and errors have the same meaning as the parameters of the same name in the Unicode encode()
method. The codec to be used is looked up using the Python codec registry. Returns NULL if an
exception was raised by the codec.
PyObject* PyUnicode AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)
Return value: New reference.
Encodes a Unicode object and returns the result as Python string object. encoding and errors
have the same meaning as the parameters of the same name in the Unicode encode() method.
The codec to be used is looked up using the Python codec registry. Returns NULL if an exception
was raised by the codec.
These are the UTF-8 codec APIs:
PyObject* PyUnicode DecodeUTF8(const char *s, int size, const char *errors)
Return value: New reference.
Creates a Unicode object by decoding size bytes of the UTF-8 encoded string s. Returns NULL if
an exception was raised by the codec.
PyObject* PyUnicode EncodeUTF8(const Py UNICODE *s, int size, const char *errors)
Return value: New reference.
Encodes the Py UNICODE buffer of the given size using UTF-8 and returns a Python string object.
Returns NULL if an exception was raised by the codec.
PyObject* PyUnicode AsUTF8String(PyObject *unicode)
Return value: New reference.
The following APIs are capable of handling Unicode objects and strings on input (we refer to them as
strings in the descriptions) and return Unicode objects or integers as apporpriate.
They all return NULL or -1 if an exception occurs.
PyObject* PyUnicode Concat(PyObject *left, PyObject *right)
Return value: New reference.
Concat two strings giving a new Unicode string.
PyObject* PyUnicode Split(PyObject *s, PyObject *sep, int maxsplit)
Return value: New reference.
Split a string giving a list of Unicode strings. If sep is NULL, splitting will be done at all whitespace
substrings. Otherwise, splits occur at the given separator. At most maxsplit splits will be done. If
negative, no limit is set. Separators are not included in the resulting list.
PyObject* PyUnicode Splitlines(PyObject *s, int maxsplit)
Python objects implemented in C can export a group of functions called the “buffer interface.” These
functions can be used by an object to expose its data in a raw, byte-oriented format. Clients of the
object can use the buffer interface to access the object data directly, without needing to copy it first.
Two examples of objects that support the buffer interface are strings and arrays. The string object
exposes the character contents in the buffer interface’s byte-oriented form. An array can also expose its
contents, but it should be noted that array elements may be multi-byte values.
An example user of the buffer interface is the file object’s write() method. Any object that can export
PyTupleObject
This subtype of PyObject represents a Python tuple object.
PyTypeObject PyTuple Type
This instance of PyTypeObject represents the Python tuple type; it is the same object as
types.TupleType in the Python layer..
int PyTuple Check(PyObject *p)
Return true if p is a tuple object or an instance of a subtype of the tuple type. Changed in version
2.2: Allowed subtypes to be accepted.
int PyTuple CheckExact(PyObject *p)
Return true if p is a tuple object, but not an instance of a subtype of the tuple type. New in
version 2.2.
PyObject* PyTuple New(int len)
Return value: New reference.
Return a new tuple object of size len, or NULL on failure.
int PyTuple Size(PyObject *p)
Takes a pointer to a tuple object, and returns the size of that tuple.
int PyTuple GET SIZE(PyObject *p)
Return the size of the tuple p, which must be non-NULL and point to a tuple; no error checking is
performed.
PyObject* PyTuple GetItem(PyObject *p, int pos)
Return value: Borrowed reference.
Returns the object at position pos in the tuple pointed to by p. If pos is out of bounds, returns
NULL and sets an IndexError exception.
PyObject* PyTuple GET ITEM(PyObject *p, int pos)
Return value: Borrowed reference.
Like PyTuple GetItem(), but does no checking of its arguments.
PyObject* PyTuple GetSlice(PyObject *p, int low, int high)
Return value: New reference.
Takes a slice of the tuple pointed to by p from low to high and returns it as a new tuple.
int PyTuple SetItem(PyObject *p, int pos, PyObject *o)
Inserts a reference to object o at position pos of the tuple pointed to by p. It returns 0 on success.
Note: This function “steals” a reference to o.
void PyTuple SET ITEM(PyObject *p, int pos, PyObject *o)
Like PyTuple SetItem(), but does no error checking, and should only be used to fill in brand new
tuples. Note: This function “steals” a reference to o.
int PyTuple Resize(PyObject **p, int newsize)
Can be used to resize a tuple. newsize will be the new length of the tuple. Because tuples are
supposed to be immutable, this should only be used if there is only one reference to the object. Do
not use this if the tuple may already be known to some other part of the code. The tuple will always
grow or shrink at the end. Think of this as destroying the old tuple and creating a new one, only
more efficiently. Returns 0 on success. Client code should never assume that the resulting value
of *p will be the same as before calling this function. If the object referenced by *p is replaced,
the original *p is destroyed. On failure, returns -1 and sets *p to NULL, and raises MemoryError
or SystemError. Changed in version 2.2: Removed unused third parameter, last is sticky.
PyListObject
This subtype of PyObject represents a Python list object.
PyTypeObject PyList Type
This instance of PyTypeObject represents the Python list type. This is the same object as
types.ListType.
int PyList Check(PyObject *p)
Returns true if its argument is a PyListObject.
PyObject* PyList New(int len)
Return value: New reference.
Returns a new list of length len on success, or NULL on failure.
int PyList Size(PyObject *list)
Returns the length of the list object in list; this is equivalent to ‘len(list)’ on a list object.
int PyList GET SIZE(PyObject *list)
Macro form of PyList Size() without error checking.
PyObject* PyList GetItem(PyObject *list, int index )
Return value: Borrowed reference.
Returns the object at position pos in the list pointed to by p. If pos is out of bounds, returns NULL
and sets an IndexError exception.
PyObject* PyList GET ITEM(PyObject *list, int i )
Return value: Borrowed reference.
Macro form of PyList GetItem() without error checking.
int PyList SetItem(PyObject *list, int index, PyObject *item)
Sets the item at index index in list to item. Returns 0 on success or -1 on failure. Note: This
function “steals” a reference to item and discards a reference to an item already in the list at the
affected position.
void PyList SET ITEM(PyObject *list, int i, PyObject *o)
Macro form of PyList SetItem() without error checking. This is normally only used to fill in
new lists where there is no previous content. Note: This function “steals” a reference to item,
and, unlike PyList SetItem(), does not discard a reference to any item that it being replaced;
any reference in list at position i will be leaked.
int PyList Insert(PyObject *list, int index, PyObject *item)
Inserts the item item into list list in front of index index . Returns 0 if successful; returns -1 and
raises an exception if unsuccessful. Analogous to list.insert(index , item).
int PyList Append(PyObject *list, PyObject *item)
Appends the object item at the end of list list. Returns 0 if successful; returns -1 and sets an
exception if unsuccessful. Analogous to list.append(item).
PyObject* PyList GetSlice(PyObject *list, int low, int high)
Return value: New reference.
Returns a list of the objects in list containing the objects between low and high. Returns NULL and
sets an exception if unsuccessful. Analogous to list[low :high].
int PyList SetSlice(PyObject *list, int low, int high, PyObject *itemlist)
Sets the slice of list between low and high to the contents of itemlist. Analogous to list[low :high]
= itemlist. Returns 0 on success, -1 on failure.
int PyList Sort(PyObject *list)
Sorts the items of list in place. Returns 0 on success, -1 on failure. This is equivalent to
‘list.sort()’.
int PyList Reverse(PyObject *list)
Reverses the items of list in place. Returns 0 on success, -1 on failure. This is the equivalent of
‘list.reverse()’.
PyDictObject
This subtype of PyObject represents a Python dictionary object.
PyTypeObject PyDict Type
This instance of PyTypeObject represents the Python dictionary type. This is exposed to Python
programs as types.DictType and types.DictionaryType.
int PyDict Check(PyObject *p)
Returns true if its argument is a PyDictObject.
PyObject* PyDict New()
Return value: New reference.
Returns a new empty dictionary, or NULL on failure.
PyObject* PyDictProxy New(PyObject *dict)
Return value: New reference.
Return a proxy object for a mapping which enforces read-only behavior. This is normally used
to create a proxy to prevent modification of the dictionary for non-dynamic class types. New in
version 2.2.
void PyDict Clear(PyObject *p)
Empties an existing dictionary of all key-value pairs.
PyObject* PyDict Copy(PyObject *p)
Return value: New reference.
Returns a new dictionary that contains the same key-value pairs as p. New in version 1.6.
int PyDict SetItem(PyObject *p, PyObject *key, PyObject *val )
Inserts value into the dictionary p with a key of key. key must be hashable; if it isn’t, TypeError
will be raised. Returns 0 on success or -1 on failure.
int PyDict SetItemString(PyObject *p, char *key, PyObject *val )
Inserts value into the dictionary p using key as a key. key should be a char*. The key object is
created using PyString FromString(key). Returns 0 on success or -1 on failure.
int PyDict DelItem(PyObject *p, PyObject *key)
Removes the entry in dictionary p with key key. key must be hashable; if it isn’t, TypeError is
raised.
int PyDict DelItemString(PyObject *p, char *key)
Removes the entry in dictionary p which has a key specified by the string key. Returns 0 on success
or -1 on failure.
PyObject* PyDict GetItem(PyObject *p, PyObject *key)
Return value: Borrowed reference.
Returns the object from dictionary p which has a key key. Returns NULL if the key key is not
present, but without setting an exception.
PyObject* PyDict GetItemString(PyObject *p, char *key)
Return value: Borrowed reference.
This is the same as PyDict GetItem(), but key is specified as a char*, rather than a PyObject*.
PyObject* PyDict Items(PyObject *p)
Return value: New reference.
Returns a PyListObject containing all the items from the dictionary, as in the dictinoary method
Python’s built-in file objects are implemented entirely on the FILE* support from the C standard library.
This is an implementation detail and may change in future releases of Python.
PyFileObject
This subtype of PyObject represents a Python file object.
PyTypeObject PyFile Type
This instance of PyTypeObject represents the Python file type. This is exposed to Python programs
as types.FileType.
int PyFile Check(PyObject *p)
Returns true if its argument is a PyFileObject or a subtype of PyFileObject. Changed in
version 2.2: Allowed subtypes to be accepted.
int PyFile CheckExact(PyObject *p)
Returns true if its argument is a PyFileObject, but not a subtype of PyFileObject. New in
version 2.2.
PyObject* PyFile FromString(char *filename, char *mode)
Return value: New reference.
On success, returns a new file object that is opened on the file given by filename, with a file mode
given by mode, where mode has the same semantics as the standard C routine fopen(). On failure,
returns NULL.
PyObject* PyFile FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE*))
Return value: New reference.
Creates a new PyFileObject from the already-open standard C file pointer, fp. The function close
will be called when the file should be closed. Returns NULL on failure.
FILE* PyFile AsFile(PyFileObject *p)
Returns the file object associated with p as a FILE*.
PyObject* PyFile GetLine(PyObject *p, int n)
Return value: New reference.
Equivalent to p.readline([n ]), this function reads one line from the object p. p may be a file
object or any object with a readline() method. If n is 0, exactly one line is read, regardless of the
length of the line. If n is greater than 0, no more than n bytes will be read from the file; a partial
line can be returned. In both cases, an empty string is returned if the end of the file is reached
immediately. If n is less than 0, however, one line is read regardless of length, but EOFError is
raised if the end of the file is reached immediately.
PyObject* PyFile Name(PyObject *p)
Return value: Borrowed reference.
Returns the name of the file specified by p as a string object.
void PyFile SetBufSize(PyFileObject *p, int n)
Available on systems with setvbuf() only. This should only be called immediately after file object
There are some useful functions that are useful for working with method objects.
PyTypeObject PyMethod Type
This instance of PyTypeObject represents the Python method type. This is exposed to Python
programs as types.MethodType.
int PyMethod Check(PyObject *o)
Return true if o is a method object (has type PyMethod Type). The parameter must not be NULL.
PyObject* PyMethod New(PyObject *func. PyObject *self, PyObject *class)
Return value: New reference.
Return a new method object, with func being any callable object; this is the function that will be
called when the method is called. If this method should be bound to an instance, self should be
the instance and class should be the class of self , otherwise self should be NULL and class should
be the class which provides the unbound method..
PyObject* PyMethod Class(PyObject *meth)
Return value: Borrowed reference.
Return the class object from which the method meth was created; if this was created from an
instance, it will be the class of the instance.
Python provides two general-purpose iterator objects. The first, a sequence iterator, works with an
arbitrary sequence supporting the getitem () method. The second works with a callable object
and a sentinel value, calling the callable for each item in the sequence, and ending the iteration when
the sentinel value is returned.
PyTypeObject PySeqIter Type
Type object for iterator objects returned by PySeqIter New() and the one-argument form of the
iter() built-in function for built-in sequence types. New in version 2.2.
int PySeqIter Check(op)
Return true if the type of op is PySeqIter Type. New in version 2.2.
PyObject* PySeqIter New(PyObject *seq)
Return value: New reference.
Return an iterator that works with a general sequence object, seq. The iteration ends when the
sequence raises IndexError for the subscripting operation. New in version 2.2.
PyTypeObject PyCallIter Type
Type object for iterator objects returned by PyCallIter New() and the two-argument form of the
iter() built-in function. New in version 2.2.
int PyCallIter Check(op)
Return true if the type of op is PyCallIter Type. New in version 2.2.
PyObject* PyCallIter New(PyObject *callable, PyObject *sentinel )
Return value: New reference.
Return a new iterator. The first parameter, callable, can be any Python callable object that can
be called with no parameters; each call to it should return the next item in the iteration. When
callable returns a value equal to sentinel , the iteration will be terminated. New in version 2.2.
“Descriptors” are objects that describe some attribute of an object. They are found in the dictionary of
type objects.
PyTypeObject PyProperty Type
The type object for the built-in descriptor types. New in version 2.2.
PyObject* PyDescr NewGetSet(PyTypeObject *type, PyGetSetDef *getset)
Return value: New reference.
New in version 2.2.
PyObject* PyDescr NewMember(PyTypeObject *type, PyMemberDef *meth)
Return value: New reference.
New in version 2.2.
PyObject* PyDescr NewMethod(PyTypeObject *type, PyMethodDef *meth)
Return value: New reference.
New in version 2.2.
PyObject* PyDescr NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped )
Return value: New reference.
New in version 2.2.
int PyDescr IsData(PyObject *descr )
Returns true if the descriptor objects descr describes a data attribute, or false if it describes a
method. descr must be a descriptor object; there is no error checking. New in version 2.2.
Python supports weak references as first-class objects. There are two specific object types which directly
implement weak references. The first is a simple reference object, and the second acts as a proxy for the
original object as much as it can.
int PyWeakref Check(ob)
Return true if ob is either a reference or proxy object. New in version 2.2.
int PyWeakref CheckRef(ob)
Return true if ob is a reference object. New in version 2.2.
int PyWeakref CheckProxy(ob)
Return true if ob is a proxy object. New in version 2.2.
PyObject* PyWeakref NewRef(PyObject *ob, PyObject *callback )
Return value: New reference.
Return a weak reference object for the object ob. This will always return a new reference, but is
not guaranteed to create a new object; an existing reference object may be returned. The second
parameter, callback , can be a callable object that receives notification when ob is garbage collected;
it should accept a single paramter, which will be the weak reference object itself. callback may also
be None or NULL. If ob is not a weakly-referencable object, or if callback is not callable, None, or
NULL, this will return NULL and raise TypeError. New in version 2.2.
PyObject* PyWeakref NewProxy(PyObject *ob, PyObject *callback )
Return value: New reference.
Return a weak reference proxy object for the object ob. This will always return a new reference,
but is not guaranteed to create a new object; an existing proxy object may be returned. The
second parameter, callback , can be a callable object that receives notification when ob is garbage
collected; it should accept a single paramter, which will be the weak reference object itself. callback
may also be None or NULL. If ob is not a weakly-referencable object, or if callback is not callable,
None, or NULL, this will return NULL and raise TypeError. New in version 2.2.
PyObject* PyWeakref GetObject(PyObject *ref )
Return value: Borrowed reference.
Returns the referenced object from a weak reference, ref . If the referent is no longer live, returns
NULL. New in version 2.2.
PyObject* PyWeakref GET OBJECT(PyObject *ref )
Return value: Borrowed reference.
Similar to PyWeakref GetObject(), but implemented as a macro that does no error checking.
7.5.9 CObjects
Refer to Extending and Embedding the Python Interpreter, section 1.12, “Providing a C API for an
Extension Module,” for more information on using these objects.
PyCObject
This subtype of PyObject represents an opaque value, useful for C extension modules who need
to pass an opaque value (as a void* pointer) through Python code to other C code. It is often
used to make a C function pointer defined in one module available to other modules, so the regular
import mechanism can be used to access C APIs defined in dynamically loaded modules.
int PyCObject Check(PyObject *p)
Returns true if its argument is a PyCObject.
PyObject* PyCObject FromVoidPtr(void* cobj, void (*destr)(void *))
Return value: New reference.
Creates a PyCObject from the void *cobj . The destr function will be called when the object is
reclaimed, unless it is NULL.
PyObject* PyCObject FromVoidPtrAndDesc(void* cobj, void* desc, void (*destr)(void *, void *))
Return value: New reference.
Creates a PyCObject from the void *cobj . The destr function will be called when the object is
reclaimed. The desc argument can be used to pass extra callback data for the destructor function.
void* PyCObject AsVoidPtr(PyObject* self )
Returns the object void * that the PyCObject self was created with.
void* PyCObject GetDesc(PyObject* self )
Returns the description void * that the PyCObject self was created with.
“Cell” objects are used to implement variables referenced by multiple scopes. For each such variable,
a cell object is created to store the value; the local variables of each stack frame that references the
value contains a reference to the cells from outer scopes which also use that variable. When the value
is accessed, the value contained in the cell is used instead of the cell object itself. This de-referencing of
the cell object requires support from the generated byte-code; these are not automatically de-referenced
when accessed. Cell objects are not likely to be useful elsewhere.
PyCellObject
The C structure used for cell objects.
PyTypeObject PyCell Type
The type object corresponding to cell objects
int PyCell Check(ob)
Return true if ob is a cell object; ob must not be NULL.
PyObject* PyCell New(PyObject *ob)
Return value: New reference.
Create and return a new cell object containing the value ob. The parameter may be NULL.
PyObject* PyCell Get(PyObject *cell )
Return value: New reference.
Return the contents of the cell cell .
PyObject* PyCell GET(PyObject *cell )
Return value: Borrowed reference.
Return the contents of the cell cell , but without checking that cell is non-NULL and a call object.
int PyCell Set(PyObject *cell, PyObject *value)
EIGHT
void Py Initialize()
Initialize the Python interpreter. In an application embedding Python, this should be called
before using any other Python/C API functions; with the exception of Py SetProgramName(),
PyEval InitThreads(), PyEval ReleaseLock(), and PyEval AcquireLock(). This initializes
the table of loaded modules (sys.modules), and creates the fundamental modules builtin ,
main and sys. It also initializes the module search path (sys.path). It does not set sys.argv;
use PySys SetArgv() for that. This is a no-op when called for a second time (without calling
Py Finalize() first). There is no return value; it is a fatal error if the initialization fails.
int Py IsInitialized()
Return true (nonzero) when the Python interpreter has been initialized, false (zero) if not. After
Py Finalize() is called, this returns false until Py Initialize() is called again.
void Py Finalize()
Undo all initializations made by Py Initialize() and subsequent use of Python/C API func-
tions, and destroy all sub-interpreters (see Py NewInterpreter() below) that were created and
not yet destroyed since the last call to Py Initialize(). Ideally, this frees all memory allo-
cated by the Python interpreter. This is a no-op when called for a second time (without calling
Py Initialize() again first). There is no return value; errors during finalization are ignored.
This function is provided for a number of reasons. An embedding application might want to restart
Python without having to restart the application itself. An application that has loaded the Python
interpreter from a dynamically loadable library (or DLL) might want to free all memory allocated
by Python before unloading the DLL. During a hunt for memory leaks in an application a developer
might want to free all memory allocated by Python before exiting from the application.
Bugs and caveats: The destruction of modules and objects in modules is done in random order;
this may cause destructors ( del () methods) to fail when they depend on other objects
(even functions) or modules. Dynamically loaded extension modules loaded by Python are not
unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you
find a leak, please report it). Memory tied up in circular references between objects is not freed.
Some memory allocated by extension modules may not be freed. Some extension may not work
properly if their initialization routine is called more than once; this can happen if an applcation
calls Py Initialize() and Py Finalize() more than once.
PyThreadState* Py NewInterpreter()
Create a new sub-interpreter. This is an (almost) totally separate environment for the execution of
Python code. In particular, the new interpreter has separate, independent versions of all imported
modules, including the fundamental modules builtin , main and sys. The table of
loaded modules (sys.modules) and the module search path (sys.path) are also separate. The new
environment has no sys.argv variable. It has new standard I/O stream file objects sys.stdin,
sys.stdout and sys.stderr (however these refer to the same underlying FILE structures in the
C library).
The return value points to the first thread state created in the new sub-interpreter. This thread
state is made the current thread state. Note that no actual thread is created; see the discussion
of thread states below. If creation of the new interpreter is unsuccessful, NULL is returned; no
exception is set since the exception state is stored in the current thread state and there may not be
61
a current thread state. (Like all other Python/C API functions, the global interpreter lock must
be held before calling this function and is still held when it returns; however, unlike most other
Python/C API functions, there needn’t be a current thread state on entry.)
Extension modules are shared between (sub-)interpreters as follows: the first time a particular
extension is imported, it is initialized normally, and a (shallow) copy of its module’s dictionary is
squirreled away. When the same extension is imported by another (sub-)interpreter, a new module
is initialized and filled with the contents of this copy; the extension’s init function is not called.
Note that this is different from what happens when an extension is imported after the interpreter
has been completely re-initialized by calling Py Finalize() and Py Initialize(); in that case,
the extension’s initmodule function is called again.
Bugs and caveats: Because sub-interpreters (and the main interpreter) are part of the same
process, the insulation between them isn’t perfect — for example, using low-level file operations
like os.close() they can (accidentally or maliciously) affect each other’s open files. Because of
the way extensions are shared between (sub-)interpreters, some extensions may not work properly;
this is especially likely when the extension makes use of (static) global variables, or when the
extension manipulates its module’s dictionary after its initialization. It is possible to insert objects
created in one sub-interpreter into a namespace of another sub-interpreter; this should be done
with great care to avoid sharing user-defined functions, methods, instances or classes between
sub-interpreters, since import operations executed by such objects may affect the wrong (sub-
)interpreter’s dictionary of loaded modules. (XXX This is a hard-to-fix bug that will be addressed
in a future release.)
void Py EndInterpreter(PyThreadState *tstate)
Destroy the (sub-)interpreter represented by the given thread state. The given thread state must
be the current thread state. See the discussion of thread states below. When the call returns,
the current thread state is NULL. All thread states associated with this interpreted are destroyed.
(The global interpreter lock must be held before calling this function and is still held when it
returns.) Py Finalize() will destroy all sub-interpreters that haven’t been explicitly destroyed
at that point.
void Py SetProgramName(char *name)
This function should be called before Py Initialize() is called for the first time, if it is called
at all. It tells the interpreter the value of the argv[0] argument to the main() function of the
program. This is used by Py GetPath() and some other functions below to find the Python run-
time libraries relative to the interpreter executable. The default value is ’python’. The argument
should point to a zero-terminated character string in static storage whose contents will not change
for the duration of the program’s execution. No code in the Python interpreter will change the
contents of this storage.
char* Py GetProgramName()
Return the program name set with Py SetProgramName(), or the default. The returned string
points into static storage; the caller should not modify its value.
char* Py GetPrefix()
Return the prefix for installed platform-independent files. This is derived through a number of com-
plicated rules from the program name set with Py SetProgramName() and some environment vari-
ables; for example, if the program name is ’/usr/local/bin/python’, the prefix is ’/usr/local’.
The returned string points into static storage; the caller should not modify its value. This corre-
sponds to the prefix variable in the top-level ‘Makefile’ and the --prefix argument to the configure
script at build time. The value is available to Python code as sys.prefix. It is only useful on
Unix. See also the next function.
char* Py GetExecPrefix()
Return the exec-prefix for installed platform-dependent files. This is derived through a number
of complicated rules from the program name set with Py SetProgramName() and some environ-
ment variables; for example, if the program name is ’/usr/local/bin/python’, the exec-prefix
is ’/usr/local’. The returned string points into static storage; the caller should not modify
its value. This corresponds to the exec prefix variable in the top-level ‘Makefile’ and the --exec-
prefix argument to the configure script at build time. The value is available to Python code as
sys.exec prefix. It is only useful on Unix.
"[GCC 2.7.2.2]"
63
The returned string points into static storage; the caller should not modify its value. The value is
available to Python code as part of the variable sys.version.
const char* Py GetBuildInfo()
Return information about the sequence number and build date and time of the current Python
interpreter instance, for example
Py_BEGIN_ALLOW_THREADS
...Do some blocking I/O operation...
Py_END_ALLOW_THREADS
PyThreadState *_save;
_save = PyEval_SaveThread();
...Do some blocking I/O operation...
PyEval_RestoreThread(_save);
Using even lower level primitives, we can get roughly the same effect as follows:
PyThreadState *_save;
_save = PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
...Do some blocking I/O operation...
PyEval_AcquireLock();
PyThreadState_Swap(_save);
There are some subtle differences; in particular, PyEval RestoreThread() saves and restores the value
of the global variable errno, since the lock manipulation does not guarantee that errno is left alone.
Also, when thread support is disabled, PyEval SaveThread() and PyEval RestoreThread() don’t
manipulate the lock; in this case, PyEval ReleaseLock() and PyEval AcquireLock() are not available.
This is done so that dynamically loaded extensions compiled with thread support enabled can be loaded
by an interpreter that was compiled with disabled thread support.
The global interpreter lock is used to protect the pointer to the current thread state. When releasing
the lock and saving the thread state, the current thread state pointer must be retrieved before the lock
is released (since another thread could immediately acquire the lock and store its own thread state in
the global variable). Conversely, when acquiring the lock and restoring the thread state, the lock must
be acquired before storing the thread state pointer.
Why am I going on with so much detail about this? Because when threads are created from C, they
don’t have the global interpreter lock, nor is there a thread state data structure for them. Such threads
must bootstrap themselves into existence, by first creating a thread state data structure, then acquiring
the lock, and finally storing their thread state pointer, before they can start using the Python/C API.
When they are done, they should reset the thread state pointer, release the lock, and finally free their
thread state data structure.
When creating a thread data structure, you need to provide an interpreter state data structure. The
interpreter state data structure hold global data that is shared by all threads in an interpreter, for
example the module administration (sys.modules). Depending on your needs, you can either create a
new interpreter state data structure, or share the interpreter state data structure used by the Python
main thread (to access the latter, you must obtain the thread state and access its interp member; this
must be done by a thread that is created by Python or by the main thread after Python is initialized).
PyInterpreterState
This data structure represents the state shared by a number of cooperating threads. Threads
belonging to the same interpreter share their module administration and a few other internal
items. There are no public members in this structure.
Threads belonging to different interpreters initially share nothing, except process state like available
memory, open file descriptors and such. The global interpreter lock is also shared by all threads,
regardless of to which interpreter they belong.
PyThreadState
This data structure represents the state of a single thread. The only public data member is
PyInterpreterState *interp, which points to this thread’s interpreter state.
NINE
Memory Management
9.1 Overview
Memory management in Python involves a private heap containing all Python objects and data struc-
tures. The management of this private heap is ensured internally by the Python memory manager. The
Python memory manager has different components which deal with various dynamic storage management
aspects, like sharing, segmentation, preallocation or caching.
At the lowest level, a raw memory allocator ensures that there is enough room in the private heap
for storing all Python-related data by interacting with the memory manager of the operating system.
On top of the raw memory allocator, several object-specific allocators operate on the same heap and
implement distinct memory management policies adapted to the peculiarities of every object type. For
example, integer objects are managed differently within the heap than strings, tuples or dictionaries
because integers imply different storage requirements and speed/space tradeoffs. The Python memory
manager thus delegates some of the work to the object-specific allocators, but ensures that the latter
operate within the bounds of the private heap.
It is important to understand that the management of the Python heap is performed by the interpreter
itself and that the user has no control on it, even if she regularly manipulates object pointers to memory
blocks inside that heap. The allocation of heap space for Python objects and other internal buffers is
performed on demand by the Python memory manager through the Python/C API functions listed in
this document.
To avoid memory corruption, extension writers should never try to operate on Python objects with the
functions exported by the C library: malloc(), calloc(), realloc() and free(). This will result in
mixed calls between the C allocator and the Python memory manager with fatal consequences, because
they implement different algorithms and operate on different heaps. However, one may safely allocate
and release memory blocks with the C library allocator for individual purposes, as shown in the following
example:
PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyString_FromString(buf);
free(buf); /* malloc’ed */
return res;
In this example, the memory request for the I/O buffer is handled by the C library allocator. The Python
memory manager is involved only in the allocation of the string object returned as a result.
In most situations, however, it is recommended to allocate memory from the Python heap specifically
because the latter is under control of the Python memory manager. For example, this is required when
the interpreter is extended with new object types written in C. Another reason for using the Python
heap is the desire to inform the Python memory manager about the memory needs of the extension
69
module. Even when the requested memory is used exclusively for internal, highly-specific purposes,
delegating all memory requests to the Python memory manager causes the interpreter to have a more
accurate image of its memory footprint as a whole. Consequently, under certain circumstances, the
Python memory manager may or may not trigger appropriate actions, like garbage collection, memory
compaction or other preventive procedures. Note that by using the C library allocator as shown in
the previous example, the allocated memory for the I/O buffer escapes completely the Python memory
manager.
9.3 Examples
Here is the example from section 9.1, rewritten so that the I/O buffer is allocated from the Python heap
by using the first function set:
PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyString_FromString(buf);
PyMem_Del(buf); /* allocated with PyMem_New */
return res;
Note that in the two examples above, the buffer is always manipulated via functions belonging to the
same set. Indeed, it is required to use the same memory API family for a given memory block, so that
the risk of mixing different allocators is reduced to a minimum. The following code sequence contains
two errors, one of which is labeled as fatal because it mixes two different allocators operating on different
heaps.
9.3. Examples 71
72
CHAPTER
TEN
73
check type for a NULL value.
void PyObject DEL(PyObject *op)
Macro version of PyObject Del().
PyObject* Py InitModule(char *name, PyMethodDef *methods)
Return value: Borrowed reference.
Create a new module object based on a name and table of functions, returning the new module
object.
PyObject* Py InitModule3(char *name, PyMethodDef *methods, char *doc)
Return value: Borrowed reference.
Create a new module object based on a name and table of functions, returning the new module
object. If doc is non-NULL, it will be used to define the docstring for the module.
PyObject* Py InitModule4(char *name, PyMethodDef *methods, char *doc, PyObject *self, int apiver )
Return value: Borrowed reference.
Create a new module object based on a name and table of functions, returning the new module
object. If doc is non-NULL, it will be used to define the docstring for the module. If self is non-NULL,
it will passed to the functions of the module as their (otherwise NULL) first parameter. (This was
added as an experimental feature, and there are no known uses in the current version of Python.)
For apiver , the only value which should be passed is defined by the constant PYTHON API VERSION.
Note: Most uses of this function should probably be using the Py InitModule3() instead; only
use this if you are sure you need it.
DL IMPORT
PyObject Py NoneStruct
Object which is visible in Python as None. This should only be accessed using the Py None macro,
which evaluates to a pointer to this object.
1. The memory for the object must be allocated using PyObject GC New() or
PyObject GC VarNew().
2. Once all the fields which may contain references to other containers are initialized, it must call
PyObject GC Track().
1. Before fields which refer to other containers are invalidated, PyObject GC UnTrack() must be
called.
2. The object’s memory must be deallocated using PyObject GC Del().
This example shows only enough of the implementation of an extension type to show how the garbage
collector support needs to be added. It shows the definition of the object structure, the tp traverse,
tp clear and tp dealloc implementations, the type structure, and a constructor — the module ini-
tialization needed to export the constructor to Python is not shown as there are no special considerations
there for the collector. To make this interesting, assume that the module exposes ways for the container
field of the object to be modified. Note that since no checks are made on the type of the object used to
initialize container, we have to assume that it may be a container.
#include "Python.h"
typedef struct {
PyObject_HEAD
PyObject *container;
} MyObject;
static int
my_traverse(MyObject *self, visitproc visit, void *arg)
{
if (self->container != NULL)
return visit(self->container, arg);
else
return 0;
}
static int
my_clear(MyObject *self)
{
Py_XDECREF(self->container);
self->container = NULL;
return 0;
}
static void
my_dealloc(MyObject *self)
{
PyObject_GC_UnTrack((PyObject *) self);
Py_XDECREF(self->container);
PyObject_GC_Del(self);
}
Reporting Bugs
Python is a mature programming language which has established a reputation for stability. In order to
maintain this reputation, the developers would like to know of any deficiencies you find in Python or its
documentation.
Before submitting a report, you will be required to log into SourceForge; this will make it possible for
the developers to contact you for additional information if needed. It is not possible to submit a bug
report anonymously.
All bug reports should be submitted via the Python Bug Tracker on SourceForge
(http://sourceforge.net/bugs/?group id=5470). The bug tracker offers a Web form which allows per-
tinent information to be entered and submitted to the developers.
The first step in filing a report is to determine whether the problem has already been reported. The
advantage in doing so, aside from saving the developers time, is that you learn what has been done to
fix it; it may be that the problem has already been fixed for the next release, or additional information
is needed (in which case you are welcome to provide it if you can!). To do this, search the bug database
using the search box near the bottom of the page.
If the problem you’re reporting is not already in the bug tracker, go back to the Python Bug Tracker
(http://sourceforge.net/bugs/?group id=5470). Select the “Submit a Bug” link at the top of the page to
open the bug reporting form.
The submission form has a number of fields. The only fields that are required are the “Summary” and
“Details” fields. For the summary, enter a very short description of the problem; less than ten words is
good. In the Details field, describe the problem in detail, including what you expected to happen and
what did happen. Be sure to include the version of Python you used, whether any extension modules
were involved, and what hardware and software platform you were using (including version information
as appropriate).
The only other field that you may want to set is the “Category” field, which allows you to place the bug
report into a broad category (such as “Documentation” or “Library”).
Each bug report will be assigned to a developer who will determine what needs to be done to correct the
problem. You will receive an update each time action is taken on the bug.
See Also:
How to Report Bugs Effectively
(http://www-mice.cs.ucl.ac.uk/multimedia/software/documentation/ReportingBugs.html)
Article which goes into some detail about how to create a useful bug report. This describes what
kind of information is useful and why it is useful.
Bug Writing Guidelines
(http://www.mozilla.org/quality/bug-writing-guidelines.html)
Information about writing a good bug report. Some of this is specific to the Mozilla project, but
describes general good practices.
81
82
APPENDIX
Note: GPL-compatible doesn’t mean that we’re distributing Python under the GPL. All Python licenses,
unlike the GPL, let you distribute a modified version without making your changes open source. The
GPL-compatible licenses make it possible to combine Python with other software that is released under
the GPL; the others don’t.
Thanks to the many outside volunteers who have worked under Guido’s direction to make these releases
possible.
83
1. This LICENSE AGREEMENT is between the Python Software Foundation (“PSF”), and the
Individual or Organization (“Licensee”) accessing and otherwise using Python 2.2.1 software in
source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a
nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display
publicly, prepare derivative works, distribute, and otherwise use Python 2.2.1 alone or in any
derivative version, provided, however, that PSF’s License Agreement and PSF’s notice of copyright,
i.e., “Copyright
c 2001, 2002 Python Software Foundation; All Rights Reserved” are retained in
Python 2.2.1 alone or in any derivative version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on or incorporates Python 2.2.1 or
any part thereof, and wants to make the derivative work available to others as provided herein,
then Licensee hereby agrees to include in any such work a brief summary of the changes made to
Python 2.2.1.
4. PSF is making Python 2.2.1 available to Licensee on an “AS IS” basis. PSF MAKES NO REPRE-
SENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT
NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WAR-
RANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR
THAT THE USE OF PYTHON 2.2.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.2.1
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RE-
SULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.2.1, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material breach of its terms and
conditions.
7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership,
or joint venture between PSF and Licensee. This License Agreement does not grant permission
to use PSF trademarks or trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.
8. By copying, installing or otherwise using Python 2.2.1, Licensee agrees to be bound by the terms
and conditions of this License Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, hav-
ing an office at 1895 Preston White Drive, Reston, VA 20191 (“CNRI”), and the Individual or
Organization (“Licensee”) accessing and otherwise using Python 1.6.1 software in source or binary
form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee
a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or dis-
play publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in
any derivative version, provided, however, that CNRI’s License Agreement and CNRI’s notice of
copyright, i.e., “Copyright
c 1995-2001 Corporation for National Research Initiatives; All Rights
Reserved” are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee.
Alternately, in lieu of CNRI’s License Agreement, Licensee may substitute the following text (omit-
ting the quotes): “Python 1.6.1 is made available subject to the terms and conditions in CNRI’s
License Agreement. This Agreement together with Python 1.6.1 may be located on the Inter-
net using the following unique, persistent identifier (known as a handle): 1895.22/1013. This
Agreement may also be obtained from a proxy server on the Internet using the following URL:
http://hdl.handle.net/1895.22/1013.”
3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or
any part thereof, and wants to make the derivative work available to others as provided herein,
then Licensee hereby agrees to include in any such work a brief summary of the changes made to
Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an “AS IS” basis. CNRI MAKES NO
REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE
OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RE-
SULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material breach of its terms and
conditions.
7. This License Agreement shall be governed by the federal intellectual property law of the United
States, including without limitation the federal copyright law, and, to the extent such U.S. federal
law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia’s conflict of
law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python
1.6.1 that incorporate non-separable material that was previously distributed under the GNU
General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
Copyright
c 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights
reserved.
Permission to use, copy, modify, and distribute this software and its documentation for any purpose and
without fee is hereby granted, provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in supporting documentation, and that the
name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSO-
EVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CON-
NECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Symbols CObject
PyImport FindExtension(), 21 object, 59
PyImport Fini(), 21 coerce() (built-in function), 30
PyImport FixupExtension(), 21 compile() (built-in function), 20
PyImport Init(), 21 complex number
PyObject Del(), 73 object, 38
PyObject GC TRACK(), 77 copyright (in module sys), 63
PyObject GC UNTRACK(), 77
PyObject New(), 73 D
PyObject NewVar(), 73 dictionary
PyString Resize(), 41 object, 52
PyTuple Resize(), 50 DictionaryType (in module types), 52
Py NoneStruct, 74 DictType (in module types), 52
Py c diff(), 38 divmod() (built-in function), 28
Py c neg(), 38
Py c pow(), 39 E
Py c prod(), 39 environment variables
Py c quot(), 39 PATH, 7
Py c sum(), 38 PYTHONHOME, 7
all (package variable), 20 PYTHONPATH, 7
builtin (built-in module), 7, 61 exec prefix, 1, 2
dict (module attribute), 56 prefix, 1, 2
doc (module attribute), 56 EOFError (built-in exception), 54
file (module attribute), 56 errno, 65
import () (built-in function), 20 exc info() (in module sys), 5, 64
main (built-in module), 7, 61 exc traceback (in module sys), 5, 13
name (module attribute), 56 exc type (in module sys), 5, 13
exc value (in module sys), 5, 13
A Exception (built-in exception), 17
abort(), 19 exceptions (built-in module), 7
abs() (built-in function), 29 exec prefix, 1, 2
apply() (built-in function), 26 executable (in module sys), 63
argv (in module sys), 64 exit(), 20
B F
buffer file
object, 48 object, 54
buffer interface, 48 FileType (in module types), 54
BufferType (in module types), 49 float() (built-in function), 31
floating point
C object, 38
calloc(), 69 FloatType (in modules types), 38
cleanup functions, 20 fopen(), 54
close() (in module os), 62 free(), 69
cmp() (built-in function), 26 freeze utility, 21
87
G ModuleType (in module types), 56
global interpreter lock, 64
N
H None
hash() (built-in function), 27 object, 36
numeric
I object, 36
ihooks (standard module), 20
incr item(), 6, 7
O
instance object
object, 55 buffer, 48
int() (built-in function), 30 CObject, 59
getcharbufferproc (C type), 76 complex number, 38
getreadbufferproc (C type), 76 dictionary, 52
getsegcountproc (C type), 76 file, 54
getwritebufferproc (C type), 76 floating point, 38
inquiry (C type), 78 instance, 55
Py tracefunc (C type), 67 integer, 36
traverseproc (C type), 78 list, 51
visitproc (C type), 78 long integer, 36
integer mapping, 52
object, 36 method, 55
interpreter lock, 64 module, 56
IntType (in modules types), 36 None, 36
numeric, 36
K sequence, 39
string, 39
KeyboardInterrupt (built-in exception), 15
tuple, 50
L type, 2, 35
OverflowError (built-in exception), 37
len() (built-in function), 27, 31, 32, 51, 53
list P
object, 51
package variable
ListType (in module types), 51
all , 20
lock, interpreter, 64
PATH, 7
long() (built-in function), 31
path
long integer
module search, 7, 61, 63
object, 36
path (in module sys), 7, 61, 63
LONG MAX, 36, 37
platform (in module sys), 63
LongType (in modules types), 36
pow() (built-in function), 28, 30
M prefix, 1, 2
Py AtExit(), 20
main(), 62, 64 Py BEGIN ALLOW THREADS, 65
malloc(), 69 Py BEGIN ALLOW THREADS (macro), 66
mapping Py BLOCK THREADS (macro), 67
object, 52 Py BuildValue(), 24
METH KEYWORDS (data in ), 75 Py CompileString(), 10
METH NOARGS (data in ), 75 Py CompileString(), 10
METH O (data in ), 75 Py complex (C type), 38
METH OLDARGS (data in ), 75 Py DECREF(), 11
METH VARARGS (data in ), 74 Py DECREF(), 2
method Py END ALLOW THREADS, 65
object, 55 Py END ALLOW THREADS (macro), 66
MethodType (in module types), 55 Py END OF BUFFER, 49
module Py EndInterpreter(), 62
object, 56 Py eval input, 10
search path, 7, 61, 63 Py Exit(), 20
modules (in module sys), 20, 61 Py FatalError(), 19
88 Index
Py FatalError(), 64 Py XDECREF(), 7
Py FdIsInteractive(), 19 Py XINCREF(), 11
Py file input, 10 PyArg Parse(), 23
Py Finalize(), 61 PyArg ParseTuple(), 23
Py Finalize(), 20, 61, 62 PyArg ParseTupleAndKeywords(), 23
Py FindMethod(), 75 PyArg UnpackTuple(), 23
Py GetBuildInfo(), 64 PyBuffer Check(), 49
Py GetCompiler(), 63 PyBuffer FromMemory(), 49
Py GetCopyright(), 63 PyBuffer FromObject(), 49
Py GetExecPrefix(), 62 PyBuffer FromReadWriteMemory(), 49
Py GetExecPrefix(), 7 PyBuffer FromReadWriteObject(), 49
Py GetPath(), 63 PyBuffer New(), 49
Py GetPath(), 7, 62 PyBuffer Type, 49
Py GetPlatform(), 63 PyBufferObject (C type), 49
Py GetPrefix(), 62 PyBufferProcs, 49
Py GetPrefix(), 7 PyBufferProcs (C type), 76
Py GetProgramFullPath(), 63 PyCallable Check(), 26
Py GetProgramFullPath(), 7 PyCallIter Check(), 57
Py GetProgramName(), 62 PyCallIter New(), 57
Py GetVersion(), 63 PyCallIter Type, 57
Py INCREF(), 11 PyCell Check(), 59
Py INCREF(), 2 PyCell GET(), 59
Py Initialize(), 61 PyCell Get(), 59
Py Initialize(), 7, 62, 66 PyCell New(), 59
Py InitModule(), 74 PyCell SET(), 60
Py InitModule3(), 74 PyCell Set(), 59
Py InitModule4(), 74 PyCell Type, 59
Py IsInitialized(), 61 PyCellObject (C type), 59
Py IsInitialized(), 7 PyCFunction (C type), 74
Py Main(), 9 PyCObject (C type), 59
Py NewInterpreter(), 61 PyCObject AsVoidPtr(), 59
Py None, 36 PyCObject Check(), 59
Py PRINT RAW, 55 PyCObject FromVoidPtr(), 59
Py SetProgramName(), 62 PyCObject FromVoidPtrAndDesc(), 59
Py SetProgramName(), 7, 61–63 PyCObject GetDesc(), 59
Py single input, 10 PyComplex AsCComplex(), 39
Py TPFLAGS HAVE GC (data in ), 77 PyComplex Check(), 39
Py TPFLAGS HAVE GETCHARBUFFER (data in ), PyComplex CheckExact(), 39
76 PyComplex FromCComplex(), 39
Py UNBLOCK THREADS (macro), 67 PyComplex FromDoubles(), 39
Py UNICODE (C type), 41 PyComplex ImagAsDouble(), 39
Py UNICODE ISALNUM(), 42 PyComplex RealAsDouble(), 39
Py UNICODE ISALPHA(), 42 PyComplex Type, 39
Py UNICODE ISDECIMAL(), 42 PyComplexObject (C type), 39
Py UNICODE ISDIGIT(), 42 PyDescr IsData(), 57
Py UNICODE ISLINEBREAK(), 42 PyDescr NewGetSet(), 57
Py UNICODE ISLOWER(), 42 PyDescr NewMember(), 57
Py UNICODE ISNUMERIC(), 42 PyDescr NewMethod(), 57
Py UNICODE ISSPACE(), 42 PyDescr NewWrapper(), 57
Py UNICODE ISTITLE(), 42 PyDict Check(), 52
Py UNICODE ISUPPER(), 42 PyDict Clear(), 52
Py UNICODE TODECIMAL(), 43 PyDict Copy(), 52
Py UNICODE TODIGIT(), 43 PyDict DelItem(), 52
Py UNICODE TOLOWER(), 43 PyDict DelItemString(), 52
Py UNICODE TONUMERIC(), 43 PyDict GetItem(), 52
Py UNICODE TOTITLE(), 43 PyDict GetItemString(), 52
Py UNICODE TOUPPER(), 43 PyDict Items(), 52
Py XDECREF(), 11 PyDict Keys(), 53
Index 89
PyDict Merge(), 53 PyFile FromString(), 54
PyDict MergeFromSeq2(), 53 PyFile GetLine(), 54
PyDict New(), 52 PyFile Name(), 54
PyDict Next(), 53 PyFile SetBufSize(), 54
PyDict SetItem(), 52 PyFile SoftSpace(), 55
PyDict SetItemString(), 52 PyFile Type, 54
PyDict Size(), 53 PyFile WriteObject(), 55
PyDict Type, 52 PyFile WriteString(), 55
PyDict Update(), 53 PyFileObject (C type), 54
PyDict Values(), 53 PyFloat AS DOUBLE(), 38
PyDictObject (C type), 52 PyFloat AsDouble(), 38
PyDictProxy New(), 52 PyFloat Check(), 38
PyErr BadArgument(), 14 PyFloat CheckExact(), 38
PyErr BadInternalCall(), 15 PyFloat FromDouble(), 38
PyErr CheckSignals(), 15 PyFloat Type, 38
PyErr Clear(), 14 PyFloatObject (C type), 38
PyErr Clear(), 5, 7 PyImport AddModule(), 20
PyErr ExceptionMatches(), 13 PyImport AppendInittab(), 21
PyErr ExceptionMatches(), 7 PyImport Cleanup(), 21
PyErr Fetch(), 14 PyImport ExecCodeModule(), 20
PyErr Format(), 14 PyImport ExtendInittab(), 22
PyErr GivenExceptionMatches(), 13 PyImport FrozenModules, 21
PyErr NewException(), 15 PyImport GetMagicNumber(), 21
PyErr NoMemory(), 14 PyImport GetModuleDict(), 21
PyErr NormalizeException(), 13 PyImport Import(), 20
PyErr Occurred(), 13 PyImport ImportFrozenModule(), 21
PyErr Occurred(), 5 PyImport ImportModule(), 20
PyErr Print(), 13 PyImport ImportModuleEx(), 20
PyErr Restore(), 14 PyImport ReloadModule(), 20
PyErr SetFromErrno(), 14 PyInstance Check(), 55
PyErr SetFromErrnoWithFilename(), 15 PyInstance New(), 55
PyErr SetInterrupt(), 15 PyInstance NewRaw(), 55
PyErr SetNone(), 14 PyInstance Type, 55
PyErr SetObject(), 14 PyInt AS LONG(), 36
PyErr SetString(), 14 PyInt AsLong(), 36
PyErr SetString(), 5 PyInt Check(), 36
PyErr Warn(), 15 PyInt CheckExact(), 36
PyErr WarnExplicit(), 15 PyInt FromLong(), 36
PyErr WriteUnraisable(), 16 PyInt GetMax(), 36
PyEval AcquireLock(), 66 PyInt Type, 36
PyEval AcquireLock(), 61, 65 PyInterpreterState (C type), 65
PyEval AcquireThread(), 66 PyInterpreterState Clear(), 67
PyEval InitThreads(), 66 PyInterpreterState Delete(), 67
PyEval InitThreads(), 61 PyInterpreterState Head(), 68
PyEval ReleaseLock(), 66 PyInterpreterState New(), 67
PyEval ReleaseLock(), 61, 65, 66 PyInterpreterState Next(), 68
PyEval ReleaseThread(), 66 PyInterpreterState ThreadHead(), 68
PyEval ReleaseThread(), 66 PyIntObject (C type), 36
PyEval RestoreThread(), 66 PyIter Check(), 33
PyEval RestoreThread(), 65, 66 PyIter Next(), 33
PyEval SaveThread(), 66 PyList Append(), 51
PyEval SaveThread(), 65, 66 PyList AsTuple(), 52
PyEval SetProfile(), 68 PyList Check(), 51
PyEval SetTrace(), 68 PyList GET ITEM(), 51
PyFile AsFile(), 54 PyList GET SIZE(), 51
PyFile Check(), 54 PyList GetItem(), 51
PyFile CheckExact(), 54 PyList GetItem(), 4
PyFile FromFile(), 54 PyList GetSlice(), 51
90 Index
PyList Insert(), 51 PyMethod Function(), 56
PyList New(), 51 PyMethod GET CLASS(), 56
PyList Reverse(), 51 PyMethod GET FUNCTION(), 56
PyList SET ITEM(), 51 PyMethod GET SELF(), 56
PyList SetItem(), 51 PyMethod New(), 55
PyList SetItem(), 3 PyMethod Self(), 56
PyList SetSlice(), 51 PyMethod Type, 55
PyList Size(), 51 PyMethodDef (C type), 74
PyList Sort(), 51 PyModule AddIntConstant(), 56
PyList Type, 51 PyModule AddObject(), 56
PyListObject (C type), 51 PyModule AddStringConstant(), 56
PyLong AsDouble(), 37 PyModule Check(), 56
PyLong AsLong(), 37 PyModule CheckExact(), 56
PyLong AsLongLong(), 37 PyModule GetDict(), 56
PyLong AsUnsignedLong(), 37 PyModule GetFilename(), 56
PyLong AsUnsignedLongLong(), 37 PyModule GetName(), 56
PyLong AsVoidPtr(), 38 PyModule New(), 56
PyLong Check(), 36 PyModule Type, 56
PyLong CheckExact(), 36 PyNumber Absolute(), 29
PyLong FromDouble(), 37 PyNumber Add(), 28
PyLong FromLong(), 37 PyNumber And(), 29
PyLong FromLongLong(), 37 PyNumber Check(), 28
PyLong FromString(), 37 PyNumber Coerce(), 30
PyLong FromUnicode(), 37 PyNumber Divide(), 28
PyLong FromUnsignedLong(), 37 PyNumber Divmod(), 28
PyLong FromUnsignedLongLong(), 37 PyNumber Float(), 31
PyLong FromVoidPtr(), 37 PyNumber FloorDivide(), 28
PyLong Type, 36 PyNumber InPlaceAdd(), 29
PyLongObject (C type), 36 PyNumber InPlaceAnd(), 30
PyMapping Check(), 32 PyNumber InPlaceDivide(), 29
PyMapping DelItem(), 32 PyNumber InPlaceFloorDivide(), 30
PyMapping DelItemString(), 32 PyNumber InPlaceLshift(), 30
PyMapping GetItemString(), 33 PyNumber InPlaceMultiply(), 29
PyMapping HasKey(), 33 PyNumber InPlaceOr(), 30
PyMapping HasKeyString(), 33 PyNumber InPlacePower(), 30
PyMapping Items(), 33 PyNumber InPlaceRemainder(), 30
PyMapping Keys(), 33 PyNumber InPlaceRshift(), 30
PyMapping Length(), 32 PyNumber InPlaceSubtract(), 29
PyMapping SetItemString(), 33 PyNumber InPlaceTrueDivide(), 30
PyMapping Values(), 33 PyNumber InPlaceXor(), 30
PyMappingMethods (C type), 75 PyNumber Int(), 30
PyMarshal ReadLastObjectFromFile(), 22 PyNumber Invert(), 29
PyMarshal ReadLongFromFile(), 22 PyNumber Long(), 31
PyMarshal ReadObjectFromFile(), 22 PyNumber Lshift(), 29
PyMarshal ReadObjectFromString(), 22 PyNumber Multiply(), 28
PyMarshal ReadShortFromFile(), 22 PyNumber Negative(), 29
PyMarshal WriteLongToFile(), 22 PyNumber Or(), 29
PyMarshal WriteObjectToFile(), 22 PyNumber Positive(), 29
PyMarshal WriteObjectToString(), 22 PyNumber Power(), 28
PyMarshal WriteShortToFile(), 22 PyNumber Remainder(), 28
PyMem Del(), 70 PyNumber Rshift(), 29
PyMem Free(), 70 PyNumber Subtract(), 28
PyMem Malloc(), 70 PyNumber TrueDivide(), 28
PyMem New(), 70 PyNumber Xor(), 29
PyMem Realloc(), 70 PyNumberMethods (C type), 75
PyMem Resize(), 70 PyObject AsCharBuffer(), 34
PyMethod Check(), 55 PyObject AsFileDescriptor(), 27
PyMethod Class(), 55 PyObject AsReadBuffer(), 34
Index 91
PyObject AsWriteBuffer(), 34 PyRun InteractiveOne(), 9
PyObject CallFunction(), 26 PyRun SimpleFile(), 9
PyObject CallFunctionObjArgs(), 27 PyRun SimpleString(), 9
PyObject CallMethod(), 27 PyRun String(), 10
PyObject CallMethodObjArgs(), 27 PySeqIter Check(), 57
PyObject CallObject(), 26 PySeqIter New(), 57
PyObject CheckReadBuffer(), 34 PySeqIter Type, 57
PyObject Cmp(), 25 PySequence Check(), 31
PyObject Compare(), 26 PySequence Concat(), 31
PyObject DEL(), 74 PySequence Contains(), 32
PyObject Del(), 73 PySequence Count(), 32
PyObject DelAttr(), 25 PySequence DelItem(), 31
PyObject DelAttrString(), 25 PySequence DelSlice(), 32
PyObject DelItem(), 27 PySequence Fast(), 32
PyObject Dir(), 27 PySequence Fast GET ITEM(), 32
PyObject GC Del(), 77 PySequence Fast GET SIZE(), 32
PyObject GC New(), 77 PySequence GetItem(), 31
PyObject GC NewVar(), 77 PySequence GetItem(), 4
PyObject GC Resize(), 77 PySequence GetSlice(), 31
PyObject GC Track(), 77 PySequence Index(), 32
PyObject GC UnTrack(), 77 PySequence InPlaceConcat(), 31
PyObject GetAttr(), 25 PySequence InPlaceRepeat(), 31
PyObject GetAttrString(), 25 PySequence Length(), 31
PyObject GetItem(), 27 PySequence List(), 32
PyObject GetIter(), 28 PySequence Repeat(), 31
PyObject HasAttr(), 25 PySequence SetItem(), 31
PyObject HasAttrString(), 25 PySequence SetSlice(), 31
PyObject Hash(), 27 PySequence Size(), 31
PyObject Init(), 73 PySequence Tuple(), 32
PyObject InitVar(), 73 PySequenceMethods (C type), 75
PyObject IsInstance(), 26 PySlice Check(), 58
PyObject IsSubclass(), 26 PySlice GetIndices(), 58
PyObject IsTrue(), 27 PySlice New(), 58
PyObject Length(), 27 PySlice Type, 58
PyObject NEW(), 73 PyString AS STRING(), 40
PyObject New(), 73 PyString AsDecodedObject(), 41
PyObject NEW VAR(), 73 PyString AsEncodedObject(), 41
PyObject NewVar(), 73 PyString AsString(), 40
PyObject Print(), 25 PyString AsStringAndSize(), 40
PyObject Repr(), 26 PyString Check(), 39
PyObject SetAttr(), 25 PyString CheckExact(), 40
PyObject SetAttrString(), 25 PyString Concat(), 40
PyObject SetItem(), 27 PyString ConcatAndDel(), 41
PyObject Str(), 26 PyString Decode(), 41
PyObject Type(), 27 PyString Encode(), 41
PyObject TypeCheck(), 27 PyString Format(), 41
PyObject Unicode(), 26 PyString FromFormat(), 40
PyOS AfterFork(), 19 PyString FromFormatV(), 40
PyOS CheckStack(), 19 PyString FromString(), 40
PyOS GetLastModificationTime(), 19 PyString FromString(), 52
PyOS getsig(), 19 PyString FromStringAndSize(), 40
PyOS setsig(), 19 PyString GET SIZE(), 40
PyParser SimpleParseFile(), 10 PyString InternFromString(), 41
PyParser SimpleParseString(), 9 PyString InternInPlace(), 41
PyProperty Type, 57 PyString Size(), 40
PyRun AnyFile(), 9 PyString Type, 39
PyRun File(), 10 PyStringObject (C type), 39
PyRun InteractiveLoop(), 9 PySys SetArgv(), 64
92 Index
PySys SetArgv(), 7, 61 PyUnicode DecodeASCII(), 46
PYTHONHOME, 7 PyUnicode DecodeCharmap(), 46
PYTHONPATH, 7 PyUnicode DecodeLatin1(), 46
PyThreadState, 64 PyUnicode DecodeMBCS(), 47
PyThreadState (C type), 65 PyUnicode DecodeRawUnicodeEscape(), 45
PyThreadState Clear(), 67 PyUnicode DecodeUnicodeEscape(), 45
PyThreadState Delete(), 67 PyUnicode DecodeUTF16(), 45
PyThreadState Get(), 67 PyUnicode DecodeUTF8(), 44
PyThreadState GetDict(), 67 PyUnicode Encode(), 44
PyThreadState New(), 67 PyUnicode EncodeASCII(), 46
PyThreadState Next(), 68 PyUnicode EncodeCharmap(), 47
PyThreadState Swap(), 67 PyUnicode EncodeLatin1(), 46
PyTrace CALL, 68 PyUnicode EncodeMBCS(), 47
PyTrace EXCEPT, 68 PyUnicode EncodeRawUnicodeEscape(), 46
PyTrace LINE, 68 PyUnicode EncodeUnicodeEscape(), 45
PyTrace RETURN, 68 PyUnicode EncodeUTF16(), 45
PyTuple Check(), 50 PyUnicode EncodeUTF8(), 44
PyTuple CheckExact(), 50 PyUnicode Find(), 48
PyTuple GET ITEM(), 50 PyUnicode Format(), 48
PyTuple GET SIZE(), 50 PyUnicode FromEncodedObject(), 43
PyTuple GetItem(), 50 PyUnicode FromObject(), 43
PyTuple GetSlice(), 50 PyUnicode FromUnicode(), 43
PyTuple New(), 50 PyUnicode FromWideChar(), 44
PyTuple SET ITEM(), 50 PyUnicode GET DATA SIZE(), 42
PyTuple SetItem(), 50 PyUnicode GET SIZE(), 42
PyTuple SetItem(), 3 PyUnicode GetSize(), 43
PyTuple Size(), 50 PyUnicode Join(), 48
PyTuple Type, 50 PyUnicode Replace(), 48
PyTupleObject (C type), 50 PyUnicode Split(), 47
PyType Check(), 35 PyUnicode Splitlines(), 47
PyType GenericAlloc(), 35 PyUnicode Tailmatch(), 48
PyType GenericNew(), 35 PyUnicode Translate(), 48
PyType HasFeature(), 35 PyUnicode TranslateCharmap(), 47
PyType HasFeature(), 76 PyUnicode Type, 42
PyType IsSubtype(), 35 PyUnicodeObject (C type), 42
PyType Ready(), 35 PyWeakref Check(), 58
PyType Type, 35 PyWeakref CheckProxy(), 58
PyTypeObject (C type), 35 PyWeakref CheckRef(), 58
PyUnicode AS DATA(), 42 PyWeakref GET OBJECT(), 58
PyUnicode AS UNICODE(), 42 PyWeakref GetObject(), 58
PyUnicode AsASCIIString(), 46 PyWeakref NewProxy(), 58
PyUnicode AsCharmapString(), 47 PyWeakref NewRef(), 58
PyUnicode AsEncodedString(), 44 PyWrapper New(), 58
PyUnicode AsLatin1String(), 46
PyUnicode AsMBCSString(), 47 R
PyUnicode AsRawUnicodeEscapeString(), 46 realloc(), 69
PyUnicode AsUnicode(), 43 reload() (built-in function), 20
PyUnicode AsUnicodeEscapeString(), 45 repr() (built-in function), 26
PyUnicode AsUTF16String(), 45 rexec (standard module), 20
PyUnicode AsUTF8String(), 44
PyUnicode AsWideChar(), 44 S
PyUnicode Check(), 42 search
PyUnicode CheckExact(), 42 path, module, 7, 61, 63
PyUnicode Compare(), 48 sequence
PyUnicode Concat(), 47 object, 39
PyUnicode Contains(), 48 set all(), 4
PyUnicode Count(), 48 setcheckinterval() (in module sys), 64
PyUnicode Decode(), 44 setvbuf(), 54
Index 93
SIGINT, 15
signal (built-in module), 15
SliceType (in module types), 58
softspace (file attribute), 55
stderr (in module sys), 61
stdin (in module sys), 61
stdout (in module sys), 61
str() (built-in function), 26
strerror(), 14
string
object, 39
StringType (in module types), 39
frozen (C type), 21
inittab (C type), 21
sum list(), 4
sum sequence(), 5, 6
sys (built-in module), 7, 61
SystemError (built-in exception), 56
T
thread (built-in module), 66
tuple
object, 50
tuple() (built-in function), 32, 52
TupleType (in module types), 50
type
object, 2, 35
type() (built-in function), 27
TypeType (in module types), 35
U
ULONG MAX, 37
unistr() (built-in function), 26
V
version (in module sys), 63, 64
94 Index