Python/C API Reference Manual: Release 2.1.1
Python/C API Reference Manual: Release 2.1.1
Python/C API Reference Manual: Release 2.1.1
Release 2.1.1
PythonLabs
E-mail: [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 OS Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.2 Process Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.3 Importing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
9 Memory Management 61
9.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
9.2 Memory Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
9.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
i
10 Defining New Object Types 65
10.1 Common Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
10.2 Mapping Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
10.3 Number Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
10.4 Sequence Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
10.5 Buffer Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
10.6 Supporting Cyclic Garbarge Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
A Reporting Bugs 73
Index 79
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 ap-
plications 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>, <lim-
its.h>, and <stdlib.h> (if available).
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 U NIX, 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. Do not place
the parent directories on the search path and then use ‘#include <python2.1/Python.h>’; this will break on
1
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-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.
2 Chapter 1. Introduction
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 Py-
Object SetItem() refuse to do this since tuples are an immutable data type. You should only use PyTu-
ple 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");
l = Py_BuildValue("[iis]", 1, 2, "three");
It is much more common to use PyObject SetItem() and friends with items whose references you are only
borrowing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding
reference counts is much saner, since you don’t have to increment a reference count so you can give a reference away
(“have it be stolen”). For example, this function sets all items of a list (actually, any mutable sequence) to a given item:
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 function) 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().
4 Chapter 1. Introduction
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;
}
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; unhandled 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
1.3. Exceptions 5
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 appli-
cation). 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 correspond-
ing 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 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:
6 Chapter 1. Introduction
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 */
This example represents an endorsed use of the goto statement in C! It illustrates the use of Py-
Err 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.
Py Initialize() does not set the “script argument list” (sys.argv). If this variable is needed by Python code
that will be executed later, it must be set explicitly with a call to PySys SetArgv(argc, argv) subsequent to the
call to Py Initialize().
On most systems (in particular, on U NIX and Windows, although the details are slightly different),
Py Initialize() calculates the module search path based upon its best guess for the location of the standard
Python interpreter executable, assuming that the Python library is found in a fixed location relative to the Python in-
terpreter executable. In particular, it looks for a directory named ‘lib/python2.1’ relative to the parent directory where
the executable named ‘python’ is found on the shell command search path (the environment variable PATH).
For instance, if the Python executable is found in ‘/usr/local/bin/python’, it will assume that the libraries are in
‘/usr/local/lib/python2.1’. (In fact, this particular path is also the “fallback” location, used when no executable file
named ‘python’ is found along PATH.) The user can override this behavior by setting the environment variable
PYTHONHOME, or insert additional directories in front of the standard path by setting PYTHONPATH.
The embedding application can steer the search by calling Py SetProgramName(file) before calling
Py Initialize(). Note that PYTHONHOME still overrides this and PYTHONPATH is still inserted in
front of the standard path. An application that requires total control has to provide its own implementation of
Py GetPath(), Py GetPrefix(), Py GetExecPrefix(), and Py GetProgramFullPath() (all de-
fined in ‘Modules/getpath.c’).
Sometimes, it is desirable to “uninitialize” Python. For instance, the application may want to start over (make another
call to Py Initialize()) or the application is simply done with its use of Python and wants to free all memory al-
located by Python. This can be accomplished by calling Py Finalize(). The function Py IsInitialized()
returns true if Python is currently in the initialized state. More information about these functions is given in a later
chapter.
8 Chapter 1. Introduction
CHAPTER
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 U NIX 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 in case of 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.
9
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 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 param-
eter 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 U NIX 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 Parse*() 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.
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.
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)
13
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. 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
‘x’ A string, as a char * 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.
A new reference is returned, which is owned by the caller.
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 indicates
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 allocation
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 then calls ‘PyErr SetObject(type,
object)’. On U NIX, when the errno value is EINTR, indicating an interrupted system call, this calls Py-
Err CheckSignals(), and if that set the error indicator, leaves it set to that. The function always returns
15
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, such as parsing function arguments and constructing Python
values from C values.
5.1 OS Utilities
int Py FdIsInteractive(FILE *fp, char *filename)
Return true (nonzero) if the standard I/O file fp with name filename is deemed interactive. This is the case for files
for which ‘isatty(fileno(fp))’ is true. If the global flag Py InteractiveFlag is true, this function
also returns true if the filename pointer is NULL or if the name is equal to one of the strings ’<stdin>’ or
’???’.
long PyOS GetLastModificationTime(char *filename)
Return the time of last modification of the file filename. The result is encoded in the same way as the timestamp
returned by the standard C library function time().
void PyOS AfterFork()
Function to update some internal state after a process fork; this should be called in the new process if the Python
interpreter will continue to be used. If a new executable is loaded into the new process, this function does not
need to be called.
int PyOS CheckStack()
Return true when the interpreter runs out of stack space. This is a reliable check, but is only available when
USE STACKCHECK is defined (currently on Windows using the Microsoft Visual C++ compiler and on the
Macintosh). USE CHECKSTACK will be defined automatically; you should never change the definition in your
own code.
PyOS sighandler t PyOS getsig(int i)
Return the current signal handler for signal i. This is a thin wrapper around either sigaction or signal.
Do not call those functions directly! PyOS sighandler t is a typedef alias for void (*)(int).
PyOS sighandler t PyOS setsig(int i, PyOS sighandler t h)
Set the signal handler for signal i to be h; return the old signal handler. This is a thin wrapper around either
sigaction or signal. Do not call those functions directly! PyOS sighandler t is a typedef alias for
void (*)(int).
19
the object administration appears to be corrupted. On U NIX, the standard C library function abort() is called
which will attempt to produce a ‘core’ file.
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
PyObject* PyImport ExecCodeModule(char *name, PyObject *co)
Return value: New reference.
Given a module name (possibly of the form package.module) and a code object read from a Python bytecode
file or obtained from the built-in function compile(), load the module. Return a new 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 PyIm-
port 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 _inittab {
char *name;
void (*initfunc)(void);
};
22 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.
23
statement ‘del o.attr name’.
int PyObject Cmp(PyObject *o1, PyObject *o2, int *result)
Compare the values of o1 and o2 using a routine provided by o1, if one exists, otherwise with a routine provided
by o2. The result of the comparison is returned in result. Returns -1 on failure. 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 pro-
vided 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)
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 arguments 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)’.
PyObject* PyObject CallFunction(PyObject *callable object, char *format, ...)
Return value: New reference.
Call a callable Python object callable object, with a variable number of C arguments. The C arguments are
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.
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.
31
7.2 Numeric Objects
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.
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.
PyObject* PyLong FromLong(long v)
Return value: New reference.
Returns a new PyLongObject object from v, or NULL on failure.
PyObject* PyLong FromUnsignedLong(unsigned long v)
Return value: New reference.
Returns a new PyLongObject object from a C unsigned long, or NULL on failure.
PyObject* PyLong FromDouble(double v)
Return value: New reference.
Returns a new PyLongObject object from the integer part of v, or NULL on failure.
long PyLong AsLong(PyObject *pylong)
Returns a C long representation of the contents of pylong. If pylong is greater than LONG MAX, an Over-
flowError is raised.
unsigned long PyLong AsUnsignedLong(PyObject *pylong)
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.
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:
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.
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.
PyObject* PyString FromString(const char *v)
Return value: New reference.
Returns a new string object with the value v on success, and NULL on failure.
PyObject* PyString FromStringAndSize(const char *v, int len)
Return value: New reference.
Returns a new string object with the value v and length len on success, and NULL on failure. If v is NULL, the
contents of the string are uninitialized.
int PyString Size(PyObject *string)
Returns the length of the string in string object string.
int PyString GET SIZE(PyObject *string)
Macro form of PyString Size() but without error checking.
char* PyString AsString(PyObject *string)
Returns a null-terminated representation of the contents of string. The pointer refers to the internal buffer
of string, not a copy. The data must not be modified in any way, unless the string was just created using
PyString FromStringAndSize(NULL, size). It must not be deallocated.
char* PyString AS STRING(PyObject *string)
Macro form of PyString AsString() but without error checking.
int PyString AsStringAndSize(PyObject *obj, char **buffer, int *length)
Returns a null-terminated representation of the contents of the object obj through the output variables buffer and
length.
The function accepts both string and Unicode objects as input. For Unicode objects it returns the default encoded
version of the object. If length is set to NULL, the resulting buffer may not contain null characters; if it does, the
function returns -1 and a TypeError is raised.
The buffer refers to an internal string buffer of obj, not a copy. The data must not be modified in any way,
unless the string was just created using PyString FromStringAndSize(NULL, size). It must not be
deallocated.
void PyString Concat(PyObject **string, PyObject *newpart)
Creates a new string object in *string containing the contents of newpart appended to string; the caller will own
the new reference. The reference to the old value of string will be stolen. If the new string cannot be created,
the old reference to string will still be discarded and the value of *string will be set to NULL; the appropriate
exception will be set.
void PyString ConcatAndDel(PyObject **string, PyObject *newpart)
Creates a new string object in *string containing the contents of newpart appended to string. This version
decrements the reference count of newpart.
int PyString Resize(PyObject **string, int newsize)
A way to resize a string object even though it is “immutable”. Only use this to build up a brand new string
object; don’t use this if the string may already be known in other parts of the code.
These are the basic Unicode object types used for the Unicode implementation in Python:
Py UNICODE
This type represents a 16-bit unsigned storage type which is used by Python internally as basis for holding
Unicode ordinals. On platforms where wchar t is available and also has 16-bits, Py UNICODE is a typedef
alias for wchar t to enhance native platform compatibility. On all other platforms, Py UNICODE is a typedef
alias for unsigned short.
PyUnicodeObject
This subtype of PyObject represents a Python Unicode object.
PyTypeObject PyUnicode Type
This instance of PyTypeObject represents the Python Unicode type.
The following APIs are really C macros and can be used to do fast checks and to access internal read-only data of
Unicode objects:
int PyUnicode Check(PyObject *o)
Returns true if the object o is a Unicode object.
Create a Unicode Object from the Py UNICODE buffer u of the given size. u may be NULL which causes the
contents to be undefined. It is the user’s responsibility to fill in the needed data. The buffer is copied into the
new object.
Py UNICODE* PyUnicode AsUnicode(PyObject *unicode)
Return a read-only pointer to the Unicode object’s internal Py UNICODE buffer.
int PyUnicode GetSize(PyObject *unicode)
Return the length of the Unicode object.
PyObject* PyUnicode FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
Return value: New reference.
Coerce an encoded object obj to an Unicode object and return a reference with incremented refcount.
Coercion is done in the following way:
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 in case of 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.
PyObject* PyUnicode FromWideChar(const wchar t *w, int size)
Return value: New reference.
Create a Unicode Object from the whcar t buffer w of the given size. Returns NULL on failure.
int PyUnicode AsWideChar(PyUnicodeObject *unicode, wchar t *w, int size)
Copies the Unicode Object contents into the whcar t buffer w. At most size whcar t characters are copied.
Returns the number of whcar t characters copied or -1 in case of an error.
Builtin 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.
and then switches according to all byte order marks (BOM) it finds in the input data. BOM marks are not copied
If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two
modes, no BOM mark is prepended.
Note that Py UNICODE data is being interpreted as UTF-16 reduced to UCS-2. This trick makes it possible to
add full UTF-16 capabilities at a later point without comprimising the APIs.
Returns NULL in case an exception was raised by the codec.
PyObject* PyUnicode AsUTF16String(PyObject *unicode)
Return value: New reference.
Returns a Python string using the UTF-16 encoding in native byte order. The string always starts with a BOM
mark. Error handling is “strict”. Returns NULL in case an exception was raised by the codec.
These are the “Unicode Esacpe” codec APIs:
PyObject* PyUnicode DecodeUnicodeEscape(const char *s, int size, const char *errors)
Return value: New reference.
Creates a Unicode object by decoding size bytes of the Unicode-Esacpe encoded string s. Returns NULL in case
an exception was raised by the codec.
PyObject* PyUnicode EncodeUnicodeEscape(const Py UNICODE *s, int size, const char *errors)
Return value: New reference.
Encodes the Py UNICODE buffer of the given size using Unicode-Escape and returns a Python string object.
Returns NULL in case an exception was raised by the codec.
PyObject* PyUnicode AsUnicodeEscapeString(PyObject *unicode)
Return value: New reference.
Encodes a Unicode objects using Unicode-Escape and returns the result as Python string object. Error handling
is “strict”. Returns NULL in case an exception was raised by the codec.
These are the “Raw Unicode Esacpe” codec APIs:
PyObject* PyUnicode DecodeRawUnicodeEscape(const char *s, int size, const char *errors)
Return value: New reference.
Creates a Unicode object by decoding size bytes of the Raw-Unicode-Esacpe encoded string s. Returns NULL
in case an exception was raised by the codec.
PyObject* PyUnicode EncodeRawUnicodeEscape(const Py UNICODE *s, int size, const char *errors)
Return value: New reference.
Encodes the Py UNICODE buffer of the given size using Raw-Unicode-Escape and returns a Python string
object. Returns NULL in case an exception was raised by the codec.
PyObject* PyUnicode AsRawUnicodeEscapeString(PyObject *unicode)
Return value: New reference.
Encodes a Unicode objects using Raw-Unicode-Escape and returns the result as Python string object. Error
handling is “strict”. Returns NULL in case an exception was raised by the codec.
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 in case an exception occurrs.
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)
Return value: New reference.
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 a
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 the argument is a tuple object.
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.
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.
Does the same, 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)
Does the same, 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, int last is sticky)
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. The
last is sticky flag is not used and should always be false. Think of this as destroying the old tuple and creating
a new one, only more efficiently. Returns 0 on success and -1 on failure (in which case a MemoryError or
SystemError will be raised).
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
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.
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. Empties an existing dictionary of all
key-value pairs.
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 items()
(see the Python Library Reference).
PyObject* PyDict Keys(PyObject *p)
Return value: New reference.
Returns a PyListObject containing all the keys from the dictionary, as in the dictionary method keys()
(see the Python Library Reference).
PyObject* PyDict Values(PyObject *p)
The dictionary p should not be mutated during iteration. It is safe (since Python 2.1) to modify the values of the
keys as you iterate over the dictionary, for example:
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.
7.5.4 CObjects
Refer to Extending and Embedding the Python Interpreter, section 1.12 (“Providing a C API for an Extension Mod-
ule”), 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.
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(), PyE-
val 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 functions, 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 allocated 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
53
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 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 insu-
lation 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 dic-
tionary 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 complicated rules
from the program name set with Py SetProgramName() and some environment variables; 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 corresponds 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 U NIX. See also the next function.
char* Py GetExecPrefix()
Return the exec-prefix for installed platform-dependent files. This is derived through a number of compli-
cated rules from the program name set with Py SetProgramName() and some environment 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 U NIX.
Background: The exec-prefix differs from the prefix when platform dependent files (such as executables and
shared libraries) are installed in a different directory tree. In a typical installation, platform dependent files may
The first word (up to the first space character) is the current Python version; the first three characters are the
major and minor version separated by a period. The returned string points into static storage; the caller should
not modify its value. The value is available to Python code as the list sys.version.
const char* Py GetPlatform()
Return the platform identifier for the current platform. On U NIX, this is formed from the “official” name of the
operating system, converted to lower case, followed by the major revision number; e.g., for Solaris 2.x, which
is also known as SunOS 5.x, the value is ’sunos5’. On Macintosh, it is ’mac’. On Windows, it is ’win’.
The returned string points into static storage; the caller should not modify its value. The value is available to
Python code as sys.platform.
const char* Py GetCopyright()
Return the official copyright string for the current Python version, for example
’Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam’
The returned string points into static storage; the caller should not modify its value. The value is available to
Python code as the list sys.copyright.
const char* Py GetCompiler()
Return an indication of the compiler used to build the current Python version, in square brackets, for example:
"[GCC 2.7.2.2]"
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()
55
Return information about the sequence number and build date and time of the current Python interpreter instance,
for example
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.
int PySys SetArgv(int argc, char **argv)
Set sys.argv based on argc and argv. These parameters are similar to those passed to the program’s main()
function with the difference that the first entry should refer to the script file to be executed rather than the exe-
cutable hosting the Python interpreter. If there isn’t a script that will be run, the first entry in argv can be an empty
string. If this function fails to initialize sys.argv, a fatal condition is signalled using Py FatalError().
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.
NINE
Memory Management
9.1 Overview
Memory management in Python involves a private heap containing all Python objects and data structures. The man-
agement 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
61
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 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 inter-
preter 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:
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyString_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;
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.
char *buf1 = PyMem_New(char, BUFSIZ);
char *buf2 = (char *) malloc(BUFSIZ);
char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
...
PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
free(buf2); /* Right -- allocated via malloc() */
free(buf1); /* Fatal -- should be PyMem_Del() */
In addition to the functions aimed at handling raw memory blocks from the Python heap, objects in Python are
allocated and released with PyObject New(), PyObject NewVar() and PyObject Del(), or with their
corresponding macros PyObject NEW(), PyObject NEW VAR() and PyObject DEL().
These will be explained in the next chapter on defining and implementing new object types in C.
9.3. Examples 63
64
CHAPTER
TEN
65
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.
int PyArg ParseTuple(PyObject *args, char *format, ...)
Parse the parameters of a function that takes only positional parameters into local variables. See Extending and
Embedding the Python Interpreter for more information.
int PyArg ParseTupleAndKeywords(PyObject *args, PyObject *kw, char *format, char *keywords[], ...)
Parse the parameters of a function that takes both positional and keyword parameters into local variables. See
Extending and Embedding the Python Interpreter for more information.
int PyArg Parse(PyObject *args, char *format, ...)
Function used to deconstruct the argument lists of “old-style” functions — these are functions which use the
METH OLDARGS parameter parsing method. This is not recommended for new code, and most code in the
standard interpreter has been modified to no longer use this.
Py BuildValue
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 New() or PyObject VarNew().
1. Before fields which refer to other containers are invalidated, PyObject GC Fini() must be called.
2. The object’s memory must be deallocated using PyObject 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 initialization 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.
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_Fini((PyObject *) self);
Py_XDECREF(self->container);
PyObject_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.
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 pertinent infor-
mation to be entered and submitted to the developers.
Before submitting a report, please log into SourceForge if you are a member; this will make it possible for the devel-
opers to contact you for additional information if needed. If you are not a SourceForge member but would not mind
the developers contacting you, you may include your email address in your bug description. In this case, please realize
that the information is publically available and cannot be protected.
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. If
you have a SourceForge account and logged in to report 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.
73
74
APPENDIX
75
4. PSF is making Python 2.1.1 available to Licensee on an “AS IS” basis. PSF MAKES NO REPRESENTA-
TIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION,
PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABIL-
ITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.1.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.1.1 FOR ANY
INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING,
DISTRIBUTING, OR OTHERWISE USING PYTHON 2.1.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.1.1, Licensee agrees to be bound by the terms and conditions
of this License Agreement.
1. This LICENSE AGREEMENT is between BeOpen.com (“BeOpen”), having an office at 160 Saratoga Avenue,
Santa Clara, CA 95051, and the Individual or Organization (“Licensee”) accessing and otherwise using this
software in source or binary form and its associated documentation (“the Software”).
2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee
a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided,
however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared
by Licensee.
3. BeOpen is making the Software available to Licensee on an “AS IS” basis. BEOPEN MAKES NO REPRE-
SENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMI-
TATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MER-
CHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFT-
WARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF AD-
VISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of Cali-
fornia, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement
does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote
products or services of Licensee, or any third party. As an exception, the “BeOpen Python” logos available at
http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions
of this License Agreement.
ACCEPT
CWI PERMISSIONS STATEMENT AND DISCLAIMER
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 SOFT-
WARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT
79
object, 33 modules (in module sys), 20, 53
FloatType (in modules types), 33 ModuleType (in module types), 50
fopen(), 49
free(), 61 N
freeze utility, 21 None
object, 31
G numeric
global interpreter lock, 56 object, 32
H O
hash() (built-in function), 25 object
buffer, 43
I CObject, 50
ihooks (standard module), 20 complex number, 33
incr item(), 6, 7 dictionary, 47
instance file, 48
object, 49 floating point, 33
int() (built-in function), 28 instance, 49
getcharbufferproc (C type), 68 integer, 32
getreadbufferproc (C type), 68 list, 45
getsegcountproc (C type), 68 long integer, 32
getwritebufferproc (C type), 68 mapping, 47
inquiry (C type), 69 module, 50
traverseproc (C type), 69 None, 31
visitproc (C type), 69 numeric, 32
integer sequence, 34
object, 32 string, 35
interpreter lock, 56 tuple, 45
IntType (in modules types), 32 type, 2, 31
OverflowError (built-in exception), 32, 33
K
KeyboardInterrupt (built-in exception), 15 P
package variable
L all , 20
len() (built-in function), 25, 28, 30, 46, 48 PATH, 8
list path
object, 45 module search, 8, 53, 55
ListType (in module types), 46 path (in module sys), 8, 53, 55
lock, interpreter, 56 platform (in module sys), 55
long() (built-in function), 28 pow() (built-in function), 26, 27
long integer prefix, 1, 2
object, 32 Py AtExit(), 20
LONG MAX, 32 Py BEGIN ALLOW THREADS, 57
LongType (in modules types), 32 Py BEGIN ALLOW THREADS (macro), 58
Py BLOCK THREADS (macro), 59
M Py CompileString(), 10
Py CompileString(), 10
main(), 54, 56
Py complex (C type), 33
malloc(), 61
Py DECREF(), 11
mapping
Py DECREF(), 2
object, 47
Py END ALLOW THREADS, 57
module
Py END ALLOW THREADS (macro), 59
object, 50
Py END OF BUFFER, 44
search path, 8, 53, 55
80 Index
Py EndInterpreter(), 54 Py UNICODE ISUPPER(), 37
Py eval input, 10 Py UNICODE TODECIMAL(), 37
Py Exit(), 20 Py UNICODE TODIGIT(), 37
Py FatalError(), 19 Py UNICODE TOLOWER(), 37
Py FatalError(), 56 Py UNICODE TONUMERIC(), 38
Py FdIsInteractive(), 19 Py UNICODE TOTITLE(), 37
Py file input, 10 Py UNICODE TOUPPER(), 37
Py Finalize(), 53 Py XDECREF(), 11
Py Finalize(), 20, 53, 54 Py XDECREF(), 7
Py FindMethod(), 67 Py XINCREF(), 11
Py GetBuildInfo(), 55 PyArg Parse(), 66
Py GetCompiler(), 55 PyArg ParseTuple(), 66
Py GetCopyright(), 55 PyArg ParseTupleAndKeywords(), 66
Py GetExecPrefix(), 54 PyBuffer Check(), 44
Py GetExecPrefix(), 8 PyBuffer FromMemory(), 44
Py GetPath(), 55 PyBuffer FromObject(), 44
Py GetPath(), 8, 54 PyBuffer FromReadWriteMemory(), 44
Py GetPlatform(), 55 PyBuffer FromReadWriteObject(), 44
Py GetPrefix(), 54 PyBuffer New(), 44
Py GetPrefix(), 8 PyBuffer Type, 44
Py GetProgramFullPath(), 55 PyBufferObject (C type), 44
Py GetProgramFullPath(), 8 PyBufferProcs, 44
Py GetProgramName(), 54 PyBufferProcs (C type), 67
Py GetVersion(), 55 PyCallable Check(), 24
Py INCREF(), 11 PyCFunction (C type), 66
Py INCREF(), 2 PyCObject (C type), 50
Py Initialize(), 53 PyCObject AsVoidPtr(), 51
Py Initialize(), 8, 54, 58 PyCObject Check(), 51
Py InitModule(), 66 PyCObject FromVoidPtr(), 51
Py InitModule3(), 66 PyCObject FromVoidPtrAndDesc(), 51
Py InitModule4(), 66 PyCObject GetDesc(), 51
Py IsInitialized(), 53 PyComplex AsCComplex(), 34
Py IsInitialized(), 8 PyComplex Check(), 34
Py Main(), 9 PyComplex FromCComplex(), 34
Py NewInterpreter(), 53 PyComplex FromDoubles(), 34
Py None, 31 PyComplex ImagAsDouble(), 34
Py PRINT RAW, 49 PyComplex RealAsDouble(), 34
Py SetProgramName(), 54 PyComplex Type, 34
Py SetProgramName(), 8, 53–55 PyComplexObject (C type), 34
Py single input, 10 PyDict Check(), 47
Py TPFLAGS GC (data in ), 68 PyDict Clear(), 47
Py TPFLAGS HAVE GETCHARBUFFER (data in ), PyDict Copy(), 47
68 PyDict DelItem(), 47
Py UNBLOCK THREADS (macro), 59 PyDict DelItemString(), 47
Py UNICODE (C type), 36 PyDict GetItem(), 47
Py UNICODE ISALNUM(), 37 PyDict GetItemString(), 47
Py UNICODE ISALPHA(), 37 PyDict Items(), 47
Py UNICODE ISDECIMAL(), 37 PyDict Keys(), 47
Py UNICODE ISDIGIT(), 37 PyDict New(), 47
Py UNICODE ISLINEBREAK(), 37 PyDict Next(), 48
Py UNICODE ISLOWER(), 37 PyDict SetItem(), 47
Py UNICODE ISNUMERIC(), 37 PyDict SetItemString(), 47
Py UNICODE ISSPACE(), 37 PyDict Size(), 48
Py UNICODE ISTITLE(), 37 PyDict Type, 47
Index 81
PyDict Values(), 47 PyFloat AS DOUBLE(), 33
PyDictObject (C type), 47 PyFloat AsDouble(), 33
PyErr BadArgument(), 14 PyFloat Check(), 33
PyErr BadInternalCall(), 15 PyFloat FromDouble(), 33
PyErr CheckSignals(), 15 PyFloat Type, 33
PyErr Clear(), 13 PyFloatObject (C type), 33
PyErr Clear(), 6, 7 PyGC HEAD SIZE (data in ), 68
PyErr ExceptionMatches(), 13 PyImport AddModule(), 20
PyErr ExceptionMatches(), 7 PyImport AppendInittab(), 21
PyErr Fetch(), 13 PyImport Cleanup(), 21
PyErr Format(), 14 PyImport ExecCodeModule(), 21
PyErr GivenExceptionMatches(), 13 PyImport ExtendInittab(), 22
PyErr NewException(), 15 PyImport FrozenModules, 21
PyErr NoMemory(), 14 PyImport GetMagicNumber(), 21
PyErr NormalizeException(), 13 PyImport GetModuleDict(), 21
PyErr Occurred(), 13 PyImport Import(), 20
PyErr Occurred(), 6 PyImport ImportFrozenModule(), 21
PyErr Print(), 13 PyImport ImportModule(), 20
PyErr Restore(), 14 PyImport ImportModuleEx(), 20
PyErr SetFromErrno(), 14 PyImport ReloadModule(), 20
PyErr SetFromErrnoWithFilename(), 15 PyInstance Check(), 49
PyErr SetInterrupt(), 15 PyInstance New(), 49
PyErr SetNone(), 14 PyInstance NewRaw(), 50
PyErr SetObject(), 14 PyInstance Type, 49
PyErr SetString(), 14 PyInt AS LONG(), 32
PyErr SetString(), 6 PyInt AsLong(), 32
PyErr Warn(), 15 PyInt Check(), 32
PyErr WarnExplicit(), 15 PyInt FromLong(), 32
PyErr WriteUnraisable(), 16 PyInt GetMax(), 32
PyEval AcquireLock(), 58 PyInt Type, 32
PyEval AcquireLock(), 53, 57 PyInterpreterState (C type), 57
PyEval AcquireThread(), 58 PyInterpreterState Clear(), 59
PyEval InitThreads(), 58 PyInterpreterState Delete(), 59
PyEval InitThreads(), 53 PyInterpreterState New(), 59
PyEval ReleaseLock(), 58 PyIntObject (C type), 32
PyEval ReleaseLock(), 53, 57, 58 PyList Append(), 46
PyEval ReleaseThread(), 58 PyList AsTuple(), 46
PyEval ReleaseThread(), 58 PyList Check(), 46
PyEval RestoreThread(), 58 PyList GET ITEM(), 46
PyEval RestoreThread(), 57, 58 PyList GET SIZE(), 46
PyEval SaveThread(), 58 PyList GetItem(), 46
PyEval SaveThread(), 57, 58 PyList GetItem(), 4
PyFile AsFile(), 49 PyList GetSlice(), 46
PyFile Check(), 48 PyList Insert(), 46
PyFile FromFile(), 49 PyList New(), 46
PyFile FromString(), 49 PyList Reverse(), 46
PyFile GetLine(), 49 PyList SET ITEM(), 46
PyFile Name(), 49 PyList SetItem(), 46
PyFile SetBufSize(), 49 PyList SetItem(), 3
PyFile SoftSpace(), 49 PyList SetSlice(), 46
PyFile Type, 48 PyList Size(), 46
PyFile WriteObject(), 49 PyList Sort(), 46
PyFile WriteString(), 49 PyList Type, 45
PyFileObject (C type), 48 PyListObject (C type), 45
82 Index
PyLong AsDouble(), 33 PyNumber InPlaceRshift(), 27
PyLong AsLong(), 32 PyNumber InPlaceSubtract(), 27
PyLong AsUnsignedLong(), 32 PyNumber InPlaceXor(), 28
PyLong Check(), 32 PyNumber Int(), 28
PyLong FromDouble(), 32 PyNumber Invert(), 26
PyLong FromLong(), 32 PyNumber Long(), 28
PyLong FromString(), 33 PyNumber Lshift(), 26
PyLong FromUnsignedLong(), 32 PyNumber Multiply(), 26
PyLong Type, 32 PyNumber Negative(), 26
PyLongObject (C type), 32 PyNumber Or(), 27
PyMapping Check(), 30 PyNumber Positive(), 26
PyMapping DelItem(), 30 PyNumber Power(), 26
PyMapping DelItemString(), 30 PyNumber Remainder(), 26
PyMapping GetItemString(), 30 PyNumber Rshift(), 26
PyMapping HasKey(), 30 PyNumber Subtract(), 26
PyMapping HasKeyString(), 30 PyNumber Xor(), 27
PyMapping Items(), 30 PyNumberMethods (C type), 67
PyMapping Keys(), 30 PyObject AsFileDescriptor(), 25
PyMapping Length(), 30 PyObject CallFunction(), 24
PyMapping SetItemString(), 30 PyObject CallMethod(), 25
PyMapping Values(), 30 PyObject CallObject(), 24
PyMappingMethods (C type), 67 PyObject Cmp(), 24
PyMem Del(), 62 PyObject Compare(), 24
PyMem Free(), 62 PyObject DEL(), 66
PyMem Malloc(), 62 PyObject Del(), 65
PyMem New(), 62 PyObject DelAttr(), 23
PyMem Realloc(), 62 PyObject DelAttrString(), 23
PyMem Resize(), 62 PyObject DelItem(), 25
PyMethodDef (C type), 66 PyObject GC Fini(), 69
PyModule AddIntConstant(), 50 PyObject GC Init(), 69
PyModule AddObject(), 50 PyObject GetAttr(), 23
PyModule AddStringConstant(), 50 PyObject GetAttrString(), 23
PyModule Check(), 50 PyObject GetItem(), 25
PyModule GetDict(), 50 PyObject HasAttr(), 23
PyModule GetFilename(), 50 PyObject HasAttrString(), 23
PyModule GetName(), 50 PyObject Hash(), 25
PyModule New(), 50 PyObject Init(), 65
PyModule Type, 50 PyObject InitVar(), 65
PyNumber Absolute(), 26 PyObject IsInstance(), 24
PyNumber Add(), 25 PyObject IsSubclass(), 24
PyNumber And(), 26 PyObject IsTrue(), 25
PyNumber Check(), 25 PyObject Length(), 25
PyNumber Coerce(), 28 PyObject NEW(), 65
PyNumber Divide(), 26 PyObject New(), 65
PyNumber Divmod(), 26 PyObject NEW VAR(), 65
PyNumber Float(), 28 PyObject NewVar(), 65
PyNumber InPlaceAdd(), 27 PyObject Print(), 23
PyNumber InPlaceAnd(), 27 PyObject Repr(), 24
PyNumber InPlaceDivide(), 27 PyObject SetAttr(), 23
PyNumber InPlaceLshift(), 27 PyObject SetAttrString(), 23
PyNumber InPlaceMultiply(), 27 PyObject SetItem(), 25
PyNumber InPlaceOr(), 28 PyObject Str(), 24
PyNumber InPlacePower(), 27 PyObject Type(), 25
PyNumber InPlaceRemainder(), 27 PyObject Unicode(), 24
Index 83
PyOS AfterFork(), 19 PyStringObject (C type), 35
PyOS CheckStack(), 19 PySys SetArgv(), 56
PyOS GetLastModificationTime(), 19 PySys SetArgv(), 8, 53
PyOS getsig(), 19 PYTHONHOME, 8
PyOS setsig(), 19 PYTHONPATH, 8
PyParser SimpleParseFile(), 10 PyThreadState, 56
PyParser SimpleParseString(), 10 PyThreadState (C type), 58
PyRun AnyFile(), 9 PyThreadState Clear(), 59
PyRun File(), 10 PyThreadState Delete(), 59
PyRun InteractiveLoop(), 9 PyThreadState Get(), 59
PyRun InteractiveOne(), 9 PyThreadState GetDict(), 59
PyRun SimpleFile(), 9 PyThreadState New(), 59
PyRun SimpleString(), 9 PyThreadState Swap(), 59
PyRun String(), 10 PyTuple Check(), 45
PySequence Check(), 28 PyTuple GET ITEM(), 45
PySequence Concat(), 28 PyTuple GetItem(), 45
PySequence Contains(), 29 PyTuple GetSlice(), 45
PySequence Count(), 29 PyTuple New(), 45
PySequence DelItem(), 29 PyTuple SET ITEM(), 45
PySequence DelSlice(), 29 PyTuple SetItem(), 45
PySequence Fast(), 29 PyTuple SetItem(), 3
PySequence Fast GET ITEM(), 30 PyTuple Size(), 45
PySequence GetItem(), 29 PyTuple Type, 45
PySequence GetItem(), 4 PyTupleObject (C type), 45
PySequence GetSlice(), 29 PyType Check(), 31
PySequence Index(), 29 PyType HasFeature(), 31
PySequence InPlaceConcat(), 28 PyType HasFeature(), 68
PySequence InPlaceRepeat(), 29 PyType Type, 31
PySequence Length(), 28 PyTypeObject (C type), 31
PySequence List(), 29 PyUnicode AS DATA(), 37
PySequence Repeat(), 28 PyUnicode AS UNICODE(), 37
PySequence SetItem(), 29 PyUnicode AsASCIIString(), 41
PySequence SetSlice(), 29 PyUnicode AsCharmapString(), 42
PySequence Size(), 28 PyUnicode AsEncodedString(), 39
PySequence Tuple(), 29 PyUnicode AsLatin1String(), 41
PySequenceMethods (C type), 67 PyUnicode AsMBCSString(), 42
PyString AS STRING(), 35 PyUnicode AsRawUnicodeEscapeString(),
PyString AsEncodedString(), 36 40
PyString AsString(), 35 PyUnicode AsUnicode(), 38
PyString AsStringAndSize(), 35 PyUnicode AsUnicodeEscapeString(), 40
PyString Check(), 35 PyUnicode AsUTF16String(), 40
PyString Concat(), 35 PyUnicode AsUTF8String(), 39
PyString ConcatAndDel(), 35 PyUnicode AsWideChar(), 38
PyString Decode(), 36 PyUnicode Check(), 36
PyString Encode(), 36 PyUnicode Compare(), 43
PyString Format(), 36 PyUnicode Concat(), 42
PyString FromString(), 35 PyUnicode Contains(), 43
PyString FromString(), 47 PyUnicode Count(), 43
PyString FromStringAndSize(), 35 PyUnicode Decode(), 39
PyString GET SIZE(), 35 PyUnicode DecodeASCII(), 41
PyString InternFromString(), 36 PyUnicode DecodeCharmap(), 41
PyString InternInPlace(), 36 PyUnicode DecodeLatin1(), 41
PyString Size(), 35 PyUnicode DecodeMBCS(), 42
PyString Type, 35
84 Index
PyUnicode DecodeRawUnicodeEscape(), str() (built-in function), 24
40 strerror(), 14
PyUnicode DecodeUnicodeEscape(), 40 string
PyUnicode DecodeUTF16(), 39 object, 35
PyUnicode DecodeUTF8(), 39 StringType (in module types), 35
PyUnicode Encode(), 39 frozen (C type), 21
PyUnicode EncodeASCII(), 41 inittab (C type), 21
PyUnicode EncodeCharmap(), 41 sum list(), 5
PyUnicode EncodeLatin1(), 41 sum sequence(), 5, 6
PyUnicode EncodeMBCS(), 42 sys (built-in module), 8, 53
PyUnicode EncodeRawUnicodeEscape(), SystemError (built-in exception), 50
40
PyUnicode EncodeUnicodeEscape(), 40 T
PyUnicode EncodeUTF16(), 40 thread (built-in module), 58
PyUnicode EncodeUTF8(), 39 tuple
PyUnicode Find(), 43 object, 45
PyUnicode Format(), 43 tuple() (built-in function), 29, 46
PyUnicode FromEncodedObject(), 38 TupleType (in module types), 45
PyUnicode FromObject(), 38 type
PyUnicode FromUnicode(), 38 object, 2, 31
PyUnicode FromWideChar(), 38 type() (built-in function), 25
PyUnicode GET DATA SIZE(), 37 TypeType (in module types), 31
PyUnicode GET SIZE(), 37
PyUnicode GetSize(), 38 U
PyUnicode Join(), 43 ULONG MAX, 33
PyUnicode Replace(), 43 unistr() (built-in function), 24
PyUnicode Split(), 42
PyUnicode Splitlines(), 42 V
PyUnicode Tailmatch(), 43
version (in module sys), 55, 56
PyUnicode Translate(), 43
PyUnicode TranslateCharmap(), 42
PyUnicode Type, 36
PyUnicodeObject (C type), 36
R
realloc(), 61
reload() (built-in function), 20
repr() (built-in function), 24
rexec (standard module), 20
S
search
path, module, 8, 53, 55
sequence
object, 34
set all(), 4
setcheckinterval() (in module sys), 56
setvbuf(), 49
SIGINT, 15
signal (built-in module), 15
softspace (file attribute), 49
stderr (in module sys), 53
stdin (in module sys), 53
stdout (in module sys), 53
Index 85