3 \title{Python/C API Reference Manual
}
7 \makeindex % tell \index to actually write the .idx file
19 This manual documents the API used by
\C{} (or
\Cpp{}) programmers who
20 want to write extension modules or embed Python. It is a companion to
21 \emph{Extending and Embedding the Python Interpreter
}, which describes
22 the general principles of extension writing but does not
document the
23 API functions in detail.
25 \strong{Warning:
} The current version of this
document is incomplete.
26 I hope that it is nevertheless useful. I will continue to work on it,
27 and release new versions from time to time, independent from Python
34 % XXX Consider moving all this back to ext.tex and giving api.tex
35 % XXX a *really* short intro only.
37 \chapter{Introduction
}
40 The Application Programmer's Interface to Python gives
\C{} and
\Cpp{}
41 programmers access to the Python interpreter at a variety of levels.
42 The API is equally usable from
\Cpp{}, but for brevity it is generally
43 referred to as the Python/
\C{} API. There are two fundamentally
44 different reasons for using the Python/
\C{} API. The first reason is
45 to write
\emph{extension modules
} for specific purposes; these are
46 \C{} modules that extend the Python interpreter. This is probably the
47 most common use. The second reason is to use Python as a component in
48 a larger application; this technique is generally referred to as
49 \dfn{embedding
} Python in an application.
51 Writing an extension module is a relatively well-understood process,
52 where a ``cookbook'' approach works well. There are several tools
53 that automate the process to some extent. While people have embedded
54 Python in other applications since its early existence, the process of
55 embedding Python is less straightforward that writing an extension.
56 Python
1.5 introduces a number of new API functions as well as some
57 changes to the build process that make embedding much simpler.
58 This manual describes the
\version\ state of affairs.
59 % XXX Eventually, take the historical notes out
61 Many API functions are useful independent of whether you're embedding
62 or extending Python; moreover, most applications that embed Python
63 will need to provide a custom extension as well, so it's probably a
64 good idea to become familiar with writing an extension before
65 attempting to embed Python in a real application.
67 \section{Include Files
}
70 All function, type and macro definitions needed to use the Python/C
71 API are included in your code by the following line:
77 This implies inclusion of the following standard headers:
78 \code{<stdio.h>
},
\code{<string.h>
},
\code{<errno.h>
}, and
79 \code{<stdlib.h>
} (if available).
81 All user visible names defined by Python.h (except those defined by
82 the included standard headers) have one of the prefixes
\samp{Py
} or
83 \samp{_Py
}. Names beginning with
\samp{_Py
} are for internal use
84 only. Structure member names do not have a reserved prefix.
86 \strong{Important:
} user code should never define names that begin
87 with
\samp{Py
} or
\samp{_Py
}. This confuses the reader, and
88 jeopardizes the portability of the user code to future Python
89 versions, which may define additional names beginning with one of
92 \section{Objects, Types and Reference Counts
}
95 Most Python/C API functions have one or more arguments as well as a
96 return value of type
\code{PyObject *
}. This type is a pointer
97 to an opaque data type representing an arbitrary Python
98 object. Since all Python object types are treated the same way by the
99 Python language in most situations (e.g., assignments, scope rules,
100 and argument passing), it is only fitting that they should be
101 represented by a single
\C{} type. All Python objects live on the heap:
102 you never declare an automatic or static variable of type
103 \code{PyObject
}, only pointer variables of type
\code{PyObject *
} can
106 All Python objects (even Python integers) have a
\dfn{type
} and a
107 \dfn{reference count
}. An object's type determines what kind of object
108 it is (e.g., an integer, a list, or a user-defined function; there are
109 many more as explained in the
\emph{Python Reference Manual
}). For
110 each of the well-known types there is a macro to check whether an
111 object is of that type; for instance,
\samp{PyList_Check(
\var{a
})
} is
112 true iff the object pointed to by
\var{a
} is a Python list.
114 \subsection{Reference Counts
}
117 The reference count is important because today's computers have a
118 finite (and often severely limited) memory size; it counts how many
119 different places there are that have a reference to an object. Such a
120 place could be another object, or a global (or static)
\C{} variable, or
121 a local variable in some
\C{} function. When an object's reference count
122 becomes zero, the object is deallocated. If it contains references to
123 other objects, their reference count is decremented. Those other
124 objects may be deallocated in turn, if this decrement makes their
125 reference count become zero, and so on. (There's an obvious problem
126 with objects that reference each other here; for now, the solution is
129 Reference counts are always manipulated explicitly. The normal way is
130 to use the macro
\cfunction{Py_INCREF()
} to increment an object's
131 reference count by one, and
\cfunction{Py_DECREF()
} to decrement it by
132 one. The decref macro is considerably more complex than the incref one,
133 since it must check whether the reference count becomes zero and then
134 cause the object's deallocator, which is a function pointer contained
135 in the object's type structure. The type-specific deallocator takes
136 care of decrementing the reference counts for other objects contained
137 in the object, and so on, if this is a compound object type such as a
138 list. There's no chance that the reference count can overflow; at
139 least as many bits are used to hold the reference count as there are
140 distinct memory locations in virtual memory (assuming
141 \code{sizeof(long) >= sizeof(char *)
}). Thus, the reference count
142 increment is a simple operation.
144 It is not necessary to increment an object's reference count for every
145 local variable that contains a pointer to an object. In theory, the
146 object's reference count goes up by one when the variable is made to
147 point to it and it goes down by one when the variable goes out of
148 scope. However, these two cancel each other out, so at the end the
149 reference count hasn't changed. The only real reason to use the
150 reference count is to prevent the object from being deallocated as
151 long as our variable is pointing to it. If we know that there is at
152 least one other reference to the object that lives at least as long as
153 our variable, there is no need to increment the reference count
154 temporarily. An important situation where this arises is in objects
155 that are passed as arguments to
\C{} functions in an extension module
156 that are called from Python; the call mechanism guarantees to hold a
157 reference to every argument for the duration of the call.
159 However, a common pitfall is to extract an object from a list and
160 hold on to it for a while without incrementing its reference count.
161 Some other operation might conceivably remove the object from the
162 list, decrementing its reference count and possible deallocating it.
163 The real danger is that innocent-looking operations may invoke
164 arbitrary Python code which could do this; there is a code path which
165 allows control to flow back to the user from a
\cfunction{Py_DECREF()
},
166 so almost any operation is potentially dangerous.
168 A safe approach is to always use the generic operations (functions
169 whose name begins with
\samp{PyObject_
},
\samp{PyNumber_
},
170 \samp{PySequence_
} or
\samp{PyMapping_
}). These operations always
171 increment the reference count of the object they return. This leaves
172 the caller with the responsibility to call
\cfunction{Py_DECREF()
}
173 when they are done with the result; this soon becomes second nature.
175 \subsubsection{Reference Count Details
}
176 \label{refcountDetails
}
178 The reference count behavior of functions in the Python/C API is best
179 expelained in terms of
\emph{ownership of references
}. Note that we
180 talk of owning references, never of owning objects; objects are always
181 shared! When a function owns a reference, it has to dispose of it
182 properly --- either by passing ownership on (usually to its caller) or
183 by calling
\cfunction{Py_DECREF()
} or
\cfunction{Py_XDECREF()
}. When
184 a function passes ownership of a reference on to its caller, the
185 caller is said to receive a
\emph{new
} reference. When no ownership
186 is transferred, the caller is said to
\emph{borrow
} the reference.
187 Nothing needs to be done for a borrowed reference.
189 Conversely, when calling a function passes it a reference to an
190 object, there are two possibilities: the function
\emph{steals
} a
191 reference to the object, or it does not. Few functions steal
192 references; the two notable exceptions are
193 \cfunction{PyList_SetItem()
} and
\cfunction{PyTuple_SetItem()
}, which
194 steal a reference to the item (but not to the tuple or list into which
195 the item is put!). These functions were designed to steal a reference
196 because of a common idiom for populating a tuple or list with newly
197 created objects; for example, the code to create the tuple
\code{(
1,
198 2, "three")
} could look like this (forgetting about error handling for
199 the moment; a better way to code this is shown below anyway):
205 PyTuple_SetItem(t,
0, PyInt_FromLong(
1L));
206 PyTuple_SetItem(t,
1, PyInt_FromLong(
2L));
207 PyTuple_SetItem(t,
2, PyString_FromString("three"));
210 Incidentally,
\cfunction{PyTuple_SetItem()
} is the
\emph{only
} way to
211 set tuple items;
\cfunction{PySequence_SetItem()
} and
212 \cfunction{PyObject_SetItem()
} refuse to do this since tuples are an
213 immutable data type. You should only use
214 \cfunction{PyTuple_SetItem()
} for tuples that you are creating
217 Equivalent code for populating a list can be written using
218 \cfunction{PyList_New()
} and
\cfunction{PyList_SetItem()
}. Such code
219 can also use
\cfunction{PySequence_SetItem()
}; this illustrates the
220 difference between the two (the extra
\cfunction{Py_DECREF()
} calls):
226 x = PyInt_FromLong(
1L);
227 PySequence_SetItem(l,
0, x); Py_DECREF(x);
228 x = PyInt_FromLong(
2L);
229 PySequence_SetItem(l,
1, x); Py_DECREF(x);
230 x = PyString_FromString("three");
231 PySequence_SetItem(l,
2, x); Py_DECREF(x);
234 You might find it strange that the ``recommended'' approach takes more
235 code. However, in practice, you will rarely use these ways of
236 creating and populating a tuple or list. There's a generic function,
237 \cfunction{Py_BuildValue()
}, that can create most common objects from
238 \C{} values, directed by a
\dfn{format string
}. For example, the
239 above two blocks of code could be replaced by the following (which
240 also takes care of the error checking):
245 t = Py_BuildValue("(iis)",
1,
2, "three");
246 l = Py_BuildValue("
[iis
]",
1,
2, "three");
249 It is much more common to use
\cfunction{PyObject_SetItem()
} and
250 friends with items whose references you are only borrowing, like
251 arguments that were passed in to the function you are writing. In
252 that case, their behaviour regarding reference counts is much saner,
253 since you don't have to increment a reference count so you can give a
254 reference away (``have it be stolen''). For example, this function
255 sets all items of a list (actually, any mutable sequence) to a given
259 int set_all(PyObject *target, PyObject *item)
263 n = PyObject_Length(target);
266 for (i =
0; i < n; i++)
{
267 if (PyObject_SetItem(target, i, item) <
0)
274 The situation is slightly different for function return values.
275 While passing a reference to most functions does not change your
276 ownership responsibilities for that reference, many functions that
277 return a referece to an object give you ownership of the reference.
278 The reason is simple: in many cases, the returned object is created
279 on the fly, and the reference you get is the only reference to the
280 object. Therefore, the generic functions that return object
281 references, like
\cfunction{PyObject_GetItem()
} and
282 \cfunction{PySequence_GetItem()
}, always return a new reference (i.e.,
283 the caller becomes the owner of the reference).
285 It is important to realize that whether you own a reference returned
286 by a function depends on which function you call only ---
\emph{the
287 plumage
} (i.e., the type of the type of the object passed as an
288 argument to the function)
\emph{doesn't enter into it!
} Thus, if you
289 extract an item from a list using
\cfunction{PyList_GetItem()
}, you
290 don't own the reference --- but if you obtain the same item from the
291 same list using
\cfunction{PySequence_GetItem()
} (which happens to
292 take exactly the same arguments), you do own a reference to the
295 Here is an example of how you could write a function that computes the
296 sum of the items in a list of integers; once using
297 \cfunction{PyList_GetItem()
}, once using
298 \cfunction{PySequence_GetItem()
}.
301 long sum_list(PyObject *list)
307 n = PyList_Size(list);
309 return -
1; /* Not a list */
310 for (i =
0; i < n; i++)
{
311 item = PyList_GetItem(list, i); /* Can't fail */
312 if (!PyInt_Check(item)) continue; /* Skip non-integers */
313 total += PyInt_AsLong(item);
320 long sum_sequence(PyObject *sequence)
325 n = PyObject_Size(list);
327 return -
1; /* Has no length */
328 for (i =
0; i < n; i++)
{
329 item = PySequence_GetItem(list, i);
331 return -
1; /* Not a sequence, or other failure */
332 if (PyInt_Check(item))
333 total += PyInt_AsLong(item);
334 Py_DECREF(item); /* Discard reference ownership */
343 There are few other data types that play a significant role in
344 the Python/C API; most are simple
\C{} types such as
\code{int
},
345 \code{long
},
\code{double
} and
\code{char *
}. A few structure types
346 are used to describe static tables used to list the functions exported
347 by a module or the data attributes of a new object type. These will
348 be discussed together with the functions that use them.
353 The Python programmer only needs to deal with exceptions if specific
354 error handling is required; unhandled exceptions are automatically
355 propagated to the caller, then to the caller's caller, and so on, till
356 they reach the top-level interpreter, where they are reported to the
357 user accompanied by a stack traceback.
359 For
\C{} programmers, however, error checking always has to be explicit.
360 All functions in the Python/C API can raise exceptions, unless an
361 explicit claim is made otherwise in a function's documentation. In
362 general, when a function encounters an error, it sets an exception,
363 discards any object references that it owns, and returns an
364 error indicator --- usually
\NULL{} or
\code{-
1}. A few functions
365 return a Boolean true/false result, with false indicating an error.
366 Very few functions return no explicit error indicator or have an
367 ambiguous return value, and require explicit testing for errors with
368 \cfunction{PyErr_Occurred()
}.
370 Exception state is maintained in per-thread storage (this is
371 equivalent to using global storage in an unthreaded application). A
372 thread can be in one of two states: an exception has occurred, or not.
373 The function
\cfunction{PyErr_Occurred()
} can be used to check for
374 this: it returns a borrowed reference to the exception type object
375 when an exception has occurred, and
\NULL{} otherwise. There are a
376 number of functions to set the exception state:
377 \cfunction{PyErr_SetString()
} is the most common (though not the most
378 general) function to set the exception state, and
379 \cfunction{PyErr_Clear()
} clears the exception state.
381 The full exception state consists of three objects (all of which can
382 be
\NULL{}): the exception type, the corresponding exception
383 value, and the traceback. These have the same meanings as the Python
384 object
\code{sys.exc_type
},
\code{sys.exc_value
},
385 \code{sys.exc_traceback
}; however, they are not the same: the Python
386 objects represent the last exception being handled by a Python
387 \keyword{try
} \ldots\
\keyword{except
} statement, while the
\C{} level
388 exception state only exists while an exception is being passed on
389 between
\C{} functions until it reaches the Python interpreter, which
390 takes care of transferring it to
\code{sys.exc_type
} and friends.
392 Note that starting with Python
1.5, the preferred, thread-safe way to
393 access the exception state from Python code is to call the function
394 \function{sys.exc_info()
}, which returns the per-thread exception state
395 for Python code. Also, the semantics of both ways to access the
396 exception state have changed so that a function which catches an
397 exception will save and restore its thread's exception state so as to
398 preserve the exception state of its caller. This prevents common bugs
399 in exception handling code caused by an innocent-looking function
400 overwriting the exception being handled; it also reduces the often
401 unwanted lifetime extension for objects that are referenced by the
402 stack frames in the traceback.
404 As a general principle, a function that calls another function to
405 perform some task should check whether the called function raised an
406 exception, and if so, pass the exception state on to its caller. It
407 should discard any object references that it owns, and returns an
408 error indicator, but it should
\emph{not
} set another exception ---
409 that would overwrite the exception that was just raised, and lose
410 important information about the exact cause of the error.
412 A simple example of detecting exceptions and passing them on is shown
413 in the
\cfunction{sum_sequence()
} example above. It so happens that
414 that example doesn't need to clean up any owned references when it
415 detects an error. The following example function shows some error
416 cleanup. First, to remind you why you like Python, we show the
417 equivalent Python code:
420 def incr_item(dict, key):
428 Here is the corresponding
\C{} code, in all its glory:
431 int incr_item(PyObject *dict, PyObject *key)
433 /* Objects all initialized to NULL for Py_XDECREF */
434 PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
435 int rv = -
1; /* Return value initialized to -
1 (failure) */
437 item = PyObject_GetItem(dict, key);
439 /* Handle KeyError only: */
440 if (!PyErr_ExceptionMatches(PyExc_KeyError)) goto error;
442 /* Clear the error and use zero: */
444 item = PyInt_FromLong(
0L);
445 if (item == NULL) goto error;
448 const_one = PyInt_FromLong(
1L);
449 if (const_one == NULL) goto error;
451 incremented_item = PyNumber_Add(item, const_one);
452 if (incremented_item == NULL) goto error;
454 if (PyObject_SetItem(dict, key, incremented_item) <
0) goto error;
455 rv =
0; /* Success */
456 /* Continue with cleanup code */
459 /* Cleanup code, shared by success and failure path */
461 /* Use Py_XDECREF() to ignore NULL references */
463 Py_XDECREF(const_one);
464 Py_XDECREF(incremented_item);
466 return rv; /* -
1 for error,
0 for success */
470 This example represents an endorsed use of the
\code{goto
} statement
471 in
\C{}! It illustrates the use of
472 \cfunction{PyErr_ExceptionMatches()
} and
\cfunction{PyErr_Clear()
} to
473 handle specific exceptions, and the use of
\cfunction{Py_XDECREF()
} to
474 dispose of owned references that may be
\NULL{} (note the
\samp{X
} in
475 the name;
\cfunction{Py_DECREF()
} would crash when confronted with a
476 \NULL{} reference). It is important that the variables used to hold
477 owned references are initialized to
\NULL{} for this to work;
478 likewise, the proposed return value is initialized to
\code{-
1}
479 (failure) and only set to success after the final call made is
483 \section{Embedding Python
}
486 The one important task that only embedders (as opposed to extension
487 writers) of the Python interpreter have to worry about is the
488 initialization, and possibly the finalization, of the Python
489 interpreter. Most functionality of the interpreter can only be used
490 after the interpreter has been initialized.
492 The basic initialization function is
\cfunction{Py_Initialize()
}.
493 This initializes the table of loaded modules, and creates the
494 fundamental modules
\module{__builtin__
}\refbimodindex{__builtin__
},
495 \module{__main__
}\refbimodindex{__main__
} and
496 \module{sys
}\refbimodindex{sys
}. It also initializes the module
497 search path (
\code{sys.path
}).
%
498 \indexiii{module
}{search
}{path
}
500 \cfunction{Py_Initialize()
} does not set the ``script argument list''
501 (
\code{sys.argv
}). If this variable is needed by Python code that
502 will be executed later, it must be set explicitly with a call to
503 \code{PySys_SetArgv(
\var{argc
},
\var{argv
})
} subsequent to the call
504 to
\cfunction{Py_Initialize()
}.
506 On most systems (in particular, on
\UNIX{} and Windows, although the
507 details are slightly different),
\cfunction{Py_Initialize()
}
508 calculates the module search path based upon its best guess for the
509 location of the standard Python interpreter executable, assuming that
510 the Python library is found in a fixed location relative to the Python
511 interpreter executable. In particular, it looks for a directory named
512 \file{lib/python1.5
} (replacing
\file{1.5} with the current
513 interpreter version) relative to the parent directory where the
514 executable named
\file{python
} is found on the shell command search
515 path (the environment variable
\envvar{PATH
}).
517 For instance, if the Python executable is found in
518 \file{/usr/local/bin/python
}, it will assume that the libraries are in
519 \file{/usr/local/lib/python1.5
}. (In fact, this particular path
520 is also the ``fallback'' location, used when no executable file named
521 \file{python
} is found along
\envvar{PATH
}.) The user can override
522 this behavior by setting the environment variable
\envvar{PYTHONHOME
},
523 or insert additional directories in front of the standard path by
524 setting
\envvar{PYTHONPATH
}.
526 The embedding application can steer the search by calling
527 \code{Py_SetProgramName(
\var{file
})
} \emph{before
} calling
528 \cfunction{Py_Initialize()
}. Note that
\envvar{PYTHONHOME
} still
529 overrides this and
\envvar{PYTHONPATH
} is still inserted in front of
530 the standard path. An application that requires total control has to
531 provide its own implementation of
\cfunction{Py_GetPath()
},
532 \cfunction{Py_GetPrefix()
},
\cfunction{Py_GetExecPrefix()
},
533 \cfunction{Py_GetProgramFullPath()
} (all defined in
534 \file{Modules/getpath.c
}).
536 Sometimes, it is desirable to ``uninitialize'' Python. For instance,
537 the application may want to start over (make another call to
538 \cfunction{Py_Initialize()
}) or the application is simply done with its
539 use of Python and wants to free all memory allocated by Python. This
540 can be accomplished by calling
\cfunction{Py_Finalize()
}. The function
541 \cfunction{Py_IsInitialized()
} returns true iff Python is currently in the
542 initialized state. More information about these functions is given in
546 \chapter{The Very High Level Layer
}
549 The functions in this chapter will let you execute Python source code
550 given in a file or a buffer, but they will not let you interact in a
551 more detailed way with the interpreter.
553 \begin{cfuncdesc
}{int
}{PyRun_AnyFile
}{FILE *fp, char *filename
}
556 \begin{cfuncdesc
}{int
}{PyRun_SimpleString
}{char *command
}
559 \begin{cfuncdesc
}{int
}{PyRun_SimpleFile
}{FILE *fp, char *filename
}
562 \begin{cfuncdesc
}{int
}{PyRun_InteractiveOne
}{FILE *fp, char *filename
}
565 \begin{cfuncdesc
}{int
}{PyRun_InteractiveLoop
}{FILE *fp, char *filename
}
568 \begin{cfuncdesc
}{struct _node*
}{PyParser_SimpleParseString
}{char *str,
572 \begin{cfuncdesc
}{struct _node*
}{PyParser_SimpleParseFile
}{FILE *fp,
573 char *filename, int start
}
576 \begin{cfuncdesc
}{PyObject*
}{PyRun_String
}{char *str, int start,
581 \begin{cfuncdesc
}{PyObject*
}{PyRun_File
}{FILE *fp, char *filename,
582 int start, PyObject *globals,
586 \begin{cfuncdesc
}{PyObject*
}{Py_CompileString
}{char *str, char *filename,
591 \chapter{Reference Counting
}
594 The macros in this section are used for managing reference counts
597 \begin{cfuncdesc
}{void
}{Py_INCREF
}{PyObject *o
}
598 Increment the reference count for object
\var{o
}. The object must
599 not be
\NULL{}; if you aren't sure that it isn't
\NULL{}, use
600 \cfunction{Py_XINCREF()
}.
603 \begin{cfuncdesc
}{void
}{Py_XINCREF
}{PyObject *o
}
604 Increment the reference count for object
\var{o
}. The object may be
605 \NULL{}, in which case the macro has no effect.
608 \begin{cfuncdesc
}{void
}{Py_DECREF
}{PyObject *o
}
609 Decrement the reference count for object
\var{o
}. The object must
610 not be
\NULL{}; if you aren't sure that it isn't
\NULL{}, use
611 \cfunction{Py_XDECREF()
}. If the reference count reaches zero, the
612 object's type's deallocation function (which must not be
\NULL{}) is
615 \strong{Warning:
} The deallocation function can cause arbitrary Python
616 code to be invoked (e.g. when a class instance with a
\method{__del__()
}
617 method is deallocated). While exceptions in such code are not
618 propagated, the executed code has free access to all Python global
619 variables. This means that any object that is reachable from a global
620 variable should be in a consistent state before
\cfunction{Py_DECREF()
} is
621 invoked. For example, code to delete an object from a list should
622 copy a reference to the deleted object in a temporary variable, update
623 the list data structure, and then call
\cfunction{Py_DECREF()
} for the
627 \begin{cfuncdesc
}{void
}{Py_XDECREF
}{PyObject *o
}
628 Decrement the reference count for object
\var{o
}. The object may be
629 \NULL{}, in which case the macro has no effect; otherwise the effect
630 is the same as for
\cfunction{Py_DECREF()
}, and the same warning
634 The following functions or macros are only for internal use:
635 \cfunction{_Py_Dealloc()
},
\cfunction{_Py_ForgetReference()
},
636 \cfunction{_Py_NewReference()
}, as well as the global variable
639 XXX Should mention Py_Malloc(), Py_Realloc(), Py_Free(),
640 PyMem_Malloc(), PyMem_Realloc(), PyMem_Free(), PyMem_NEW(),
641 PyMem_RESIZE(), PyMem_DEL(), PyMem_XDEL().
644 \chapter{Exception Handling
}
645 \label{exceptionHandling
}
647 The functions in this chapter will let you handle and raise Python
648 exceptions. It is important to understand some of the basics of
649 Python exception handling. It works somewhat like the
\UNIX{}
650 \code{errno
} variable: there is a global indicator (per thread) of the
651 last error that occurred. Most functions don't clear this on success,
652 but will set it to indicate the cause of the error on failure. Most
653 functions also return an error indicator, usually
\NULL{} if they are
654 supposed to return a pointer, or
\code{-
1} if they return an integer
655 (exception: the
\code{PyArg_Parse*()
} functions return
\code{1} for
656 success and
\code{0} for failure). When a function must fail because
657 some function it called failed, it generally doesn't set the error
658 indicator; the function it called already set it.
660 The error indicator consists of three Python objects corresponding to
661 the Python variables
\code{sys.exc_type
},
\code{sys.exc_value
} and
662 \code{sys.exc_traceback
}. API functions exist to interact with the
663 error indicator in various ways. There is a separate error indicator
666 % XXX Order of these should be more thoughtful.
667 % Either alphabetical or some kind of structure.
669 \begin{cfuncdesc
}{void
}{PyErr_Print
}{}
670 Print a standard traceback to
\code{sys.stderr
} and clear the error
671 indicator. Call this function only when the error indicator is set.
672 (Otherwise it will cause a fatal error!)
675 \begin{cfuncdesc
}{PyObject*
}{PyErr_Occurred
}{}
676 Test whether the error indicator is set. If set, return the exception
677 \emph{type
} (the first argument to the last call to one of the
678 \code{PyErr_Set*()
} functions or to
\cfunction{PyErr_Restore()
}). If
679 not set, return
\NULL{}. You do not own a reference to the return
680 value, so you do not need to
\cfunction{Py_DECREF()
} it.
681 \strong{Note:
} do not compare the return value to a specific
682 exception; use
\cfunction{PyErr_ExceptionMatches()
} instead, shown
686 \begin{cfuncdesc
}{int
}{PyErr_ExceptionMatches
}{PyObject *exc
}
688 \samp{PyErr_GivenExceptionMatches(PyErr_Occurred(),
\var{exc
})
}.
689 This should only be called when an exception is actually set.
692 \begin{cfuncdesc
}{int
}{PyErr_GivenExceptionMatches
}{PyObject *given, PyObject *exc
}
693 Return true if the
\var{given
} exception matches the exception in
694 \var{exc
}. If
\var{exc
} is a class object, this also returns true
695 when
\var{given
} is a subclass. If
\var{exc
} is a tuple, all
696 exceptions in the tuple (and recursively in subtuples) are searched
697 for a match. This should only be called when an exception is actually
701 \begin{cfuncdesc
}{void
}{PyErr_NormalizeException
}{PyObject**exc, PyObject**val, PyObject**tb
}
702 Under certain circumstances, the values returned by
703 \cfunction{PyErr_Fetch()
} below can be ``unnormalized'', meaning that
704 \code{*
\var{exc
}} is a class object but
\code{*
\var{val
}} is not an
705 instance of the same class. This function can be used to instantiate
706 the class in that case. If the values are already normalized, nothing
710 \begin{cfuncdesc
}{void
}{PyErr_Clear
}{}
711 Clear the error indicator. If the error indicator is not set, there
715 \begin{cfuncdesc
}{void
}{PyErr_Fetch
}{PyObject **ptype, PyObject **pvalue, PyObject **ptraceback
}
716 Retrieve the error indicator into three variables whose addresses are
717 passed. If the error indicator is not set, set all three variables to
718 \NULL{}. If it is set, it will be cleared and you own a reference to
719 each object retrieved. The value and traceback object may be
\NULL{}
720 even when the type object is not.
\strong{Note:
} this function is
721 normally only used by code that needs to handle exceptions or by code
722 that needs to save and restore the error indicator temporarily.
725 \begin{cfuncdesc
}{void
}{PyErr_Restore
}{PyObject *type, PyObject *value, PyObject *traceback
}
726 Set the error indicator from the three objects. If the error
727 indicator is already set, it is cleared first. If the objects are
728 \NULL{}, the error indicator is cleared. Do not pass a
\NULL{} type
729 and non-
\NULL{} value or traceback. The exception type should be a
730 string or class; if it is a class, the value should be an instance of
731 that class. Do not pass an invalid exception type or value.
732 (Violating these rules will cause subtle problems later.) This call
733 takes away a reference to each object, i.e. you must own a reference
734 to each object before the call and after the call you no longer own
735 these references. (If you don't understand this, don't use this
736 function. I warned you.)
\strong{Note:
} this function is normally
737 only used by code that needs to save and restore the error indicator
741 \begin{cfuncdesc
}{void
}{PyErr_SetString
}{PyObject *type, char *message
}
742 This is the most common way to set the error indicator. The first
743 argument specifies the exception type; it is normally one of the
744 standard exceptions, e.g.
\code{PyExc_RuntimeError
}. You need not
745 increment its reference count. The second argument is an error
746 message; it is converted to a string object.
749 \begin{cfuncdesc
}{void
}{PyErr_SetObject
}{PyObject *type, PyObject *value
}
750 This function is similar to
\cfunction{PyErr_SetString()
} but lets you
751 specify an arbitrary Python object for the ``value'' of the exception.
752 You need not increment its reference count.
755 \begin{cfuncdesc
}{void
}{PyErr_SetNone
}{PyObject *type
}
756 This is a shorthand for
\samp{PyErr_SetObject(
\var{type
}, Py_None)
}.
759 \begin{cfuncdesc
}{int
}{PyErr_BadArgument
}{}
760 This is a shorthand for
\samp{PyErr_SetString(PyExc_TypeError,
761 \var{message
})
}, where
\var{message
} indicates that a built-in operation
762 was invoked with an illegal argument. It is mostly for internal use.
765 \begin{cfuncdesc
}{PyObject*
}{PyErr_NoMemory
}{}
766 This is a shorthand for
\samp{PyErr_SetNone(PyExc_MemoryError)
}; it
767 returns
\NULL{} so an object allocation function can write
768 \samp{return PyErr_NoMemory();
} when it runs out of memory.
771 \begin{cfuncdesc
}{PyObject*
}{PyErr_SetFromErrno
}{PyObject *type
}
772 This is a convenience function to raise an exception when a
\C{} library
773 function has returned an error and set the
\C{} variable
\code{errno
}.
774 It constructs a tuple object whose first item is the integer
775 \code{errno
} value and whose second item is the corresponding error
776 message (gotten from
\cfunction{strerror()
}), and then calls
777 \samp{PyErr_SetObject(
\var{type
},
\var{object
})
}. On
\UNIX{}, when
778 the
\code{errno
} value is
\constant{EINTR
}, indicating an interrupted
779 system call, this calls
\cfunction{PyErr_CheckSignals()
}, and if that set
780 the error indicator, leaves it set to that. The function always
781 returns
\NULL{}, so a wrapper function around a system call can write
782 \samp{return PyErr_SetFromErrno();
} when the system call returns an
786 \begin{cfuncdesc
}{void
}{PyErr_BadInternalCall
}{}
787 This is a shorthand for
\samp{PyErr_SetString(PyExc_TypeError,
788 \var{message
})
}, where
\var{message
} indicates that an internal
789 operation (e.g. a Python/C API function) was invoked with an illegal
790 argument. It is mostly for internal use.
793 \begin{cfuncdesc
}{int
}{PyErr_CheckSignals
}{}
794 This function interacts with Python's signal handling. It checks
795 whether a signal has been sent to the processes and if so, invokes the
796 corresponding signal handler. If the
797 \module{signal
}\refbimodindex{signal
} module is supported, this can
798 invoke a signal handler written in Python. In all cases, the default
799 effect for
\constant{SIGINT
} is to raise the
800 \exception{KeyboadInterrupt
} exception. If an exception is raised the
801 error indicator is set and the function returns
\code{1}; otherwise
802 the function returns
\code{0}. The error indicator may or may not be
803 cleared if it was previously set.
806 \begin{cfuncdesc
}{void
}{PyErr_SetInterrupt
}{}
807 This function is obsolete (XXX or platform dependent?). It simulates
808 the effect of a
\constant{SIGINT
} signal arriving --- the next time
809 \cfunction{PyErr_CheckSignals()
} is called,
810 \exception{KeyboadInterrupt
} will be raised.
813 \begin{cfuncdesc
}{PyObject*
}{PyErr_NewException
}{char *name,
816 This utility function creates and returns a new exception object. The
817 \var{name
} argument must be the name of the new exception, a
\C{} string
818 of the form
\code{module.class
}. The
\var{base
} and
\var{dict
}
819 arguments are normally
\NULL{}. Normally, this creates a class
820 object derived from the root for all exceptions, the built-in name
821 \exception{Exception
} (accessible in
\C{} as
\code{PyExc_Exception
}).
822 In this case the
\code{__module__
} attribute of the new class is set to the
823 first part (up to the last dot) of the
\var{name
} argument, and the
824 class name is set to the last part (after the last dot). When the
825 user has specified the
\code{-X
} command line option to use string
826 exceptions, for backward compatibility, or when the
\var{base
}
827 argument is not a class object (and not
\NULL{}), a string object
828 created from the entire
\var{name
} argument is returned. The
829 \var{base
} argument can be used to specify an alternate base class.
830 The
\var{dict
} argument can be used to specify a dictionary of class
831 variables and methods.
835 \section{Standard Exceptions
}
836 \label{standardExceptions
}
838 All standard Python exceptions are available as global variables whose
839 names are
\samp{PyExc_
} followed by the Python exception name.
840 These have the type
\code{PyObject *
}; they are all either class
841 objects or string objects, depending on the use of the
\code{-X
}
842 option to the interpreter. For completeness, here are all the
844 \code{PyExc_Exception
},
845 \code{PyExc_StandardError
},
846 \code{PyExc_ArithmeticError
},
847 \code{PyExc_LookupError
},
848 \code{PyExc_AssertionError
},
849 \code{PyExc_AttributeError
},
850 \code{PyExc_EOFError
},
851 \code{PyExc_FloatingPointError
},
852 \code{PyExc_IOError
},
853 \code{PyExc_ImportError
},
854 \code{PyExc_IndexError
},
855 \code{PyExc_KeyError
},
856 \code{PyExc_KeyboardInterrupt
},
857 \code{PyExc_MemoryError
},
858 \code{PyExc_NameError
},
859 \code{PyExc_OverflowError
},
860 \code{PyExc_RuntimeError
},
861 \code{PyExc_SyntaxError
},
862 \code{PyExc_SystemError
},
863 \code{PyExc_SystemExit
},
864 \code{PyExc_TypeError
},
865 \code{PyExc_ValueError
},
866 \code{PyExc_ZeroDivisionError
}.
872 The functions in this chapter perform various utility tasks, such as
873 parsing function arguments and constructing Python values from
\C{}
876 \section{OS Utilities
}
879 \begin{cfuncdesc
}{int
}{Py_FdIsInteractive
}{FILE *fp, char *filename
}
880 Return true (nonzero) if the standard I/O file
\var{fp
} with name
881 \var{filename
} is deemed interactive. This is the case for files for
882 which
\samp{isatty(fileno(
\var{fp
}))
} is true. If the global flag
883 \code{Py_InteractiveFlag
} is true, this function also returns true if
884 the
\var{name
} pointer is
\NULL{} or if the name is equal to one of
885 the strings
\code{"<stdin>"
} or
\code{"???"
}.
888 \begin{cfuncdesc
}{long
}{PyOS_GetLastModificationTime
}{char *filename
}
889 Return the time of last modification of the file
\var{filename
}.
890 The result is encoded in the same way as the timestamp returned by
891 the standard
\C{} library function
\cfunction{time()
}.
895 \section{Process Control
}
896 \label{processControl
}
898 \begin{cfuncdesc
}{void
}{Py_FatalError
}{char *message
}
899 Print a fatal error message and kill the process. No cleanup is
900 performed. This function should only be invoked when a condition is
901 detected that would make it dangerous to continue using the Python
902 interpreter; e.g., when the object administration appears to be
903 corrupted. On
\UNIX{}, the standard
\C{} library function
904 \cfunction{abort()
} is called which will attempt to produce a
908 \begin{cfuncdesc
}{void
}{Py_Exit
}{int status
}
909 Exit the current process. This calls
\cfunction{Py_Finalize()
} and
910 then calls the standard
\C{} library function
911 \code{exit(
\var{status
})
}.
914 \begin{cfuncdesc
}{int
}{Py_AtExit
}{void
(*func) ()}
915 Register a cleanup function to be called by \cfunction{Py_Finalize()}.
916 The cleanup function will be called with no arguments and should
917 return no value. At most 32 cleanup functions can be registered.
918 When the registration is successful, \cfunction{Py_AtExit()} returns
919 \code{0}; on failure, it returns \code{-1}. The cleanup function
920 registered last is called first. Each cleanup function will be called
921 at most once. Since Python's internal finallization will have
922 completed before the cleanup function, no Python APIs should be called
927 \section{Importing Modules}
930 \begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
931 This is a simplified interface to \cfunction{PyImport_ImportModuleEx()}
932 below, leaving the \var{globals} and \var{locals} arguments set to
933 \NULL{}. When the \var{name} argument contains a dot (i.e., when
934 it specifies a submodule of a package), the \var{fromlist} argument is
935 set to the list \code{['*']} so that the return value is the named
936 module rather than the top-level package containing it as would
937 otherwise be the case. (Unfortunately, this has an additional side
938 effect when \var{name} in fact specifies a subpackage instead of a
939 submodule: the submodules specified in the package's \code{__all__}
940 variable are loaded.) Return a new reference to the imported module,
941 or \NULL{} with an exception set on failure (the module may still
942 be created in this case --- examine \code{sys.modules} to find out).
945 \begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name, PyObject *globals, PyObject *locals, PyObject *fromlist}
946 Import a module. This is best described by referring to the built-in
947 Python function \function{__import__()}\bifuncindex{__import__}, as
948 the standard \function{__import__()} function calls this function
951 The return value is a new reference to the imported module or
952 top-level package, or \NULL{} with an exception set on failure
953 (the module may still be created in this case). Like for
954 \function{__import__()}, the return value when a submodule of a
955 package was requested is normally the top-level package, unless a
956 non-empty \var{fromlist} was given.
959 \begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
960 This is a higher-level interface that calls the current ``import hook
961 function''. It invokes the \function{__import__()} function from the
962 \code{__builtins__} of the current globals. This means that the
963 import is done using whatever import hooks are installed in the
964 current environment, e.g. by \module{rexec}\refstmodindex{rexec} or
965 \module{ihooks}\refstmodindex{ihooks}.
968 \begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
969 Reload a module. This is best described by referring to the built-in
970 Python function \function{reload()}\bifuncindex{reload}, as the standard
971 \function{reload()} function calls this function directly. Return a
972 new reference to the reloaded module, or \NULL{} with an exception set
973 on failure (the module still exists in this case).
976 \begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
977 Return the module object corresponding to a module name. The
978 \var{name} argument may be of the form \code{package.module}). First
979 check the modules dictionary if there's one there, and if not, create
980 a new one and insert in in the modules dictionary. Because the former
981 action is most common, this does not return a new reference, and you
982 do not own the returned reference. Return \NULL{} with an
983 exception set on failure.
986 \begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
987 Given a module name (possibly of the form \code{package.module}) and a
988 code object read from a Python bytecode file or obtained from the
989 built-in function \function{compile()}\bifuncindex{compile}, load the
990 module. Return a new reference to the module object, or \NULL{} with
991 an exception set if an error occurred (the module may still be created
992 in this case). (This function would reload the module if it was
996 \begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
997 Return the magic number for Python bytecode files (a.k.a. \file{.pyc}
998 and \file{.pyo} files). The magic number should be present in the
999 first four bytes of the bytecode file, in little-endian byte order.
1002 \begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
1003 Return the dictionary used for the module administration
1004 (a.k.a. \code{sys.modules}). Note that this is a per-interpreter
1008 \begin{cfuncdesc}{void}{_PyImport_Init}{}
1009 Initialize the import mechanism. For internal use only.
1012 \begin{cfuncdesc}{void}{PyImport_Cleanup}{}
1013 Empty the module table. For internal use only.
1016 \begin{cfuncdesc}{void}{_PyImport_Fini}{}
1017 Finalize the import mechanism. For internal use only.
1020 \begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
1021 For internal use only.
1024 \begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
1025 For internal use only.
1028 \begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *}
1029 Load a frozen module. Return \code{1} for success, \code{0} if the
1030 module is not found, and \code{-1} with an exception set if the
1031 initialization failed. To access the imported module on a successful
1032 load, use \cfunction{PyImport_ImportModule()}.
1033 (Note the misnomer --- this function would reload the module if it was
1037 \begin{ctypedesc}{struct _frozen}
1038 This is the structure type definition for frozen module descriptors,
1039 as generated by the \program{freeze}\index{freeze utility} utility
1040 (see \file{Tools/freeze/} in the Python source distribution). Its
1046 unsigned char *code;
1052 \begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
1053 This pointer is initialized to point to an array of \code{struct
1054 _frozen} records, terminated by one whose members are all \NULL{}
1055 or zero. When a frozen module is imported, it is searched in this
1056 table. Third-party code could play tricks with this to provide a
1057 dynamically created collection of frozen modules.
1061 \chapter{Abstract Objects Layer}
1064 The functions in this chapter interact with Python objects regardless
1065 of their type, or with wide classes of object types (e.g. all
1066 numerical types, or all sequence types). When used on object types
1067 for which they do not apply, they will flag a Python exception.
1069 \section{Object Protocol}
1072 \begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
1073 Print an object \var{o}, on file \var{fp}. Returns \code{-1} on error
1074 The flags argument is used to enable certain printing
1075 options. The only option currently supported is
1076 \constant{Py_Print_RAW}.
1079 \begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
1080 Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1081 \code{0} otherwise. This is equivalent to the Python expression
1082 \samp{hasattr(\var{o}, \var{attr_name})}.
1083 This function always succeeds.
1086 \begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o, char *attr_name}
1087 Retrieve an attribute named \var{attr_name} from object \var{o}.
1088 Returns the attribute value on success, or \NULL{} on failure.
1089 This is the equivalent of the Python expression
1090 \samp{\var{o}.\var{attr_name}}.
1094 \begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
1095 Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
1096 \code{0} otherwise. This is equivalent to the Python expression
1097 \samp{hasattr(\var{o}, \var{attr_name})}.
1098 This function always succeeds.
1102 \begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o, PyObject *attr_name}
1103 Retrieve an attribute named \var{attr_name} from object \var{o}.
1104 Returns the attribute value on success, or \NULL{} on failure.
1105 This is the equivalent of the Python expression
1106 \samp{\var{o}.\var{attr_name}}.
1110 \begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o, char *attr_name, PyObject *v}
1111 Set the value of the attribute named \var{attr_name}, for object
1112 \var{o}, to the value \var{v}. Returns \code{-1} on failure. This is
1113 the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1118 \begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o, PyObject *attr_name, PyObject *v}
1119 Set the value of the attribute named \var{attr_name}, for
1121 to the value \var{v}. Returns \code{-1} on failure. This is
1122 the equivalent of the Python statement \samp{\var{o}.\var{attr_name} =
1127 \begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
1128 Delete attribute named \var{attr_name}, for object \var{o}. Returns
1129 \code{-1} on failure. This is the equivalent of the Python
1130 statement: \samp{del \var{o}.\var{attr_name}}.
1134 \begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
1135 Delete attribute named \var{attr_name}, for object \var{o}. Returns
1136 \code{-1} on failure. This is the equivalent of the Python
1137 statement \samp{del \var{o}.\var{attr_name}}.
1141 \begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
1142 Compare the values of \var{o1} and \var{o2} using a routine provided
1143 by \var{o1}, if one exists, otherwise with a routine provided by
1144 \var{o2}. The result of the comparison is returned in \var{result}.
1145 Returns \code{-1} on failure. This is the equivalent of the Python
1146 statement \samp{\var{result} = cmp(\var{o1}, \var{o2})}.
1150 \begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
1151 Compare the values of \var{o1} and \var{o2} using a routine provided
1152 by \var{o1}, if one exists, otherwise with a routine provided by
1153 \var{o2}. Returns the result of the comparison on success. On error,
1154 the value returned is undefined; use \cfunction{PyErr_Occurred()} to
1155 detect an error. This is equivalent to the
1156 Python expression \samp{cmp(\var{o1}, \var{o2})}.
1160 \begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
1161 Compute the string representation of object, \var{o}. Returns the
1162 string representation on success, \NULL{} on failure. This is
1163 the equivalent of the Python expression \samp{repr(\var{o})}.
1164 Called by the \function{repr()}\bifuncindex{repr} built-in function
1165 and by reverse quotes.
1169 \begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
1170 Compute the string representation of object \var{o}. Returns the
1171 string representation on success, \NULL{} on failure. This is
1172 the equivalent of the Python expression \samp{str(\var{o})}.
1173 Called by the \function{str()}\bifuncindex{str} built-in function and
1174 by the \keyword{print} statement.
1178 \begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
1179 Determine if the object \var{o}, is callable. Return \code{1} if the
1180 object is callable and \code{0} otherwise.
1181 This function always succeeds.
1185 \begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object, PyObject *args}
1186 Call a callable Python object \var{callable_object}, with
1187 arguments given by the tuple \var{args}. If no arguments are
1188 needed, then args may be \NULL{}. Returns the result of the
1189 call on success, or \NULL{} on failure. This is the equivalent
1190 of the Python expression \samp{apply(\var{o}, \var{args})}.
1193 \begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable_object, char *format, ...}
1194 Call a callable Python object \var{callable_object}, with a
1195 variable number of \C{} arguments. The \C{} arguments are described
1196 using a \cfunction{Py_BuildValue()} style format string. The format may
1197 be \NULL{}, indicating that no arguments are provided. Returns the
1198 result of the call on success, or \NULL{} on failure. This is
1199 the equivalent of the Python expression \samp{apply(\var{o},
1204 \begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o, char *m, char *format, ...}
1205 Call the method named \var{m} of object \var{o} with a variable number
1206 of C arguments. The \C{} arguments are described by a
1207 \cfunction{Py_BuildValue()} format string. The format may be \NULL{},
1208 indicating that no arguments are provided. Returns the result of the
1209 call on success, or \NULL{} on failure. This is the equivalent of the
1210 Python expression \samp{\var{o}.\var{method}(\var{args})}.
1211 Note that Special method names, such as \method{__add__()},
1212 \method{__getitem__()}, and so on are not supported. The specific
1213 abstract-object routines for these must be used.
1217 \begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
1218 Compute and return the hash value of an object \var{o}. On
1219 failure, return \code{-1}. This is the equivalent of the Python
1220 expression \samp{hash(\var{o})}.
1224 \begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
1225 Returns \code{1} if the object \var{o} is considered to be true, and
1226 \code{0} otherwise. This is equivalent to the Python expression
1227 \samp{not not \var{o}}.
1228 This function always succeeds.
1232 \begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
1233 On success, returns a type object corresponding to the object
1234 type of object \var{o}. On failure, returns \NULL{}. This is
1235 equivalent to the Python expression \samp{type(\var{o})}.
1239 \begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
1240 Return the length of object \var{o}. If the object \var{o} provides
1241 both sequence and mapping protocols, the sequence length is
1242 returned. On error, \code{-1} is returned. This is the equivalent
1243 to the Python expression \samp{len(\var{o})}.
1247 \begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
1248 Return element of \var{o} corresponding to the object \var{key} or
1249 \NULL{} on failure. This is the equivalent of the Python expression
1250 \samp{\var{o}[\var{key}]}.
1254 \begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o, PyObject *key, PyObject *v}
1255 Map the object \var{key} to the value \var{v}.
1256 Returns \code{-1} on failure. This is the equivalent
1257 of the Python statement \samp{\var{o}[\var{key}] = \var{v}}.
1261 \begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key, PyObject *v}
1262 Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
1263 failure. This is the equivalent of the Python statement \samp{del
1264 \var{o}[\var{key}]}.
1268 \section{Number Protocol}
1271 \begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
1272 Returns \code{1} if the object \var{o} provides numeric protocols, and
1274 This function always succeeds.
1278 \begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
1279 Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
1280 failure. This is the equivalent of the Python expression
1281 \samp{\var{o1} + \var{o2}}.
1285 \begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
1286 Returns the result of subtracting \var{o2} from \var{o1}, or \NULL{}
1287 on failure. This is the equivalent of the Python expression
1288 \samp{\var{o1} - \var{o2}}.
1292 \begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
1293 Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{} on
1294 failure. This is the equivalent of the Python expression
1295 \samp{\var{o1} * \var{o2}}.
1299 \begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
1300 Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
1302 This is the equivalent of the Python expression \samp{\var{o1} /
1307 \begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
1308 Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{} on
1309 failure. This is the equivalent of the Python expression
1310 \samp{\var{o1} \% \var{o2}}.
1314 \begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
1315 See the built-in function \function{divmod()}\bifuncindex{divmod}.
1316 Returns \NULL{} on failure. This is the equivalent of the Python
1317 expression \samp{divmod(\var{o1}, \var{o2})}.
1321 \begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1, PyObject *o2, PyObject *o3}
1322 See the built-in function \function{pow()}\bifuncindex{pow}. Returns
1323 \NULL{} on failure. This is the equivalent of the Python expression
1324 \samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3} is optional.
1325 If \var{o3} is to be ignored, pass \code{Py_None} in its place.
1329 \begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
1330 Returns the negation of \var{o} on success, or \NULL{} on failure.
1331 This is the equivalent of the Python expression \samp{-\var{o}}.
1335 \begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
1336 Returns \var{o} on success, or \NULL{} on failure.
1337 This is the equivalent of the Python expression \samp{+\var{o}}.
1341 \begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
1342 Returns the absolute value of \var{o}, or \NULL{} on failure. This is
1343 the equivalent of the Python expression \samp{abs(\var{o})}.
1347 \begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
1348 Returns the bitwise negation of \var{o} on success, or \NULL{} on
1349 failure. This is the equivalent of the Python expression
1354 \begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
1355 Returns the result of left shifting \var{o1} by \var{o2} on success,
1356 or \NULL{} on failure. This is the equivalent of the Python
1357 expression \samp{\var{o1} << \var{o2}}.
1361 \begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
1362 Returns the result of right shifting \var{o1} by \var{o2} on success,
1363 or \NULL{} on failure. This is the equivalent of the Python
1364 expression \samp{\var{o1} >> \var{o2}}.
1368 \begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
1369 Returns the result of ``anding'' \var{o2} and \var{o2} on success and
1370 \NULL{} on failure. This is the equivalent of the Python
1371 expression \samp{\var{o1} and \var{o2}}.
1375 \begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
1376 Returns the bitwise exclusive or of \var{o1} by \var{o2} on success,
1377 or \NULL{} on failure. This is the equivalent of the Python
1378 expression \samp{\var{o1} \^{ }\var{o2}}.
1381 \begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
1382 Returns the result of \var{o1} and \var{o2} on success, or \NULL{} on
1383 failure. This is the equivalent of the Python expression
1384 \samp{\var{o1} or \var{o2}}.
1388 \begin{cfuncdesc}{PyObject*}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
1389 This function takes the addresses of two variables of type
1392 If the objects pointed to by \code{*\var{p1}} and \code{*\var{p2}}
1393 have the same type, increment their reference count and return
1394 \code{0} (success). If the objects can be converted to a common
1395 numeric type, replace \code{*p1} and \code{*p2} by their converted
1396 value (with 'new' reference counts), and return \code{0}.
1397 If no conversion is possible, or if some other error occurs,
1398 return \code{-1} (failure) and don't increment the reference counts.
1399 The call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the
1400 Python statement \samp{\var{o1}, \var{o2} = coerce(\var{o1},
1405 \begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
1406 Returns the \var{o} converted to an integer object on success, or
1407 \NULL{} on failure. This is the equivalent of the Python
1408 expression \samp{int(\var{o})}.
1412 \begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
1413 Returns the \var{o} converted to a long integer object on success,
1414 or \NULL{} on failure. This is the equivalent of the Python
1415 expression \samp{long(\var{o})}.
1419 \begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
1420 Returns the \var{o} converted to a float object on success, or \NULL{}
1421 on failure. This is the equivalent of the Python expression
1422 \samp{float(\var{o})}.
1426 \section{Sequence Protocol}
1429 \begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
1430 Return \code{1} if the object provides sequence protocol, and \code{0}
1432 This function always succeeds.
1436 \begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
1437 Return the concatenation of \var{o1} and \var{o2} on success, and \NULL{} on
1438 failure. This is the equivalent of the Python
1439 expression \samp{\var{o1} + \var{o2}}.
1443 \begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
1444 Return the result of repeating sequence object \var{o} \var{count}
1445 times, or \NULL{} on failure. This is the equivalent of the Python
1446 expression \samp{\var{o} * \var{count}}.
1450 \begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
1451 Return the \var{i}th element of \var{o}, or \NULL{} on failure. This
1452 is the equivalent of the Python expression \samp{\var{o}[\var{i}]}.
1456 \begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
1457 Return the slice of sequence object \var{o} between \var{i1} and
1458 \var{i2}, or \NULL{} on failure. This is the equivalent of the Python
1459 expression \samp{\var{o}[\var{i1}:\var{i2}]}.
1463 \begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
1464 Assign object \var{v} to the \var{i}th element of \var{o}.
1465 Returns \code{-1} on failure. This is the equivalent of the Python
1466 statement \samp{\var{o}[\var{i}] = \var{v}}.
1469 \begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
1470 Delete the \var{i}th element of object \var{v}. Returns
1471 \code{-1} on failure. This is the equivalent of the Python
1472 statement \samp{del \var{o}[\var{i}]}.
1475 \begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1, int i2, PyObject *v}
1476 Assign the sequence object \var{v} to the slice in sequence
1477 object \var{o} from \var{i1} to \var{i2}. This is the equivalent of
1478 the Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
1481 \begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
1482 Delete the slice in sequence object \var{o} from \var{i1} to \var{i2}.
1483 Returns \code{-1} on failure. This is the equivalent of the Python
1484 statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
1487 \begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
1488 Returns the \var{o} as a tuple on success, and \NULL{} on failure.
1489 This is equivalent to the Python expression \code{tuple(\var{o})}.
1492 \begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
1493 Return the number of occurrences of \var{value} in \var{o}, that is,
1494 return the number of keys for which \code{\var{o}[\var{key}] ==
1495 \var{value}}. On failure, return \code{-1}. This is equivalent to
1496 the Python expression \samp{\var{o}.count(\var{value})}.
1499 \begin{cfuncdesc}{int}{PySequence_In}{PyObject *o, PyObject *value}
1500 Determine if \var{o} contains \var{value}. If an item in \var{o} is
1501 equal to \var{value}, return \code{1}, otherwise return \code{0}. On
1502 error, return \code{-1}. This is equivalent to the Python expression
1503 \samp{\var{value} in \var{o}}.
1506 \begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
1507 Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
1508 \var{value}}. On error, return \code{-1}. This is equivalent to
1509 the Python expression \samp{\var{o}.index(\var{value})}.
1513 \section{Mapping Protocol}
1516 \begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
1517 Return \code{1} if the object provides mapping protocol, and \code{0}
1519 This function always succeeds.
1523 \begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
1524 Returns the number of keys in object \var{o} on success, and \code{-1}
1525 on failure. For objects that do not provide sequence protocol,
1526 this is equivalent to the Python expression \samp{len(\var{o})}.
1530 \begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
1531 Remove the mapping for object \var{key} from the object \var{o}.
1532 Return \code{-1} on failure. This is equivalent to
1533 the Python statement \samp{del \var{o}[\var{key}]}.
1537 \begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
1538 Remove the mapping for object \var{key} from the object \var{o}.
1539 Return \code{-1} on failure. This is equivalent to
1540 the Python statement \samp{del \var{o}[\var{key}]}.
1544 \begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
1545 On success, return \code{1} if the mapping object has the key \var{key}
1546 and \code{0} otherwise. This is equivalent to the Python expression
1547 \samp{\var{o}.has_key(\var{key})}.
1548 This function always succeeds.
1552 \begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
1553 Return \code{1} if the mapping object has the key \var{key} and
1554 \code{0} otherwise. This is equivalent to the Python expression
1555 \samp{\var{o}.has_key(\var{key})}.
1556 This function always succeeds.
1560 \begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
1561 On success, return a list of the keys in object \var{o}. On
1562 failure, return \NULL{}. This is equivalent to the Python
1563 expression \samp{\var{o}.keys()}.
1567 \begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
1568 On success, return a list of the values in object \var{o}. On
1569 failure, return \NULL{}. This is equivalent to the Python
1570 expression \samp{\var{o}.values()}.
1574 \begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
1575 On success, return a list of the items in object \var{o}, where
1576 each item is a tuple containing a key-value pair. On
1577 failure, return \NULL{}. This is equivalent to the Python
1578 expression \samp{\var{o}.items()}.
1581 \begin{cfuncdesc}{int}{PyMapping_Clear}{PyObject *o}
1582 Make object \var{o} empty. Returns \code{1} on success and \code{0}
1583 on failure. This is equivalent to the Python statement
1584 \samp{for key in \var{o}.keys(): del \var{o}[key]}.
1588 \begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
1589 Return element of \var{o} corresponding to the object \var{key} or
1590 \NULL{} on failure. This is the equivalent of the Python expression
1591 \samp{\var{o}[\var{key}]}.
1594 \begin{cfuncdesc}{PyObject*}{PyMapping_SetItemString}{PyObject *o, char *key, PyObject *v}
1595 Map the object \var{key} to the value \var{v} in object \var{o}.
1596 Returns \code{-1} on failure. This is the equivalent of the Python
1597 statement \samp{\var{o}[\var{key}] = \var{v}}.
1601 \section{Constructors}
1603 \begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *file_name, char *mode}
1604 On success, returns a new file object that is opened on the
1605 file given by \var{file_name}, with a file mode given by \var{mode},
1606 where \var{mode} has the same semantics as the standard \C{} routine
1607 \cfunction{fopen()}. On failure, return \code{-1}.
1610 \begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp, char *file_name, char *mode, int close_on_del}
1611 Return a new file object for an already opened standard \C{} file
1612 pointer, \var{fp}. A file name, \var{file_name}, and open mode,
1613 \var{mode}, must be provided as well as a flag, \var{close_on_del},
1614 that indicates whether the file is to be closed when the file object
1615 is destroyed. On failure, return \code{-1}.
1618 \begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
1619 Returns a new float object with the value \var{v} on success, and
1623 \begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long v}
1624 Returns a new int object with the value \var{v} on success, and
1628 \begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
1629 Returns a new list of length \var{len} on success, and \NULL{} on
1633 \begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
1634 Returns a new long object with the value \var{v} on success, and
1638 \begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
1639 Returns a new long object with the value \var{v} on success, and
1643 \begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1644 Returns a new empty dictionary on success, and \NULL{} on
1648 \begin{cfuncdesc}{PyObject*}{PyString_FromString}{char *v}
1649 Returns a new string object with the value \var{v} on success, and
1653 \begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{char *v, int len}
1654 Returns a new string object with the value \var{v} and length
1655 \var{len} on success, and \NULL{} on failure. If \var{v} is \NULL{},
1656 the contents of the string are uninitialized.
1659 \begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
1660 Returns a new tuple of length \var{len} on success, and \NULL{} on
1665 \chapter{Concrete Objects Layer}
1668 The functions in this chapter are specific to certain Python object
1669 types. Passing them an object of the wrong type is not a good idea;
1670 if you receive an object from a Python program and you are not sure
1671 that it has the right type, you must perform a type check first;
1672 e.g. to check that an object is a dictionary, use
1673 \cfunction{PyDict_Check()}. The chapter is structured like the
1674 ``family tree'' of Python object types.
1677 \section{Fundamental Objects}
1680 This section describes Python type objects and the singleton object
1684 \subsection{Type Objects}
1687 \begin{ctypedesc}{PyTypeObject}
1691 \begin{cvardesc}{PyObject *}{PyType_Type}
1696 \subsection{The None Object}
1699 \begin{cvardesc}{PyObject *}{Py_None}
1704 \section{Sequence Objects}
1705 \label{sequenceObjects}
1707 Generic operations on sequence objects were discussed in the previous
1708 chapter; this section deals with the specific kinds of sequence
1709 objects that are intrinsic to the Python language.
1712 \subsection{String Objects}
1713 \label{stringObjects}
1715 \begin{ctypedesc}{PyStringObject}
1716 This subtype of \code{PyObject} represents a Python string object.
1719 \begin{cvardesc}{PyTypeObject}{PyString_Type}
1720 This instance of \code{PyTypeObject} represents the Python string type.
1723 \begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
1727 \begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
1731 \begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
1734 \begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
1737 \begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
1740 \begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
1744 \begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
1748 \begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
1751 \begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
1755 \begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
1758 \begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
1761 \begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
1765 \begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
1770 \subsection{Tuple Objects}
1771 \label{tupleObjects}
1773 \begin{ctypedesc}{PyTupleObject}
1774 This subtype of \code{PyObject} represents a Python tuple object.
1777 \begin{cvardesc}{PyTypeObject}{PyTuple_Type}
1778 This instance of \code{PyTypeObject} represents the Python tuple type.
1781 \begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
1782 Return true if the argument is a tuple object.
1785 \begin{cfuncdesc}{PyObject*}{PyTuple_New}{int s}
1786 Return a new tuple object of size \var{s}.
1789 \begin{cfuncdesc}{int}{PyTuple_Size}{PyTupleObject *p}
1790 Takes a pointer to a tuple object, and returns the size
1794 \begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyTupleObject *p, int pos}
1795 Returns the object at position \var{pos} in the tuple pointed
1796 to by \var{p}. If \var{pos} is out of bounds, returns \NULL{} and
1797 raises an \exception{IndexError} exception.
1800 \begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyTupleObject *p, int pos}
1801 Does the same, but does no checking of its arguments.
1804 \begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyTupleObject *p,
1807 Takes a slice of the tuple pointed to by \var{p} from
1808 \var{low} to \var{high} and returns it as a new tuple.
1811 \begin{cfuncdesc}{int}{PyTuple_SetItem}{PyTupleObject *p,
1814 Inserts a reference to object \var{o} at position \var{pos} of
1815 the tuple pointed to by \var{p}. It returns \code{0} on success.
1818 \begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyTupleObject *p,
1822 Does the same, but does no error checking, and
1823 should \emph{only} be used to fill in brand new tuples.
1826 \begin{cfuncdesc}{int}{_PyTuple_Resize}{PyTupleObject *p,
1829 Can be used to resize a tuple. Because tuples are
1830 \emph{supposed} to be immutable, this should only be used if there is only
1831 one module referencing the object. Do \emph{not} use this if the tuple may
1832 already be known to some other part of the code. \var{last_is_sticky} is
1833 a flag --- if set, the tuple will grow or shrink at the front, otherwise
1834 it will grow or shrink at the end. Think of this as destroying the old
1835 tuple and creating a new one, only more efficiently.
1839 \subsection{List Objects}
1842 \begin{ctypedesc}{PyListObject}
1843 This subtype of \code{PyObject} represents a Python list object.
1846 \begin{cvardesc}{PyTypeObject}{PyList_Type}
1847 This instance of \code{PyTypeObject} represents the Python list type.
1850 \begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
1851 Returns true if its argument is a \code{PyListObject}.
1854 \begin{cfuncdesc}{PyObject*}{PyList_New}{int size}
1857 \begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
1860 \begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
1863 \begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
1867 \begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
1871 \begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
1874 \begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
1878 \begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
1883 \begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
1886 \begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
1889 \begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
1892 \begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
1895 \begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
1899 \section{Mapping Objects}
1902 \subsection{Dictionary Objects}
1905 \begin{ctypedesc}{PyDictObject}
1906 This subtype of \code{PyObject} represents a Python dictionary object.
1909 \begin{cvardesc}{PyTypeObject}{PyDict_Type}
1910 This instance of \code{PyTypeObject} represents the Python dictionary type.
1913 \begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
1914 Returns true if its argument is a \code{PyDictObject}.
1917 \begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1918 Returns a new empty dictionary.
1921 \begin{cfuncdesc}{void}{PyDict_Clear}{PyDictObject *p}
1922 Empties an existing dictionary of all key/value pairs.
1925 \begin{cfuncdesc}{int}{PyDict_SetItem}{PyDictObject *p,
1928 Inserts \var{value} into the dictionary with a key of \var{key}. Both
1929 \var{key} and \var{value} should be PyObjects, and \var{key} should be
1933 \begin{cfuncdesc}{int}{PyDict_SetItemString}{PyDictObject *p,
1936 Inserts \var{value} into the dictionary using \var{key}
1937 as a key. \var{key} should be a \code{char *}. The key object is
1938 created using \code{PyString_FromString(\var{key})}.
1941 \begin{cfuncdesc}{int}{PyDict_DelItem}{PyDictObject *p, PyObject *key}
1942 Removes the entry in dictionary \var{p} with key \var{key}.
1943 \var{key} is a PyObject.
1946 \begin{cfuncdesc}{int}{PyDict_DelItemString}{PyDictObject *p, char *key}
1947 Removes the entry in dictionary \var{p} which has a key
1948 specified by the \code{char *}\var{key}.
1951 \begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyDictObject *p, PyObject *key}
1952 Returns the object from dictionary \var{p} which has a key
1953 \var{key}. Returns \NULL{} if the key \var{key} is not present.
1956 \begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyDictObject *p, char *key}
1957 Does the same, but \var{key} is specified as a
1958 \code{char *}, rather than a \code{PyObject *}.
1961 \begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyDictObject *p}
1962 Returns a \code{PyListObject} containing all the items
1963 from the dictionary, as in the mapping method \method{items()} (see
1964 the \emph{Python Library Reference}).
1967 \begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyDictObject *p}
1968 Returns a \code{PyListObject} containing all the keys
1969 from the dictionary, as in the mapping method \method{keys()} (see the
1970 \emph{Python Library Reference}).
1973 \begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyDictObject *p}
1974 Returns a \code{PyListObject} containing all the values
1975 from the dictionary \var{p}, as in the mapping method
1976 \method{values()} (see the \emph{Python Library Reference}).
1979 \begin{cfuncdesc}{int}{PyDict_Size}{PyDictObject *p}
1980 Returns the number of items in the dictionary.
1983 \begin{cfuncdesc}{int}{PyDict_Next}{PyDictObject *p,
1991 \section{Numeric Objects}
1992 \label{numericObjects}
1994 \subsection{Plain Integer Objects}
1997 \begin{ctypedesc}{PyIntObject}
1998 This subtype of \code{PyObject} represents a Python integer object.
2001 \begin{cvardesc}{PyTypeObject}{PyInt_Type}
2002 This instance of \code{PyTypeObject} represents the Python plain
2006 \begin{cfuncdesc}{int}{PyInt_Check}{PyObject *}
2010 \begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
2011 Creates a new integer object with a value of \var{ival}.
2013 The current implementation keeps an array of integer objects for all
2014 integers between \code{-1} and \code{100}, when you create an int in
2015 that range you actually just get back a reference to the existing
2016 object. So it should be possible to change the value of \code{1}. I
2017 suspect the behaviour of Python in this case is undefined. :-)
2020 \begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyIntObject *io}
2021 Returns the value of the object \var{io}. No error checking is
2025 \begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
2026 Will first attempt to cast the object to a \code{PyIntObject}, if
2027 it is not already one, and then return its value.
2030 \begin{cfuncdesc}{long}{PyInt_GetMax}{}
2031 Returns the systems idea of the largest integer it can handle
2032 (\constant{LONG_MAX}, as defined in the system header files).
2036 \subsection{Long Integer Objects}
2039 \begin{ctypedesc}{PyLongObject}
2040 This subtype of \code{PyObject} represents a Python long integer
2044 \begin{cvardesc}{PyTypeObject}{PyLong_Type}
2045 This instance of \code{PyTypeObject} represents the Python long
2049 \begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
2050 Returns true if its argument is a \code{PyLongObject}.
2053 \begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
2056 \begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
2059 \begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
2062 \begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
2065 \begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
2068 \begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
2071 \begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
2076 \subsection{Floating Point Objects}
2077 \label{floatObjects}
2079 \begin{ctypedesc}{PyFloatObject}
2080 This subtype of \code{PyObject} represents a Python floating point
2084 \begin{cvardesc}{PyTypeObject}{PyFloat_Type}
2085 This instance of \code{PyTypeObject} represents the Python floating
2089 \begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
2090 Returns true if its argument is a \code{PyFloatObject}.
2093 \begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
2096 \begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
2099 \begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
2103 \subsection{Complex Number Objects}
2104 \label{complexObjects}
2106 \begin{ctypedesc}{Py_complex}
2107 The \C{} structure which corresponds to the value portion of a Python
2108 complex number object. Most of the functions for dealing with complex
2109 number objects use structures of this type as input or output values,
2110 as appropriate. It is defined as:
2120 \begin{ctypedesc}{PyComplexObject}
2121 This subtype of \code{PyObject} represents a Python complex number object.
2124 \begin{cvardesc}{PyTypeObject}{PyComplex_Type}
2125 This instance of \code{PyTypeObject} represents the Python complex
2129 \begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
2130 Returns true if its argument is a \code{PyComplexObject}.
2133 \begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
2136 \begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
2139 \begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
2142 \begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
2145 \begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
2149 \begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
2152 \begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
2155 \begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
2158 \begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
2161 \begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
2164 \begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
2169 \section{Other Objects}
2170 \label{otherObjects}
2172 \subsection{File Objects}
2175 \begin{ctypedesc}{PyFileObject}
2176 This subtype of \code{PyObject} represents a Python file object.
2179 \begin{cvardesc}{PyTypeObject}{PyFile_Type}
2180 This instance of \code{PyTypeObject} represents the Python file type.
2183 \begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2184 Returns true if its argument is a \code{PyFileObject}.
2187 \begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *name, char *mode}
2188 Creates a new \code{PyFileObject} pointing to the file
2189 specified in \var{name} with the mode specified in \var{mode}.
2192 \begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
2193 char *name, char *mode, int (*close)}
2194 Creates a new \code{PyFileObject} from the already-open \var{fp}.
2195 The function \var{close} will be called when the file should be
2199 \begin{cfuncdesc}{FILE *}{PyFile_AsFile}{PyFileObject *p}
2200 Returns the file object associated with \var{p} as a \code{FILE *}.
2203 \begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
2207 \begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
2208 Returns the name of the file specified by \var{p} as a
2209 \code{PyStringObject}.
2212 \begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2213 Available on systems with \cfunction{setvbuf()} only. This should
2214 only be called immediately after file object creation.
2217 \begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyFileObject *p, int newflag}
2218 Sets the \code{softspace} attribute of \var{p} to \var{newflag}.
2219 Returns the previous value. This function clears any errors, and will
2220 return \code{0} as the previous value if the attribute either does not
2221 exist or if there were errors in retrieving it. There is no way to
2222 detect errors from this function, but doing so should not be needed.
2225 \begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
2227 Writes object \var{obj} to file object \var{p}.
2230 \begin{cfuncdesc}{int}{PyFile_WriteString}{char *s, PyFileObject *p,
2232 Writes string \var{s} to file object \var{p}.
2236 \subsection{CObjects}
2242 \chapter{Initialization, Finalization, and Threads}
2243 \label{initialization}
2245 \begin{cfuncdesc}{void}{Py_Initialize}{}
2246 Initialize the Python interpreter. In an application embedding
2247 Python, this should be called before using any other Python/C API
2248 functions; with the exception of \cfunction{Py_SetProgramName()},
2249 \cfunction{PyEval_InitThreads()}, \cfunction{PyEval_ReleaseLock()},
2250 and \cfunction{PyEval_AcquireLock()}. This initializes the table of
2251 loaded modules (\code{sys.modules}), and creates the fundamental
2252 modules \module{__builtin__}\refbimodindex{__builtin__},
2253 \module{__main__}\refbimodindex{__main__} and
2254 \module{sys}\refbimodindex{sys}. It also initializes the module
2255 search path (\code{sys.path}).%
2256 \indexiii{module}{search}{path}
2257 It does not set \code{sys.argv}; use \cfunction{PySys_SetArgv()} for
2258 that. This is a no-op when called for a second time (without calling
2259 \cfunction{Py_Finalize()} first). There is no return value; it is a
2260 fatal error if the initialization fails.
2263 \begin{cfuncdesc}{int}{Py_IsInitialized}{}
2264 Return true (nonzero) when the Python interpreter has been
2265 initialized, false (zero) if not. After \cfunction{Py_Finalize()} is
2266 called, this returns false until \cfunction{Py_Initialize()} is called
2270 \begin{cfuncdesc}{void}{Py_Finalize}{}
2271 Undo all initializations made by \cfunction{Py_Initialize()} and
2272 subsequent use of Python/C API functions, and destroy all
2273 sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that were
2274 created and not yet destroyed since the last call to
2275 \cfunction{Py_Initialize()}. Ideally, this frees all memory allocated
2276 by the Python interpreter. This is a no-op when called for a second
2277 time (without calling \cfunction{Py_Initialize()} again first). There
2278 is no return value; errors during finalization are ignored.
2280 This function is provided for a number of reasons. An embedding
2281 application might want to restart Python without having to restart the
2282 application itself. An application that has loaded the Python
2283 interpreter from a dynamically loadable library (or DLL) might want to
2284 free all memory allocated by Python before unloading the DLL. During a
2285 hunt for memory leaks in an application a developer might want to free
2286 all memory allocated by Python before exiting from the application.
2288 \strong{Bugs and caveats:} The destruction of modules and objects in
2289 modules is done in random order; this may cause destructors
2290 (\method{__del__()} methods) to fail when they depend on other objects
2291 (even functions) or modules. Dynamically loaded extension modules
2292 loaded by Python are not unloaded. Small amounts of memory allocated
2293 by the Python interpreter may not be freed (if you find a leak, please
2294 report it). Memory tied up in circular references between objects is
2295 not freed. Some memory allocated by extension modules may not be
2296 freed. Some extension may not work properly if their initialization
2297 routine is called more than once; this can happen if an applcation
2298 calls \cfunction{Py_Initialize()} and \cfunction{Py_Finalize()} more
2302 \begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
2303 Create a new sub-interpreter. This is an (almost) totally separate
2304 environment for the execution of Python code. In particular, the new
2305 interpreter has separate, independent versions of all imported
2306 modules, including the fundamental modules
2307 \module{__builtin__}\refbimodindex{__builtin__},
2308 \module{__main__}\refbimodindex{__main__} and
2309 \module{sys}\refbimodindex{sys}. The table of loaded modules
2310 (\code{sys.modules}) and the module search path (\code{sys.path}) are
2311 also separate. The new environment has no \code{sys.argv} variable.
2312 It has new standard I/O stream file objects \code{sys.stdin},
2313 \code{sys.stdout} and \code{sys.stderr} (however these refer to the
2314 same underlying \code{FILE} structures in the \C{} library).
2316 The return value points to the first thread state created in the new
2317 sub-interpreter. This thread state is made the current thread state.
2318 Note that no actual thread is created; see the discussion of thread
2319 states below. If creation of the new interpreter is unsuccessful,
2320 \NULL{} is returned; no exception is set since the exception state
2321 is stored in the current thread state and there may not be a current
2322 thread state. (Like all other Python/C API functions, the global
2323 interpreter lock must be held before calling this function and is
2324 still held when it returns; however, unlike most other Python/C API
2325 functions, there needn't be a current thread state on entry.)
2327 Extension modules are shared between (sub-)interpreters as follows:
2328 the first time a particular extension is imported, it is initialized
2329 normally, and a (shallow) copy of its module's dictionary is
2330 squirreled away. When the same extension is imported by another
2331 (sub-)interpreter, a new module is initialized and filled with the
2332 contents of this copy; the extension's \code{init} function is not
2333 called. Note that this is different from what happens when an
2334 extension is imported after the interpreter has been completely
2335 re-initialized by calling \cfunction{Py_Finalize()} and
2336 \cfunction{Py_Initialize()}; in that case, the extension's \code{init}
2337 function \emph{is} called again.
2339 \strong{Bugs and caveats:} Because sub-interpreters (and the main
2340 interpreter) are part of the same process, the insulation between them
2341 isn't perfect --- for example, using low-level file operations like
2342 \code{os.close()} they can (accidentally or maliciously) affect each
2343 other's open files. Because of the way extensions are shared between
2344 (sub-)interpreters, some extensions may not work properly; this is
2345 especially likely when the extension makes use of (static) global
2346 variables, or when the extension manipulates its module's dictionary
2347 after its initialization. It is possible to insert objects created in
2348 one sub-interpreter into a namespace of another sub-interpreter; this
2349 should be done with great care to avoid sharing user-defined
2350 functions, methods, instances or classes between sub-interpreters,
2351 since import operations executed by such objects may affect the
2352 wrong (sub-)interpreter's dictionary of loaded modules. (XXX This is
2353 a hard-to-fix bug that will be addressed in a future release.)
2356 \begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
2357 Destroy the (sub-)interpreter represented by the given thread state.
2358 The given thread state must be the current thread state. See the
2359 discussion of thread states below. When the call returns, the current
2360 thread state is \NULL{}. All thread states associated with this
2361 interpreted are destroyed. (The global interpreter lock must be held
2362 before calling this function and is still held when it returns.)
2363 \cfunction{Py_Finalize()} will destroy all sub-interpreters that haven't
2364 been explicitly destroyed at that point.
2367 \begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
2368 This function should be called before \cfunction{Py_Initialize()} is called
2369 for the first time, if it is called at all. It tells the interpreter
2370 the value of the \code{argv[0]} argument to the \cfunction{main()} function
2371 of the program. This is used by \cfunction{Py_GetPath()} and some other
2372 functions below to find the Python run-time libraries relative to the
2373 interpreter executable. The default value is \code{"python"}. The
2374 argument should point to a zero-terminated character string in static
2375 storage whose contents will not change for the duration of the
2376 program's execution. No code in the Python interpreter will change
2377 the contents of this storage.
2380 \begin{cfuncdesc}{char*}{Py_GetProgramName}{}
2381 Return the program name set with \cfunction{Py_SetProgramName()}, or the
2382 default. The returned string points into static storage; the caller
2383 should not modify its value.
2386 \begin{cfuncdesc}{char*}{Py_GetPrefix}{}
2387 Return the \emph{prefix} for installed platform-independent files. This
2388 is derived through a number of complicated rules from the program name
2389 set with \cfunction{Py_SetProgramName()} and some environment variables;
2390 for example, if the program name is \code{"/usr/local/bin/python"},
2391 the prefix is \code{"/usr/local"}. The returned string points into
2392 static storage; the caller should not modify its value. This
2393 corresponds to the \makevar{prefix} variable in the top-level
2394 \file{Makefile} and the \code{-}\code{-prefix} argument to the
2395 \program{configure} script at build time. The value is available to
2396 Python code as \code{sys.prefix}. It is only useful on \UNIX{}. See
2397 also the next function.
2400 \begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
2401 Return the \emph{exec-prefix} for installed platform-\emph{de}pendent
2402 files. This is derived through a number of complicated rules from the
2403 program name set with \cfunction{Py_SetProgramName()} and some environment
2404 variables; for example, if the program name is
2405 \code{"/usr/local/bin/python"}, the exec-prefix is
2406 \code{"/usr/local"}. The returned string points into static storage;
2407 the caller should not modify its value. This corresponds to the
2408 \makevar{exec_prefix} variable in the top-level \file{Makefile} and the
2409 \code{-}\code{-exec_prefix} argument to the \program{configure} script
2410 at build time. The value is available to Python code as
2411 \code{sys.exec_prefix}. It is only useful on \UNIX{}.
2413 Background: The exec-prefix differs from the prefix when platform
2414 dependent files (such as executables and shared libraries) are
2415 installed in a different directory tree. In a typical installation,
2416 platform dependent files may be installed in the
2417 \code{"/usr/local/plat"} subtree while platform independent may be
2418 installed in \code{"/usr/local"}.
2420 Generally speaking, a platform is a combination of hardware and
2421 software families, e.g. Sparc machines running the Solaris 2.x
2422 operating system are considered the same platform, but Intel machines
2423 running Solaris 2.x are another platform, and Intel machines running
2424 Linux are yet another platform. Different major revisions of the same
2425 operating system generally also form different platforms. Non-\UNIX{}
2426 operating systems are a different story; the installation strategies
2427 on those systems are so different that the prefix and exec-prefix are
2428 meaningless, and set to the empty string. Note that compiled Python
2429 bytecode files are platform independent (but not independent from the
2430 Python version by which they were compiled!).
2432 System administrators will know how to configure the \program{mount} or
2433 \program{automount} programs to share \code{"/usr/local"} between platforms
2434 while having \code{"/usr/local/plat"} be a different filesystem for each
2438 \begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
2439 Return the full program name of the Python executable; this is
2440 computed as a side-effect of deriving the default module search path
2441 from the program name (set by \cfunction{Py_SetProgramName()} above). The
2442 returned string points into static storage; the caller should not
2443 modify its value. The value is available to Python code as
2444 \code{sys.executable}.
2447 \begin{cfuncdesc}{char*}{Py_GetPath}{}
2448 \indexiii{module}{search}{path}
2449 Return the default module search path; this is computed from the
2450 program name (set by \cfunction{Py_SetProgramName()} above) and some
2451 environment variables. The returned string consists of a series of
2452 directory names separated by a platform dependent delimiter character.
2453 The delimiter character is \code{':'} on \UNIX{}, \code{';'} on
2454 DOS/Windows, and \code{'\\n'} (the \ASCII{} newline character) on
2455 Macintosh. The returned string points into static storage; the caller
2456 should not modify its value. The value is available to Python code
2457 as the list \code{sys.path}, which may be modified to change the
2458 future search path for loaded modules.
2460 % XXX should give the exact rules
2463 \begin{cfuncdesc}{const char*}{Py_GetVersion}{}
2464 Return the version of this Python interpreter. This is a string that
2465 looks something like
2468 "1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
2471 The first word (up to the first space character) is the current Python
2472 version; the first three characters are the major and minor version
2473 separated by a period. The returned string points into static storage;
2474 the caller should not modify its value. The value is available to
2475 Python code as the list \code{sys.version}.
2478 \begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
2479 Return the platform identifier for the current platform. On \UNIX{},
2480 this is formed from the ``official'' name of the operating system,
2481 converted to lower case, followed by the major revision number; e.g.,
2482 for Solaris 2.x, which is also known as SunOS 5.x, the value is
2483 \code{"sunos5"}. On Macintosh, it is \code{"mac"}. On Windows, it
2484 is \code{"win"}. The returned string points into static storage;
2485 the caller should not modify its value. The value is available to
2486 Python code as \code{sys.platform}.
2489 \begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
2490 Return the official copyright string for the current Python version,
2493 \code{"Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam"}
2495 The returned string points into static storage; the caller should not
2496 modify its value. The value is available to Python code as the list
2497 \code{sys.copyright}.
2500 \begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
2501 Return an indication of the compiler used to build the current Python
2502 version, in square brackets, for example:
2508 The returned string points into static storage; the caller should not
2509 modify its value. The value is available to Python code as part of
2510 the variable \code{sys.version}.
2513 \begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
2514 Return information about the sequence number and build date and time
2515 of the current Python interpreter instance, for example
2518 "#67, Aug 1 1997, 22:34:28"
2521 The returned string points into static storage; the caller should not
2522 modify its value. The value is available to Python code as part of
2523 the variable \code{sys.version}.
2526 \begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
2530 % XXX Other PySys thingies (doesn't really belong in this chapter)
2532 \section{Thread State and the Global Interpreter Lock}
2535 The Python interpreter is not fully thread safe. In order to support
2536 multi-threaded Python programs, there's a global lock that must be
2537 held by the current thread before it can safely access Python objects.
2538 Without the lock, even the simplest operations could cause problems in
2539 a multi-threaded program: for example, when two threads simultaneously
2540 increment the reference count of the same object, the reference count
2541 could end up being incremented only once instead of twice.
2543 Therefore, the rule exists that only the thread that has acquired the
2544 global interpreter lock may operate on Python objects or call Python/C
2545 API functions. In order to support multi-threaded Python programs,
2546 the interpreter regularly release and reacquires the lock --- by
2547 default, every ten bytecode instructions (this can be changed with
2548 \function{sys.setcheckinterval()}). The lock is also released and
2549 reacquired around potentially blocking I/O operations like reading or
2550 writing a file, so that other threads can run while the thread that
2551 requests the I/O is waiting for the I/O operation to complete.
2553 The Python interpreter needs to keep some bookkeeping information
2554 separate per thread --- for this it uses a data structure called
2555 \code{PyThreadState}. This is new in Python 1.5; in earlier versions,
2556 such state was stored in global variables, and switching threads could
2557 cause problems. In particular, exception handling is now thread safe,
2558 when the application uses \function{sys.exc_info()} to access the
2559 exception last raised in the current thread.
2561 There's one global variable left, however: the pointer to the current
2562 \code{PyThreadState} structure. While most thread packages have a way
2563 to store ``per-thread global data,'' Python's internal platform
2564 independent thread abstraction doesn't support this yet. Therefore,
2565 the current thread state must be manipulated explicitly.
2567 This is easy enough in most cases. Most code manipulating the global
2568 interpreter lock has the following simple structure:
2571 Save the thread state in a local variable.
2572 Release the interpreter lock.
2573 ...Do some blocking I/O operation...
2574 Reacquire the interpreter lock.
2575 Restore the thread state from the local variable.
2578 This is so common that a pair of macros exists to simplify it:
2581 Py_BEGIN_ALLOW_THREADS
2582 ...Do some blocking I/O operation...
2583 Py_END_ALLOW_THREADS
2586 The \code{Py_BEGIN_ALLOW_THREADS} macro opens a new block and declares
2587 a hidden local variable; the \code{Py_END_ALLOW_THREADS} macro closes
2588 the block. Another advantage of using these two macros is that when
2589 Python is compiled without thread support, they are defined empty,
2590 thus saving the thread state and lock manipulations.
2592 When thread support is enabled, the block above expands to the
2597 PyThreadState *_save;
2598 _save = PyEval_SaveThread();
2599 ...Do some blocking I/O operation...
2600 PyEval_RestoreThread(_save);
2604 Using even lower level primitives, we can get roughly the same effect
2609 PyThreadState *_save;
2610 _save = PyThreadState_Swap(NULL);
2611 PyEval_ReleaseLock();
2612 ...Do some blocking I/O operation...
2613 PyEval_AcquireLock();
2614 PyThreadState_Swap(_save);
2618 There are some subtle differences; in particular,
2619 \cfunction{PyEval_RestoreThread()} saves and restores the value of the
2620 global variable \code{errno}, since the lock manipulation does not
2621 guarantee that \code{errno} is left alone. Also, when thread support
2622 is disabled, \cfunction{PyEval_SaveThread()} and
2623 \cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
2624 case, \cfunction{PyEval_ReleaseLock()} and
2625 \cfunction{PyEval_AcquireLock()} are not available. This is done so
2626 that dynamically loaded extensions compiled with thread support
2627 enabled can be loaded by an interpreter that was compiled with
2628 disabled thread support.
2630 The global interpreter lock is used to protect the pointer to the
2631 current thread state. When releasing the lock and saving the thread
2632 state, the current thread state pointer must be retrieved before the
2633 lock is released (since another thread could immediately acquire the
2634 lock and store its own thread state in the global variable).
2635 Reversely, when acquiring the lock and restoring the thread state, the
2636 lock must be acquired before storing the thread state pointer.
2638 Why am I going on with so much detail about this? Because when
2639 threads are created from \C{}, they don't have the global interpreter
2640 lock, nor is there a thread state data structure for them. Such
2641 threads must bootstrap themselves into existence, by first creating a
2642 thread state data structure, then acquiring the lock, and finally
2643 storing their thread state pointer, before they can start using the
2644 Python/C API. When they are done, they should reset the thread state
2645 pointer, release the lock, and finally free their thread state data
2648 When creating a thread data structure, you need to provide an
2649 interpreter state data structure. The interpreter state data
2650 structure hold global data that is shared by all threads in an
2651 interpreter, for example the module administration
2652 (\code{sys.modules}). Depending on your needs, you can either create
2653 a new interpreter state data structure, or share the interpreter state
2654 data structure used by the Python main thread (to access the latter,
2655 you must obtain the thread state and access its \code{interp} member;
2656 this must be done by a thread that is created by Python or by the main
2657 thread after Python is initialized).
2661 \begin{ctypedesc}{PyInterpreterState}
2662 This data structure represents the state shared by a number of
2663 cooperating threads. Threads belonging to the same interpreter
2664 share their module administration and a few other internal items.
2665 There are no public members in this structure.
2667 Threads belonging to different interpreters initially share nothing,
2668 except process state like available memory, open file descriptors and
2669 such. The global interpreter lock is also shared by all threads,
2670 regardless of to which interpreter they belong.
2673 \begin{ctypedesc}{PyThreadState}
2674 This data structure represents the state of a single thread. The only
2675 public data member is \code{PyInterpreterState *interp}, which points
2676 to this thread's interpreter state.
2679 \begin{cfuncdesc}{void}{PyEval_InitThreads}{}
2680 Initialize and acquire the global interpreter lock. It should be
2681 called in the main thread before creating a second thread or engaging
2682 in any other thread operations such as
2683 \cfunction{PyEval_ReleaseLock()} or
2684 \code{PyEval_ReleaseThread(\var{tstate})}. It is not needed before
2685 calling \cfunction{PyEval_SaveThread()} or
2686 \cfunction{PyEval_RestoreThread()}.
2688 This is a no-op when called for a second time. It is safe to call
2689 this function before calling \cfunction{Py_Initialize()}.
2691 When only the main thread exists, no lock operations are needed. This
2692 is a common situation (most Python programs do not use threads), and
2693 the lock operations slow the interpreter down a bit. Therefore, the
2694 lock is not created initially. This situation is equivalent to having
2695 acquired the lock: when there is only a single thread, all object
2696 accesses are safe. Therefore, when this function initializes the
2697 lock, it also acquires it. Before the Python
2698 \module{thread}\refbimodindex{thread} module creates a new thread,
2699 knowing that either it has the lock or the lock hasn't been created
2700 yet, it calls \cfunction{PyEval_InitThreads()}. When this call
2701 returns, it is guaranteed that the lock has been created and that it
2704 It is \strong{not} safe to call this function when it is unknown which
2705 thread (if any) currently has the global interpreter lock.
2707 This function is not available when thread support is disabled at
2711 \begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
2712 Acquire the global interpreter lock. The lock must have been created
2713 earlier. If this thread already has the lock, a deadlock ensues.
2714 This function is not available when thread support is disabled at
2718 \begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
2719 Release the global interpreter lock. The lock must have been created
2720 earlier. This function is not available when thread support is
2721 disabled at compile time.
2724 \begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
2725 Acquire the global interpreter lock and then set the current thread
2726 state to \var{tstate}, which should not be \NULL{}. The lock must
2727 have been created earlier. If this thread already has the lock,
2728 deadlock ensues. This function is not available when thread support
2729 is disabled at compile time.
2732 \begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
2733 Reset the current thread state to \NULL{} and release the global
2734 interpreter lock. The lock must have been created earlier and must be
2735 held by the current thread. The \var{tstate} argument, which must not
2736 be \NULL{}, is only used to check that it represents the current
2737 thread state --- if it isn't, a fatal error is reported. This
2738 function is not available when thread support is disabled at compile
2742 \begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
2743 Release the interpreter lock (if it has been created and thread
2744 support is enabled) and reset the thread state to \NULL{},
2745 returning the previous thread state (which is not \NULL{}). If
2746 the lock has been created, the current thread must have acquired it.
2747 (This function is available even when thread support is disabled at
2751 \begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
2752 Acquire the interpreter lock (if it has been created and thread
2753 support is enabled) and set the thread state to \var{tstate}, which
2754 must not be \NULL{}. If the lock has been created, the current
2755 thread must not have acquired it, otherwise deadlock ensues. (This
2756 function is available even when thread support is disabled at compile
2760 % XXX These aren't really C types, but the ctypedesc macro is the simplest!
2761 \begin{ctypedesc}{Py_BEGIN_ALLOW_THREADS}
2762 This macro expands to
2763 \samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
2764 Note that it contains an opening brace; it must be matched with a
2765 following \code{Py_END_ALLOW_THREADS} macro. See above for further
2766 discussion of this macro. It is a no-op when thread support is
2767 disabled at compile time.
2770 \begin{ctypedesc}{Py_END_ALLOW_THREADS}
2771 This macro expands to
2772 \samp{PyEval_RestoreThread(_save); \}}.
2773 Note that it contains a closing brace; it must be matched with an
2774 earlier \code{Py_BEGIN_ALLOW_THREADS} macro. See above for further
2775 discussion of this macro. It is a no-op when thread support is
2776 disabled at compile time.
2779 \begin{ctypedesc}{Py_BEGIN_BLOCK_THREADS}
2780 This macro expands to \samp{PyEval_RestoreThread(_save);} i.e. it
2781 is equivalent to \code{Py_END_ALLOW_THREADS} without the closing
2782 brace. It is a no-op when thread support is disabled at compile
2786 \begin{ctypedesc}{Py_BEGIN_UNBLOCK_THREADS}
2787 This macro expands to \samp{_save = PyEval_SaveThread();} i.e. it is
2788 equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace
2789 and variable declaration. It is a no-op when thread support is
2790 disabled at compile time.
2793 All of the following functions are only available when thread support
2794 is enabled at compile time, and must be called only when the
2795 interpreter lock has been created.
2797 \begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
2798 Create a new interpreter state object. The interpreter lock must be
2802 \begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
2803 Reset all information in an interpreter state object. The interpreter
2807 \begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
2808 Destroy an interpreter state object. The interpreter lock need not be
2809 held. The interpreter state must have been reset with a previous
2810 call to \cfunction{PyInterpreterState_Clear()}.
2813 \begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
2814 Create a new thread state object belonging to the given interpreter
2815 object. The interpreter lock must be held.
2818 \begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
2819 Reset all information in a thread state object. The interpreter lock
2823 \begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
2824 Destroy a thread state object. The interpreter lock need not be
2825 held. The thread state must have been reset with a previous
2826 call to \cfunction{PyThreadState_Clear()}.
2829 \begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
2830 Return the current thread state. The interpreter lock must be held.
2831 When the current thread state is \NULL{}, this issues a fatal
2832 error (so that the caller needn't check for \NULL{}).
2835 \begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
2836 Swap the current thread state with the thread state given by the
2837 argument \var{tstate}, which may be \NULL{}. The interpreter lock
2842 \chapter{Defining New Object Types}
2845 \begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
2848 \begin{cfuncdesc}{PyObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
2851 \begin{cfuncdesc}{TYPE}{_PyObject_NEW}{TYPE, PyTypeObject *}
2854 \begin{cfuncdesc}{TYPE}{_PyObject_NEW_VAR}{TYPE, PyTypeObject *, int size}
2858 PyObject, PyVarObject
2860 PyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD
2863 unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
2864 intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
2865 getreadbufferproc, getwritebufferproc, getsegcountproc,
2866 destructor, printfunc, getattrfunc, getattrofunc, setattrfunc,
2867 setattrofunc, cmpfunc, reprfunc, hashfunc
2885 Py_None, _Py_NoneStruct
2891 XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
2894 \input{api.ind} % Index -- must be last