History

add hg and python

cinap_lenrek committed 15 years ago

Commit 4bb9e221 parent 987265c3706 files · +1228772 −-233Browse files

Showing the changes to sys/src/cmd/python/Doc/api (12 of 3706 files). Show all

Unified · Split

12 files
  1. sys/src/cmd/python/Doc/api/abstract.tex +1057 −0
  2. sys/src/cmd/python/Doc/api/api.tex +60 −0
  3. sys/src/cmd/python/Doc/api/concrete.tex +3203 −0
  4. sys/src/cmd/python/Doc/api/exceptions.tex +442 −0
  5. sys/src/cmd/python/Doc/api/init.tex +884 −0
  6. sys/src/cmd/python/Doc/api/intro.tex +627 −0
  7. sys/src/cmd/python/Doc/api/memory.tex +204 −0
  8. sys/src/cmd/python/Doc/api/newtypes.tex +1780 −0
  9. sys/src/cmd/python/Doc/api/refcounting.tex +69 −0
  10. sys/src/cmd/python/Doc/api/refcounts.dat +1756 −0
  11. sys/src/cmd/python/Doc/api/utilities.tex +1023 −0
  12. sys/src/cmd/python/Doc/api/veryhigh.tex +287 −0
sys/src/cmd/python/Doc/api/abstract.tex+1057−0
@@ -0,0 +1,1057 @@
1+\chapter{Abstract Objects Layer \label{abstract}}
2+
3+The functions in this chapter interact with Python objects regardless
4+of their type, or with wide classes of object types (e.g. all
5+numerical types, or all sequence types). When used on object types
6+for which they do not apply, they will raise a Python exception.
7+
8+It is not possible to use these functions on objects that are not properly
9+initialized, such as a list object that has been created by
10+\cfunction{PyList_New()}, but whose items have not been set to some
11+non-\code{NULL} value yet.
12+
13+\section{Object Protocol \label{object}}
14+
15+\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
16+ Print an object \var{o}, on file \var{fp}. Returns \code{-1} on
17+ error. The flags argument is used to enable certain printing
18+ options. The only option currently supported is
19+ \constant{Py_PRINT_RAW}; if given, the \function{str()} of the
20+ object is written instead of the \function{repr()}.
21+\end{cfuncdesc}
22+
23+\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, const char *attr_name}
24+ Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
25+ \code{0} otherwise. This is equivalent to the Python expression
26+ \samp{hasattr(\var{o}, \var{attr_name})}. This function always
27+ succeeds.
28+\end{cfuncdesc}
29+
30+\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
31+ const char *attr_name}
32+ Retrieve an attribute named \var{attr_name} from object \var{o}.
33+ Returns the attribute value on success, or \NULL{} on failure.
34+ This is the equivalent of the Python expression
35+ \samp{\var{o}.\var{attr_name}}.
36+\end{cfuncdesc}
37+
38+
39+\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
40+ Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
41+ \code{0} otherwise. This is equivalent to the Python expression
42+ \samp{hasattr(\var{o}, \var{attr_name})}. This function always
43+ succeeds.
44+\end{cfuncdesc}
45+
46+
47+\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
48+ PyObject *attr_name}
49+ Retrieve an attribute named \var{attr_name} from object \var{o}.
50+ Returns the attribute value on success, or \NULL{} on failure. This
51+ is the equivalent of the Python expression
52+ \samp{\var{o}.\var{attr_name}}.
53+\end{cfuncdesc}
54+
55+
56+\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o,
57+ const char *attr_name, PyObject *v}
58+ Set the value of the attribute named \var{attr_name}, for object
59+ \var{o}, to the value \var{v}. Returns \code{-1} on failure. This
60+ is the equivalent of the Python statement
61+ \samp{\var{o}.\var{attr_name} = \var{v}}.
62+\end{cfuncdesc}
63+
64+
65+\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o,
66+ PyObject *attr_name, PyObject *v}
67+ Set the value of the attribute named \var{attr_name}, for object
68+ \var{o}, to the value \var{v}. Returns \code{-1} on failure. This
69+ is the equivalent of the Python statement
70+ \samp{\var{o}.\var{attr_name} = \var{v}}.
71+\end{cfuncdesc}
72+
73+
74+\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, const char *attr_name}
75+ Delete attribute named \var{attr_name}, for object \var{o}. Returns
76+ \code{-1} on failure. This is the equivalent of the Python
77+ statement: \samp{del \var{o}.\var{attr_name}}.
78+\end{cfuncdesc}
79+
80+
81+\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
82+ Delete attribute named \var{attr_name}, for object \var{o}. Returns
83+ \code{-1} on failure. This is the equivalent of the Python
84+ statement \samp{del \var{o}.\var{attr_name}}.
85+\end{cfuncdesc}
86+
87+
88+\begin{cfuncdesc}{PyObject*}{PyObject_RichCompare}{PyObject *o1,
89+ PyObject *o2, int opid}
90+ Compare the values of \var{o1} and \var{o2} using the operation
91+ specified by \var{opid}, which must be one of
92+ \constant{Py_LT},
93+ \constant{Py_LE},
94+ \constant{Py_EQ},
95+ \constant{Py_NE},
96+ \constant{Py_GT}, or
97+ \constant{Py_GE}, corresponding to
98+ \code{<},
99+ \code{<=},
100+ \code{==},
101+ \code{!=},
102+ \code{>}, or
103+ \code{>=} respectively. This is the equivalent of the Python expression
104+ \samp{\var{o1} op \var{o2}}, where \code{op} is the operator
105+ corresponding to \var{opid}. Returns the value of the comparison on
106+ success, or \NULL{} on failure.
107+\end{cfuncdesc}
108+
109+\begin{cfuncdesc}{int}{PyObject_RichCompareBool}{PyObject *o1,
110+ PyObject *o2, int opid}
111+ Compare the values of \var{o1} and \var{o2} using the operation
112+ specified by \var{opid}, which must be one of
113+ \constant{Py_LT},
114+ \constant{Py_LE},
115+ \constant{Py_EQ},
116+ \constant{Py_NE},
117+ \constant{Py_GT}, or
118+ \constant{Py_GE}, corresponding to
119+ \code{<},
120+ \code{<=},
121+ \code{==},
122+ \code{!=},
123+ \code{>}, or
124+ \code{>=} respectively. Returns \code{-1} on error, \code{0} if the
125+ result is false, \code{1} otherwise. This is the equivalent of the
126+ Python expression \samp{\var{o1} op \var{o2}}, where
127+ \code{op} is the operator corresponding to \var{opid}.
128+\end{cfuncdesc}
129+
130+\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
131+ Compare the values of \var{o1} and \var{o2} using a routine provided
132+ by \var{o1}, if one exists, otherwise with a routine provided by
133+ \var{o2}. The result of the comparison is returned in
134+ \var{result}. Returns \code{-1} on failure. This is the equivalent
135+ of the Python statement\bifuncindex{cmp} \samp{\var{result} =
136+ cmp(\var{o1}, \var{o2})}.
137+\end{cfuncdesc}
138+
139+
140+\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
141+ Compare the values of \var{o1} and \var{o2} using a routine provided
142+ by \var{o1}, if one exists, otherwise with a routine provided by
143+ \var{o2}. Returns the result of the comparison on success. On
144+ error, the value returned is undefined; use
145+ \cfunction{PyErr_Occurred()} to detect an error. This is equivalent
146+ to the Python expression\bifuncindex{cmp} \samp{cmp(\var{o1},
147+ \var{o2})}.
148+\end{cfuncdesc}
149+
150+
151+\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
152+ Compute a string representation of object \var{o}. Returns the
153+ string representation on success, \NULL{} on failure. This is the
154+ equivalent of the Python expression \samp{repr(\var{o})}. Called by
155+ the \function{repr()}\bifuncindex{repr} built-in function and by
156+ reverse quotes.
157+\end{cfuncdesc}
158+
159+
160+\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
161+ Compute a string representation of object \var{o}. Returns the
162+ string representation on success, \NULL{} on failure. This is the
163+ equivalent of the Python expression \samp{str(\var{o})}. Called by
164+ the \function{str()}\bifuncindex{str} built-in function and by the
165+ \keyword{print} statement.
166+\end{cfuncdesc}
167+
168+
169+\begin{cfuncdesc}{PyObject*}{PyObject_Unicode}{PyObject *o}
170+ Compute a Unicode string representation of object \var{o}. Returns
171+ the Unicode string representation on success, \NULL{} on failure.
172+ This is the equivalent of the Python expression
173+ \samp{unicode(\var{o})}. Called by the
174+ \function{unicode()}\bifuncindex{unicode} built-in function.
175+\end{cfuncdesc}
176+
177+\begin{cfuncdesc}{int}{PyObject_IsInstance}{PyObject *inst, PyObject *cls}
178+ Returns \code{1} if \var{inst} is an instance of the class \var{cls}
179+ or a subclass of \var{cls}, or \code{0} if not. On error, returns
180+ \code{-1} and sets an exception. If \var{cls} is a type object
181+ rather than a class object, \cfunction{PyObject_IsInstance()}
182+ returns \code{1} if \var{inst} is of type \var{cls}. If \var{cls}
183+ is a tuple, the check will be done against every entry in \var{cls}.
184+ The result will be \code{1} when at least one of the checks returns
185+ \code{1}, otherwise it will be \code{0}. If \var{inst} is not a class
186+ instance and \var{cls} is neither a type object, nor a class object,
187+ nor a tuple, \var{inst} must have a \member{__class__} attribute
188+ --- the class relationship of the value of that attribute with
189+ \var{cls} will be used to determine the result of this function.
190+ \versionadded{2.1}
191+ \versionchanged[Support for a tuple as the second argument added]{2.2}
192+\end{cfuncdesc}
193+
194+Subclass determination is done in a fairly straightforward way, but
195+includes a wrinkle that implementors of extensions to the class system
196+may want to be aware of. If \class{A} and \class{B} are class
197+objects, \class{B} is a subclass of \class{A} if it inherits from
198+\class{A} either directly or indirectly. If either is not a class
199+object, a more general mechanism is used to determine the class
200+relationship of the two objects. When testing if \var{B} is a
201+subclass of \var{A}, if \var{A} is \var{B},
202+\cfunction{PyObject_IsSubclass()} returns true. If \var{A} and
203+\var{B} are different objects, \var{B}'s \member{__bases__} attribute
204+is searched in a depth-first fashion for \var{A} --- the presence of
205+the \member{__bases__} attribute is considered sufficient for this
206+determination.
207+
208+\begin{cfuncdesc}{int}{PyObject_IsSubclass}{PyObject *derived,
209+ PyObject *cls}
210+ Returns \code{1} if the class \var{derived} is identical to or
211+ derived from the class \var{cls}, otherwise returns \code{0}. In
212+ case of an error, returns \code{-1}. If \var{cls}
213+ is a tuple, the check will be done against every entry in \var{cls}.
214+ The result will be \code{1} when at least one of the checks returns
215+ \code{1}, otherwise it will be \code{0}. If either \var{derived} or
216+ \var{cls} is not an actual class object (or tuple), this function
217+ uses the generic algorithm described above.
218+ \versionadded{2.1}
219+ \versionchanged[Older versions of Python did not support a tuple
220+ as the second argument]{2.3}
221+\end{cfuncdesc}
222+
223+
224+\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
225+ Determine if the object \var{o} is callable. Return \code{1} if the
226+ object is callable and \code{0} otherwise. This function always
227+ succeeds.
228+\end{cfuncdesc}
229+
230+
231+\begin{cfuncdesc}{PyObject*}{PyObject_Call}{PyObject *callable_object,
232+ PyObject *args,
233+ PyObject *kw}
234+ Call a callable Python object \var{callable_object}, with arguments
235+ given by the tuple \var{args}, and named arguments given by the
236+ dictionary \var{kw}. If no named arguments are needed, \var{kw} may
237+ be \NULL{}. \var{args} must not be \NULL{}, use an empty tuple if
238+ no arguments are needed. Returns the result of the call on success,
239+ or \NULL{} on failure. This is the equivalent of the Python
240+ expression \samp{apply(\var{callable_object}, \var{args}, \var{kw})}
241+ or \samp{\var{callable_object}(*\var{args}, **\var{kw})}.
242+ \bifuncindex{apply}
243+ \versionadded{2.2}
244+\end{cfuncdesc}
245+
246+
247+\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
248+ PyObject *args}
249+ Call a callable Python object \var{callable_object}, with arguments
250+ given by the tuple \var{args}. If no arguments are needed, then
251+ \var{args} may be \NULL. Returns the result of the call on
252+ success, or \NULL{} on failure. This is the equivalent of the
253+ Python expression \samp{apply(\var{callable_object}, \var{args})} or
254+ \samp{\var{callable_object}(*\var{args})}.
255+ \bifuncindex{apply}
256+\end{cfuncdesc}
257+
258+\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable,
259+ char *format, \moreargs}
260+ Call a callable Python object \var{callable}, with a variable
261+ number of C arguments. The C arguments are described using a
262+ \cfunction{Py_BuildValue()} style format string. The format may be
263+ \NULL, indicating that no arguments are provided. Returns the
264+ result of the call on success, or \NULL{} on failure. This is the
265+ equivalent of the Python expression \samp{apply(\var{callable},
266+ \var{args})} or \samp{\var{callable}(*\var{args})}.
267+ Note that if you only pass \ctype{PyObject *} args,
268+ \cfunction{PyObject_CallFunctionObjArgs} is a faster alternative.
269+ \bifuncindex{apply}
270+\end{cfuncdesc}
271+
272+
273+\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o,
274+ char *method, char *format,
275+ \moreargs}
276+ Call the method named \var{method} of object \var{o} with a variable
277+ number of C arguments. The C arguments are described by a
278+ \cfunction{Py_BuildValue()} format string that should
279+ produce a tuple. The format may be \NULL,
280+ indicating that no arguments are provided. Returns the result of the
281+ call on success, or \NULL{} on failure. This is the equivalent of
282+ the Python expression \samp{\var{o}.\var{method}(\var{args})}.
283+ Note that if you only pass \ctype{PyObject *} args,
284+ \cfunction{PyObject_CallMethodObjArgs} is a faster alternative.
285+\end{cfuncdesc}
286+
287+
288+\begin{cfuncdesc}{PyObject*}{PyObject_CallFunctionObjArgs}{PyObject *callable,
289+ \moreargs,
290+ \code{NULL}}
291+ Call a callable Python object \var{callable}, with a variable
292+ number of \ctype{PyObject*} arguments. The arguments are provided
293+ as a variable number of parameters followed by \NULL.
294+ Returns the result of the call on success, or \NULL{} on failure.
295+ \versionadded{2.2}
296+\end{cfuncdesc}
297+
298+
299+\begin{cfuncdesc}{PyObject*}{PyObject_CallMethodObjArgs}{PyObject *o,
300+ PyObject *name,
301+ \moreargs,
302+ \code{NULL}}
303+ Calls a method of the object \var{o}, where the name of the method
304+ is given as a Python string object in \var{name}. It is called with
305+ a variable number of \ctype{PyObject*} arguments. The arguments are
306+ provided as a variable number of parameters followed by \NULL.
307+ Returns the result of the call on success, or \NULL{} on failure.
308+ \versionadded{2.2}
309+\end{cfuncdesc}
310+
311+
312+\begin{cfuncdesc}{long}{PyObject_Hash}{PyObject *o}
313+ Compute and return the hash value of an object \var{o}. On failure,
314+ return \code{-1}. This is the equivalent of the Python expression
315+ \samp{hash(\var{o})}.\bifuncindex{hash}
316+\end{cfuncdesc}
317+
318+
319+\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
320+ Returns \code{1} if the object \var{o} is considered to be true, and
321+ \code{0} otherwise. This is equivalent to the Python expression
322+ \samp{not not \var{o}}. On failure, return \code{-1}.
323+\end{cfuncdesc}
324+
325+
326+\begin{cfuncdesc}{int}{PyObject_Not}{PyObject *o}
327+ Returns \code{0} if the object \var{o} is considered to be true, and
328+ \code{1} otherwise. This is equivalent to the Python expression
329+ \samp{not \var{o}}. On failure, return \code{-1}.
330+\end{cfuncdesc}
331+
332+
333+\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
334+ When \var{o} is non-\NULL, returns a type object corresponding to
335+ the object type of object \var{o}. On failure, raises
336+ \exception{SystemError} and returns \NULL. This is equivalent to
337+ the Python expression \code{type(\var{o})}.\bifuncindex{type}
338+ This function increments the reference count of the return value.
339+ There's really no reason to use this function instead of the
340+ common expression \code{\var{o}->ob_type}, which returns a pointer
341+ of type \ctype{PyTypeObject*}, except when the incremented reference
342+ count is needed.
343+\end{cfuncdesc}
344+
345+\begin{cfuncdesc}{int}{PyObject_TypeCheck}{PyObject *o, PyTypeObject *type}
346+ Return true if the object \var{o} is of type \var{type} or a subtype
347+ of \var{type}. Both parameters must be non-\NULL.
348+ \versionadded{2.2}
349+\end{cfuncdesc}
350+
351+\begin{cfuncdesc}{Py_ssize_t}{PyObject_Length}{PyObject *o}
352+\cfuncline{Py_ssize_t}{PyObject_Size}{PyObject *o}
353+ Return the length of object \var{o}. If the object \var{o} provides
354+ either the sequence and mapping protocols, the sequence length is
355+ returned. On error, \code{-1} is returned. This is the equivalent
356+ to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
357+\end{cfuncdesc}
358+
359+
360+\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
361+ Return element of \var{o} corresponding to the object \var{key} or
362+ \NULL{} on failure. This is the equivalent of the Python expression
363+ \samp{\var{o}[\var{key}]}.
364+\end{cfuncdesc}
365+
366+
367+\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o,
368+ PyObject *key, PyObject *v}
369+ Map the object \var{key} to the value \var{v}. Returns \code{-1} on
370+ failure. This is the equivalent of the Python statement
371+ \samp{\var{o}[\var{key}] = \var{v}}.
372+\end{cfuncdesc}
373+
374+
375+\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
376+ Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
377+ failure. This is the equivalent of the Python statement \samp{del
378+ \var{o}[\var{key}]}.
379+\end{cfuncdesc}
380+
381+\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
382+ Derives a file-descriptor from a Python object. If the object is an
383+ integer or long integer, its value is returned. If not, the
384+ object's \method{fileno()} method is called if it exists; the method
385+ must return an integer or long integer, which is returned as the
386+ file descriptor value. Returns \code{-1} on failure.
387+\end{cfuncdesc}
388+
389+\begin{cfuncdesc}{PyObject*}{PyObject_Dir}{PyObject *o}
390+ This is equivalent to the Python expression \samp{dir(\var{o})},
391+ returning a (possibly empty) list of strings appropriate for the
392+ object argument, or \NULL{} if there was an error. If the argument
393+ is \NULL, this is like the Python \samp{dir()}, returning the names
394+ of the current locals; in this case, if no execution frame is active
395+ then \NULL{} is returned but \cfunction{PyErr_Occurred()} will
396+ return false.
397+\end{cfuncdesc}
398+
399+\begin{cfuncdesc}{PyObject*}{PyObject_GetIter}{PyObject *o}
400+ This is equivalent to the Python expression \samp{iter(\var{o})}.
401+ It returns a new iterator for the object argument, or the object
402+ itself if the object is already an iterator. Raises
403+ \exception{TypeError} and returns \NULL{} if the object cannot be
404+ iterated.
405+\end{cfuncdesc}
406+
407+
408+\section{Number Protocol \label{number}}
409+
410+\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
411+ Returns \code{1} if the object \var{o} provides numeric protocols,
412+ and false otherwise. This function always succeeds.
413+\end{cfuncdesc}
414+
415+
416+\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
417+ Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
418+ failure. This is the equivalent of the Python expression
419+ \samp{\var{o1} + \var{o2}}.
420+\end{cfuncdesc}
421+
422+
423+\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
424+ Returns the result of subtracting \var{o2} from \var{o1}, or \NULL{}
425+ on failure. This is the equivalent of the Python expression
426+ \samp{\var{o1} - \var{o2}}.
427+\end{cfuncdesc}
428+
429+
430+\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
431+ Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{}
432+ on failure. This is the equivalent of the Python expression
433+ \samp{\var{o1} * \var{o2}}.
434+\end{cfuncdesc}
435+
436+
437+\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
438+ Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
439+ failure. This is the equivalent of the Python expression
440+ \samp{\var{o1} / \var{o2}}.
441+\end{cfuncdesc}
442+
443+
444+\begin{cfuncdesc}{PyObject*}{PyNumber_FloorDivide}{PyObject *o1, PyObject *o2}
445+ Return the floor of \var{o1} divided by \var{o2}, or \NULL{} on
446+ failure. This is equivalent to the ``classic'' division of
447+ integers.
448+ \versionadded{2.2}
449+\end{cfuncdesc}
450+
451+
452+\begin{cfuncdesc}{PyObject*}{PyNumber_TrueDivide}{PyObject *o1, PyObject *o2}
453+ Return a reasonable approximation for the mathematical value of
454+ \var{o1} divided by \var{o2}, or \NULL{} on failure. The return
455+ value is ``approximate'' because binary floating point numbers are
456+ approximate; it is not possible to represent all real numbers in
457+ base two. This function can return a floating point value when
458+ passed two integers.
459+ \versionadded{2.2}
460+\end{cfuncdesc}
461+
462+
463+\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
464+ Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{}
465+ on failure. This is the equivalent of the Python expression
466+ \samp{\var{o1} \%\ \var{o2}}.
467+\end{cfuncdesc}
468+
469+
470+\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
471+ See the built-in function \function{divmod()}\bifuncindex{divmod}.
472+ Returns \NULL{} on failure. This is the equivalent of the Python
473+ expression \samp{divmod(\var{o1}, \var{o2})}.
474+\end{cfuncdesc}
475+
476+
477+\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1,
478+ PyObject *o2, PyObject *o3}
479+ See the built-in function \function{pow()}\bifuncindex{pow}.
480+ Returns \NULL{} on failure. This is the equivalent of the Python
481+ expression \samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3}
482+ is optional. If \var{o3} is to be ignored, pass \cdata{Py_None} in
483+ its place (passing \NULL{} for \var{o3} would cause an illegal
484+ memory access).
485+\end{cfuncdesc}
486+
487+
488+\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
489+ Returns the negation of \var{o} on success, or \NULL{} on failure.
490+ This is the equivalent of the Python expression \samp{-\var{o}}.
491+\end{cfuncdesc}
492+
493+
494+\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
495+ Returns \var{o} on success, or \NULL{} on failure. This is the
496+ equivalent of the Python expression \samp{+\var{o}}.
497+\end{cfuncdesc}
498+
499+
500+\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
501+ Returns the absolute value of \var{o}, or \NULL{} on failure. This
502+ is the equivalent of the Python expression \samp{abs(\var{o})}.
503+ \bifuncindex{abs}
504+\end{cfuncdesc}
505+
506+
507+\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
508+ Returns the bitwise negation of \var{o} on success, or \NULL{} on
509+ failure. This is the equivalent of the Python expression
510+ \samp{\~\var{o}}.
511+\end{cfuncdesc}
512+
513+
514+\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
515+ Returns the result of left shifting \var{o1} by \var{o2} on success,
516+ or \NULL{} on failure. This is the equivalent of the Python
517+ expression \samp{\var{o1} <\code{<} \var{o2}}.
518+\end{cfuncdesc}
519+
520+
521+\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
522+ Returns the result of right shifting \var{o1} by \var{o2} on
523+ success, or \NULL{} on failure. This is the equivalent of the
524+ Python expression \samp{\var{o1} >\code{>} \var{o2}}.
525+\end{cfuncdesc}
526+
527+
528+\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
529+ Returns the ``bitwise and'' of \var{o1} and \var{o2} on success and
530+ \NULL{} on failure. This is the equivalent of the Python expression
531+ \samp{\var{o1} \&\ \var{o2}}.
532+\end{cfuncdesc}
533+
534+
535+\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
536+ Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on
537+ success, or \NULL{} on failure. This is the equivalent of the
538+ Python expression \samp{\var{o1} \textasciicircum{} \var{o2}}.
539+\end{cfuncdesc}
540+
541+\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
542+ Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
543+ \NULL{} on failure. This is the equivalent of the Python expression
544+ \samp{\var{o1} | \var{o2}}.
545+\end{cfuncdesc}
546+
547+
548+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAdd}{PyObject *o1, PyObject *o2}
549+ Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
550+ failure. The operation is done \emph{in-place} when \var{o1}
551+ supports it. This is the equivalent of the Python statement
552+ \samp{\var{o1} += \var{o2}}.
553+\end{cfuncdesc}
554+
555+
556+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceSubtract}{PyObject *o1,
557+ PyObject *o2}
558+ Returns the result of subtracting \var{o2} from \var{o1}, or \NULL{}
559+ on failure. The operation is done \emph{in-place} when \var{o1}
560+ supports it. This is the equivalent of the Python statement
561+ \samp{\var{o1} -= \var{o2}}.
562+\end{cfuncdesc}
563+
564+
565+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceMultiply}{PyObject *o1,
566+ PyObject *o2}
567+ Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{}
568+ on failure. The operation is done \emph{in-place} when \var{o1}
569+ supports it. This is the equivalent of the Python statement
570+ \samp{\var{o1} *= \var{o2}}.
571+\end{cfuncdesc}
572+
573+
574+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceDivide}{PyObject *o1,
575+ PyObject *o2}
576+ Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
577+ failure. The operation is done \emph{in-place} when \var{o1}
578+ supports it. This is the equivalent of the Python statement
579+ \samp{\var{o1} /= \var{o2}}.
580+\end{cfuncdesc}
581+
582+
583+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceFloorDivide}{PyObject *o1,
584+ PyObject *o2}
585+ Returns the mathematical floor of dividing \var{o1} by \var{o2}, or
586+ \NULL{} on failure. The operation is done \emph{in-place} when
587+ \var{o1} supports it. This is the equivalent of the Python
588+ statement \samp{\var{o1} //= \var{o2}}.
589+ \versionadded{2.2}
590+\end{cfuncdesc}
591+
592+
593+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceTrueDivide}{PyObject *o1,
594+ PyObject *o2}
595+ Return a reasonable approximation for the mathematical value of
596+ \var{o1} divided by \var{o2}, or \NULL{} on failure. The return
597+ value is ``approximate'' because binary floating point numbers are
598+ approximate; it is not possible to represent all real numbers in
599+ base two. This function can return a floating point value when
600+ passed two integers. The operation is done \emph{in-place} when
601+ \var{o1} supports it.
602+ \versionadded{2.2}
603+\end{cfuncdesc}
604+
605+
606+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRemainder}{PyObject *o1,
607+ PyObject *o2}
608+ Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{}
609+ on failure. The operation is done \emph{in-place} when \var{o1}
610+ supports it. This is the equivalent of the Python statement
611+ \samp{\var{o1} \%= \var{o2}}.
612+\end{cfuncdesc}
613+
614+
615+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlacePower}{PyObject *o1,
616+ PyObject *o2, PyObject *o3}
617+ See the built-in function \function{pow()}.\bifuncindex{pow}
618+ Returns \NULL{} on failure. The operation is done \emph{in-place}
619+ when \var{o1} supports it. This is the equivalent of the Python
620+ statement \samp{\var{o1} **= \var{o2}} when o3 is \cdata{Py_None},
621+ or an in-place variant of \samp{pow(\var{o1}, \var{o2}, \var{o3})}
622+ otherwise. If \var{o3} is to be ignored, pass \cdata{Py_None} in its
623+ place (passing \NULL{} for \var{o3} would cause an illegal memory
624+ access).
625+\end{cfuncdesc}
626+
627+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceLshift}{PyObject *o1,
628+ PyObject *o2}
629+ Returns the result of left shifting \var{o1} by \var{o2} on success,
630+ or \NULL{} on failure. The operation is done \emph{in-place} when
631+ \var{o1} supports it. This is the equivalent of the Python
632+ statement \samp{\var{o1} <\code{<=} \var{o2}}.
633+\end{cfuncdesc}
634+
635+
636+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRshift}{PyObject *o1,
637+ PyObject *o2}
638+ Returns the result of right shifting \var{o1} by \var{o2} on
639+ success, or \NULL{} on failure. The operation is done
640+ \emph{in-place} when \var{o1} supports it. This is the equivalent
641+ of the Python statement \samp{\var{o1} >>= \var{o2}}.
642+\end{cfuncdesc}
643+
644+
645+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAnd}{PyObject *o1, PyObject *o2}
646+ Returns the ``bitwise and'' of \var{o1} and \var{o2} on success and
647+ \NULL{} on failure. The operation is done \emph{in-place} when
648+ \var{o1} supports it. This is the equivalent of the Python
649+ statement \samp{\var{o1} \&= \var{o2}}.
650+\end{cfuncdesc}
651+
652+
653+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceXor}{PyObject *o1, PyObject *o2}
654+ Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on
655+ success, or \NULL{} on failure. The operation is done
656+ \emph{in-place} when \var{o1} supports it. This is the equivalent
657+ of the Python statement \samp{\var{o1} \textasciicircum= \var{o2}}.
658+\end{cfuncdesc}
659+
660+\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2}
661+ Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
662+ \NULL{} on failure. The operation is done \emph{in-place} when
663+ \var{o1} supports it. This is the equivalent of the Python
664+ statement \samp{\var{o1} |= \var{o2}}.
665+\end{cfuncdesc}
666+
667+\begin{cfuncdesc}{int}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
668+ This function takes the addresses of two variables of type
669+ \ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}}
670+ and \code{*\var{p2}} have the same type, increment their reference
671+ count and return \code{0} (success). If the objects can be converted
672+ to a common numeric type, replace \code{*p1} and \code{*p2} by their
673+ converted value (with 'new' reference counts), and return \code{0}.
674+ If no conversion is possible, or if some other error occurs, return
675+ \code{-1} (failure) and don't increment the reference counts. The
676+ call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
677+ statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
678+ \bifuncindex{coerce}
679+\end{cfuncdesc}
680+
681+\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
682+ Returns the \var{o} converted to an integer object on success, or
683+ \NULL{} on failure. If the argument is outside the integer range
684+ a long object will be returned instead. This is the equivalent
685+ of the Python expression \samp{int(\var{o})}.\bifuncindex{int}
686+\end{cfuncdesc}
687+
688+\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
689+ Returns the \var{o} converted to a long integer object on success,
690+ or \NULL{} on failure. This is the equivalent of the Python
691+ expression \samp{long(\var{o})}.\bifuncindex{long}
692+\end{cfuncdesc}
693+
694+\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
695+ Returns the \var{o} converted to a float object on success, or
696+ \NULL{} on failure. This is the equivalent of the Python expression
697+ \samp{float(\var{o})}.\bifuncindex{float}
698+\end{cfuncdesc}
699+
700+\begin{cfuncdesc}{PyObject*}{PyNumber_Index}{PyObject *o}
701+ Returns the \var{o} converted to a Python int or long on success or \NULL{}
702+ with a TypeError exception raised on failure.
703+ \versionadded{2.5}
704+\end{cfuncdesc}
705+
706+\begin{cfuncdesc}{Py_ssize_t}{PyNumber_AsSsize_t}{PyObject *o, PyObject *exc}
707+ Returns \var{o} converted to a Py_ssize_t value if \var{o}
708+ can be interpreted as an integer. If \var{o} can be converted to a Python
709+ int or long but the attempt to convert to a Py_ssize_t value
710+ would raise an \exception{OverflowError}, then the \var{exc} argument
711+ is the type of exception that will be raised (usually \exception{IndexError}
712+ or \exception{OverflowError}). If \var{exc} is \NULL{}, then the exception
713+ is cleared and the value is clipped to \var{PY_SSIZE_T_MIN}
714+ for a negative integer or \var{PY_SSIZE_T_MAX} for a positive integer.
715+ \versionadded{2.5}
716+\end{cfuncdesc}
717+
718+\begin{cfuncdesc}{int}{PyIndex_Check}{PyObject *o}
719+ Returns True if \var{o} is an index integer (has the nb_index slot of
720+ the tp_as_number structure filled in).
721+ \versionadded{2.5}
722+\end{cfuncdesc}
723+
724+
725+\section{Sequence Protocol \label{sequence}}
726+
727+\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
728+ Return \code{1} if the object provides sequence protocol, and
729+ \code{0} otherwise. This function always succeeds.
730+\end{cfuncdesc}
731+
732+\begin{cfuncdesc}{Py_ssize_t}{PySequence_Size}{PyObject *o}
733+ Returns the number of objects in sequence \var{o} on success, and
734+ \code{-1} on failure. For objects that do not provide sequence
735+ protocol, this is equivalent to the Python expression
736+ \samp{len(\var{o})}.\bifuncindex{len}
737+\end{cfuncdesc}
738+
739+\begin{cfuncdesc}{Py_ssize_t}{PySequence_Length}{PyObject *o}
740+ Alternate name for \cfunction{PySequence_Size()}.
741+\end{cfuncdesc}
742+
743+\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
744+ Return the concatenation of \var{o1} and \var{o2} on success, and
745+ \NULL{} on failure. This is the equivalent of the Python
746+ expression \samp{\var{o1} + \var{o2}}.
747+\end{cfuncdesc}
748+
749+
750+\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, Py_ssize_t count}
751+ Return the result of repeating sequence object \var{o} \var{count}
752+ times, or \NULL{} on failure. This is the equivalent of the Python
753+ expression \samp{\var{o} * \var{count}}.
754+\end{cfuncdesc}
755+
756+\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceConcat}{PyObject *o1,
757+ PyObject *o2}
758+ Return the concatenation of \var{o1} and \var{o2} on success, and
759+ \NULL{} on failure. The operation is done \emph{in-place} when
760+ \var{o1} supports it. This is the equivalent of the Python
761+ expression \samp{\var{o1} += \var{o2}}.
762+\end{cfuncdesc}
763+
764+
765+\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceRepeat}{PyObject *o, Py_ssize_t count}
766+ Return the result of repeating sequence object \var{o} \var{count}
767+ times, or \NULL{} on failure. The operation is done \emph{in-place}
768+ when \var{o} supports it. This is the equivalent of the Python
769+ expression \samp{\var{o} *= \var{count}}.
770+\end{cfuncdesc}
771+
772+
773+\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, Py_ssize_t i}
774+ Return the \var{i}th element of \var{o}, or \NULL{} on failure.
775+ This is the equivalent of the Python expression
776+ \samp{\var{o}[\var{i}]}.
777+\end{cfuncdesc}
778+
779+
780+\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, Py_ssize_t i1, Py_ssize_t i2}
781+ Return the slice of sequence object \var{o} between \var{i1} and
782+ \var{i2}, or \NULL{} on failure. This is the equivalent of the
783+ Python expression \samp{\var{o}[\var{i1}:\var{i2}]}.
784+\end{cfuncdesc}
785+
786+
787+\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, Py_ssize_t i, PyObject *v}
788+ Assign object \var{v} to the \var{i}th element of \var{o}. Returns
789+ \code{-1} on failure. This is the equivalent of the Python
790+ statement \samp{\var{o}[\var{i}] = \var{v}}. This function \emph{does not}
791+ steal a reference to \var{v}.
792+\end{cfuncdesc}
793+
794+\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, Py_ssize_t i}
795+ Delete the \var{i}th element of object \var{o}. Returns \code{-1}
796+ on failure. This is the equivalent of the Python statement
797+ \samp{del \var{o}[\var{i}]}.
798+\end{cfuncdesc}
799+
800+\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, Py_ssize_t i1,
801+ Py_ssize_t i2, PyObject *v}
802+ Assign the sequence object \var{v} to the slice in sequence object
803+ \var{o} from \var{i1} to \var{i2}. This is the equivalent of the
804+ Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
805+\end{cfuncdesc}
806+
807+\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, Py_ssize_t i1, Py_ssize_t i2}
808+ Delete the slice in sequence object \var{o} from \var{i1} to
809+ \var{i2}. Returns \code{-1} on failure. This is the equivalent of
810+ the Python statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
811+\end{cfuncdesc}
812+
813+\begin{cfuncdesc}{Py_ssize_t}{PySequence_Count}{PyObject *o, PyObject *value}
814+ Return the number of occurrences of \var{value} in \var{o}, that is,
815+ return the number of keys for which \code{\var{o}[\var{key}] ==
816+ \var{value}}. On failure, return \code{-1}. This is equivalent to
817+ the Python expression \samp{\var{o}.count(\var{value})}.
818+\end{cfuncdesc}
819+
820+\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
821+ Determine if \var{o} contains \var{value}. If an item in \var{o} is
822+ equal to \var{value}, return \code{1}, otherwise return \code{0}.
823+ On error, return \code{-1}. This is equivalent to the Python
824+ expression \samp{\var{value} in \var{o}}.
825+\end{cfuncdesc}
826+
827+\begin{cfuncdesc}{Py_ssize_t}{PySequence_Index}{PyObject *o, PyObject *value}
828+ Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
829+ \var{value}}. On error, return \code{-1}. This is equivalent to
830+ the Python expression \samp{\var{o}.index(\var{value})}.
831+\end{cfuncdesc}
832+
833+\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
834+ Return a list object with the same contents as the arbitrary
835+ sequence \var{o}. The returned list is guaranteed to be new.
836+\end{cfuncdesc}
837+
838+\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
839+ Return a tuple object with the same contents as the arbitrary
840+ sequence \var{o} or \NULL{} on failure. If \var{o} is a tuple,
841+ a new reference will be returned, otherwise a tuple will be
842+ constructed with the appropriate contents. This is equivalent
843+ to the Python expression \samp{tuple(\var{o})}.
844+ \bifuncindex{tuple}
845+\end{cfuncdesc}
846+
847+\begin{cfuncdesc}{PyObject*}{PySequence_Fast}{PyObject *o, const char *m}
848+ Returns the sequence \var{o} as a tuple, unless it is already a
849+ tuple or list, in which case \var{o} is returned. Use
850+ \cfunction{PySequence_Fast_GET_ITEM()} to access the members of the
851+ result. Returns \NULL{} on failure. If the object is not a
852+ sequence, raises \exception{TypeError} with \var{m} as the message
853+ text.
854+\end{cfuncdesc}
855+
856+\begin{cfuncdesc}{PyObject*}{PySequence_Fast_GET_ITEM}{PyObject *o, Py_ssize_t i}
857+ Return the \var{i}th element of \var{o}, assuming that \var{o} was
858+ returned by \cfunction{PySequence_Fast()}, \var{o} is not \NULL,
859+ and that \var{i} is within bounds.
860+\end{cfuncdesc}
861+
862+\begin{cfuncdesc}{PyObject**}{PySequence_Fast_ITEMS}{PyObject *o}
863+ Return the underlying array of PyObject pointers. Assumes that
864+ \var{o} was returned by \cfunction{PySequence_Fast()} and
865+ \var{o} is not \NULL.
866+ \versionadded{2.4}
867+\end{cfuncdesc}
868+
869+\begin{cfuncdesc}{PyObject*}{PySequence_ITEM}{PyObject *o, Py_ssize_t i}
870+ Return the \var{i}th element of \var{o} or \NULL{} on failure.
871+ Macro form of \cfunction{PySequence_GetItem()} but without checking
872+ that \cfunction{PySequence_Check(\var{o})} is true and without
873+ adjustment for negative indices.
874+ \versionadded{2.3}
875+\end{cfuncdesc}
876+
877+\begin{cfuncdesc}{Py_ssize_t}{PySequence_Fast_GET_SIZE}{PyObject *o}
878+ Returns the length of \var{o}, assuming that \var{o} was
879+ returned by \cfunction{PySequence_Fast()} and that \var{o} is
880+ not \NULL. The size can also be gotten by calling
881+ \cfunction{PySequence_Size()} on \var{o}, but
882+ \cfunction{PySequence_Fast_GET_SIZE()} is faster because it can
883+ assume \var{o} is a list or tuple.
884+\end{cfuncdesc}
885+
886+
887+\section{Mapping Protocol \label{mapping}}
888+
889+\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
890+ Return \code{1} if the object provides mapping protocol, and
891+ \code{0} otherwise. This function always succeeds.
892+\end{cfuncdesc}
893+
894+
895+\begin{cfuncdesc}{Py_ssize_t}{PyMapping_Length}{PyObject *o}
896+ Returns the number of keys in object \var{o} on success, and
897+ \code{-1} on failure. For objects that do not provide mapping
898+ protocol, this is equivalent to the Python expression
899+ \samp{len(\var{o})}.\bifuncindex{len}
900+\end{cfuncdesc}
901+
902+
903+\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
904+ Remove the mapping for object \var{key} from the object \var{o}.
905+ Return \code{-1} on failure. This is equivalent to the Python
906+ statement \samp{del \var{o}[\var{key}]}.
907+\end{cfuncdesc}
908+
909+
910+\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
911+ Remove the mapping for object \var{key} from the object \var{o}.
912+ Return \code{-1} on failure. This is equivalent to the Python
913+ statement \samp{del \var{o}[\var{key}]}.
914+\end{cfuncdesc}
915+
916+
917+\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
918+ On success, return \code{1} if the mapping object has the key
919+ \var{key} and \code{0} otherwise. This is equivalent to the Python
920+ expression \samp{\var{o}.has_key(\var{key})}. This function always
921+ succeeds.
922+\end{cfuncdesc}
923+
924+
925+\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
926+ Return \code{1} if the mapping object has the key \var{key} and
927+ \code{0} otherwise. This is equivalent to the Python expression
928+ \samp{\var{o}.has_key(\var{key})}. This function always succeeds.
929+\end{cfuncdesc}
930+
931+
932+\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
933+ On success, return a list of the keys in object \var{o}. On
934+ failure, return \NULL. This is equivalent to the Python expression
935+ \samp{\var{o}.keys()}.
936+\end{cfuncdesc}
937+
938+
939+\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
940+ On success, return a list of the values in object \var{o}. On
941+ failure, return \NULL. This is equivalent to the Python expression
942+ \samp{\var{o}.values()}.
943+\end{cfuncdesc}
944+
945+
946+\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
947+ On success, return a list of the items in object \var{o}, where each
948+ item is a tuple containing a key-value pair. On failure, return
949+ \NULL. This is equivalent to the Python expression
950+ \samp{\var{o}.items()}.
951+\end{cfuncdesc}
952+
953+
954+\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
955+ Return element of \var{o} corresponding to the object \var{key} or
956+ \NULL{} on failure. This is the equivalent of the Python expression
957+ \samp{\var{o}[\var{key}]}.
958+\end{cfuncdesc}
959+
960+\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key,
961+ PyObject *v}
962+ Map the object \var{key} to the value \var{v} in object \var{o}.
963+ Returns \code{-1} on failure. This is the equivalent of the Python
964+ statement \samp{\var{o}[\var{key}] = \var{v}}.
965+\end{cfuncdesc}
966+
967+
968+\section{Iterator Protocol \label{iterator}}
969+
970+\versionadded{2.2}
971+
972+There are only a couple of functions specifically for working with
973+iterators.
974+
975+\begin{cfuncdesc}{int}{PyIter_Check}{PyObject *o}
976+ Return true if the object \var{o} supports the iterator protocol.
977+\end{cfuncdesc}
978+
979+\begin{cfuncdesc}{PyObject*}{PyIter_Next}{PyObject *o}
980+ Return the next value from the iteration \var{o}. If the object is
981+ an iterator, this retrieves the next value from the iteration, and
982+ returns \NULL{} with no exception set if there are no remaining
983+ items. If the object is not an iterator, \exception{TypeError} is
984+ raised, or if there is an error in retrieving the item, returns
985+ \NULL{} and passes along the exception.
986+\end{cfuncdesc}
987+
988+To write a loop which iterates over an iterator, the C code should
989+look something like this:
990+
991+\begin{verbatim}
992+PyObject *iterator = PyObject_GetIter(obj);
993+PyObject *item;
994+
995+if (iterator == NULL) {
996+ /* propagate error */
997+}
998+
999+while (item = PyIter_Next(iterator)) {
1000+ /* do something with item */
1001+ ...
1002+ /* release reference when done */
1003+ Py_DECREF(item);
1004+}
1005+
1006+Py_DECREF(iterator);
1007+
1008+if (PyErr_Occurred()) {
1009+ /* propagate error */
1010+}
1011+else {
1012+ /* continue doing useful work */
1013+}
1014+\end{verbatim}
1015+
1016+
1017+\section{Buffer Protocol \label{abstract-buffer}}
1018+
1019+\begin{cfuncdesc}{int}{PyObject_AsCharBuffer}{PyObject *obj,
1020+ const char **buffer,
1021+ Py_ssize_t *buffer_len}
1022+ Returns a pointer to a read-only memory location useable as character-
1023+ based input. The \var{obj} argument must support the single-segment
1024+ character buffer interface. On success, returns \code{0}, sets
1025+ \var{buffer} to the memory location and \var{buffer_len} to the buffer
1026+ length. Returns \code{-1} and sets a \exception{TypeError} on error.
1027+ \versionadded{1.6}
1028+\end{cfuncdesc}
1029+
1030+\begin{cfuncdesc}{int}{PyObject_AsReadBuffer}{PyObject *obj,
1031+ const void **buffer,
1032+ Py_ssize_t *buffer_len}
1033+ Returns a pointer to a read-only memory location containing
1034+ arbitrary data. The \var{obj} argument must support the
1035+ single-segment readable buffer interface. On success, returns
1036+ \code{0}, sets \var{buffer} to the memory location and \var{buffer_len}
1037+ to the buffer length. Returns \code{-1} and sets a
1038+ \exception{TypeError} on error.
1039+ \versionadded{1.6}
1040+\end{cfuncdesc}
1041+
1042+\begin{cfuncdesc}{int}{PyObject_CheckReadBuffer}{PyObject *o}
1043+ Returns \code{1} if \var{o} supports the single-segment readable
1044+ buffer interface. Otherwise returns \code{0}.
1045+ \versionadded{2.2}
1046+\end{cfuncdesc}
1047+
1048+\begin{cfuncdesc}{int}{PyObject_AsWriteBuffer}{PyObject *obj,
1049+ void **buffer,
1050+ Py_ssize_t *buffer_len}
1051+ Returns a pointer to a writeable memory location. The \var{obj}
1052+ argument must support the single-segment, character buffer
1053+ interface. On success, returns \code{0}, sets \var{buffer} to the
1054+ memory location and \var{buffer_len} to the buffer length. Returns
1055+ \code{-1} and sets a \exception{TypeError} on error.
1056+ \versionadded{1.6}
1057+\end{cfuncdesc}
sys/src/cmd/python/Doc/api/api.tex+60−0
@@ -0,0 +1,60 @@
1+\documentclass{manual}
2+
3+\title{Python/C API Reference Manual}
4+
5+\input{boilerplate}
6+
7+\makeindex % tell \index to actually write the .idx file
8+
9+
10+\begin{document}
11+
12+\maketitle
13+
14+\ifhtml
15+\chapter*{Front Matter\label{front}}
16+\fi
17+
18+\input{copyright}
19+
20+\begin{abstract}
21+
22+\noindent
23+This manual documents the API used by C and \Cpp{} programmers who
24+want to write extension modules or embed Python. It is a companion to
25+\citetitle[../ext/ext.html]{Extending and Embedding the Python
26+Interpreter}, which describes the general principles of extension
27+writing but does not document the API functions in detail.
28+
29+\warning{The current version of this document is incomplete. I hope
30+that it is nevertheless useful. I will continue to work on it, and
31+release new versions from time to time, independent from Python source
32+code releases.}
33+
34+\end{abstract}
35+
36+\tableofcontents
37+
38+
39+\input{intro}
40+\input{veryhigh}
41+\input{refcounting}
42+\input{exceptions}
43+\input{utilities}
44+\input{abstract}
45+\input{concrete}
46+\input{init}
47+\input{memory}
48+\input{newtypes}
49+
50+
51+\appendix
52+\chapter{Reporting Bugs}
53+\input{reportingbugs}
54+
55+\chapter{History and License}
56+\input{license}
57+
58+\input{api.ind} % Index -- must be last
59+
60+\end{document}
sys/src/cmd/python/Doc/api/concrete.tex+3203−0
@@ -0,0 +1,3203 @@
1+\chapter{Concrete Objects Layer \label{concrete}}
2+
3+
4+The functions in this chapter are specific to certain Python object
5+types. Passing them an object of the wrong type is not a good idea;
6+if you receive an object from a Python program and you are not sure
7+that it has the right type, you must perform a type check first;
8+for example, to check that an object is a dictionary, use
9+\cfunction{PyDict_Check()}. The chapter is structured like the
10+``family tree'' of Python object types.
11+
12+\warning{While the functions described in this chapter carefully check
13+the type of the objects which are passed in, many of them do not check
14+for \NULL{} being passed instead of a valid object. Allowing \NULL{}
15+to be passed in can cause memory access violations and immediate
16+termination of the interpreter.}
17+
18+
19+\section{Fundamental Objects \label{fundamental}}
20+
21+This section describes Python type objects and the singleton object
22+\code{None}.
23+
24+
25+\subsection{Type Objects \label{typeObjects}}
26+
27+\obindex{type}
28+\begin{ctypedesc}{PyTypeObject}
29+ The C structure of the objects used to describe built-in types.
30+\end{ctypedesc}
31+
32+\begin{cvardesc}{PyObject*}{PyType_Type}
33+ This is the type object for type objects; it is the same object as
34+ \code{type} and \code{types.TypeType} in the Python layer.
35+ \withsubitem{(in module types)}{\ttindex{TypeType}}
36+\end{cvardesc}
37+
38+\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
39+ Return true if the object \var{o} is a type object, including
40+ instances of types derived from the standard type object. Return
41+ false in all other cases.
42+\end{cfuncdesc}
43+
44+\begin{cfuncdesc}{int}{PyType_CheckExact}{PyObject *o}
45+ Return true if the object \var{o} is a type object, but not a
46+ subtype of the standard type object. Return false in all other
47+ cases.
48+ \versionadded{2.2}
49+\end{cfuncdesc}
50+
51+\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
52+ Return true if the type object \var{o} sets the feature
53+ \var{feature}. Type features are denoted by single bit flags.
54+\end{cfuncdesc}
55+
56+\begin{cfuncdesc}{int}{PyType_IS_GC}{PyObject *o}
57+ Return true if the type object includes support for the cycle
58+ detector; this tests the type flag \constant{Py_TPFLAGS_HAVE_GC}.
59+ \versionadded{2.0}
60+\end{cfuncdesc}
61+
62+\begin{cfuncdesc}{int}{PyType_IsSubtype}{PyTypeObject *a, PyTypeObject *b}
63+ Return true if \var{a} is a subtype of \var{b}.
64+ \versionadded{2.2}
65+\end{cfuncdesc}
66+
67+\begin{cfuncdesc}{PyObject*}{PyType_GenericAlloc}{PyTypeObject *type,
68+ Py_ssize_t nitems}
69+ \versionadded{2.2}
70+\end{cfuncdesc}
71+
72+\begin{cfuncdesc}{PyObject*}{PyType_GenericNew}{PyTypeObject *type,
73+ PyObject *args, PyObject *kwds}
74+ \versionadded{2.2}
75+\end{cfuncdesc}
76+
77+\begin{cfuncdesc}{int}{PyType_Ready}{PyTypeObject *type}
78+ Finalize a type object. This should be called on all type objects
79+ to finish their initialization. This function is responsible for
80+ adding inherited slots from a type's base class. Return \code{0}
81+ on success, or return \code{-1} and sets an exception on error.
82+ \versionadded{2.2}
83+\end{cfuncdesc}
84+
85+
86+\subsection{The None Object \label{noneObject}}
87+
88+\obindex{None}
89+Note that the \ctype{PyTypeObject} for \code{None} is not directly
90+exposed in the Python/C API. Since \code{None} is a singleton,
91+testing for object identity (using \samp{==} in C) is sufficient.
92+There is no \cfunction{PyNone_Check()} function for the same reason.
93+
94+\begin{cvardesc}{PyObject*}{Py_None}
95+ The Python \code{None} object, denoting lack of value. This object
96+ has no methods. It needs to be treated just like any other object
97+ with respect to reference counts.
98+\end{cvardesc}
99+
100+\begin{csimplemacrodesc}{Py_RETURN_NONE}
101+ Properly handle returning \cdata{Py_None} from within a C function.
102+\end{csimplemacrodesc}
103+
104+
105+\section{Numeric Objects \label{numericObjects}}
106+
107+\obindex{numeric}
108+
109+
110+\subsection{Plain Integer Objects \label{intObjects}}
111+
112+\obindex{integer}
113+\begin{ctypedesc}{PyIntObject}
114+ This subtype of \ctype{PyObject} represents a Python integer
115+ object.
116+\end{ctypedesc}
117+
118+\begin{cvardesc}{PyTypeObject}{PyInt_Type}
119+ This instance of \ctype{PyTypeObject} represents the Python plain
120+ integer type. This is the same object as \code{int} and
121+ \code{types.IntType}.
122+ \withsubitem{(in modules types)}{\ttindex{IntType}}
123+\end{cvardesc}
124+
125+\begin{cfuncdesc}{int}{PyInt_Check}{PyObject *o}
126+ Return true if \var{o} is of type \cdata{PyInt_Type} or a subtype
127+ of \cdata{PyInt_Type}.
128+ \versionchanged[Allowed subtypes to be accepted]{2.2}
129+\end{cfuncdesc}
130+
131+\begin{cfuncdesc}{int}{PyInt_CheckExact}{PyObject *o}
132+ Return true if \var{o} is of type \cdata{PyInt_Type}, but not a
133+ subtype of \cdata{PyInt_Type}.
134+ \versionadded{2.2}
135+\end{cfuncdesc}
136+
137+\begin{cfuncdesc}{PyObject*}{PyInt_FromString}{char *str, char **pend,
138+ int base}
139+ Return a new \ctype{PyIntObject} or \ctype{PyLongObject} based on the
140+ string value in \var{str}, which is interpreted according to the radix in
141+ \var{base}. If \var{pend} is non-\NULL{}, \code{*\var{pend}} will point to
142+ the first character in \var{str} which follows the representation of the
143+ number. If \var{base} is \code{0}, the radix will be determined based on
144+ the leading characters of \var{str}: if \var{str} starts with \code{'0x'}
145+ or \code{'0X'}, radix 16 will be used; if \var{str} starts with
146+ \code{'0'}, radix 8 will be used; otherwise radix 10 will be used. If
147+ \var{base} is not \code{0}, it must be between \code{2} and \code{36},
148+ inclusive. Leading spaces are ignored. If there are no digits,
149+ \exception{ValueError} will be raised. If the string represents a number
150+ too large to be contained within the machine's \ctype{long int} type and
151+ overflow warnings are being suppressed, a \ctype{PyLongObject} will be
152+ returned. If overflow warnings are not being suppressed, \NULL{} will be
153+ returned in this case.
154+\end{cfuncdesc}
155+
156+\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
157+ Create a new integer object with a value of \var{ival}.
158+
159+ The current implementation keeps an array of integer objects for all
160+ integers between \code{-5} and \code{256}, when you create an int in
161+ that range you actually just get back a reference to the existing
162+ object. So it should be possible to change the value of \code{1}. I
163+ suspect the behaviour of Python in this case is undefined. :-)
164+\end{cfuncdesc}
165+
166+\begin{cfuncdesc}{PyObject*}{PyInt_FromSsize_t}{Py_ssize_t ival}
167+ Create a new integer object with a value of \var{ival}.
168+ If the value exceeds \code{LONG_MAX}, a long integer object is
169+ returned.
170+
171+ \versionadded{2.5}
172+\end{cfuncdesc}
173+
174+\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
175+ Will first attempt to cast the object to a \ctype{PyIntObject}, if
176+ it is not already one, and then return its value. If there is an
177+ error, \code{-1} is returned, and the caller should check
178+ \code{PyErr_Occurred()} to find out whether there was an error, or
179+ whether the value just happened to be -1.
180+\end{cfuncdesc}
181+
182+\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
183+ Return the value of the object \var{io}. No error checking is
184+ performed.
185+\end{cfuncdesc}
186+
187+\begin{cfuncdesc}{unsigned long}{PyInt_AsUnsignedLongMask}{PyObject *io}
188+ Will first attempt to cast the object to a \ctype{PyIntObject} or
189+ \ctype{PyLongObject}, if it is not already one, and then return its
190+ value as unsigned long. This function does not check for overflow.
191+ \versionadded{2.3}
192+\end{cfuncdesc}
193+
194+\begin{cfuncdesc}{unsigned PY_LONG_LONG}{PyInt_AsUnsignedLongLongMask}{PyObject *io}
195+ Will first attempt to cast the object to a \ctype{PyIntObject} or
196+ \ctype{PyLongObject}, if it is not already one, and then return its
197+ value as unsigned long long, without checking for overflow.
198+ \versionadded{2.3}
199+\end{cfuncdesc}
200+
201+\begin{cfuncdesc}{Py_ssize_t}{PyInt_AsSsize_t}{PyObject *io}
202+ Will first attempt to cast the object to a \ctype{PyIntObject} or
203+ \ctype{PyLongObject}, if it is not already one, and then return its
204+ value as \ctype{Py_ssize_t}.
205+ \versionadded{2.5}
206+\end{cfuncdesc}
207+
208+\begin{cfuncdesc}{long}{PyInt_GetMax}{}
209+ Return the system's idea of the largest integer it can handle
210+ (\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
211+ header files).
212+\end{cfuncdesc}
213+
214+\subsection{Boolean Objects \label{boolObjects}}
215+
216+Booleans in Python are implemented as a subclass of integers. There
217+are only two booleans, \constant{Py_False} and \constant{Py_True}. As
218+such, the normal creation and deletion functions don't apply to
219+booleans. The following macros are available, however.
220+
221+\begin{cfuncdesc}{int}{PyBool_Check}{PyObject *o}
222+ Return true if \var{o} is of type \cdata{PyBool_Type}.
223+ \versionadded{2.3}
224+\end{cfuncdesc}
225+
226+\begin{cvardesc}{PyObject*}{Py_False}
227+ The Python \code{False} object. This object has no methods. It needs to
228+ be treated just like any other object with respect to reference counts.
229+\end{cvardesc}
230+
231+\begin{cvardesc}{PyObject*}{Py_True}
232+ The Python \code{True} object. This object has no methods. It needs to
233+ be treated just like any other object with respect to reference counts.
234+\end{cvardesc}
235+
236+\begin{csimplemacrodesc}{Py_RETURN_FALSE}
237+ Return \constant{Py_False} from a function, properly incrementing its
238+ reference count.
239+\versionadded{2.4}
240+\end{csimplemacrodesc}
241+
242+\begin{csimplemacrodesc}{Py_RETURN_TRUE}
243+ Return \constant{Py_True} from a function, properly incrementing its
244+ reference count.
245+\versionadded{2.4}
246+\end{csimplemacrodesc}
247+
248+\begin{cfuncdesc}{PyObject*}{PyBool_FromLong}{long v}
249+ Return a new reference to \constant{Py_True} or \constant{Py_False}
250+ depending on the truth value of \var{v}.
251+\versionadded{2.3}
252+\end{cfuncdesc}
253+
254+\subsection{Long Integer Objects \label{longObjects}}
255+
256+\obindex{long integer}
257+\begin{ctypedesc}{PyLongObject}
258+ This subtype of \ctype{PyObject} represents a Python long integer
259+ object.
260+\end{ctypedesc}
261+
262+\begin{cvardesc}{PyTypeObject}{PyLong_Type}
263+ This instance of \ctype{PyTypeObject} represents the Python long
264+ integer type. This is the same object as \code{long} and
265+ \code{types.LongType}.
266+ \withsubitem{(in modules types)}{\ttindex{LongType}}
267+\end{cvardesc}
268+
269+\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
270+ Return true if its argument is a \ctype{PyLongObject} or a subtype
271+ of \ctype{PyLongObject}.
272+ \versionchanged[Allowed subtypes to be accepted]{2.2}
273+\end{cfuncdesc}
274+
275+\begin{cfuncdesc}{int}{PyLong_CheckExact}{PyObject *p}
276+ Return true if its argument is a \ctype{PyLongObject}, but not a
277+ subtype of \ctype{PyLongObject}.
278+ \versionadded{2.2}
279+\end{cfuncdesc}
280+
281+\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
282+ Return a new \ctype{PyLongObject} object from \var{v}, or \NULL{}
283+ on failure.
284+\end{cfuncdesc}
285+
286+\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
287+ Return a new \ctype{PyLongObject} object from a C \ctype{unsigned
288+ long}, or \NULL{} on failure.
289+\end{cfuncdesc}
290+
291+\begin{cfuncdesc}{PyObject*}{PyLong_FromLongLong}{PY_LONG_LONG v}
292+ Return a new \ctype{PyLongObject} object from a C \ctype{long long},
293+ or \NULL{} on failure.
294+\end{cfuncdesc}
295+
296+\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLongLong}{unsigned PY_LONG_LONG v}
297+ Return a new \ctype{PyLongObject} object from a C \ctype{unsigned
298+ long long}, or \NULL{} on failure.
299+\end{cfuncdesc}
300+
301+\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
302+ Return a new \ctype{PyLongObject} object from the integer part of
303+ \var{v}, or \NULL{} on failure.
304+\end{cfuncdesc}
305+
306+\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
307+ int base}
308+ Return a new \ctype{PyLongObject} based on the string value in
309+ \var{str}, which is interpreted according to the radix in
310+ \var{base}. If \var{pend} is non-\NULL{}, \code{*\var{pend}} will
311+ point to the first character in \var{str} which follows the
312+ representation of the number. If \var{base} is \code{0}, the radix
313+ will be determined based on the leading characters of \var{str}: if
314+ \var{str} starts with \code{'0x'} or \code{'0X'}, radix 16 will be
315+ used; if \var{str} starts with \code{'0'}, radix 8 will be used;
316+ otherwise radix 10 will be used. If \var{base} is not \code{0}, it
317+ must be between \code{2} and \code{36}, inclusive. Leading spaces
318+ are ignored. If there are no digits, \exception{ValueError} will be
319+ raised.
320+\end{cfuncdesc}
321+
322+\begin{cfuncdesc}{PyObject*}{PyLong_FromUnicode}{Py_UNICODE *u,
323+ Py_ssize_t length, int base}
324+ Convert a sequence of Unicode digits to a Python long integer
325+ value. The first parameter, \var{u}, points to the first character
326+ of the Unicode string, \var{length} gives the number of characters,
327+ and \var{base} is the radix for the conversion. The radix must be
328+ in the range [2, 36]; if it is out of range, \exception{ValueError}
329+ will be raised.
330+ \versionadded{1.6}
331+\end{cfuncdesc}
332+
333+\begin{cfuncdesc}{PyObject*}{PyLong_FromVoidPtr}{void *p}
334+ Create a Python integer or long integer from the pointer \var{p}.
335+ The pointer value can be retrieved from the resulting value using
336+ \cfunction{PyLong_AsVoidPtr()}.
337+ \versionadded{1.5.2}
338+ \versionchanged[If the integer is larger than LONG_MAX,
339+ a positive long integer is returned]{2.5}
340+ \end{cfuncdesc}
341+
342+\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
343+ Return a C \ctype{long} representation of the contents of
344+ \var{pylong}. If \var{pylong} is greater than
345+ \constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError}
346+ is raised.
347+ \withsubitem{(built-in exception)}{\ttindex{OverflowError}}
348+\end{cfuncdesc}
349+
350+\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
351+ Return a C \ctype{unsigned long} representation of the contents of
352+ \var{pylong}. If \var{pylong} is greater than
353+ \constant{ULONG_MAX}\ttindex{ULONG_MAX}, an
354+ \exception{OverflowError} is raised.
355+ \withsubitem{(built-in exception)}{\ttindex{OverflowError}}
356+\end{cfuncdesc}
357+
358+\begin{cfuncdesc}{PY_LONG_LONG}{PyLong_AsLongLong}{PyObject *pylong}
359+ Return a C \ctype{long long} from a Python long integer. If
360+ \var{pylong} cannot be represented as a \ctype{long long}, an
361+ \exception{OverflowError} will be raised.
362+ \versionadded{2.2}
363+\end{cfuncdesc}
364+
365+\begin{cfuncdesc}{unsigned PY_LONG_LONG}{PyLong_AsUnsignedLongLong}{PyObject
366+ *pylong}
367+ Return a C \ctype{unsigned long long} from a Python long integer.
368+ If \var{pylong} cannot be represented as an \ctype{unsigned long
369+ long}, an \exception{OverflowError} will be raised if the value is
370+ positive, or a \exception{TypeError} will be raised if the value is
371+ negative.
372+ \versionadded{2.2}
373+\end{cfuncdesc}
374+
375+\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLongMask}{PyObject *io}
376+ Return a C \ctype{unsigned long} from a Python long integer, without
377+ checking for overflow.
378+ \versionadded{2.3}
379+\end{cfuncdesc}
380+
381+\begin{cfuncdesc}{unsigned PY_LONG_LONG}{PyLong_AsUnsignedLongLongMask}{PyObject *io}
382+ Return a C \ctype{unsigned long long} from a Python long integer, without
383+ checking for overflow.
384+ \versionadded{2.3}
385+\end{cfuncdesc}
386+
387+\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
388+ Return a C \ctype{double} representation of the contents of
389+ \var{pylong}. If \var{pylong} cannot be approximately represented
390+ as a \ctype{double}, an \exception{OverflowError} exception is
391+ raised and \code{-1.0} will be returned.
392+\end{cfuncdesc}
393+
394+\begin{cfuncdesc}{void*}{PyLong_AsVoidPtr}{PyObject *pylong}
395+ Convert a Python integer or long integer \var{pylong} to a C
396+ \ctype{void} pointer. If \var{pylong} cannot be converted, an
397+ \exception{OverflowError} will be raised. This is only assured to
398+ produce a usable \ctype{void} pointer for values created with
399+ \cfunction{PyLong_FromVoidPtr()}.
400+ \versionadded{1.5.2}
401+ \versionchanged[For values outside 0..LONG_MAX, both signed and
402+ unsigned integers are acccepted]{2.5}
403+\end{cfuncdesc}
404+
405+
406+\subsection{Floating Point Objects \label{floatObjects}}
407+
408+\obindex{floating point}
409+\begin{ctypedesc}{PyFloatObject}
410+ This subtype of \ctype{PyObject} represents a Python floating point
411+ object.
412+\end{ctypedesc}
413+
414+\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
415+ This instance of \ctype{PyTypeObject} represents the Python floating
416+ point type. This is the same object as \code{float} and
417+ \code{types.FloatType}.
418+ \withsubitem{(in modules types)}{\ttindex{FloatType}}
419+\end{cvardesc}
420+
421+\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
422+ Return true if its argument is a \ctype{PyFloatObject} or a subtype
423+ of \ctype{PyFloatObject}.
424+ \versionchanged[Allowed subtypes to be accepted]{2.2}
425+\end{cfuncdesc}
426+
427+\begin{cfuncdesc}{int}{PyFloat_CheckExact}{PyObject *p}
428+ Return true if its argument is a \ctype{PyFloatObject}, but not a
429+ subtype of \ctype{PyFloatObject}.
430+ \versionadded{2.2}
431+\end{cfuncdesc}
432+
433+\begin{cfuncdesc}{PyObject*}{PyFloat_FromString}{PyObject *str, char **pend}
434+ Create a \ctype{PyFloatObject} object based on the string value in
435+ \var{str}, or \NULL{} on failure. The \var{pend} argument is ignored. It
436+ remains only for backward compatibility.
437+\end{cfuncdesc}
438+
439+\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
440+ Create a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
441+ failure.
442+\end{cfuncdesc}
443+
444+\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
445+ Return a C \ctype{double} representation of the contents of
446+ \var{pyfloat}.
447+\end{cfuncdesc}
448+
449+\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
450+ Return a C \ctype{double} representation of the contents of
451+ \var{pyfloat}, but without error checking.
452+\end{cfuncdesc}
453+
454+
455+\subsection{Complex Number Objects \label{complexObjects}}
456+
457+\obindex{complex number}
458+Python's complex number objects are implemented as two distinct types
459+when viewed from the C API: one is the Python object exposed to
460+Python programs, and the other is a C structure which represents the
461+actual complex number value. The API provides functions for working
462+with both.
463+
464+\subsubsection{Complex Numbers as C Structures}
465+
466+Note that the functions which accept these structures as parameters
467+and return them as results do so \emph{by value} rather than
468+dereferencing them through pointers. This is consistent throughout
469+the API.
470+
471+\begin{ctypedesc}{Py_complex}
472+ The C structure which corresponds to the value portion of a Python
473+ complex number object. Most of the functions for dealing with
474+ complex number objects use structures of this type as input or
475+ output values, as appropriate. It is defined as:
476+
477+\begin{verbatim}
478+typedef struct {
479+ double real;
480+ double imag;
481+} Py_complex;
482+\end{verbatim}
483+\end{ctypedesc}
484+
485+\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
486+ Return the sum of two complex numbers, using the C
487+ \ctype{Py_complex} representation.
488+\end{cfuncdesc}
489+
490+\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
491+ Return the difference between two complex numbers, using the C
492+ \ctype{Py_complex} representation.
493+\end{cfuncdesc}
494+
495+\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
496+ Return the negation of the complex number \var{complex}, using the C
497+ \ctype{Py_complex} representation.
498+\end{cfuncdesc}
499+
500+\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
501+ Return the product of two complex numbers, using the C
502+ \ctype{Py_complex} representation.
503+\end{cfuncdesc}
504+
505+\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
506+ Py_complex divisor}
507+ Return the quotient of two complex numbers, using the C
508+ \ctype{Py_complex} representation.
509+\end{cfuncdesc}
510+
511+\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
512+ Return the exponentiation of \var{num} by \var{exp}, using the C
513+ \ctype{Py_complex} representation.
514+\end{cfuncdesc}
515+
516+
517+\subsubsection{Complex Numbers as Python Objects}
518+
519+\begin{ctypedesc}{PyComplexObject}
520+ This subtype of \ctype{PyObject} represents a Python complex number
521+ object.
522+\end{ctypedesc}
523+
524+\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
525+ This instance of \ctype{PyTypeObject} represents the Python complex
526+ number type. It is the same object as \code{complex} and
527+ \code{types.ComplexType}.
528+\end{cvardesc}
529+
530+\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
531+ Return true if its argument is a \ctype{PyComplexObject} or a
532+ subtype of \ctype{PyComplexObject}.
533+ \versionchanged[Allowed subtypes to be accepted]{2.2}
534+\end{cfuncdesc}
535+
536+\begin{cfuncdesc}{int}{PyComplex_CheckExact}{PyObject *p}
537+ Return true if its argument is a \ctype{PyComplexObject}, but not a
538+ subtype of \ctype{PyComplexObject}.
539+ \versionadded{2.2}
540+\end{cfuncdesc}
541+
542+\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
543+ Create a new Python complex number object from a C
544+ \ctype{Py_complex} value.
545+\end{cfuncdesc}
546+
547+\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
548+ Return a new \ctype{PyComplexObject} object from \var{real} and
549+ \var{imag}.
550+\end{cfuncdesc}
551+
552+\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
553+ Return the real part of \var{op} as a C \ctype{double}.
554+\end{cfuncdesc}
555+
556+\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
557+ Return the imaginary part of \var{op} as a C \ctype{double}.
558+\end{cfuncdesc}
559+
560+\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
561+ Return the \ctype{Py_complex} value of the complex number
562+ \var{op}.
563+\end{cfuncdesc}
564+
565+
566+
567+\section{Sequence Objects \label{sequenceObjects}}
568+
569+\obindex{sequence}
570+Generic operations on sequence objects were discussed in the previous
571+chapter; this section deals with the specific kinds of sequence
572+objects that are intrinsic to the Python language.
573+
574+
575+\subsection{String Objects \label{stringObjects}}
576+
577+These functions raise \exception{TypeError} when expecting a string
578+parameter and are called with a non-string parameter.
579+
580+\obindex{string}
581+\begin{ctypedesc}{PyStringObject}
582+ This subtype of \ctype{PyObject} represents a Python string object.
583+\end{ctypedesc}
584+
585+\begin{cvardesc}{PyTypeObject}{PyString_Type}
586+ This instance of \ctype{PyTypeObject} represents the Python string
587+ type; it is the same object as \code{str} and \code{types.StringType}
588+ in the Python layer.
589+ \withsubitem{(in module types)}{\ttindex{StringType}}.
590+\end{cvardesc}
591+
592+\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
593+ Return true if the object \var{o} is a string object or an instance
594+ of a subtype of the string type.
595+ \versionchanged[Allowed subtypes to be accepted]{2.2}
596+\end{cfuncdesc}
597+
598+\begin{cfuncdesc}{int}{PyString_CheckExact}{PyObject *o}
599+ Return true if the object \var{o} is a string object, but not an
600+ instance of a subtype of the string type.
601+ \versionadded{2.2}
602+\end{cfuncdesc}
603+
604+\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
605+ Return a new string object with a copy of the string \var{v} as value
606+ on success, and \NULL{} on failure. The parameter \var{v} must not be
607+ \NULL{}; it will not be checked.
608+\end{cfuncdesc}
609+
610+\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
611+ Py_ssize_t len}
612+ Return a new string object with a copy of the string \var{v} as value
613+ and length \var{len} on success, and \NULL{} on failure. If \var{v} is
614+ \NULL{}, the contents of the string are uninitialized.
615+\end{cfuncdesc}
616+
617+\begin{cfuncdesc}{PyObject*}{PyString_FromFormat}{const char *format, ...}
618+ Take a C \cfunction{printf()}-style \var{format} string and a
619+ variable number of arguments, calculate the size of the resulting
620+ Python string and return a string with the values formatted into
621+ it. The variable arguments must be C types and must correspond
622+ exactly to the format characters in the \var{format} string. The
623+ following format characters are allowed:
624+
625+ % This should be exactly the same as the table in PyErr_Format.
626+ % One should just refer to the other.
627+
628+ % The descriptions for %zd and %zu are wrong, but the truth is complicated
629+ % because not all compilers support the %z width modifier -- we fake it
630+ % when necessary via interpolating PY_FORMAT_SIZE_T.
631+
632+ % %u, %lu, %zu should have "new in Python 2.5" blurbs.
633+
634+ \begin{tableiii}{l|l|l}{member}{Format Characters}{Type}{Comment}
635+ \lineiii{\%\%}{\emph{n/a}}{The literal \% character.}
636+ \lineiii{\%c}{int}{A single character, represented as an C int.}
637+ \lineiii{\%d}{int}{Exactly equivalent to \code{printf("\%d")}.}
638+ \lineiii{\%u}{unsigned int}{Exactly equivalent to \code{printf("\%u")}.}
639+ \lineiii{\%ld}{long}{Exactly equivalent to \code{printf("\%ld")}.}
640+ \lineiii{\%lu}{unsigned long}{Exactly equivalent to \code{printf("\%lu")}.}
641+ \lineiii{\%zd}{Py_ssize_t}{Exactly equivalent to \code{printf("\%zd")}.}
642+ \lineiii{\%zu}{size_t}{Exactly equivalent to \code{printf("\%zu")}.}
643+ \lineiii{\%i}{int}{Exactly equivalent to \code{printf("\%i")}.}
644+ \lineiii{\%x}{int}{Exactly equivalent to \code{printf("\%x")}.}
645+ \lineiii{\%s}{char*}{A null-terminated C character array.}
646+ \lineiii{\%p}{void*}{The hex representation of a C pointer.
647+ Mostly equivalent to \code{printf("\%p")} except that it is
648+ guaranteed to start with the literal \code{0x} regardless of
649+ what the platform's \code{printf} yields.}
650+ \end{tableiii}
651+
652+ An unrecognized format character causes all the rest of the format
653+ string to be copied as-is to the result string, and any extra
654+ arguments discarded.
655+\end{cfuncdesc}
656+
657+\begin{cfuncdesc}{PyObject*}{PyString_FromFormatV}{const char *format,
658+ va_list vargs}
659+ Identical to \function{PyString_FromFormat()} except that it takes
660+ exactly two arguments.
661+\end{cfuncdesc}
662+
663+\begin{cfuncdesc}{Py_ssize_t}{PyString_Size}{PyObject *string}
664+ Return the length of the string in string object \var{string}.
665+\end{cfuncdesc}
666+
667+\begin{cfuncdesc}{Py_ssize_t}{PyString_GET_SIZE}{PyObject *string}
668+ Macro form of \cfunction{PyString_Size()} but without error
669+ checking.
670+\end{cfuncdesc}
671+
672+\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
673+ Return a NUL-terminated representation of the contents of
674+ \var{string}. The pointer refers to the internal buffer of
675+ \var{string}, not a copy. The data must not be modified in any way,
676+ unless the string was just created using
677+ \code{PyString_FromStringAndSize(NULL, \var{size})}.
678+ It must not be deallocated. If \var{string} is a Unicode object,
679+ this function computes the default encoding of \var{string} and
680+ operates on that. If \var{string} is not a string object at all,
681+ \cfunction{PyString_AsString()} returns \NULL{} and raises
682+ \exception{TypeError}.
683+\end{cfuncdesc}
684+
685+\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
686+ Macro form of \cfunction{PyString_AsString()} but without error
687+ checking. Only string objects are supported; no Unicode objects
688+ should be passed.
689+\end{cfuncdesc}
690+
691+\begin{cfuncdesc}{int}{PyString_AsStringAndSize}{PyObject *obj,
692+ char **buffer,
693+ Py_ssize_t *length}
694+ Return a NUL-terminated representation of the contents of the
695+ object \var{obj} through the output variables \var{buffer} and
696+ \var{length}.
697+
698+ The function accepts both string and Unicode objects as input. For
699+ Unicode objects it returns the default encoded version of the
700+ object. If \var{length} is \NULL{}, the resulting buffer may not
701+ contain NUL characters; if it does, the function returns \code{-1}
702+ and a \exception{TypeError} is raised.
703+
704+ The buffer refers to an internal string buffer of \var{obj}, not a
705+ copy. The data must not be modified in any way, unless the string
706+ was just created using \code{PyString_FromStringAndSize(NULL,
707+ \var{size})}. It must not be deallocated. If \var{string} is a
708+ Unicode object, this function computes the default encoding of
709+ \var{string} and operates on that. If \var{string} is not a string
710+ object at all, \cfunction{PyString_AsStringAndSize()} returns
711+ \code{-1} and raises \exception{TypeError}.
712+\end{cfuncdesc}
713+
714+\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
715+ PyObject *newpart}
716+ Create a new string object in \var{*string} containing the contents
717+ of \var{newpart} appended to \var{string}; the caller will own the
718+ new reference. The reference to the old value of \var{string} will
719+ be stolen. If the new string cannot be created, the old reference
720+ to \var{string} will still be discarded and the value of
721+ \var{*string} will be set to \NULL{}; the appropriate exception will
722+ be set.
723+\end{cfuncdesc}
724+
725+\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
726+ PyObject *newpart}
727+ Create a new string object in \var{*string} containing the contents
728+ of \var{newpart} appended to \var{string}. This version decrements
729+ the reference count of \var{newpart}.
730+\end{cfuncdesc}
731+
732+\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, Py_ssize_t newsize}
733+ A way to resize a string object even though it is ``immutable''.
734+ Only use this to build up a brand new string object; don't use this
735+ if the string may already be known in other parts of the code. It
736+ is an error to call this function if the refcount on the input string
737+ object is not one.
738+ Pass the address of an existing string object as an lvalue (it may
739+ be written into), and the new size desired. On success, \var{*string}
740+ holds the resized string object and \code{0} is returned; the address in
741+ \var{*string} may differ from its input value. If the
742+ reallocation fails, the original string object at \var{*string} is
743+ deallocated, \var{*string} is set to \NULL{}, a memory exception is set,
744+ and \code{-1} is returned.
745+\end{cfuncdesc}
746+
747+\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
748+ PyObject *args}
749+ Return a new string object from \var{format} and \var{args}.
750+ Analogous to \code{\var{format} \%\ \var{args}}. The \var{args}
751+ argument must be a tuple.
752+\end{cfuncdesc}
753+
754+\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
755+ Intern the argument \var{*string} in place. The argument must be
756+ the address of a pointer variable pointing to a Python string
757+ object. If there is an existing interned string that is the same as
758+ \var{*string}, it sets \var{*string} to it (decrementing the
759+ reference count of the old string object and incrementing the
760+ reference count of the interned string object), otherwise it leaves
761+ \var{*string} alone and interns it (incrementing its reference
762+ count). (Clarification: even though there is a lot of talk about
763+ reference counts, think of this function as reference-count-neutral;
764+ you own the object after the call if and only if you owned it before
765+ the call.)
766+\end{cfuncdesc}
767+
768+\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
769+ A combination of \cfunction{PyString_FromString()} and
770+ \cfunction{PyString_InternInPlace()}, returning either a new string
771+ object that has been interned, or a new (``owned'') reference to an
772+ earlier interned string object with the same value.
773+\end{cfuncdesc}
774+
775+\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
776+ Py_ssize_t size,
777+ const char *encoding,
778+ const char *errors}
779+ Create an object by decoding \var{size} bytes of the encoded
780+ buffer \var{s} using the codec registered for
781+ \var{encoding}. \var{encoding} and \var{errors} have the same
782+ meaning as the parameters of the same name in the
783+ \function{unicode()} built-in function. The codec to be used is
784+ looked up using the Python codec registry. Return \NULL{} if
785+ an exception was raised by the codec.
786+\end{cfuncdesc}
787+
788+\begin{cfuncdesc}{PyObject*}{PyString_AsDecodedObject}{PyObject *str,
789+ const char *encoding,
790+ const char *errors}
791+ Decode a string object by passing it to the codec registered for
792+ \var{encoding} and return the result as Python
793+ object. \var{encoding} and \var{errors} have the same meaning as the
794+ parameters of the same name in the string \method{encode()} method.
795+ The codec to be used is looked up using the Python codec registry.
796+ Return \NULL{} if an exception was raised by the codec.
797+\end{cfuncdesc}
798+
799+\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const char *s,
800+ Py_ssize_t size,
801+ const char *encoding,
802+ const char *errors}
803+ Encode the \ctype{char} buffer of the given size by passing it to
804+ the codec registered for \var{encoding} and return a Python object.
805+ \var{encoding} and \var{errors} have the same meaning as the
806+ parameters of the same name in the string \method{encode()} method.
807+ The codec to be used is looked up using the Python codec
808+ registry. Return \NULL{} if an exception was raised by the
809+ codec.
810+\end{cfuncdesc}
811+
812+\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedObject}{PyObject *str,
813+ const char *encoding,
814+ const char *errors}
815+ Encode a string object using the codec registered for
816+ \var{encoding} and return the result as Python object.
817+ \var{encoding} and \var{errors} have the same meaning as the
818+ parameters of the same name in the string \method{encode()} method.
819+ The codec to be used is looked up using the Python codec registry.
820+ Return \NULL{} if an exception was raised by the codec.
821+\end{cfuncdesc}
822+
823+
824+\subsection{Unicode Objects \label{unicodeObjects}}
825+\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
826+
827+%--- Unicode Type -------------------------------------------------------
828+
829+These are the basic Unicode object types used for the Unicode
830+implementation in Python:
831+
832+\begin{ctypedesc}{Py_UNICODE}
833+ This type represents the storage type which is used by Python
834+ internally as basis for holding Unicode ordinals. Python's default
835+ builds use a 16-bit type for \ctype{Py_UNICODE} and store Unicode
836+ values internally as UCS2. It is also possible to build a UCS4
837+ version of Python (most recent Linux distributions come with UCS4
838+ builds of Python). These builds then use a 32-bit type for
839+ \ctype{Py_UNICODE} and store Unicode data internally as UCS4. On
840+ platforms where \ctype{wchar_t} is available and compatible with the
841+ chosen Python Unicode build variant, \ctype{Py_UNICODE} is a typedef
842+ alias for \ctype{wchar_t} to enhance native platform compatibility.
843+ On all other platforms, \ctype{Py_UNICODE} is a typedef alias for
844+ either \ctype{unsigned short} (UCS2) or \ctype{unsigned long}
845+ (UCS4).
846+\end{ctypedesc}
847+
848+Note that UCS2 and UCS4 Python builds are not binary compatible.
849+Please keep this in mind when writing extensions or interfaces.
850+
851+\begin{ctypedesc}{PyUnicodeObject}
852+ This subtype of \ctype{PyObject} represents a Python Unicode object.
853+\end{ctypedesc}
854+
855+\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
856+ This instance of \ctype{PyTypeObject} represents the Python Unicode
857+ type. It is exposed to Python code as \code{unicode} and
858+ \code{types.UnicodeType}.
859+\end{cvardesc}
860+
861+The following APIs are really C macros and can be used to do fast
862+checks and to access internal read-only data of Unicode objects:
863+
864+\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
865+ Return true if the object \var{o} is a Unicode object or an
866+ instance of a Unicode subtype.
867+ \versionchanged[Allowed subtypes to be accepted]{2.2}
868+\end{cfuncdesc}
869+
870+\begin{cfuncdesc}{int}{PyUnicode_CheckExact}{PyObject *o}
871+ Return true if the object \var{o} is a Unicode object, but not an
872+ instance of a subtype.
873+ \versionadded{2.2}
874+\end{cfuncdesc}
875+
876+\begin{cfuncdesc}{Py_ssize_t}{PyUnicode_GET_SIZE}{PyObject *o}
877+ Return the size of the object. \var{o} has to be a
878+ \ctype{PyUnicodeObject} (not checked).
879+\end{cfuncdesc}
880+
881+\begin{cfuncdesc}{Py_ssize_t}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
882+ Return the size of the object's internal buffer in bytes. \var{o}
883+ has to be a \ctype{PyUnicodeObject} (not checked).
884+\end{cfuncdesc}
885+
886+\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
887+ Return a pointer to the internal \ctype{Py_UNICODE} buffer of the
888+ object. \var{o} has to be a \ctype{PyUnicodeObject} (not checked).
889+\end{cfuncdesc}
890+
891+\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
892+ Return a pointer to the internal buffer of the object.
893+ \var{o} has to be a \ctype{PyUnicodeObject} (not checked).
894+\end{cfuncdesc}
895+
896+% --- Unicode character properties ---------------------------------------
897+
898+Unicode provides many different character properties. The most often
899+needed ones are available through these macros which are mapped to C
900+functions depending on the Python configuration.
901+
902+\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
903+ Return 1 or 0 depending on whether \var{ch} is a whitespace
904+ character.
905+\end{cfuncdesc}
906+
907+\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
908+ Return 1 or 0 depending on whether \var{ch} is a lowercase character.
909+\end{cfuncdesc}
910+
911+\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
912+ Return 1 or 0 depending on whether \var{ch} is an uppercase
913+ character.
914+\end{cfuncdesc}
915+
916+\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
917+ Return 1 or 0 depending on whether \var{ch} is a titlecase character.
918+\end{cfuncdesc}
919+
920+\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
921+ Return 1 or 0 depending on whether \var{ch} is a linebreak character.
922+\end{cfuncdesc}
923+
924+\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
925+ Return 1 or 0 depending on whether \var{ch} is a decimal character.
926+\end{cfuncdesc}
927+
928+\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
929+ Return 1 or 0 depending on whether \var{ch} is a digit character.
930+\end{cfuncdesc}
931+
932+\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
933+ Return 1 or 0 depending on whether \var{ch} is a numeric character.
934+\end{cfuncdesc}
935+
936+\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
937+ Return 1 or 0 depending on whether \var{ch} is an alphabetic
938+ character.
939+\end{cfuncdesc}
940+
941+\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
942+ Return 1 or 0 depending on whether \var{ch} is an alphanumeric
943+ character.
944+\end{cfuncdesc}
945+
946+These APIs can be used for fast direct character conversions:
947+
948+\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
949+ Return the character \var{ch} converted to lower case.
950+\end{cfuncdesc}
951+
952+\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
953+ Return the character \var{ch} converted to upper case.
954+\end{cfuncdesc}
955+
956+\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
957+ Return the character \var{ch} converted to title case.
958+\end{cfuncdesc}
959+
960+\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
961+ Return the character \var{ch} converted to a decimal positive
962+ integer. Return \code{-1} if this is not possible. This macro
963+ does not raise exceptions.
964+\end{cfuncdesc}
965+
966+\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
967+ Return the character \var{ch} converted to a single digit integer.
968+ Return \code{-1} if this is not possible. This macro does not raise
969+ exceptions.
970+\end{cfuncdesc}
971+
972+\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
973+ Return the character \var{ch} converted to a double.
974+ Return \code{-1.0} if this is not possible. This macro does not raise
975+ exceptions.
976+\end{cfuncdesc}
977+
978+% --- Plain Py_UNICODE ---------------------------------------------------
979+
980+To create Unicode objects and access their basic sequence properties,
981+use these APIs:
982+
983+\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
984+ Py_ssize_t size}
985+ Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
986+ given size. \var{u} may be \NULL{} which causes the contents to be
987+ undefined. It is the user's responsibility to fill in the needed
988+ data. The buffer is copied into the new object. If the buffer is
989+ not \NULL{}, the return value might be a shared object. Therefore,
990+ modification of the resulting Unicode object is only allowed when
991+ \var{u} is \NULL{}.
992+\end{cfuncdesc}
993+
994+\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
995+ Return a read-only pointer to the Unicode object's internal
996+ \ctype{Py_UNICODE} buffer, \NULL{} if \var{unicode} is not a Unicode
997+ object.
998+\end{cfuncdesc}
999+
1000+\begin{cfuncdesc}{Py_ssize_t}{PyUnicode_GetSize}{PyObject *unicode}
1001+ Return the length of the Unicode object.
1002+\end{cfuncdesc}
1003+
1004+\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
1005+ const char *encoding,
1006+ const char *errors}
1007+ Coerce an encoded object \var{obj} to an Unicode object and return a
1008+ reference with incremented refcount.
1009+
1010+ String and other char buffer compatible objects are decoded
1011+ according to the given encoding and using the error handling
1012+ defined by errors. Both can be \NULL{} to have the interface
1013+ use the default values (see the next section for details).
1014+
1015+ All other objects, including Unicode objects, cause a
1016+ \exception{TypeError} to be set.
1017+
1018+ The API returns \NULL{} if there was an error. The caller is
1019+ responsible for decref'ing the returned objects.
1020+\end{cfuncdesc}
1021+
1022+\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
1023+ Shortcut for \code{PyUnicode_FromEncodedObject(obj, NULL, "strict")}
1024+ which is used throughout the interpreter whenever coercion to
1025+ Unicode is needed.
1026+\end{cfuncdesc}
1027+
1028+% --- wchar_t support for platforms which support it ---------------------
1029+
1030+If the platform supports \ctype{wchar_t} and provides a header file
1031+wchar.h, Python can interface directly to this type using the
1032+following functions. Support is optimized if Python's own
1033+\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
1034+
1035+\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
1036+ Py_ssize_t size}
1037+ Create a Unicode object from the \ctype{wchar_t} buffer \var{w} of
1038+ the given size. Return \NULL{} on failure.
1039+\end{cfuncdesc}
1040+
1041+\begin{cfuncdesc}{Py_ssize_t}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
1042+ wchar_t *w,
1043+ Py_ssize_t size}
1044+ Copy the Unicode object contents into the \ctype{wchar_t} buffer
1045+ \var{w}. At most \var{size} \ctype{wchar_t} characters are copied
1046+ (excluding a possibly trailing 0-termination character). Return
1047+ the number of \ctype{wchar_t} characters copied or -1 in case of an
1048+ error. Note that the resulting \ctype{wchar_t} string may or may
1049+ not be 0-terminated. It is the responsibility of the caller to make
1050+ sure that the \ctype{wchar_t} string is 0-terminated in case this is
1051+ required by the application.
1052+\end{cfuncdesc}
1053+
1054+
1055+\subsubsection{Built-in Codecs \label{builtinCodecs}}
1056+
1057+Python provides a set of builtin codecs which are written in C
1058+for speed. All of these codecs are directly usable via the
1059+following functions.
1060+
1061+Many of the following APIs take two arguments encoding and
1062+errors. These parameters encoding and errors have the same semantics
1063+as the ones of the builtin unicode() Unicode object constructor.
1064+
1065+Setting encoding to \NULL{} causes the default encoding to be used
1066+which is \ASCII. The file system calls should use
1067+\cdata{Py_FileSystemDefaultEncoding} as the encoding for file
1068+names. This variable should be treated as read-only: On some systems,
1069+it will be a pointer to a static string, on others, it will change at
1070+run-time (such as when the application invokes setlocale).
1071+
1072+Error handling is set by errors which may also be set to \NULL{}
1073+meaning to use the default handling defined for the codec. Default
1074+error handling for all builtin codecs is ``strict''
1075+(\exception{ValueError} is raised).
1076+
1077+The codecs all use a similar interface. Only deviation from the
1078+following generic ones are documented for simplicity.
1079+
1080+% --- Generic Codecs -----------------------------------------------------
1081+
1082+These are the generic codec APIs:
1083+
1084+\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
1085+ Py_ssize_t size,
1086+ const char *encoding,
1087+ const char *errors}
1088+ Create a Unicode object by decoding \var{size} bytes of the encoded
1089+ string \var{s}. \var{encoding} and \var{errors} have the same
1090+ meaning as the parameters of the same name in the
1091+ \function{unicode()} builtin function. The codec to be used is
1092+ looked up using the Python codec registry. Return \NULL{} if an
1093+ exception was raised by the codec.
1094+\end{cfuncdesc}
1095+
1096+\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
1097+ Py_ssize_t size,
1098+ const char *encoding,
1099+ const char *errors}
1100+ Encode the \ctype{Py_UNICODE} buffer of the given size and return
1101+ a Python string object. \var{encoding} and \var{errors} have the
1102+ same meaning as the parameters of the same name in the Unicode
1103+ \method{encode()} method. The codec to be used is looked up using
1104+ the Python codec registry. Return \NULL{} if an exception was
1105+ raised by the codec.
1106+\end{cfuncdesc}
1107+
1108+\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
1109+ const char *encoding,
1110+ const char *errors}
1111+ Encode a Unicode object and return the result as Python string
1112+ object. \var{encoding} and \var{errors} have the same meaning as the
1113+ parameters of the same name in the Unicode \method{encode()} method.
1114+ The codec to be used is looked up using the Python codec registry.
1115+ Return \NULL{} if an exception was raised by the codec.
1116+\end{cfuncdesc}
1117+
1118+% --- UTF-8 Codecs -------------------------------------------------------
1119+
1120+These are the UTF-8 codec APIs:
1121+
1122+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
1123+ Py_ssize_t size,
1124+ const char *errors}
1125+ Create a Unicode object by decoding \var{size} bytes of the UTF-8
1126+ encoded string \var{s}. Return \NULL{} if an exception was raised
1127+ by the codec.
1128+\end{cfuncdesc}
1129+
1130+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8Stateful}{const char *s,
1131+ Py_ssize_t size,
1132+ const char *errors,
1133+ Py_ssize_t *consumed}
1134+ If \var{consumed} is \NULL{}, behave like \cfunction{PyUnicode_DecodeUTF8()}.
1135+ If \var{consumed} is not \NULL{}, trailing incomplete UTF-8 byte sequences
1136+ will not be treated as an error. Those bytes will not be decoded and the
1137+ number of bytes that have been decoded will be stored in \var{consumed}.
1138+ \versionadded{2.4}
1139+\end{cfuncdesc}
1140+
1141+\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
1142+ Py_ssize_t size,
1143+ const char *errors}
1144+ Encode the \ctype{Py_UNICODE} buffer of the given size using UTF-8
1145+ and return a Python string object. Return \NULL{} if an exception
1146+ was raised by the codec.
1147+\end{cfuncdesc}
1148+
1149+\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
1150+ Encode a Unicode objects using UTF-8 and return the result as
1151+ Python string object. Error handling is ``strict''. Return
1152+ \NULL{} if an exception was raised by the codec.
1153+\end{cfuncdesc}
1154+
1155+% --- UTF-16 Codecs ------------------------------------------------------ */
1156+
1157+These are the UTF-16 codec APIs:
1158+
1159+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
1160+ Py_ssize_t size,
1161+ const char *errors,
1162+ int *byteorder}
1163+ Decode \var{length} bytes from a UTF-16 encoded buffer string and
1164+ return the corresponding Unicode object. \var{errors} (if
1165+ non-\NULL{}) defines the error handling. It defaults to ``strict''.
1166+
1167+ If \var{byteorder} is non-\NULL{}, the decoder starts decoding using
1168+ the given byte order:
1169+
1170+\begin{verbatim}
1171+ *byteorder == -1: little endian
1172+ *byteorder == 0: native order
1173+ *byteorder == 1: big endian
1174+\end{verbatim}
1175+
1176+ and then switches according to all byte order marks (BOM) it finds
1177+ in the input data. BOMs are not copied into the resulting Unicode
1178+ string. After completion, \var{*byteorder} is set to the current
1179+ byte order at the end of input data.
1180+
1181+ If \var{byteorder} is \NULL{}, the codec starts in native order mode.
1182+
1183+ Return \NULL{} if an exception was raised by the codec.
1184+\end{cfuncdesc}
1185+
1186+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16Stateful}{const char *s,
1187+ Py_ssize_t size,
1188+ const char *errors,
1189+ int *byteorder,
1190+ Py_ssize_t *consumed}
1191+ If \var{consumed} is \NULL{}, behave like
1192+ \cfunction{PyUnicode_DecodeUTF16()}. If \var{consumed} is not \NULL{},
1193+ \cfunction{PyUnicode_DecodeUTF16Stateful()} will not treat trailing incomplete
1194+ UTF-16 byte sequences (such as an odd number of bytes or a split surrogate pair)
1195+ as an error. Those bytes will not be decoded and the number of bytes that
1196+ have been decoded will be stored in \var{consumed}.
1197+ \versionadded{2.4}
1198+\end{cfuncdesc}
1199+
1200+\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
1201+ Py_ssize_t size,
1202+ const char *errors,
1203+ int byteorder}
1204+ Return a Python string object holding the UTF-16 encoded value of
1205+ the Unicode data in \var{s}. If \var{byteorder} is not \code{0},
1206+ output is written according to the following byte order:
1207+
1208+\begin{verbatim}
1209+ byteorder == -1: little endian
1210+ byteorder == 0: native byte order (writes a BOM mark)
1211+ byteorder == 1: big endian
1212+\end{verbatim}
1213+
1214+ If byteorder is \code{0}, the output string will always start with
1215+ the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark
1216+ is prepended.
1217+
1218+ If \var{Py_UNICODE_WIDE} is defined, a single \ctype{Py_UNICODE}
1219+ value may get represented as a surrogate pair. If it is not
1220+ defined, each \ctype{Py_UNICODE} values is interpreted as an
1221+ UCS-2 character.
1222+
1223+ Return \NULL{} if an exception was raised by the codec.
1224+\end{cfuncdesc}
1225+
1226+\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
1227+ Return a Python string using the UTF-16 encoding in native byte
1228+ order. The string always starts with a BOM mark. Error handling is
1229+ ``strict''. Return \NULL{} if an exception was raised by the
1230+ codec.
1231+\end{cfuncdesc}
1232+
1233+% --- Unicode-Escape Codecs ----------------------------------------------
1234+
1235+These are the ``Unicode Escape'' codec APIs:
1236+
1237+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
1238+ Py_ssize_t size,
1239+ const char *errors}
1240+ Create a Unicode object by decoding \var{size} bytes of the
1241+ Unicode-Escape encoded string \var{s}. Return \NULL{} if an
1242+ exception was raised by the codec.
1243+\end{cfuncdesc}
1244+
1245+\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
1246+ Py_ssize_t size}
1247+ Encode the \ctype{Py_UNICODE} buffer of the given size using
1248+ Unicode-Escape and return a Python string object. Return \NULL{}
1249+ if an exception was raised by the codec.
1250+\end{cfuncdesc}
1251+
1252+\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
1253+ Encode a Unicode objects using Unicode-Escape and return the
1254+ result as Python string object. Error handling is ``strict''.
1255+ Return \NULL{} if an exception was raised by the codec.
1256+\end{cfuncdesc}
1257+
1258+% --- Raw-Unicode-Escape Codecs ------------------------------------------
1259+
1260+These are the ``Raw Unicode Escape'' codec APIs:
1261+
1262+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
1263+ Py_ssize_t size,
1264+ const char *errors}
1265+ Create a Unicode object by decoding \var{size} bytes of the
1266+ Raw-Unicode-Escape encoded string \var{s}. Return \NULL{} if an
1267+ exception was raised by the codec.
1268+\end{cfuncdesc}
1269+
1270+\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
1271+ Py_ssize_t size,
1272+ const char *errors}
1273+ Encode the \ctype{Py_UNICODE} buffer of the given size using
1274+ Raw-Unicode-Escape and return a Python string object. Return
1275+ \NULL{} if an exception was raised by the codec.
1276+\end{cfuncdesc}
1277+
1278+\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
1279+ Encode a Unicode objects using Raw-Unicode-Escape and return the
1280+ result as Python string object. Error handling is ``strict''.
1281+ Return \NULL{} if an exception was raised by the codec.
1282+\end{cfuncdesc}
1283+
1284+% --- Latin-1 Codecs -----------------------------------------------------
1285+
1286+These are the Latin-1 codec APIs:
1287+Latin-1 corresponds to the first 256 Unicode ordinals and only these
1288+are accepted by the codecs during encoding.
1289+
1290+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
1291+ Py_ssize_t size,
1292+ const char *errors}
1293+ Create a Unicode object by decoding \var{size} bytes of the Latin-1
1294+ encoded string \var{s}. Return \NULL{} if an exception was raised
1295+ by the codec.
1296+\end{cfuncdesc}
1297+
1298+\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
1299+ Py_ssize_t size,
1300+ const char *errors}
1301+ Encode the \ctype{Py_UNICODE} buffer of the given size using
1302+ Latin-1 and return a Python string object. Return \NULL{} if an
1303+ exception was raised by the codec.
1304+\end{cfuncdesc}
1305+
1306+\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
1307+ Encode a Unicode objects using Latin-1 and return the result as
1308+ Python string object. Error handling is ``strict''. Return
1309+ \NULL{} if an exception was raised by the codec.
1310+\end{cfuncdesc}
1311+
1312+% --- ASCII Codecs -------------------------------------------------------
1313+
1314+These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
1315+accepted. All other codes generate errors.
1316+
1317+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
1318+ Py_ssize_t size,
1319+ const char *errors}
1320+ Create a Unicode object by decoding \var{size} bytes of the
1321+ \ASCII{} encoded string \var{s}. Return \NULL{} if an exception
1322+ was raised by the codec.
1323+\end{cfuncdesc}
1324+
1325+\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
1326+ Py_ssize_t size,
1327+ const char *errors}
1328+ Encode the \ctype{Py_UNICODE} buffer of the given size using
1329+ \ASCII{} and return a Python string object. Return \NULL{} if an
1330+ exception was raised by the codec.
1331+\end{cfuncdesc}
1332+
1333+\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
1334+ Encode a Unicode objects using \ASCII{} and return the result as
1335+ Python string object. Error handling is ``strict''. Return
1336+ \NULL{} if an exception was raised by the codec.
1337+\end{cfuncdesc}
1338+
1339+% --- Character Map Codecs -----------------------------------------------
1340+
1341+These are the mapping codec APIs:
1342+
1343+This codec is special in that it can be used to implement many
1344+different codecs (and this is in fact what was done to obtain most of
1345+the standard codecs included in the \module{encodings} package). The
1346+codec uses mapping to encode and decode characters.
1347+
1348+Decoding mappings must map single string characters to single Unicode
1349+characters, integers (which are then interpreted as Unicode ordinals)
1350+or None (meaning "undefined mapping" and causing an error).
1351+
1352+Encoding mappings must map single Unicode characters to single string
1353+characters, integers (which are then interpreted as Latin-1 ordinals)
1354+or None (meaning "undefined mapping" and causing an error).
1355+
1356+The mapping objects provided must only support the __getitem__ mapping
1357+interface.
1358+
1359+If a character lookup fails with a LookupError, the character is
1360+copied as-is meaning that its ordinal value will be interpreted as
1361+Unicode or Latin-1 ordinal resp. Because of this, mappings only need
1362+to contain those mappings which map characters to different code
1363+points.
1364+
1365+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
1366+ Py_ssize_t size,
1367+ PyObject *mapping,
1368+ const char *errors}
1369+ Create a Unicode object by decoding \var{size} bytes of the encoded
1370+ string \var{s} using the given \var{mapping} object. Return
1371+ \NULL{} if an exception was raised by the codec. If \var{mapping} is \NULL{}
1372+ latin-1 decoding will be done. Else it can be a dictionary mapping byte or a
1373+ unicode string, which is treated as a lookup table. Byte values greater
1374+ that the length of the string and U+FFFE "characters" are treated as
1375+ "undefined mapping".
1376+ \versionchanged[Allowed unicode string as mapping argument]{2.4}
1377+\end{cfuncdesc}
1378+
1379+\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
1380+ Py_ssize_t size,
1381+ PyObject *mapping,
1382+ const char *errors}
1383+ Encode the \ctype{Py_UNICODE} buffer of the given size using the
1384+ given \var{mapping} object and return a Python string object.
1385+ Return \NULL{} if an exception was raised by the codec.
1386+\end{cfuncdesc}
1387+
1388+\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
1389+ PyObject *mapping}
1390+ Encode a Unicode objects using the given \var{mapping} object and
1391+ return the result as Python string object. Error handling is
1392+ ``strict''. Return \NULL{} if an exception was raised by the
1393+ codec.
1394+\end{cfuncdesc}
1395+
1396+The following codec API is special in that maps Unicode to Unicode.
1397+
1398+\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
1399+ Py_ssize_t size,
1400+ PyObject *table,
1401+ const char *errors}
1402+ Translate a \ctype{Py_UNICODE} buffer of the given length by
1403+ applying a character mapping \var{table} to it and return the
1404+ resulting Unicode object. Return \NULL{} when an exception was
1405+ raised by the codec.
1406+
1407+ The \var{mapping} table must map Unicode ordinal integers to Unicode
1408+ ordinal integers or None (causing deletion of the character).
1409+
1410+ Mapping tables need only provide the \method{__getitem__()}
1411+ interface; dictionaries and sequences work well. Unmapped character
1412+ ordinals (ones which cause a \exception{LookupError}) are left
1413+ untouched and are copied as-is.
1414+\end{cfuncdesc}
1415+
1416+% --- MBCS codecs for Windows --------------------------------------------
1417+
1418+These are the MBCS codec APIs. They are currently only available on
1419+Windows and use the Win32 MBCS converters to implement the
1420+conversions. Note that MBCS (or DBCS) is a class of encodings, not
1421+just one. The target encoding is defined by the user settings on the
1422+machine running the codec.
1423+
1424+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
1425+ Py_ssize_t size,
1426+ const char *errors}
1427+ Create a Unicode object by decoding \var{size} bytes of the MBCS
1428+ encoded string \var{s}. Return \NULL{} if an exception was
1429+ raised by the codec.
1430+\end{cfuncdesc}
1431+
1432+\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCSStateful}{const char *s,
1433+ int size,
1434+ const char *errors,
1435+ int *consumed}
1436+ If \var{consumed} is \NULL{}, behave like
1437+ \cfunction{PyUnicode_DecodeMBCS()}. If \var{consumed} is not \NULL{},
1438+ \cfunction{PyUnicode_DecodeMBCSStateful()} will not decode trailing lead
1439+ byte and the number of bytes that have been decoded will be stored in
1440+ \var{consumed}.
1441+ \versionadded{2.5}
1442+\end{cfuncdesc}
1443+
1444+\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
1445+ Py_ssize_t size,
1446+ const char *errors}
1447+ Encode the \ctype{Py_UNICODE} buffer of the given size using MBCS
1448+ and return a Python string object. Return \NULL{} if an exception
1449+ was raised by the codec.
1450+\end{cfuncdesc}
1451+
1452+\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
1453+ Encode a Unicode objects using MBCS and return the result as
1454+ Python string object. Error handling is ``strict''. Return
1455+ \NULL{} if an exception was raised by the codec.
1456+\end{cfuncdesc}
1457+
1458+% --- Methods & Slots ----------------------------------------------------
1459+
1460+\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
1461+
1462+The following APIs are capable of handling Unicode objects and strings
1463+on input (we refer to them as strings in the descriptions) and return
1464+Unicode objects or integers as appropriate.
1465+
1466+They all return \NULL{} or \code{-1} if an exception occurs.
1467+
1468+\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
1469+ PyObject *right}
1470+ Concat two strings giving a new Unicode string.
1471+\end{cfuncdesc}
1472+
1473+\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
1474+ PyObject *sep,
1475+ Py_ssize_t maxsplit}
1476+ Split a string giving a list of Unicode strings. If sep is \NULL{},
1477+ splitting will be done at all whitespace substrings. Otherwise,
1478+ splits occur at the given separator. At most \var{maxsplit} splits
1479+ will be done. If negative, no limit is set. Separators are not
1480+ included in the resulting list.
1481+\end{cfuncdesc}
1482+
1483+\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
1484+ int keepend}
1485+ Split a Unicode string at line breaks, returning a list of Unicode
1486+ strings. CRLF is considered to be one line break. If \var{keepend}
1487+ is 0, the Line break characters are not included in the resulting
1488+ strings.
1489+\end{cfuncdesc}
1490+
1491+\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
1492+ PyObject *table,
1493+ const char *errors}
1494+ Translate a string by applying a character mapping table to it and
1495+ return the resulting Unicode object.
1496+
1497+ The mapping table must map Unicode ordinal integers to Unicode
1498+ ordinal integers or None (causing deletion of the character).
1499+
1500+ Mapping tables need only provide the \method{__getitem__()}
1501+ interface; dictionaries and sequences work well. Unmapped character
1502+ ordinals (ones which cause a \exception{LookupError}) are left
1503+ untouched and are copied as-is.
1504+
1505+ \var{errors} has the usual meaning for codecs. It may be \NULL{}
1506+ which indicates to use the default error handling.
1507+\end{cfuncdesc}
1508+
1509+\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
1510+ PyObject *seq}
1511+ Join a sequence of strings using the given separator and return the
1512+ resulting Unicode string.
1513+\end{cfuncdesc}
1514+
1515+\begin{cfuncdesc}{int}{PyUnicode_Tailmatch}{PyObject *str,
1516+ PyObject *substr,
1517+ Py_ssize_t start,
1518+ Py_ssize_t end,
1519+ int direction}
1520+ Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
1521+ the given tail end (\var{direction} == -1 means to do a prefix
1522+ match, \var{direction} == 1 a suffix match), 0 otherwise.
1523+ Return \code{-1} if an error occurred.
1524+\end{cfuncdesc}
1525+
1526+\begin{cfuncdesc}{Py_ssize_t}{PyUnicode_Find}{PyObject *str,
1527+ PyObject *substr,
1528+ Py_ssize_t start,
1529+ Py_ssize_t end,
1530+ int direction}
1531+ Return the first position of \var{substr} in
1532+ \var{str}[\var{start}:\var{end}] using the given \var{direction}
1533+ (\var{direction} == 1 means to do a forward search,
1534+ \var{direction} == -1 a backward search). The return value is the
1535+ index of the first match; a value of \code{-1} indicates that no
1536+ match was found, and \code{-2} indicates that an error occurred and
1537+ an exception has been set.
1538+\end{cfuncdesc}
1539+
1540+\begin{cfuncdesc}{Py_ssize_t}{PyUnicode_Count}{PyObject *str,
1541+ PyObject *substr,
1542+ Py_ssize_t start,
1543+ Py_ssize_t end}
1544+ Return the number of non-overlapping occurrences of \var{substr} in
1545+ \code{\var{str}[\var{start}:\var{end}]}. Return \code{-1} if an
1546+ error occurred.
1547+\end{cfuncdesc}
1548+
1549+\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
1550+ PyObject *substr,
1551+ PyObject *replstr,
1552+ Py_ssize_t maxcount}
1553+ Replace at most \var{maxcount} occurrences of \var{substr} in
1554+ \var{str} with \var{replstr} and return the resulting Unicode object.
1555+ \var{maxcount} == -1 means replace all occurrences.
1556+\end{cfuncdesc}
1557+
1558+\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
1559+ Compare two strings and return -1, 0, 1 for less than, equal, and
1560+ greater than, respectively.
1561+\end{cfuncdesc}
1562+
1563+\begin{cfuncdesc}{int}{PyUnicode_RichCompare}{PyObject *left,
1564+ PyObject *right,
1565+ int op}
1566+
1567+ Rich compare two unicode strings and return one of the following:
1568+ \begin{itemize}
1569+ \item \code{NULL} in case an exception was raised
1570+ \item \constant{Py_True} or \constant{Py_False} for successful comparisons
1571+ \item \constant{Py_NotImplemented} in case the type combination is unknown
1572+ \end{itemize}
1573+
1574+ Note that \constant{Py_EQ} and \constant{Py_NE} comparisons can cause a
1575+ \exception{UnicodeWarning} in case the conversion of the arguments to
1576+ Unicode fails with a \exception{UnicodeDecodeError}.
1577+
1578+ Possible values for \var{op} are
1579+ \constant{Py_GT}, \constant{Py_GE}, \constant{Py_EQ},
1580+ \constant{Py_NE}, \constant{Py_LT}, and \constant{Py_LE}.
1581+\end{cfuncdesc}
1582+
1583+\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
1584+ PyObject *args}
1585+ Return a new string object from \var{format} and \var{args}; this
1586+ is analogous to \code{\var{format} \%\ \var{args}}. The
1587+ \var{args} argument must be a tuple.
1588+\end{cfuncdesc}
1589+
1590+\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
1591+ PyObject *element}
1592+ Check whether \var{element} is contained in \var{container} and
1593+ return true or false accordingly.
1594+
1595+ \var{element} has to coerce to a one element Unicode
1596+ string. \code{-1} is returned if there was an error.
1597+\end{cfuncdesc}
1598+
1599+
1600+\subsection{Buffer Objects \label{bufferObjects}}
1601+\sectionauthor{Greg Stein}{gstein@lyra.org}
1602+
1603+\obindex{buffer}
1604+Python objects implemented in C can export a group of functions called
1605+the ``buffer\index{buffer interface} interface.'' These functions can
1606+be used by an object to expose its data in a raw, byte-oriented
1607+format. Clients of the object can use the buffer interface to access
1608+the object data directly, without needing to copy it first.
1609+
1610+Two examples of objects that support
1611+the buffer interface are strings and arrays. The string object exposes
1612+the character contents in the buffer interface's byte-oriented
1613+form. An array can also expose its contents, but it should be noted
1614+that array elements may be multi-byte values.
1615+
1616+An example user of the buffer interface is the file object's
1617+\method{write()} method. Any object that can export a series of bytes
1618+through the buffer interface can be written to a file. There are a
1619+number of format codes to \cfunction{PyArg_ParseTuple()} that operate
1620+against an object's buffer interface, returning data from the target
1621+object.
1622+
1623+More information on the buffer interface is provided in the section
1624+``Buffer Object Structures'' (section~\ref{buffer-structs}), under
1625+the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
1626+
1627+A ``buffer object'' is defined in the \file{bufferobject.h} header
1628+(included by \file{Python.h}). These objects look very similar to
1629+string objects at the Python programming level: they support slicing,
1630+indexing, concatenation, and some other standard string
1631+operations. However, their data can come from one of two sources: from
1632+a block of memory, or from another object which exports the buffer
1633+interface.
1634+
1635+Buffer objects are useful as a way to expose the data from another
1636+object's buffer interface to the Python programmer. They can also be
1637+used as a zero-copy slicing mechanism. Using their ability to
1638+reference a block of memory, it is possible to expose any data to the
1639+Python programmer quite easily. The memory could be a large, constant
1640+array in a C extension, it could be a raw block of memory for
1641+manipulation before passing to an operating system library, or it
1642+could be used to pass around structured data in its native, in-memory
1643+format.
1644+
1645+\begin{ctypedesc}{PyBufferObject}
1646+ This subtype of \ctype{PyObject} represents a buffer object.
1647+\end{ctypedesc}
1648+
1649+\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
1650+ The instance of \ctype{PyTypeObject} which represents the Python
1651+ buffer type; it is the same object as \code{buffer} and
1652+ \code{types.BufferType} in the Python layer.
1653+ \withsubitem{(in module types)}{\ttindex{BufferType}}.
1654+\end{cvardesc}
1655+
1656+\begin{cvardesc}{int}{Py_END_OF_BUFFER}
1657+ This constant may be passed as the \var{size} parameter to
1658+ \cfunction{PyBuffer_FromObject()} or
1659+ \cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the
1660+ new \ctype{PyBufferObject} should refer to \var{base} object from
1661+ the specified \var{offset} to the end of its exported buffer. Using
1662+ this enables the caller to avoid querying the \var{base} object for
1663+ its length.
1664+\end{cvardesc}
1665+
1666+\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
1667+ Return true if the argument has type \cdata{PyBuffer_Type}.
1668+\end{cfuncdesc}
1669+
1670+\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
1671+ Py_ssize_t offset, Py_ssize_t size}
1672+ Return a new read-only buffer object. This raises
1673+ \exception{TypeError} if \var{base} doesn't support the read-only
1674+ buffer protocol or doesn't provide exactly one buffer segment, or it
1675+ raises \exception{ValueError} if \var{offset} is less than zero. The
1676+ buffer will hold a reference to the \var{base} object, and the
1677+ buffer's contents will refer to the \var{base} object's buffer
1678+ interface, starting as position \var{offset} and extending for
1679+ \var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
1680+ the new buffer's contents extend to the length of the \var{base}
1681+ object's exported buffer data.
1682+\end{cfuncdesc}
1683+
1684+\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
1685+ Py_ssize_t offset,
1686+ Py_ssize_t size}
1687+ Return a new writable buffer object. Parameters and exceptions are
1688+ similar to those for \cfunction{PyBuffer_FromObject()}. If the
1689+ \var{base} object does not export the writeable buffer protocol,
1690+ then \exception{TypeError} is raised.
1691+\end{cfuncdesc}
1692+
1693+\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, Py_ssize_t size}
1694+ Return a new read-only buffer object that reads from a specified
1695+ location in memory, with a specified size. The caller is
1696+ responsible for ensuring that the memory buffer, passed in as
1697+ \var{ptr}, is not deallocated while the returned buffer object
1698+ exists. Raises \exception{ValueError} if \var{size} is less than
1699+ zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be
1700+ passed for the \var{size} parameter; \exception{ValueError} will be
1701+ raised in that case.
1702+\end{cfuncdesc}
1703+
1704+\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, Py_ssize_t size}
1705+ Similar to \cfunction{PyBuffer_FromMemory()}, but the returned
1706+ buffer is writable.
1707+\end{cfuncdesc}
1708+
1709+\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{Py_ssize_t size}
1710+ Return a new writable buffer object that maintains its own memory
1711+ buffer of \var{size} bytes. \exception{ValueError} is returned if
1712+ \var{size} is not zero or positive. Note that the memory buffer (as
1713+ returned by \cfunction{PyObject_AsWriteBuffer()}) is not specifically
1714+ aligned.
1715+\end{cfuncdesc}
1716+
1717+
1718+\subsection{Tuple Objects \label{tupleObjects}}
1719+
1720+\obindex{tuple}
1721+\begin{ctypedesc}{PyTupleObject}
1722+ This subtype of \ctype{PyObject} represents a Python tuple object.
1723+\end{ctypedesc}
1724+
1725+\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
1726+ This instance of \ctype{PyTypeObject} represents the Python tuple
1727+ type; it is the same object as \code{tuple} and \code{types.TupleType}
1728+ in the Python layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
1729+\end{cvardesc}
1730+
1731+\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
1732+ Return true if \var{p} is a tuple object or an instance of a subtype
1733+ of the tuple type.
1734+ \versionchanged[Allowed subtypes to be accepted]{2.2}
1735+\end{cfuncdesc}
1736+
1737+\begin{cfuncdesc}{int}{PyTuple_CheckExact}{PyObject *p}
1738+ Return true if \var{p} is a tuple object, but not an instance of a
1739+ subtype of the tuple type.
1740+ \versionadded{2.2}
1741+\end{cfuncdesc}
1742+
1743+\begin{cfuncdesc}{PyObject*}{PyTuple_New}{Py_ssize_t len}
1744+ Return a new tuple object of size \var{len}, or \NULL{} on failure.
1745+\end{cfuncdesc}
1746+
1747+\begin{cfuncdesc}{PyObject*}{PyTuple_Pack}{Py_ssize_t n, \moreargs}
1748+ Return a new tuple object of size \var{n}, or \NULL{} on failure.
1749+ The tuple values are initialized to the subsequent \var{n} C arguments
1750+ pointing to Python objects. \samp{PyTuple_Pack(2, \var{a}, \var{b})}
1751+ is equivalent to \samp{Py_BuildValue("(OO)", \var{a}, \var{b})}.
1752+ \versionadded{2.4}
1753+\end{cfuncdesc}
1754+
1755+\begin{cfuncdesc}{int}{PyTuple_Size}{PyObject *p}
1756+ Take a pointer to a tuple object, and return the size of that
1757+ tuple.
1758+\end{cfuncdesc}
1759+
1760+\begin{cfuncdesc}{int}{PyTuple_GET_SIZE}{PyObject *p}
1761+ Return the size of the tuple \var{p}, which must be non-\NULL{} and
1762+ point to a tuple; no error checking is performed.
1763+\end{cfuncdesc}
1764+
1765+\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyObject *p, Py_ssize_t pos}
1766+ Return the object at position \var{pos} in the tuple pointed to by
1767+ \var{p}. If \var{pos} is out of bounds, return \NULL{} and sets an
1768+ \exception{IndexError} exception.
1769+\end{cfuncdesc}
1770+
1771+\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyObject *p, Py_ssize_t pos}
1772+ Like \cfunction{PyTuple_GetItem()}, but does no checking of its
1773+ arguments.
1774+\end{cfuncdesc}
1775+
1776+\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyObject *p,
1777+ Py_ssize_t low, Py_ssize_t high}
1778+ Take a slice of the tuple pointed to by \var{p} from \var{low} to
1779+ \var{high} and return it as a new tuple.
1780+\end{cfuncdesc}
1781+
1782+\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
1783+ Py_ssize_t pos, PyObject *o}
1784+ Insert a reference to object \var{o} at position \var{pos} of the
1785+ tuple pointed to by \var{p}. Return \code{0} on success.
1786+ \note{This function ``steals'' a reference to \var{o}.}
1787+\end{cfuncdesc}
1788+
1789+\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
1790+ Py_ssize_t pos, PyObject *o}
1791+ Like \cfunction{PyTuple_SetItem()}, but does no error checking, and
1792+ should \emph{only} be used to fill in brand new tuples. \note{This
1793+ function ``steals'' a reference to \var{o}.}
1794+\end{cfuncdesc}
1795+
1796+\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyObject **p, Py_ssize_t newsize}
1797+ Can be used to resize a tuple. \var{newsize} will be the new length
1798+ of the tuple. Because tuples are \emph{supposed} to be immutable,
1799+ this should only be used if there is only one reference to the
1800+ object. Do \emph{not} use this if the tuple may already be known to
1801+ some other part of the code. The tuple will always grow or shrink
1802+ at the end. Think of this as destroying the old tuple and creating
1803+ a new one, only more efficiently. Returns \code{0} on success.
1804+ Client code should never assume that the resulting value of
1805+ \code{*\var{p}} will be the same as before calling this function.
1806+ If the object referenced by \code{*\var{p}} is replaced, the
1807+ original \code{*\var{p}} is destroyed. On failure, returns
1808+ \code{-1} and sets \code{*\var{p}} to \NULL{}, and raises
1809+ \exception{MemoryError} or
1810+ \exception{SystemError}.
1811+ \versionchanged[Removed unused third parameter, \var{last_is_sticky}]{2.2}
1812+\end{cfuncdesc}
1813+
1814+
1815+\subsection{List Objects \label{listObjects}}
1816+
1817+\obindex{list}
1818+\begin{ctypedesc}{PyListObject}
1819+ This subtype of \ctype{PyObject} represents a Python list object.
1820+\end{ctypedesc}
1821+
1822+\begin{cvardesc}{PyTypeObject}{PyList_Type}
1823+ This instance of \ctype{PyTypeObject} represents the Python list
1824+ type. This is the same object as \code{list} and \code{types.ListType}
1825+ in the Python layer.\withsubitem{(in module types)}{\ttindex{ListType}}
1826+\end{cvardesc}
1827+
1828+\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
1829+ Return true if \var{p} is a list object or an instance of a
1830+ subtype of the list type.
1831+ \versionchanged[Allowed subtypes to be accepted]{2.2}
1832+\end{cfuncdesc}
1833+
1834+\begin{cfuncdesc}{int}{PyList_CheckExact}{PyObject *p}
1835+ Return true if \var{p} is a list object, but not an instance of a
1836+ subtype of the list type.
1837+ \versionadded{2.2}
1838+\end{cfuncdesc}
1839+
1840+\begin{cfuncdesc}{PyObject*}{PyList_New}{Py_ssize_t len}
1841+ Return a new list of length \var{len} on success, or \NULL{} on
1842+ failure.
1843+ \note{If \var{length} is greater than zero, the returned list object's
1844+ items are set to \code{NULL}. Thus you cannot use abstract
1845+ API functions such as \cfunction{PySequence_SetItem()}
1846+ or expose the object to Python code before setting all items to a
1847+ real object with \cfunction{PyList_SetItem()}.}
1848+\end{cfuncdesc}
1849+
1850+\begin{cfuncdesc}{Py_ssize_t}{PyList_Size}{PyObject *list}
1851+ Return the length of the list object in \var{list}; this is
1852+ equivalent to \samp{len(\var{list})} on a list object.
1853+ \bifuncindex{len}
1854+\end{cfuncdesc}
1855+
1856+\begin{cfuncdesc}{Py_ssize_t}{PyList_GET_SIZE}{PyObject *list}
1857+ Macro form of \cfunction{PyList_Size()} without error checking.
1858+\end{cfuncdesc}
1859+
1860+\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, Py_ssize_t index}
1861+ Return the object at position \var{pos} in the list pointed to by
1862+ \var{p}. The position must be positive, indexing from the end of the
1863+ list is not supported. If \var{pos} is out of bounds, return \NULL{}
1864+ and set an \exception{IndexError} exception.
1865+\end{cfuncdesc}
1866+
1867+\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, Py_ssize_t i}
1868+ Macro form of \cfunction{PyList_GetItem()} without error checking.
1869+\end{cfuncdesc}
1870+
1871+\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, Py_ssize_t index,
1872+ PyObject *item}
1873+ Set the item at index \var{index} in list to \var{item}. Return
1874+ \code{0} on success or \code{-1} on failure. \note{This function
1875+ ``steals'' a reference to \var{item} and discards a reference to an
1876+ item already in the list at the affected position.}
1877+\end{cfuncdesc}
1878+
1879+\begin{cfuncdesc}{void}{PyList_SET_ITEM}{PyObject *list, Py_ssize_t i,
1880+ PyObject *o}
1881+ Macro form of \cfunction{PyList_SetItem()} without error checking.
1882+ This is normally only used to fill in new lists where there is no
1883+ previous content.
1884+ \note{This function ``steals'' a reference to \var{item}, and,
1885+ unlike \cfunction{PyList_SetItem()}, does \emph{not} discard a
1886+ reference to any item that it being replaced; any reference in
1887+ \var{list} at position \var{i} will be leaked.}
1888+\end{cfuncdesc}
1889+
1890+\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, Py_ssize_t index,
1891+ PyObject *item}
1892+ Insert the item \var{item} into list \var{list} in front of index
1893+ \var{index}. Return \code{0} if successful; return \code{-1} and
1894+ set an exception if unsuccessful. Analogous to
1895+ \code{\var{list}.insert(\var{index}, \var{item})}.
1896+\end{cfuncdesc}
1897+
1898+\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
1899+ Append the object \var{item} at the end of list \var{list}.
1900+ Return \code{0} if successful; return \code{-1} and set an
1901+ exception if unsuccessful. Analogous to
1902+ \code{\var{list}.append(\var{item})}.
1903+\end{cfuncdesc}
1904+
1905+\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
1906+ Py_ssize_t low, Py_ssize_t high}
1907+ Return a list of the objects in \var{list} containing the objects
1908+ \emph{between} \var{low} and \var{high}. Return \NULL{} and set
1909+ an exception if unsuccessful.
1910+ Analogous to \code{\var{list}[\var{low}:\var{high}]}.
1911+\end{cfuncdesc}
1912+
1913+\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
1914+ Py_ssize_t low, Py_ssize_t high,
1915+ PyObject *itemlist}
1916+ Set the slice of \var{list} between \var{low} and \var{high} to the
1917+ contents of \var{itemlist}. Analogous to
1918+ \code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}.
1919+ The \var{itemlist} may be \NULL{}, indicating the assignment
1920+ of an empty list (slice deletion).
1921+ Return \code{0} on success, \code{-1} on failure.
1922+\end{cfuncdesc}
1923+
1924+\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
1925+ Sort the items of \var{list} in place. Return \code{0} on
1926+ success, \code{-1} on failure. This is equivalent to
1927+ \samp{\var{list}.sort()}.
1928+\end{cfuncdesc}
1929+
1930+\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
1931+ Reverse the items of \var{list} in place. Return \code{0} on
1932+ success, \code{-1} on failure. This is the equivalent of
1933+ \samp{\var{list}.reverse()}.
1934+\end{cfuncdesc}
1935+
1936+\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
1937+ Return a new tuple object containing the contents of \var{list};
1938+ equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
1939+\end{cfuncdesc}
1940+
1941+
1942+\section{Mapping Objects \label{mapObjects}}
1943+
1944+\obindex{mapping}
1945+
1946+
1947+\subsection{Dictionary Objects \label{dictObjects}}
1948+
1949+\obindex{dictionary}
1950+\begin{ctypedesc}{PyDictObject}
1951+ This subtype of \ctype{PyObject} represents a Python dictionary
1952+ object.
1953+\end{ctypedesc}
1954+
1955+\begin{cvardesc}{PyTypeObject}{PyDict_Type}
1956+ This instance of \ctype{PyTypeObject} represents the Python
1957+ dictionary type. This is exposed to Python programs as
1958+ \code{dict} and \code{types.DictType}.
1959+ \withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
1960+\end{cvardesc}
1961+
1962+\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
1963+ Return true if \var{p} is a dict object or an instance of a
1964+ subtype of the dict type.
1965+ \versionchanged[Allowed subtypes to be accepted]{2.2}
1966+\end{cfuncdesc}
1967+
1968+\begin{cfuncdesc}{int}{PyDict_CheckExact}{PyObject *p}
1969+ Return true if \var{p} is a dict object, but not an instance of a
1970+ subtype of the dict type.
1971+ \versionadded{2.4}
1972+\end{cfuncdesc}
1973+
1974+\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1975+ Return a new empty dictionary, or \NULL{} on failure.
1976+\end{cfuncdesc}
1977+
1978+\begin{cfuncdesc}{PyObject*}{PyDictProxy_New}{PyObject *dict}
1979+ Return a proxy object for a mapping which enforces read-only
1980+ behavior. This is normally used to create a proxy to prevent
1981+ modification of the dictionary for non-dynamic class types.
1982+ \versionadded{2.2}
1983+\end{cfuncdesc}
1984+
1985+\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
1986+ Empty an existing dictionary of all key-value pairs.
1987+\end{cfuncdesc}
1988+
1989+\begin{cfuncdesc}{int}{PyDict_Contains}{PyObject *p, PyObject *key}
1990+ Determine if dictionary \var{p} contains \var{key}. If an item
1991+ in \var{p} is matches \var{key}, return \code{1}, otherwise return
1992+ \code{0}. On error, return \code{-1}. This is equivalent to the
1993+ Python expression \samp{\var{key} in \var{p}}.
1994+ \versionadded{2.4}
1995+\end{cfuncdesc}
1996+
1997+\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
1998+ Return a new dictionary that contains the same key-value pairs as
1999+ \var{p}.
2000+ \versionadded{1.6}
2001+\end{cfuncdesc}
2002+
2003+\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
2004+ PyObject *val}
2005+ Insert \var{value} into the dictionary \var{p} with a key of
2006+ \var{key}. \var{key} must be hashable; if it isn't,
2007+ \exception{TypeError} will be raised.
2008+ Return \code{0} on success or \code{-1} on failure.
2009+\end{cfuncdesc}
2010+
2011+\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p,
2012+ const char *key,
2013+ PyObject *val}
2014+ Insert \var{value} into the dictionary \var{p} using \var{key} as a
2015+ key. \var{key} should be a \ctype{char*}. The key object is created
2016+ using \code{PyString_FromString(\var{key})}. Return \code{0} on
2017+ success or \code{-1} on failure.
2018+ \ttindex{PyString_FromString()}
2019+\end{cfuncdesc}
2020+
2021+\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
2022+ Remove the entry in dictionary \var{p} with key \var{key}.
2023+ \var{key} must be hashable; if it isn't, \exception{TypeError} is
2024+ raised. Return \code{0} on success or \code{-1} on failure.
2025+\end{cfuncdesc}
2026+
2027+\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
2028+ Remove the entry in dictionary \var{p} which has a key specified by
2029+ the string \var{key}. Return \code{0} on success or \code{-1} on
2030+ failure.
2031+\end{cfuncdesc}
2032+
2033+\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
2034+ Return the object from dictionary \var{p} which has a key
2035+ \var{key}. Return \NULL{} if the key \var{key} is not present, but
2036+ \emph{without} setting an exception.
2037+\end{cfuncdesc}
2038+
2039+\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, const char *key}
2040+ This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
2041+ specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
2042+\end{cfuncdesc}
2043+
2044+\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
2045+ Return a \ctype{PyListObject} containing all the items from the
2046+ dictionary, as in the dictionary method \method{items()} (see the
2047+ \citetitle[../lib/lib.html]{Python Library Reference}).
2048+\end{cfuncdesc}
2049+
2050+\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
2051+ Return a \ctype{PyListObject} containing all the keys from the
2052+ dictionary, as in the dictionary method \method{keys()} (see the
2053+ \citetitle[../lib/lib.html]{Python Library Reference}).
2054+\end{cfuncdesc}
2055+
2056+\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
2057+ Return a \ctype{PyListObject} containing all the values from the
2058+ dictionary \var{p}, as in the dictionary method \method{values()}
2059+ (see the \citetitle[../lib/lib.html]{Python Library Reference}).
2060+\end{cfuncdesc}
2061+
2062+\begin{cfuncdesc}{Py_ssize_t}{PyDict_Size}{PyObject *p}
2063+ Return the number of items in the dictionary. This is equivalent
2064+ to \samp{len(\var{p})} on a dictionary.\bifuncindex{len}
2065+\end{cfuncdesc}
2066+
2067+\begin{cfuncdesc}{int}{PyDict_Next}{PyObject *p, Py_ssize_t *ppos,
2068+ PyObject **pkey, PyObject **pvalue}
2069+ Iterate over all key-value pairs in the dictionary \var{p}. The
2070+ \ctype{int} referred to by \var{ppos} must be initialized to
2071+ \code{0} prior to the first call to this function to start the
2072+ iteration; the function returns true for each pair in the
2073+ dictionary, and false once all pairs have been reported. The
2074+ parameters \var{pkey} and \var{pvalue} should either point to
2075+ \ctype{PyObject*} variables that will be filled in with each key and
2076+ value, respectively, or may be \NULL{}. Any references returned through
2077+ them are borrowed. \var{ppos} should not be altered during iteration.
2078+ Its value represents offsets within the internal dictionary structure,
2079+ and since the structure is sparse, the offsets are not consecutive.
2080+
2081+ For example:
2082+
2083+\begin{verbatim}
2084+PyObject *key, *value;
2085+Py_ssize_t pos = 0;
2086+
2087+while (PyDict_Next(self->dict, &pos, &key, &value)) {
2088+ /* do something interesting with the values... */
2089+ ...
2090+}
2091+\end{verbatim}
2092+
2093+ The dictionary \var{p} should not be mutated during iteration. It
2094+ is safe (since Python 2.1) to modify the values of the keys as you
2095+ iterate over the dictionary, but only so long as the set of keys
2096+ does not change. For example:
2097+
2098+\begin{verbatim}
2099+PyObject *key, *value;
2100+Py_ssize_t pos = 0;
2101+
2102+while (PyDict_Next(self->dict, &pos, &key, &value)) {
2103+ int i = PyInt_AS_LONG(value) + 1;
2104+ PyObject *o = PyInt_FromLong(i);
2105+ if (o == NULL)
2106+ return -1;
2107+ if (PyDict_SetItem(self->dict, key, o) < 0) {
2108+ Py_DECREF(o);
2109+ return -1;
2110+ }
2111+ Py_DECREF(o);
2112+}
2113+\end{verbatim}
2114+\end{cfuncdesc}
2115+
2116+\begin{cfuncdesc}{int}{PyDict_Merge}{PyObject *a, PyObject *b, int override}
2117+ Iterate over mapping object \var{b} adding key-value pairs to dictionary
2118+ \var{a}.
2119+ \var{b} may be a dictionary, or any object supporting
2120+ \function{PyMapping_Keys()} and \function{PyObject_GetItem()}.
2121+ If \var{override} is true, existing pairs in \var{a} will
2122+ be replaced if a matching key is found in \var{b}, otherwise pairs
2123+ will only be added if there is not a matching key in \var{a}.
2124+ Return \code{0} on success or \code{-1} if an exception was
2125+ raised.
2126+\versionadded{2.2}
2127+\end{cfuncdesc}
2128+
2129+\begin{cfuncdesc}{int}{PyDict_Update}{PyObject *a, PyObject *b}
2130+ This is the same as \code{PyDict_Merge(\var{a}, \var{b}, 1)} in C,
2131+ or \code{\var{a}.update(\var{b})} in Python. Return \code{0} on
2132+ success or \code{-1} if an exception was raised.
2133+ \versionadded{2.2}
2134+\end{cfuncdesc}
2135+
2136+\begin{cfuncdesc}{int}{PyDict_MergeFromSeq2}{PyObject *a, PyObject *seq2,
2137+ int override}
2138+ Update or merge into dictionary \var{a}, from the key-value pairs in
2139+ \var{seq2}. \var{seq2} must be an iterable object producing
2140+ iterable objects of length 2, viewed as key-value pairs. In case of
2141+ duplicate keys, the last wins if \var{override} is true, else the
2142+ first wins.
2143+ Return \code{0} on success or \code{-1} if an exception
2144+ was raised.
2145+ Equivalent Python (except for the return value):
2146+
2147+\begin{verbatim}
2148+def PyDict_MergeFromSeq2(a, seq2, override):
2149+ for key, value in seq2:
2150+ if override or key not in a:
2151+ a[key] = value
2152+\end{verbatim}
2153+
2154+ \versionadded{2.2}
2155+\end{cfuncdesc}
2156+
2157+
2158+\section{Other Objects \label{otherObjects}}
2159+
2160+\subsection{File Objects \label{fileObjects}}
2161+
2162+\obindex{file}
2163+Python's built-in file objects are implemented entirely on the
2164+\ctype{FILE*} support from the C standard library. This is an
2165+implementation detail and may change in future releases of Python.
2166+
2167+\begin{ctypedesc}{PyFileObject}
2168+ This subtype of \ctype{PyObject} represents a Python file object.
2169+\end{ctypedesc}
2170+
2171+\begin{cvardesc}{PyTypeObject}{PyFile_Type}
2172+ This instance of \ctype{PyTypeObject} represents the Python file
2173+ type. This is exposed to Python programs as \code{file} and
2174+ \code{types.FileType}.
2175+ \withsubitem{(in module types)}{\ttindex{FileType}}
2176+\end{cvardesc}
2177+
2178+\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
2179+ Return true if its argument is a \ctype{PyFileObject} or a subtype
2180+ of \ctype{PyFileObject}.
2181+ \versionchanged[Allowed subtypes to be accepted]{2.2}
2182+\end{cfuncdesc}
2183+
2184+\begin{cfuncdesc}{int}{PyFile_CheckExact}{PyObject *p}
2185+ Return true if its argument is a \ctype{PyFileObject}, but not a
2186+ subtype of \ctype{PyFileObject}.
2187+ \versionadded{2.2}
2188+\end{cfuncdesc}
2189+
2190+\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
2191+ On success, return a new file object that is opened on the file
2192+ given by \var{filename}, with a file mode given by \var{mode}, where
2193+ \var{mode} has the same semantics as the standard C routine
2194+ \cfunction{fopen()}\ttindex{fopen()}. On failure, return \NULL{}.
2195+\end{cfuncdesc}
2196+
2197+\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
2198+ char *name, char *mode,
2199+ int (*close)(FILE*)}
2200+ Create a new \ctype{PyFileObject} from the already-open standard C
2201+ file pointer, \var{fp}. The function \var{close} will be called
2202+ when the file should be closed. Return \NULL{} on failure.
2203+\end{cfuncdesc}
2204+
2205+\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyObject *p}
2206+ Return the file object associated with \var{p} as a \ctype{FILE*}.
2207+\end{cfuncdesc}
2208+
2209+\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
2210+ Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
2211+ function reads one line from the object \var{p}. \var{p} may be a
2212+ file object or any object with a \method{readline()} method. If
2213+ \var{n} is \code{0}, exactly one line is read, regardless of the
2214+ length of the line. If \var{n} is greater than \code{0}, no more
2215+ than \var{n} bytes will be read from the file; a partial line can be
2216+ returned. In both cases, an empty string is returned if the end of
2217+ the file is reached immediately. If \var{n} is less than \code{0},
2218+ however, one line is read regardless of length, but
2219+ \exception{EOFError} is raised if the end of the file is reached
2220+ immediately.
2221+ \withsubitem{(built-in exception)}{\ttindex{EOFError}}
2222+\end{cfuncdesc}
2223+
2224+\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
2225+ Return the name of the file specified by \var{p} as a string
2226+ object.
2227+\end{cfuncdesc}
2228+
2229+\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
2230+ Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
2231+ only. This should only be called immediately after file object
2232+ creation.
2233+\end{cfuncdesc}
2234+
2235+\begin{cfuncdesc}{int}{PyFile_Encoding}{PyFileObject *p, char *enc}
2236+ Set the file's encoding for Unicode output to \var{enc}. Return
2237+ 1 on success and 0 on failure.
2238+ \versionadded{2.3}
2239+\end{cfuncdesc}
2240+
2241+\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
2242+ This function exists for internal use by the interpreter. Set the
2243+ \member{softspace} attribute of \var{p} to \var{newflag} and
2244+ \withsubitem{(file attribute)}{\ttindex{softspace}}return the
2245+ previous value. \var{p} does not have to be a file object for this
2246+ function to work properly; any object is supported (thought its only
2247+ interesting if the \member{softspace} attribute can be set). This
2248+ function clears any errors, and will return \code{0} as the previous
2249+ value if the attribute either does not exist or if there were errors
2250+ in retrieving it. There is no way to detect errors from this
2251+ function, but doing so should not be needed.
2252+\end{cfuncdesc}
2253+
2254+\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyObject *p,
2255+ int flags}
2256+ Write object \var{obj} to file object \var{p}. The only supported
2257+ flag for \var{flags} is
2258+ \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW}; if given, the
2259+ \function{str()} of the object is written instead of the
2260+ \function{repr()}. Return \code{0} on success or \code{-1} on
2261+ failure; the appropriate exception will be set.
2262+\end{cfuncdesc}
2263+
2264+\begin{cfuncdesc}{int}{PyFile_WriteString}{const char *s, PyObject *p}
2265+ Write string \var{s} to file object \var{p}. Return \code{0} on
2266+ success or \code{-1} on failure; the appropriate exception will be
2267+ set.
2268+\end{cfuncdesc}
2269+
2270+
2271+\subsection{Instance Objects \label{instanceObjects}}
2272+
2273+\obindex{instance}
2274+There are very few functions specific to instance objects.
2275+
2276+\begin{cvardesc}{PyTypeObject}{PyInstance_Type}
2277+ Type object for class instances.
2278+\end{cvardesc}
2279+
2280+\begin{cfuncdesc}{int}{PyInstance_Check}{PyObject *obj}
2281+ Return true if \var{obj} is an instance.
2282+\end{cfuncdesc}
2283+
2284+\begin{cfuncdesc}{PyObject*}{PyInstance_New}{PyObject *class,
2285+ PyObject *arg,
2286+ PyObject *kw}
2287+ Create a new instance of a specific class. The parameters \var{arg}
2288+ and \var{kw} are used as the positional and keyword parameters to
2289+ the object's constructor.
2290+\end{cfuncdesc}
2291+
2292+\begin{cfuncdesc}{PyObject*}{PyInstance_NewRaw}{PyObject *class,
2293+ PyObject *dict}
2294+ Create a new instance of a specific class without calling its
2295+ constructor. \var{class} is the class of new object. The
2296+ \var{dict} parameter will be used as the object's \member{__dict__};
2297+ if \NULL{}, a new dictionary will be created for the instance.
2298+\end{cfuncdesc}
2299+
2300+
2301+\subsection{Function Objects \label{function-objects}}
2302+
2303+\obindex{function}
2304+There are a few functions specific to Python functions.
2305+
2306+\begin{ctypedesc}{PyFunctionObject}
2307+ The C structure used for functions.
2308+\end{ctypedesc}
2309+
2310+\begin{cvardesc}{PyTypeObject}{PyFunction_Type}
2311+ This is an instance of \ctype{PyTypeObject} and represents the
2312+ Python function type. It is exposed to Python programmers as
2313+ \code{types.FunctionType}.
2314+ \withsubitem{(in module types)}{\ttindex{MethodType}}
2315+\end{cvardesc}
2316+
2317+\begin{cfuncdesc}{int}{PyFunction_Check}{PyObject *o}
2318+ Return true if \var{o} is a function object (has type
2319+ \cdata{PyFunction_Type}). The parameter must not be \NULL{}.
2320+\end{cfuncdesc}
2321+
2322+\begin{cfuncdesc}{PyObject*}{PyFunction_New}{PyObject *code,
2323+ PyObject *globals}
2324+ Return a new function object associated with the code object
2325+ \var{code}. \var{globals} must be a dictionary with the global
2326+ variables accessible to the function.
2327+
2328+ The function's docstring, name and \var{__module__} are retrieved
2329+ from the code object, the argument defaults and closure are set to
2330+ \NULL{}.
2331+\end{cfuncdesc}
2332+
2333+\begin{cfuncdesc}{PyObject*}{PyFunction_GetCode}{PyObject *op}
2334+ Return the code object associated with the function object \var{op}.
2335+\end{cfuncdesc}
2336+
2337+\begin{cfuncdesc}{PyObject*}{PyFunction_GetGlobals}{PyObject *op}
2338+ Return the globals dictionary associated with the function object
2339+ \var{op}.
2340+\end{cfuncdesc}
2341+
2342+\begin{cfuncdesc}{PyObject*}{PyFunction_GetModule}{PyObject *op}
2343+ Return the \var{__module__} attribute of the function object \var{op}.
2344+ This is normally a string containing the module name, but can be set
2345+ to any other object by Python code.
2346+\end{cfuncdesc}
2347+
2348+\begin{cfuncdesc}{PyObject*}{PyFunction_GetDefaults}{PyObject *op}
2349+ Return the argument default values of the function object \var{op}.
2350+ This can be a tuple of arguments or \NULL{}.
2351+\end{cfuncdesc}
2352+
2353+\begin{cfuncdesc}{int}{PyFunction_SetDefaults}{PyObject *op,
2354+ PyObject *defaults}
2355+ Set the argument default values for the function object \var{op}.
2356+ \var{defaults} must be \var{Py_None} or a tuple.
2357+
2358+ Raises \exception{SystemError} and returns \code{-1} on failure.
2359+\end{cfuncdesc}
2360+
2361+\begin{cfuncdesc}{PyObject*}{PyFunction_GetClosure}{PyObject *op}
2362+ Return the closure associated with the function object \var{op}.
2363+ This can be \NULL{} or a tuple of cell objects.
2364+\end{cfuncdesc}
2365+
2366+\begin{cfuncdesc}{int}{PyFunction_SetClosure}{PyObject *op,
2367+ PyObject *closure}
2368+ Set the closure associated with the function object \var{op}.
2369+ \var{closure} must be \var{Py_None} or a tuple of cell objects.
2370+
2371+ Raises \exception{SystemError} and returns \code{-1} on failure.
2372+\end{cfuncdesc}
2373+
2374+
2375+\subsection{Method Objects \label{method-objects}}
2376+
2377+\obindex{method}
2378+There are some useful functions that are useful for working with
2379+method objects.
2380+
2381+\begin{cvardesc}{PyTypeObject}{PyMethod_Type}
2382+ This instance of \ctype{PyTypeObject} represents the Python method
2383+ type. This is exposed to Python programs as \code{types.MethodType}.
2384+ \withsubitem{(in module types)}{\ttindex{MethodType}}
2385+\end{cvardesc}
2386+
2387+\begin{cfuncdesc}{int}{PyMethod_Check}{PyObject *o}
2388+ Return true if \var{o} is a method object (has type
2389+ \cdata{PyMethod_Type}). The parameter must not be \NULL{}.
2390+\end{cfuncdesc}
2391+
2392+\begin{cfuncdesc}{PyObject*}{PyMethod_New}{PyObject *func,
2393+ PyObject *self, PyObject *class}
2394+ Return a new method object, with \var{func} being any callable
2395+ object; this is the function that will be called when the method is
2396+ called. If this method should be bound to an instance, \var{self}
2397+ should be the instance and \var{class} should be the class of
2398+ \var{self}, otherwise \var{self} should be \NULL{} and \var{class}
2399+ should be the class which provides the unbound method..
2400+\end{cfuncdesc}
2401+
2402+\begin{cfuncdesc}{PyObject*}{PyMethod_Class}{PyObject *meth}
2403+ Return the class object from which the method \var{meth} was
2404+ created; if this was created from an instance, it will be the class
2405+ of the instance.
2406+\end{cfuncdesc}
2407+
2408+\begin{cfuncdesc}{PyObject*}{PyMethod_GET_CLASS}{PyObject *meth}
2409+ Macro version of \cfunction{PyMethod_Class()} which avoids error
2410+ checking.
2411+\end{cfuncdesc}
2412+
2413+\begin{cfuncdesc}{PyObject*}{PyMethod_Function}{PyObject *meth}
2414+ Return the function object associated with the method \var{meth}.
2415+\end{cfuncdesc}
2416+
2417+\begin{cfuncdesc}{PyObject*}{PyMethod_GET_FUNCTION}{PyObject *meth}
2418+ Macro version of \cfunction{PyMethod_Function()} which avoids error
2419+ checking.
2420+\end{cfuncdesc}
2421+
2422+\begin{cfuncdesc}{PyObject*}{PyMethod_Self}{PyObject *meth}
2423+ Return the instance associated with the method \var{meth} if it is
2424+ bound, otherwise return \NULL{}.
2425+\end{cfuncdesc}
2426+
2427+\begin{cfuncdesc}{PyObject*}{PyMethod_GET_SELF}{PyObject *meth}
2428+ Macro version of \cfunction{PyMethod_Self()} which avoids error
2429+ checking.
2430+\end{cfuncdesc}
2431+
2432+
2433+\subsection{Module Objects \label{moduleObjects}}
2434+
2435+\obindex{module}
2436+There are only a few functions special to module objects.
2437+
2438+\begin{cvardesc}{PyTypeObject}{PyModule_Type}
2439+ This instance of \ctype{PyTypeObject} represents the Python module
2440+ type. This is exposed to Python programs as
2441+ \code{types.ModuleType}.
2442+ \withsubitem{(in module types)}{\ttindex{ModuleType}}
2443+\end{cvardesc}
2444+
2445+\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
2446+ Return true if \var{p} is a module object, or a subtype of a module
2447+ object.
2448+ \versionchanged[Allowed subtypes to be accepted]{2.2}
2449+\end{cfuncdesc}
2450+
2451+\begin{cfuncdesc}{int}{PyModule_CheckExact}{PyObject *p}
2452+ Return true if \var{p} is a module object, but not a subtype of
2453+ \cdata{PyModule_Type}.
2454+ \versionadded{2.2}
2455+\end{cfuncdesc}
2456+
2457+\begin{cfuncdesc}{PyObject*}{PyModule_New}{const char *name}
2458+ Return a new module object with the \member{__name__} attribute set
2459+ to \var{name}. Only the module's \member{__doc__} and
2460+ \member{__name__} attributes are filled in; the caller is
2461+ responsible for providing a \member{__file__} attribute.
2462+ \withsubitem{(module attribute)}{
2463+ \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
2464+\end{cfuncdesc}
2465+
2466+\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
2467+ Return the dictionary object that implements \var{module}'s
2468+ namespace; this object is the same as the \member{__dict__}
2469+ attribute of the module object. This function never fails.
2470+ \withsubitem{(module attribute)}{\ttindex{__dict__}}
2471+ It is recommended extensions use other \cfunction{PyModule_*()}
2472+ and \cfunction{PyObject_*()} functions rather than directly
2473+ manipulate a module's \member{__dict__}.
2474+\end{cfuncdesc}
2475+
2476+\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
2477+ Return \var{module}'s \member{__name__} value. If the module does
2478+ not provide one, or if it is not a string, \exception{SystemError}
2479+ is raised and \NULL{} is returned.
2480+ \withsubitem{(module attribute)}{\ttindex{__name__}}
2481+ \withsubitem{(built-in exception)}{\ttindex{SystemError}}
2482+\end{cfuncdesc}
2483+
2484+\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
2485+ Return the name of the file from which \var{module} was loaded using
2486+ \var{module}'s \member{__file__} attribute. If this is not defined,
2487+ or if it is not a string, raise \exception{SystemError} and return
2488+ \NULL{}.
2489+ \withsubitem{(module attribute)}{\ttindex{__file__}}
2490+ \withsubitem{(built-in exception)}{\ttindex{SystemError}}
2491+\end{cfuncdesc}
2492+
2493+\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
2494+ const char *name, PyObject *value}
2495+ Add an object to \var{module} as \var{name}. This is a convenience
2496+ function which can be used from the module's initialization
2497+ function. This steals a reference to \var{value}. Return
2498+ \code{-1} on error, \code{0} on success.
2499+ \versionadded{2.0}
2500+\end{cfuncdesc}
2501+
2502+\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
2503+ const char *name, long value}
2504+ Add an integer constant to \var{module} as \var{name}. This
2505+ convenience function can be used from the module's initialization
2506+ function. Return \code{-1} on error, \code{0} on success.
2507+ \versionadded{2.0}
2508+\end{cfuncdesc}
2509+
2510+\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
2511+ const char *name, const char *value}
2512+ Add a string constant to \var{module} as \var{name}. This
2513+ convenience function can be used from the module's initialization
2514+ function. The string \var{value} must be null-terminated. Return
2515+ \code{-1} on error, \code{0} on success.
2516+ \versionadded{2.0}
2517+\end{cfuncdesc}
2518+
2519+
2520+\subsection{Iterator Objects \label{iterator-objects}}
2521+
2522+Python provides two general-purpose iterator objects. The first, a
2523+sequence iterator, works with an arbitrary sequence supporting the
2524+\method{__getitem__()} method. The second works with a callable
2525+object and a sentinel value, calling the callable for each item in the
2526+sequence, and ending the iteration when the sentinel value is
2527+returned.
2528+
2529+\begin{cvardesc}{PyTypeObject}{PySeqIter_Type}
2530+ Type object for iterator objects returned by
2531+ \cfunction{PySeqIter_New()} and the one-argument form of the
2532+ \function{iter()} built-in function for built-in sequence types.
2533+ \versionadded{2.2}
2534+\end{cvardesc}
2535+
2536+\begin{cfuncdesc}{int}{PySeqIter_Check}{op}
2537+ Return true if the type of \var{op} is \cdata{PySeqIter_Type}.
2538+ \versionadded{2.2}
2539+\end{cfuncdesc}
2540+
2541+\begin{cfuncdesc}{PyObject*}{PySeqIter_New}{PyObject *seq}
2542+ Return an iterator that works with a general sequence object,
2543+ \var{seq}. The iteration ends when the sequence raises
2544+ \exception{IndexError} for the subscripting operation.
2545+ \versionadded{2.2}
2546+\end{cfuncdesc}
2547+
2548+\begin{cvardesc}{PyTypeObject}{PyCallIter_Type}
2549+ Type object for iterator objects returned by
2550+ \cfunction{PyCallIter_New()} and the two-argument form of the
2551+ \function{iter()} built-in function.
2552+ \versionadded{2.2}
2553+\end{cvardesc}
2554+
2555+\begin{cfuncdesc}{int}{PyCallIter_Check}{op}
2556+ Return true if the type of \var{op} is \cdata{PyCallIter_Type}.
2557+ \versionadded{2.2}
2558+\end{cfuncdesc}
2559+
2560+\begin{cfuncdesc}{PyObject*}{PyCallIter_New}{PyObject *callable,
2561+ PyObject *sentinel}
2562+ Return a new iterator. The first parameter, \var{callable}, can be
2563+ any Python callable object that can be called with no parameters;
2564+ each call to it should return the next item in the iteration. When
2565+ \var{callable} returns a value equal to \var{sentinel}, the
2566+ iteration will be terminated.
2567+ \versionadded{2.2}
2568+\end{cfuncdesc}
2569+
2570+
2571+\subsection{Descriptor Objects \label{descriptor-objects}}
2572+
2573+``Descriptors'' are objects that describe some attribute of an object.
2574+They are found in the dictionary of type objects.
2575+
2576+\begin{cvardesc}{PyTypeObject}{PyProperty_Type}
2577+ The type object for the built-in descriptor types.
2578+ \versionadded{2.2}
2579+\end{cvardesc}
2580+
2581+\begin{cfuncdesc}{PyObject*}{PyDescr_NewGetSet}{PyTypeObject *type,
2582+ struct PyGetSetDef *getset}
2583+ \versionadded{2.2}
2584+\end{cfuncdesc}
2585+
2586+\begin{cfuncdesc}{PyObject*}{PyDescr_NewMember}{PyTypeObject *type,
2587+ struct PyMemberDef *meth}
2588+ \versionadded{2.2}
2589+\end{cfuncdesc}
2590+
2591+\begin{cfuncdesc}{PyObject*}{PyDescr_NewMethod}{PyTypeObject *type,
2592+ struct PyMethodDef *meth}
2593+ \versionadded{2.2}
2594+\end{cfuncdesc}
2595+
2596+\begin{cfuncdesc}{PyObject*}{PyDescr_NewWrapper}{PyTypeObject *type,
2597+ struct wrapperbase *wrapper,
2598+ void *wrapped}
2599+ \versionadded{2.2}
2600+\end{cfuncdesc}
2601+
2602+\begin{cfuncdesc}{PyObject*}{PyDescr_NewClassMethod}{PyTypeObject *type,
2603+ PyMethodDef *method}
2604+ \versionadded{2.3}
2605+\end{cfuncdesc}
2606+
2607+\begin{cfuncdesc}{int}{PyDescr_IsData}{PyObject *descr}
2608+ Return true if the descriptor objects \var{descr} describes a data
2609+ attribute, or false if it describes a method. \var{descr} must be a
2610+ descriptor object; there is no error checking.
2611+ \versionadded{2.2}
2612+\end{cfuncdesc}
2613+
2614+\begin{cfuncdesc}{PyObject*}{PyWrapper_New}{PyObject *, PyObject *}
2615+ \versionadded{2.2}
2616+\end{cfuncdesc}
2617+
2618+
2619+\subsection{Slice Objects \label{slice-objects}}
2620+
2621+\begin{cvardesc}{PyTypeObject}{PySlice_Type}
2622+ The type object for slice objects. This is the same as
2623+ \code{slice} and \code{types.SliceType}.
2624+ \withsubitem{(in module types)}{\ttindex{SliceType}}
2625+\end{cvardesc}
2626+
2627+\begin{cfuncdesc}{int}{PySlice_Check}{PyObject *ob}
2628+ Return true if \var{ob} is a slice object; \var{ob} must not be
2629+ \NULL{}.
2630+\end{cfuncdesc}
2631+
2632+\begin{cfuncdesc}{PyObject*}{PySlice_New}{PyObject *start, PyObject *stop,
2633+ PyObject *step}
2634+ Return a new slice object with the given values. The \var{start},
2635+ \var{stop}, and \var{step} parameters are used as the values of the
2636+ slice object attributes of the same names. Any of the values may be
2637+ \NULL{}, in which case the \code{None} will be used for the
2638+ corresponding attribute. Return \NULL{} if the new object could
2639+ not be allocated.
2640+\end{cfuncdesc}
2641+
2642+\begin{cfuncdesc}{int}{PySlice_GetIndices}{PySliceObject *slice, Py_ssize_t length,
2643+ Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step}
2644+Retrieve the start, stop and step indices from the slice object
2645+\var{slice}, assuming a sequence of length \var{length}. Treats
2646+indices greater than \var{length} as errors.
2647+
2648+Returns 0 on success and -1 on error with no exception set (unless one
2649+of the indices was not \constant{None} and failed to be converted to
2650+an integer, in which case -1 is returned with an exception set).
2651+
2652+You probably do not want to use this function. If you want to use
2653+slice objects in versions of Python prior to 2.3, you would probably
2654+do well to incorporate the source of \cfunction{PySlice_GetIndicesEx},
2655+suitably renamed, in the source of your extension.
2656+\end{cfuncdesc}
2657+
2658+\begin{cfuncdesc}{int}{PySlice_GetIndicesEx}{PySliceObject *slice, Py_ssize_t length,
2659+ Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step,
2660+ Py_ssize_t *slicelength}
2661+Usable replacement for \cfunction{PySlice_GetIndices}. Retrieve the
2662+start, stop, and step indices from the slice object \var{slice}
2663+assuming a sequence of length \var{length}, and store the length of
2664+the slice in \var{slicelength}. Out of bounds indices are clipped in
2665+a manner consistent with the handling of normal slices.
2666+
2667+Returns 0 on success and -1 on error with exception set.
2668+
2669+\versionadded{2.3}
2670+\end{cfuncdesc}
2671+
2672+
2673+\subsection{Weak Reference Objects \label{weakref-objects}}
2674+
2675+Python supports \emph{weak references} as first-class objects. There
2676+are two specific object types which directly implement weak
2677+references. The first is a simple reference object, and the second
2678+acts as a proxy for the original object as much as it can.
2679+
2680+\begin{cfuncdesc}{int}{PyWeakref_Check}{ob}
2681+ Return true if \var{ob} is either a reference or proxy object.
2682+ \versionadded{2.2}
2683+\end{cfuncdesc}
2684+
2685+\begin{cfuncdesc}{int}{PyWeakref_CheckRef}{ob}
2686+ Return true if \var{ob} is a reference object.
2687+ \versionadded{2.2}
2688+\end{cfuncdesc}
2689+
2690+\begin{cfuncdesc}{int}{PyWeakref_CheckProxy}{ob}
2691+ Return true if \var{ob} is a proxy object.
2692+ \versionadded{2.2}
2693+\end{cfuncdesc}
2694+
2695+\begin{cfuncdesc}{PyObject*}{PyWeakref_NewRef}{PyObject *ob,
2696+ PyObject *callback}
2697+ Return a weak reference object for the object \var{ob}. This will
2698+ always return a new reference, but is not guaranteed to create a new
2699+ object; an existing reference object may be returned. The second
2700+ parameter, \var{callback}, can be a callable object that receives
2701+ notification when \var{ob} is garbage collected; it should accept a
2702+ single parameter, which will be the weak reference object itself.
2703+ \var{callback} may also be \code{None} or \NULL{}. If \var{ob}
2704+ is not a weakly-referencable object, or if \var{callback} is not
2705+ callable, \code{None}, or \NULL{}, this will return \NULL{} and
2706+ raise \exception{TypeError}.
2707+ \versionadded{2.2}
2708+\end{cfuncdesc}
2709+
2710+\begin{cfuncdesc}{PyObject*}{PyWeakref_NewProxy}{PyObject *ob,
2711+ PyObject *callback}
2712+ Return a weak reference proxy object for the object \var{ob}. This
2713+ will always return a new reference, but is not guaranteed to create
2714+ a new object; an existing proxy object may be returned. The second
2715+ parameter, \var{callback}, can be a callable object that receives
2716+ notification when \var{ob} is garbage collected; it should accept a
2717+ single parameter, which will be the weak reference object itself.
2718+ \var{callback} may also be \code{None} or \NULL{}. If \var{ob} is not
2719+ a weakly-referencable object, or if \var{callback} is not callable,
2720+ \code{None}, or \NULL{}, this will return \NULL{} and raise
2721+ \exception{TypeError}.
2722+ \versionadded{2.2}
2723+\end{cfuncdesc}
2724+
2725+\begin{cfuncdesc}{PyObject*}{PyWeakref_GetObject}{PyObject *ref}
2726+ Return the referenced object from a weak reference, \var{ref}. If
2727+ the referent is no longer live, returns \code{None}.
2728+ \versionadded{2.2}
2729+\end{cfuncdesc}
2730+
2731+\begin{cfuncdesc}{PyObject*}{PyWeakref_GET_OBJECT}{PyObject *ref}
2732+ Similar to \cfunction{PyWeakref_GetObject()}, but implemented as a
2733+ macro that does no error checking.
2734+ \versionadded{2.2}
2735+\end{cfuncdesc}
2736+
2737+
2738+\subsection{CObjects \label{cObjects}}
2739+
2740+\obindex{CObject}
2741+Refer to \emph{Extending and Embedding the Python Interpreter},
2742+section~1.12, ``Providing a C API for an Extension Module,'' for more
2743+information on using these objects.
2744+
2745+
2746+\begin{ctypedesc}{PyCObject}
2747+ This subtype of \ctype{PyObject} represents an opaque value, useful
2748+ for C extension modules who need to pass an opaque value (as a
2749+ \ctype{void*} pointer) through Python code to other C code. It is
2750+ often used to make a C function pointer defined in one module
2751+ available to other modules, so the regular import mechanism can be
2752+ used to access C APIs defined in dynamically loaded modules.
2753+\end{ctypedesc}
2754+
2755+\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
2756+ Return true if its argument is a \ctype{PyCObject}.
2757+\end{cfuncdesc}
2758+
2759+\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
2760+ void (*destr)(void *)}
2761+ Create a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
2762+ \var{destr} function will be called when the object is reclaimed,
2763+ unless it is \NULL{}.
2764+\end{cfuncdesc}
2765+
2766+\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
2767+ void* desc, void (*destr)(void *, void *)}
2768+ Create a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
2769+ \var{destr} function will be called when the object is reclaimed.
2770+ The \var{desc} argument can be used to pass extra callback data for
2771+ the destructor function.
2772+\end{cfuncdesc}
2773+
2774+\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
2775+ Return the object \ctype{void *} that the \ctype{PyCObject}
2776+ \var{self} was created with.
2777+\end{cfuncdesc}
2778+
2779+\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
2780+ Return the description \ctype{void *} that the \ctype{PyCObject}
2781+ \var{self} was created with.
2782+\end{cfuncdesc}
2783+
2784+\begin{cfuncdesc}{int}{PyCObject_SetVoidPtr}{PyObject* self, void* cobj}
2785+ Set the void pointer inside \var{self} to \var{cobj}.
2786+ The \ctype{PyCObject} must not have an associated destructor.
2787+ Return true on success, false on failure.
2788+\end{cfuncdesc}
2789+
2790+
2791+\subsection{Cell Objects \label{cell-objects}}
2792+
2793+``Cell'' objects are used to implement variables referenced by
2794+multiple scopes. For each such variable, a cell object is created to
2795+store the value; the local variables of each stack frame that
2796+references the value contains a reference to the cells from outer
2797+scopes which also use that variable. When the value is accessed, the
2798+value contained in the cell is used instead of the cell object
2799+itself. This de-referencing of the cell object requires support from
2800+the generated byte-code; these are not automatically de-referenced
2801+when accessed. Cell objects are not likely to be useful elsewhere.
2802+
2803+\begin{ctypedesc}{PyCellObject}
2804+ The C structure used for cell objects.
2805+\end{ctypedesc}
2806+
2807+\begin{cvardesc}{PyTypeObject}{PyCell_Type}
2808+ The type object corresponding to cell objects.
2809+\end{cvardesc}
2810+
2811+\begin{cfuncdesc}{int}{PyCell_Check}{ob}
2812+ Return true if \var{ob} is a cell object; \var{ob} must not be
2813+ \NULL{}.
2814+\end{cfuncdesc}
2815+
2816+\begin{cfuncdesc}{PyObject*}{PyCell_New}{PyObject *ob}
2817+ Create and return a new cell object containing the value \var{ob}.
2818+ The parameter may be \NULL{}.
2819+\end{cfuncdesc}
2820+
2821+\begin{cfuncdesc}{PyObject*}{PyCell_Get}{PyObject *cell}
2822+ Return the contents of the cell \var{cell}.
2823+\end{cfuncdesc}
2824+
2825+\begin{cfuncdesc}{PyObject*}{PyCell_GET}{PyObject *cell}
2826+ Return the contents of the cell \var{cell}, but without checking
2827+ that \var{cell} is non-\NULL{} and a cell object.
2828+\end{cfuncdesc}
2829+
2830+\begin{cfuncdesc}{int}{PyCell_Set}{PyObject *cell, PyObject *value}
2831+ Set the contents of the cell object \var{cell} to \var{value}. This
2832+ releases the reference to any current content of the cell.
2833+ \var{value} may be \NULL{}. \var{cell} must be non-\NULL{}; if it is
2834+ not a cell object, \code{-1} will be returned. On success, \code{0}
2835+ will be returned.
2836+\end{cfuncdesc}
2837+
2838+\begin{cfuncdesc}{void}{PyCell_SET}{PyObject *cell, PyObject *value}
2839+ Sets the value of the cell object \var{cell} to \var{value}. No
2840+ reference counts are adjusted, and no checks are made for safety;
2841+ \var{cell} must be non-\NULL{} and must be a cell object.
2842+\end{cfuncdesc}
2843+
2844+
2845+\subsection{Generator Objects \label{gen-objects}}
2846+
2847+Generator objects are what Python uses to implement generator iterators.
2848+They are normally created by iterating over a function that yields values,
2849+rather than explicitly calling \cfunction{PyGen_New}.
2850+
2851+\begin{ctypedesc}{PyGenObject}
2852+ The C structure used for generator objects.
2853+\end{ctypedesc}
2854+
2855+\begin{cvardesc}{PyTypeObject}{PyGen_Type}
2856+ The type object corresponding to generator objects
2857+\end{cvardesc}
2858+
2859+\begin{cfuncdesc}{int}{PyGen_Check}{ob}
2860+ Return true if \var{ob} is a generator object; \var{ob} must not be
2861+ \NULL{}.
2862+\end{cfuncdesc}
2863+
2864+\begin{cfuncdesc}{int}{PyGen_CheckExact}{ob}
2865+ Return true if \var{ob}'s type is \var{PyGen_Type}
2866+ is a generator object; \var{ob} must not be
2867+ \NULL{}.
2868+\end{cfuncdesc}
2869+
2870+\begin{cfuncdesc}{PyObject*}{PyGen_New}{PyFrameObject *frame}
2871+ Create and return a new generator object based on the \var{frame} object.
2872+ A reference to \var{frame} is stolen by this function.
2873+ The parameter must not be \NULL{}.
2874+\end{cfuncdesc}
2875+
2876+
2877+\subsection{DateTime Objects \label{datetime-objects}}
2878+
2879+Various date and time objects are supplied by the \module{datetime}
2880+module. Before using any of these functions, the header file
2881+\file{datetime.h} must be included in your source (note that this is
2882+not included by \file{Python.h}), and the macro
2883+\cfunction{PyDateTime_IMPORT} must be invoked. The macro puts a
2884+pointer to a C structure into a static variable,
2885+\code{PyDateTimeAPI}, that is used by the following macros.
2886+
2887+Type-check macros:
2888+
2889+\begin{cfuncdesc}{int}{PyDate_Check}{PyObject *ob}
2890+ Return true if \var{ob} is of type \cdata{PyDateTime_DateType} or
2891+ a subtype of \cdata{PyDateTime_DateType}. \var{ob} must not be
2892+ \NULL{}.
2893+ \versionadded{2.4}
2894+\end{cfuncdesc}
2895+
2896+\begin{cfuncdesc}{int}{PyDate_CheckExact}{PyObject *ob}
2897+ Return true if \var{ob} is of type \cdata{PyDateTime_DateType}.
2898+ \var{ob} must not be \NULL{}.
2899+ \versionadded{2.4}
2900+\end{cfuncdesc}
2901+
2902+\begin{cfuncdesc}{int}{PyDateTime_Check}{PyObject *ob}
2903+ Return true if \var{ob} is of type \cdata{PyDateTime_DateTimeType} or
2904+ a subtype of \cdata{PyDateTime_DateTimeType}. \var{ob} must not be
2905+ \NULL{}.
2906+ \versionadded{2.4}
2907+\end{cfuncdesc}
2908+
2909+\begin{cfuncdesc}{int}{PyDateTime_CheckExact}{PyObject *ob}
2910+ Return true if \var{ob} is of type \cdata{PyDateTime_DateTimeType}.
2911+ \var{ob} must not be \NULL{}.
2912+ \versionadded{2.4}
2913+\end{cfuncdesc}
2914+
2915+\begin{cfuncdesc}{int}{PyTime_Check}{PyObject *ob}
2916+ Return true if \var{ob} is of type \cdata{PyDateTime_TimeType} or
2917+ a subtype of \cdata{PyDateTime_TimeType}. \var{ob} must not be
2918+ \NULL{}.
2919+ \versionadded{2.4}
2920+\end{cfuncdesc}
2921+
2922+\begin{cfuncdesc}{int}{PyTime_CheckExact}{PyObject *ob}
2923+ Return true if \var{ob} is of type \cdata{PyDateTime_TimeType}.
2924+ \var{ob} must not be \NULL{}.
2925+ \versionadded{2.4}
2926+\end{cfuncdesc}
2927+
2928+\begin{cfuncdesc}{int}{PyDelta_Check}{PyObject *ob}
2929+ Return true if \var{ob} is of type \cdata{PyDateTime_DeltaType} or
2930+ a subtype of \cdata{PyDateTime_DeltaType}. \var{ob} must not be
2931+ \NULL{}.
2932+ \versionadded{2.4}
2933+\end{cfuncdesc}
2934+
2935+\begin{cfuncdesc}{int}{PyDelta_CheckExact}{PyObject *ob}
2936+ Return true if \var{ob} is of type \cdata{PyDateTime_DeltaType}.
2937+ \var{ob} must not be \NULL{}.
2938+ \versionadded{2.4}
2939+\end{cfuncdesc}
2940+
2941+\begin{cfuncdesc}{int}{PyTZInfo_Check}{PyObject *ob}
2942+ Return true if \var{ob} is of type \cdata{PyDateTime_TZInfoType} or
2943+ a subtype of \cdata{PyDateTime_TZInfoType}. \var{ob} must not be
2944+ \NULL{}.
2945+ \versionadded{2.4}
2946+\end{cfuncdesc}
2947+
2948+\begin{cfuncdesc}{int}{PyTZInfo_CheckExact}{PyObject *ob}
2949+ Return true if \var{ob} is of type \cdata{PyDateTime_TZInfoType}.
2950+ \var{ob} must not be \NULL{}.
2951+ \versionadded{2.4}
2952+\end{cfuncdesc}
2953+
2954+Macros to create objects:
2955+
2956+\begin{cfuncdesc}{PyObject*}{PyDate_FromDate}{int year, int month, int day}
2957+ Return a \code{datetime.date} object with the specified year, month
2958+ and day.
2959+ \versionadded{2.4}
2960+\end{cfuncdesc}
2961+
2962+\begin{cfuncdesc}{PyObject*}{PyDateTime_FromDateAndTime}{int year, int month,
2963+ int day, int hour, int minute, int second, int usecond}
2964+ Return a \code{datetime.datetime} object with the specified year, month,
2965+ day, hour, minute, second and microsecond.
2966+ \versionadded{2.4}
2967+\end{cfuncdesc}
2968+
2969+\begin{cfuncdesc}{PyObject*}{PyTime_FromTime}{int hour, int minute,
2970+ int second, int usecond}
2971+ Return a \code{datetime.time} object with the specified hour, minute,
2972+ second and microsecond.
2973+ \versionadded{2.4}
2974+\end{cfuncdesc}
2975+
2976+\begin{cfuncdesc}{PyObject*}{PyDelta_FromDSU}{int days, int seconds,
2977+ int useconds}
2978+ Return a \code{datetime.timedelta} object representing the given number
2979+ of days, seconds and microseconds. Normalization is performed so that
2980+ the resulting number of microseconds and seconds lie in the ranges
2981+ documented for \code{datetime.timedelta} objects.
2982+ \versionadded{2.4}
2983+\end{cfuncdesc}
2984+
2985+Macros to extract fields from date objects. The argument must be an
2986+instance of \cdata{PyDateTime_Date}, including subclasses (such as
2987+\cdata{PyDateTime_DateTime}). The argument must not be \NULL{}, and
2988+the type is not checked:
2989+
2990+\begin{cfuncdesc}{int}{PyDateTime_GET_YEAR}{PyDateTime_Date *o}
2991+ Return the year, as a positive int.
2992+ \versionadded{2.4}
2993+\end{cfuncdesc}
2994+
2995+\begin{cfuncdesc}{int}{PyDateTime_GET_MONTH}{PyDateTime_Date *o}
2996+ Return the month, as an int from 1 through 12.
2997+ \versionadded{2.4}
2998+\end{cfuncdesc}
2999+
3000+\begin{cfuncdesc}{int}{PyDateTime_GET_DAY}{PyDateTime_Date *o}
3001+ Return the day, as an int from 1 through 31.
3002+ \versionadded{2.4}
3003+\end{cfuncdesc}
3004+
3005+Macros to extract fields from datetime objects. The argument must be an
3006+instance of \cdata{PyDateTime_DateTime}, including subclasses.
3007+The argument must not be \NULL{}, and the type is not checked:
3008+
3009+\begin{cfuncdesc}{int}{PyDateTime_DATE_GET_HOUR}{PyDateTime_DateTime *o}
3010+ Return the hour, as an int from 0 through 23.
3011+ \versionadded{2.4}
3012+\end{cfuncdesc}
3013+
3014+\begin{cfuncdesc}{int}{PyDateTime_DATE_GET_MINUTE}{PyDateTime_DateTime *o}
3015+ Return the minute, as an int from 0 through 59.
3016+ \versionadded{2.4}
3017+\end{cfuncdesc}
3018+
3019+\begin{cfuncdesc}{int}{PyDateTime_DATE_GET_SECOND}{PyDateTime_DateTime *o}
3020+ Return the second, as an int from 0 through 59.
3021+ \versionadded{2.4}
3022+\end{cfuncdesc}
3023+
3024+\begin{cfuncdesc}{int}{PyDateTime_DATE_GET_MICROSECOND}{PyDateTime_DateTime *o}
3025+ Return the microsecond, as an int from 0 through 999999.
3026+ \versionadded{2.4}
3027+\end{cfuncdesc}
3028+
3029+Macros to extract fields from time objects. The argument must be an
3030+instance of \cdata{PyDateTime_Time}, including subclasses.
3031+The argument must not be \NULL{}, and the type is not checked:
3032+
3033+\begin{cfuncdesc}{int}{PyDateTime_TIME_GET_HOUR}{PyDateTime_Time *o}
3034+ Return the hour, as an int from 0 through 23.
3035+ \versionadded{2.4}
3036+\end{cfuncdesc}
3037+
3038+\begin{cfuncdesc}{int}{PyDateTime_TIME_GET_MINUTE}{PyDateTime_Time *o}
3039+ Return the minute, as an int from 0 through 59.
3040+ \versionadded{2.4}
3041+\end{cfuncdesc}
3042+
3043+\begin{cfuncdesc}{int}{PyDateTime_TIME_GET_SECOND}{PyDateTime_Time *o}
3044+ Return the second, as an int from 0 through 59.
3045+ \versionadded{2.4}
3046+\end{cfuncdesc}
3047+
3048+\begin{cfuncdesc}{int}{PyDateTime_TIME_GET_MICROSECOND}{PyDateTime_Time *o}
3049+ Return the microsecond, as an int from 0 through 999999.
3050+ \versionadded{2.4}
3051+\end{cfuncdesc}
3052+
3053+Macros for the convenience of modules implementing the DB API:
3054+
3055+\begin{cfuncdesc}{PyObject*}{PyDateTime_FromTimestamp}{PyObject *args}
3056+ Create and return a new \code{datetime.datetime} object given an argument
3057+ tuple suitable for passing to \code{datetime.datetime.fromtimestamp()}.
3058+ \versionadded{2.4}
3059+\end{cfuncdesc}
3060+
3061+\begin{cfuncdesc}{PyObject*}{PyDate_FromTimestamp}{PyObject *args}
3062+ Create and return a new \code{datetime.date} object given an argument
3063+ tuple suitable for passing to \code{datetime.date.fromtimestamp()}.
3064+ \versionadded{2.4}
3065+\end{cfuncdesc}
3066+
3067+
3068+\subsection{Set Objects \label{setObjects}}
3069+\sectionauthor{Raymond D. Hettinger}{python@rcn.com}
3070+
3071+\obindex{set}
3072+\obindex{frozenset}
3073+\versionadded{2.5}
3074+
3075+This section details the public API for \class{set} and \class{frozenset}
3076+objects. Any functionality not listed below is best accessed using the
3077+either the abstract object protocol (including
3078+\cfunction{PyObject_CallMethod()}, \cfunction{PyObject_RichCompareBool()},
3079+\cfunction{PyObject_Hash()}, \cfunction{PyObject_Repr()},
3080+\cfunction{PyObject_IsTrue()}, \cfunction{PyObject_Print()}, and
3081+\cfunction{PyObject_GetIter()})
3082+or the abstract number protocol (including
3083+\cfunction{PyNumber_Add()}, \cfunction{PyNumber_Subtract()},
3084+\cfunction{PyNumber_Or()}, \cfunction{PyNumber_Xor()},
3085+\cfunction{PyNumber_InPlaceAdd()}, \cfunction{PyNumber_InPlaceSubtract()},
3086+\cfunction{PyNumber_InPlaceOr()}, and \cfunction{PyNumber_InPlaceXor()}).
3087+
3088+\begin{ctypedesc}{PySetObject}
3089+ This subtype of \ctype{PyObject} is used to hold the internal data for
3090+ both \class{set} and \class{frozenset} objects. It is like a
3091+ \ctype{PyDictObject} in that it is a fixed size for small sets
3092+ (much like tuple storage) and will point to a separate, variable sized
3093+ block of memory for medium and large sized sets (much like list storage).
3094+ None of the fields of this structure should be considered public and
3095+ are subject to change. All access should be done through the
3096+ documented API rather than by manipulating the values in the structure.
3097+
3098+\end{ctypedesc}
3099+
3100+\begin{cvardesc}{PyTypeObject}{PySet_Type}
3101+ This is an instance of \ctype{PyTypeObject} representing the Python
3102+ \class{set} type.
3103+\end{cvardesc}
3104+
3105+\begin{cvardesc}{PyTypeObject}{PyFrozenSet_Type}
3106+ This is an instance of \ctype{PyTypeObject} representing the Python
3107+ \class{frozenset} type.
3108+\end{cvardesc}
3109+
3110+
3111+The following type check macros work on pointers to any Python object.
3112+Likewise, the constructor functions work with any iterable Python object.
3113+
3114+\begin{cfuncdesc}{int}{PyAnySet_Check}{PyObject *p}
3115+ Return true if \var{p} is a \class{set} object, a \class{frozenset}
3116+ object, or an instance of a subtype.
3117+\end{cfuncdesc}
3118+
3119+\begin{cfuncdesc}{int}{PyAnySet_CheckExact}{PyObject *p}
3120+ Return true if \var{p} is a \class{set} object or a \class{frozenset}
3121+ object but not an instance of a subtype.
3122+\end{cfuncdesc}
3123+
3124+\begin{cfuncdesc}{int}{PyFrozenSet_CheckExact}{PyObject *p}
3125+ Return true if \var{p} is a \class{frozenset} object
3126+ but not an instance of a subtype.
3127+\end{cfuncdesc}
3128+
3129+\begin{cfuncdesc}{PyObject*}{PySet_New}{PyObject *iterable}
3130+ Return a new \class{set} containing objects returned by the
3131+ \var{iterable}. The \var{iterable} may be \NULL{} to create a
3132+ new empty set. Return the new set on success or \NULL{} on
3133+ failure. Raise \exception{TypeError} if \var{iterable} is
3134+ not actually iterable. The constructor is also useful for
3135+ copying a set (\code{c=set(s)}).
3136+\end{cfuncdesc}
3137+
3138+\begin{cfuncdesc}{PyObject*}{PyFrozenSet_New}{PyObject *iterable}
3139+ Return a new \class{frozenset} containing objects returned by the
3140+ \var{iterable}. The \var{iterable} may be \NULL{} to create a
3141+ new empty frozenset. Return the new set on success or \NULL{} on
3142+ failure. Raise \exception{TypeError} if \var{iterable} is
3143+ not actually iterable.
3144+\end{cfuncdesc}
3145+
3146+
3147+The following functions and macros are available for instances of
3148+\class{set} or \class{frozenset} or instances of their subtypes.
3149+
3150+\begin{cfuncdesc}{int}{PySet_Size}{PyObject *anyset}
3151+ Return the length of a \class{set} or \class{frozenset} object.
3152+ Equivalent to \samp{len(\var{anyset})}. Raises a
3153+ \exception{PyExc_SystemError} if \var{anyset} is not a \class{set},
3154+ \class{frozenset}, or an instance of a subtype.
3155+ \bifuncindex{len}
3156+\end{cfuncdesc}
3157+
3158+\begin{cfuncdesc}{int}{PySet_GET_SIZE}{PyObject *anyset}
3159+ Macro form of \cfunction{PySet_Size()} without error checking.
3160+\end{cfuncdesc}
3161+
3162+\begin{cfuncdesc}{int}{PySet_Contains}{PyObject *anyset, PyObject *key}
3163+ Return 1 if found, 0 if not found, and -1 if an error is
3164+ encountered. Unlike the Python \method{__contains__()} method, this
3165+ function does not automatically convert unhashable sets into temporary
3166+ frozensets. Raise a \exception{TypeError} if the \var{key} is unhashable.
3167+ Raise \exception{PyExc_SystemError} if \var{anyset} is not a \class{set},
3168+ \class{frozenset}, or an instance of a subtype.
3169+\end{cfuncdesc}
3170+
3171+The following functions are available for instances of \class{set} or
3172+its subtypes but not for instances of \class{frozenset} or its subtypes.
3173+
3174+\begin{cfuncdesc}{int}{PySet_Add}{PyObject *set, PyObject *key}
3175+ Add \var{key} to a \class{set} instance. Does not apply to
3176+ \class{frozenset} instances. Return 0 on success or -1 on failure.
3177+ Raise a \exception{TypeError} if the \var{key} is unhashable.
3178+ Raise a \exception{MemoryError} if there is no room to grow.
3179+ Raise a \exception{SystemError} if \var{set} is an not an instance
3180+ of \class{set} or its subtype.
3181+\end{cfuncdesc}
3182+
3183+\begin{cfuncdesc}{int}{PySet_Discard}{PyObject *set, PyObject *key}
3184+ Return 1 if found and removed, 0 if not found (no action taken),
3185+ and -1 if an error is encountered. Does not raise \exception{KeyError}
3186+ for missing keys. Raise a \exception{TypeError} if the \var{key} is
3187+ unhashable. Unlike the Python \method{discard()} method, this function
3188+ does not automatically convert unhashable sets into temporary frozensets.
3189+ Raise \exception{PyExc_SystemError} if \var{set} is an not an instance
3190+ of \class{set} or its subtype.
3191+\end{cfuncdesc}
3192+
3193+\begin{cfuncdesc}{PyObject*}{PySet_Pop}{PyObject *set}
3194+ Return a new reference to an arbitrary object in the \var{set},
3195+ and removes the object from the \var{set}. Return \NULL{} on
3196+ failure. Raise \exception{KeyError} if the set is empty.
3197+ Raise a \exception{SystemError} if \var{set} is an not an instance
3198+ of \class{set} or its subtype.
3199+\end{cfuncdesc}
3200+
3201+\begin{cfuncdesc}{int}{PySet_Clear}{PyObject *set}
3202+ Empty an existing set of all elements.
3203+\end{cfuncdesc}
sys/src/cmd/python/Doc/api/exceptions.tex+442−0
@@ -0,0 +1,442 @@
1+\chapter{Exception Handling \label{exceptionHandling}}
2+
3+The functions described in this chapter will let you handle and raise Python
4+exceptions. It is important to understand some of the basics of
5+Python exception handling. It works somewhat like the
6+\UNIX{} \cdata{errno} variable: there is a global indicator (per
7+thread) of the last error that occurred. Most functions don't clear
8+this on success, but will set it to indicate the cause of the error on
9+failure. Most functions also return an error indicator, usually
10+\NULL{} if they are supposed to return a pointer, or \code{-1} if they
11+return an integer (exception: the \cfunction{PyArg_*()} functions
12+return \code{1} for success and \code{0} for failure).
13+
14+When a function must fail because some function it called failed, it
15+generally doesn't set the error indicator; the function it called
16+already set it. It is responsible for either handling the error and
17+clearing the exception or returning after cleaning up any resources it
18+holds (such as object references or memory allocations); it should
19+\emph{not} continue normally if it is not prepared to handle the
20+error. If returning due to an error, it is important to indicate to
21+the caller that an error has been set. If the error is not handled or
22+carefully propagated, additional calls into the Python/C API may not
23+behave as intended and may fail in mysterious ways.
24+
25+The error indicator consists of three Python objects corresponding to
26+\withsubitem{(in module sys)}{
27+ \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
28+the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
29+\code{sys.exc_traceback}. API functions exist to interact with the
30+error indicator in various ways. There is a separate error indicator
31+for each thread.
32+
33+% XXX Order of these should be more thoughtful.
34+% Either alphabetical or some kind of structure.
35+
36+\begin{cfuncdesc}{void}{PyErr_Print}{}
37+ Print a standard traceback to \code{sys.stderr} and clear the error
38+ indicator. Call this function only when the error indicator is
39+ set. (Otherwise it will cause a fatal error!)
40+\end{cfuncdesc}
41+
42+\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
43+ Test whether the error indicator is set. If set, return the
44+ exception \emph{type} (the first argument to the last call to one of
45+ the \cfunction{PyErr_Set*()} functions or to
46+ \cfunction{PyErr_Restore()}). If not set, return \NULL. You do
47+ not own a reference to the return value, so you do not need to
48+ \cfunction{Py_DECREF()} it. \note{Do not compare the return value
49+ to a specific exception; use \cfunction{PyErr_ExceptionMatches()}
50+ instead, shown below. (The comparison could easily fail since the
51+ exception may be an instance instead of a class, in the case of a
52+ class exception, or it may the a subclass of the expected
53+ exception.)}
54+\end{cfuncdesc}
55+
56+\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
57+ Equivalent to \samp{PyErr_GivenExceptionMatches(PyErr_Occurred(),
58+ \var{exc})}. This should only be called when an exception is
59+ actually set; a memory access violation will occur if no exception
60+ has been raised.
61+\end{cfuncdesc}
62+
63+\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
64+ Return true if the \var{given} exception matches the exception in
65+ \var{exc}. If \var{exc} is a class object, this also returns true
66+ when \var{given} is an instance of a subclass. If \var{exc} is a
67+ tuple, all exceptions in the tuple (and recursively in subtuples)
68+ are searched for a match. If \var{given} is \NULL, a memory access
69+ violation will occur.
70+\end{cfuncdesc}
71+
72+\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
73+ Under certain circumstances, the values returned by
74+ \cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning
75+ that \code{*\var{exc}} is a class object but \code{*\var{val}} is
76+ not an instance of the same class. This function can be used to
77+ instantiate the class in that case. If the values are already
78+ normalized, nothing happens. The delayed normalization is
79+ implemented to improve performance.
80+\end{cfuncdesc}
81+
82+\begin{cfuncdesc}{void}{PyErr_Clear}{}
83+ Clear the error indicator. If the error indicator is not set, there
84+ is no effect.
85+\end{cfuncdesc}
86+
87+\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
88+ PyObject **ptraceback}
89+ Retrieve the error indicator into three variables whose addresses
90+ are passed. If the error indicator is not set, set all three
91+ variables to \NULL. If it is set, it will be cleared and you own a
92+ reference to each object retrieved. The value and traceback object
93+ may be \NULL{} even when the type object is not. \note{This
94+ function is normally only used by code that needs to handle
95+ exceptions or by code that needs to save and restore the error
96+ indicator temporarily.}
97+\end{cfuncdesc}
98+
99+\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
100+ PyObject *traceback}
101+ Set the error indicator from the three objects. If the error
102+ indicator is already set, it is cleared first. If the objects are
103+ \NULL, the error indicator is cleared. Do not pass a \NULL{} type
104+ and non-\NULL{} value or traceback. The exception type should be a
105+ class. Do not pass an invalid exception type or value.
106+ (Violating these rules will cause subtle problems later.) This call
107+ takes away a reference to each object: you must own a reference to
108+ each object before the call and after the call you no longer own
109+ these references. (If you don't understand this, don't use this
110+ function. I warned you.) \note{This function is normally only used
111+ by code that needs to save and restore the error indicator
112+ temporarily; use \cfunction{PyErr_Fetch()} to save the current
113+ exception state.}
114+\end{cfuncdesc}
115+
116+\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, const char *message}
117+ This is the most common way to set the error indicator. The first
118+ argument specifies the exception type; it is normally one of the
119+ standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
120+ increment its reference count. The second argument is an error
121+ message; it is converted to a string object.
122+\end{cfuncdesc}
123+
124+\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
125+ This function is similar to \cfunction{PyErr_SetString()} but lets
126+ you specify an arbitrary Python object for the ``value'' of the
127+ exception.
128+\end{cfuncdesc}
129+
130+\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
131+ const char *format, \moreargs}
132+ This function sets the error indicator and returns \NULL.
133+ \var{exception} should be a Python exception (class, not
134+ an instance). \var{format} should be a string, containing format
135+ codes, similar to \cfunction{printf()}. The \code{width.precision}
136+ before a format code is parsed, but the width part is ignored.
137+
138+ % This should be exactly the same as the table in PyString_FromFormat.
139+ % One should just refer to the other.
140+
141+ % The descriptions for %zd and %zu are wrong, but the truth is complicated
142+ % because not all compilers support the %z width modifier -- we fake it
143+ % when necessary via interpolating PY_FORMAT_SIZE_T.
144+
145+ % %u, %lu, %zu should have "new in Python 2.5" blurbs.
146+
147+ \begin{tableiii}{l|l|l}{member}{Format Characters}{Type}{Comment}
148+ \lineiii{\%\%}{\emph{n/a}}{The literal \% character.}
149+ \lineiii{\%c}{int}{A single character, represented as an C int.}
150+ \lineiii{\%d}{int}{Exactly equivalent to \code{printf("\%d")}.}
151+ \lineiii{\%u}{unsigned int}{Exactly equivalent to \code{printf("\%u")}.}
152+ \lineiii{\%ld}{long}{Exactly equivalent to \code{printf("\%ld")}.}
153+ \lineiii{\%lu}{unsigned long}{Exactly equivalent to \code{printf("\%lu")}.}
154+ \lineiii{\%zd}{Py_ssize_t}{Exactly equivalent to \code{printf("\%zd")}.}
155+ \lineiii{\%zu}{size_t}{Exactly equivalent to \code{printf("\%zu")}.}
156+ \lineiii{\%i}{int}{Exactly equivalent to \code{printf("\%i")}.}
157+ \lineiii{\%x}{int}{Exactly equivalent to \code{printf("\%x")}.}
158+ \lineiii{\%s}{char*}{A null-terminated C character array.}
159+ \lineiii{\%p}{void*}{The hex representation of a C pointer.
160+ Mostly equivalent to \code{printf("\%p")} except that it is
161+ guaranteed to start with the literal \code{0x} regardless of
162+ what the platform's \code{printf} yields.}
163+ \end{tableiii}
164+
165+ An unrecognized format character causes all the rest of the format
166+ string to be copied as-is to the result string, and any extra
167+ arguments discarded.
168+\end{cfuncdesc}
169+
170+\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
171+ This is a shorthand for \samp{PyErr_SetObject(\var{type},
172+ Py_None)}.
173+\end{cfuncdesc}
174+
175+\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
176+ This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
177+ \var{message})}, where \var{message} indicates that a built-in
178+ operation was invoked with an illegal argument. It is mostly for
179+ internal use.
180+\end{cfuncdesc}
181+
182+\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
183+ This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
184+ returns \NULL{} so an object allocation function can write
185+ \samp{return PyErr_NoMemory();} when it runs out of memory.
186+\end{cfuncdesc}
187+
188+\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
189+ This is a convenience function to raise an exception when a C
190+ library function has returned an error and set the C variable
191+ \cdata{errno}. It constructs a tuple object whose first item is the
192+ integer \cdata{errno} value and whose second item is the
193+ corresponding error message (gotten from
194+ \cfunction{strerror()}\ttindex{strerror()}), and then calls
195+ \samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX, when
196+ the \cdata{errno} value is \constant{EINTR}, indicating an
197+ interrupted system call, this calls
198+ \cfunction{PyErr_CheckSignals()}, and if that set the error
199+ indicator, leaves it set to that. The function always returns
200+ \NULL, so a wrapper function around a system call can write
201+ \samp{return PyErr_SetFromErrno(\var{type});} when the system call
202+ returns an error.
203+\end{cfuncdesc}
204+
205+\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrnoWithFilename}{PyObject *type,
206+ const char *filename}
207+ Similar to \cfunction{PyErr_SetFromErrno()}, with the additional
208+ behavior that if \var{filename} is not \NULL, it is passed to the
209+ constructor of \var{type} as a third parameter. In the case of
210+ exceptions such as \exception{IOError} and \exception{OSError}, this
211+ is used to define the \member{filename} attribute of the exception
212+ instance.
213+\end{cfuncdesc}
214+
215+\begin{cfuncdesc}{PyObject*}{PyErr_SetFromWindowsErr}{int ierr}
216+ This is a convenience function to raise \exception{WindowsError}.
217+ If called with \var{ierr} of \cdata{0}, the error code returned by a
218+ call to \cfunction{GetLastError()} is used instead. It calls the
219+ Win32 function \cfunction{FormatMessage()} to retrieve the Windows
220+ description of error code given by \var{ierr} or
221+ \cfunction{GetLastError()}, then it constructs a tuple object whose
222+ first item is the \var{ierr} value and whose second item is the
223+ corresponding error message (gotten from
224+ \cfunction{FormatMessage()}), and then calls
225+ \samp{PyErr_SetObject(\var{PyExc_WindowsError}, \var{object})}.
226+ This function always returns \NULL.
227+ Availability: Windows.
228+\end{cfuncdesc}
229+
230+\begin{cfuncdesc}{PyObject*}{PyErr_SetExcFromWindowsErr}{PyObject *type,
231+ int ierr}
232+ Similar to \cfunction{PyErr_SetFromWindowsErr()}, with an additional
233+ parameter specifying the exception type to be raised.
234+ Availability: Windows.
235+ \versionadded{2.3}
236+\end{cfuncdesc}
237+
238+\begin{cfuncdesc}{PyObject*}{PyErr_SetFromWindowsErrWithFilename}{int ierr,
239+ const char *filename}
240+ Similar to \cfunction{PyErr_SetFromWindowsErr()}, with the
241+ additional behavior that if \var{filename} is not \NULL, it is
242+ passed to the constructor of \exception{WindowsError} as a third
243+ parameter.
244+ Availability: Windows.
245+\end{cfuncdesc}
246+
247+\begin{cfuncdesc}{PyObject*}{PyErr_SetExcFromWindowsErrWithFilename}
248+ {PyObject *type, int ierr, char *filename}
249+ Similar to \cfunction{PyErr_SetFromWindowsErrWithFilename()}, with
250+ an additional parameter specifying the exception type to be raised.
251+ Availability: Windows.
252+ \versionadded{2.3}
253+\end{cfuncdesc}
254+
255+\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
256+ This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
257+ \var{message})}, where \var{message} indicates that an internal
258+ operation (e.g. a Python/C API function) was invoked with an illegal
259+ argument. It is mostly for internal use.
260+\end{cfuncdesc}
261+
262+\begin{cfuncdesc}{int}{PyErr_WarnEx}{PyObject *category, char *message, int stacklevel}
263+ Issue a warning message. The \var{category} argument is a warning
264+ category (see below) or \NULL; the \var{message} argument is a
265+ message string. \var{stacklevel} is a positive number giving a
266+ number of stack frames; the warning will be issued from the
267+ currently executing line of code in that stack frame. A \var{stacklevel}
268+ of 1 is the function calling \cfunction{PyErr_WarnEx()}, 2 is
269+ the function above that, and so forth.
270+
271+ This function normally prints a warning message to \var{sys.stderr};
272+ however, it is also possible that the user has specified that
273+ warnings are to be turned into errors, and in that case this will
274+ raise an exception. It is also possible that the function raises an
275+ exception because of a problem with the warning machinery (the
276+ implementation imports the \module{warnings} module to do the heavy
277+ lifting). The return value is \code{0} if no exception is raised,
278+ or \code{-1} if an exception is raised. (It is not possible to
279+ determine whether a warning message is actually printed, nor what
280+ the reason is for the exception; this is intentional.) If an
281+ exception is raised, the caller should do its normal exception
282+ handling (for example, \cfunction{Py_DECREF()} owned references and
283+ return an error value).
284+
285+ Warning categories must be subclasses of \cdata{Warning}; the
286+ default warning category is \cdata{RuntimeWarning}. The standard
287+ Python warning categories are available as global variables whose
288+ names are \samp{PyExc_} followed by the Python exception name.
289+ These have the type \ctype{PyObject*}; they are all class objects.
290+ Their names are \cdata{PyExc_Warning}, \cdata{PyExc_UserWarning},
291+ \cdata{PyExc_UnicodeWarning}, \cdata{PyExc_DeprecationWarning},
292+ \cdata{PyExc_SyntaxWarning}, \cdata{PyExc_RuntimeWarning}, and
293+ \cdata{PyExc_FutureWarning}. \cdata{PyExc_Warning} is a subclass of
294+ \cdata{PyExc_Exception}; the other warning categories are subclasses
295+ of \cdata{PyExc_Warning}.
296+
297+ For information about warning control, see the documentation for the
298+ \module{warnings} module and the \programopt{-W} option in the
299+ command line documentation. There is no C API for warning control.
300+\end{cfuncdesc}
301+
302+\begin{cfuncdesc}{int}{PyErr_Warn}{PyObject *category, char *message}
303+ Issue a warning message. The \var{category} argument is a warning
304+ category (see below) or \NULL; the \var{message} argument is a
305+ message string. The warning will appear to be issued from the function
306+ calling \cfunction{PyErr_Warn()}, equivalent to calling
307+ \cfunction{PyErr_WarnEx()} with a \var{stacklevel} of 1.
308+
309+ Deprecated; use \cfunction{PyErr_WarnEx()} instead.
310+\end{cfuncdesc}
311+
312+\begin{cfuncdesc}{int}{PyErr_WarnExplicit}{PyObject *category,
313+ const char *message, const char *filename, int lineno,
314+ const char *module, PyObject *registry}
315+ Issue a warning message with explicit control over all warning
316+ attributes. This is a straightforward wrapper around the Python
317+ function \function{warnings.warn_explicit()}, see there for more
318+ information. The \var{module} and \var{registry} arguments may be
319+ set to \NULL{} to get the default effect described there.
320+\end{cfuncdesc}
321+
322+\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
323+ This function interacts with Python's signal handling. It checks
324+ whether a signal has been sent to the processes and if so, invokes
325+ the corresponding signal handler. If the
326+ \module{signal}\refbimodindex{signal} module is supported, this can
327+ invoke a signal handler written in Python. In all cases, the
328+ default effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
329+ \withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
330+ \exception{KeyboardInterrupt} exception. If an exception is raised
331+ the error indicator is set and the function returns \code{-1};
332+ otherwise the function returns \code{0}. The error indicator may or
333+ may not be cleared if it was previously set.
334+\end{cfuncdesc}
335+
336+\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
337+ This function simulates the effect of a
338+ \constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
339+ \cfunction{PyErr_CheckSignals()} is called,
340+ \withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
341+ \exception{KeyboardInterrupt} will be raised. It may be called
342+ without holding the interpreter lock.
343+ % XXX This was described as obsolete, but is used in
344+ % thread.interrupt_main() (used from IDLE), so it's still needed.
345+\end{cfuncdesc}
346+
347+\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
348+ PyObject *base,
349+ PyObject *dict}
350+ This utility function creates and returns a new exception object.
351+ The \var{name} argument must be the name of the new exception, a C
352+ string of the form \code{module.class}. The \var{base} and
353+ \var{dict} arguments are normally \NULL. This creates a class
354+ object derived from \exception{Exception} (accessible in C as
355+ \cdata{PyExc_Exception}).
356+
357+ The \member{__module__} attribute of the new class is set to the
358+ first part (up to the last dot) of the \var{name} argument, and the
359+ class name is set to the last part (after the last dot). The
360+ \var{base} argument can be used to specify alternate base classes;
361+ it can either be only one class or a tuple of classes.
362+ The \var{dict} argument can be used to specify a dictionary of class
363+ variables and methods.
364+\end{cfuncdesc}
365+
366+\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
367+ This utility function prints a warning message to \code{sys.stderr}
368+ when an exception has been set but it is impossible for the
369+ interpreter to actually raise the exception. It is used, for
370+ example, when an exception occurs in an \method{__del__()} method.
371+
372+ The function is called with a single argument \var{obj} that
373+ identifies the context in which the unraisable exception occurred.
374+ The repr of \var{obj} will be printed in the warning message.
375+\end{cfuncdesc}
376+
377+\section{Standard Exceptions \label{standardExceptions}}
378+
379+All standard Python exceptions are available as global variables whose
380+names are \samp{PyExc_} followed by the Python exception name. These
381+have the type \ctype{PyObject*}; they are all class objects. For
382+completeness, here are all the variables:
383+
384+\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
385+ \lineiii{PyExc_BaseException\ttindex{PyExc_BaseException}}{\exception{BaseException}}{(1), (4)}
386+ \lineiii{PyExc_Exception\ttindex{PyExc_Exception}}{\exception{Exception}}{(1)}
387+ \lineiii{PyExc_StandardError\ttindex{PyExc_StandardError}}{\exception{StandardError}}{(1)}
388+ \lineiii{PyExc_ArithmeticError\ttindex{PyExc_ArithmeticError}}{\exception{ArithmeticError}}{(1)}
389+ \lineiii{PyExc_LookupError\ttindex{PyExc_LookupError}}{\exception{LookupError}}{(1)}
390+ \lineiii{PyExc_AssertionError\ttindex{PyExc_AssertionError}}{\exception{AssertionError}}{}
391+ \lineiii{PyExc_AttributeError\ttindex{PyExc_AttributeError}}{\exception{AttributeError}}{}
392+ \lineiii{PyExc_EOFError\ttindex{PyExc_EOFError}}{\exception{EOFError}}{}
393+ \lineiii{PyExc_EnvironmentError\ttindex{PyExc_EnvironmentError}}{\exception{EnvironmentError}}{(1)}
394+ \lineiii{PyExc_FloatingPointError\ttindex{PyExc_FloatingPointError}}{\exception{FloatingPointError}}{}
395+ \lineiii{PyExc_IOError\ttindex{PyExc_IOError}}{\exception{IOError}}{}
396+ \lineiii{PyExc_ImportError\ttindex{PyExc_ImportError}}{\exception{ImportError}}{}
397+ \lineiii{PyExc_IndexError\ttindex{PyExc_IndexError}}{\exception{IndexError}}{}
398+ \lineiii{PyExc_KeyError\ttindex{PyExc_KeyError}}{\exception{KeyError}}{}
399+ \lineiii{PyExc_KeyboardInterrupt\ttindex{PyExc_KeyboardInterrupt}}{\exception{KeyboardInterrupt}}{}
400+ \lineiii{PyExc_MemoryError\ttindex{PyExc_MemoryError}}{\exception{MemoryError}}{}
401+ \lineiii{PyExc_NameError\ttindex{PyExc_NameError}}{\exception{NameError}}{}
402+ \lineiii{PyExc_NotImplementedError\ttindex{PyExc_NotImplementedError}}{\exception{NotImplementedError}}{}
403+ \lineiii{PyExc_OSError\ttindex{PyExc_OSError}}{\exception{OSError}}{}
404+ \lineiii{PyExc_OverflowError\ttindex{PyExc_OverflowError}}{\exception{OverflowError}}{}
405+ \lineiii{PyExc_ReferenceError\ttindex{PyExc_ReferenceError}}{\exception{ReferenceError}}{(2)}
406+ \lineiii{PyExc_RuntimeError\ttindex{PyExc_RuntimeError}}{\exception{RuntimeError}}{}
407+ \lineiii{PyExc_SyntaxError\ttindex{PyExc_SyntaxError}}{\exception{SyntaxError}}{}
408+ \lineiii{PyExc_SystemError\ttindex{PyExc_SystemError}}{\exception{SystemError}}{}
409+ \lineiii{PyExc_SystemExit\ttindex{PyExc_SystemExit}}{\exception{SystemExit}}{}
410+ \lineiii{PyExc_TypeError\ttindex{PyExc_TypeError}}{\exception{TypeError}}{}
411+ \lineiii{PyExc_ValueError\ttindex{PyExc_ValueError}}{\exception{ValueError}}{}
412+ \lineiii{PyExc_WindowsError\ttindex{PyExc_WindowsError}}{\exception{WindowsError}}{(3)}
413+ \lineiii{PyExc_ZeroDivisionError\ttindex{PyExc_ZeroDivisionError}}{\exception{ZeroDivisionError}}{}
414+\end{tableiii}
415+
416+\noindent
417+Notes:
418+\begin{description}
419+\item[(1)]
420+ This is a base class for other standard exceptions.
421+
422+\item[(2)]
423+ This is the same as \exception{weakref.ReferenceError}.
424+
425+\item[(3)]
426+ Only defined on Windows; protect code that uses this by testing that
427+ the preprocessor macro \code{MS_WINDOWS} is defined.
428+
429+\item[(4)]
430+ \versionadded{2.5}
431+\end{description}
432+
433+
434+\section{Deprecation of String Exceptions}
435+
436+All exceptions built into Python or provided in the standard library
437+are derived from \exception{BaseException}.
438+\withsubitem{(built-in exception)}{\ttindex{BaseException}}
439+
440+String exceptions are still supported in the interpreter to allow
441+existing code to run unmodified, but this will also change in a future
442+release.
sys/src/cmd/python/Doc/api/init.tex+884−0
@@ -0,0 +1,884 @@
1+\chapter{Initialization, Finalization, and Threads
2+ \label{initialization}}
3+
4+\begin{cfuncdesc}{void}{Py_Initialize}{}
5+ Initialize the Python interpreter. In an application embedding
6+ Python, this should be called before using any other Python/C API
7+ functions; with the exception of
8+ \cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
9+ \cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
10+ \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
11+ and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
12+ This initializes the table of loaded modules (\code{sys.modules}),
13+ and\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}
14+ creates the fundamental modules
15+ \module{__builtin__}\refbimodindex{__builtin__},
16+ \module{__main__}\refbimodindex{__main__} and
17+ \module{sys}\refbimodindex{sys}. It also initializes the module
18+ search\indexiii{module}{search}{path} path (\code{sys.path}).
19+ It does not set \code{sys.argv}; use
20+ \cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
21+ is a no-op when called for a second time (without calling
22+ \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is
23+ no return value; it is a fatal error if the initialization fails.
24+\end{cfuncdesc}
25+
26+\begin{cfuncdesc}{void}{Py_InitializeEx}{int initsigs}
27+ This function works like \cfunction{Py_Initialize()} if
28+ \var{initsigs} is 1. If \var{initsigs} is 0, it skips
29+ initialization registration of signal handlers, which
30+ might be useful when Python is embedded. \versionadded{2.4}
31+\end{cfuncdesc}
32+
33+\begin{cfuncdesc}{int}{Py_IsInitialized}{}
34+ Return true (nonzero) when the Python interpreter has been
35+ initialized, false (zero) if not. After \cfunction{Py_Finalize()}
36+ is called, this returns false until \cfunction{Py_Initialize()} is
37+ called again.
38+\end{cfuncdesc}
39+
40+\begin{cfuncdesc}{void}{Py_Finalize}{}
41+ Undo all initializations made by \cfunction{Py_Initialize()} and
42+ subsequent use of Python/C API functions, and destroy all
43+ sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that
44+ were created and not yet destroyed since the last call to
45+ \cfunction{Py_Initialize()}. Ideally, this frees all memory
46+ allocated by the Python interpreter. This is a no-op when called
47+ for a second time (without calling \cfunction{Py_Initialize()} again
48+ first). There is no return value; errors during finalization are
49+ ignored.
50+
51+ This function is provided for a number of reasons. An embedding
52+ application might want to restart Python without having to restart
53+ the application itself. An application that has loaded the Python
54+ interpreter from a dynamically loadable library (or DLL) might want
55+ to free all memory allocated by Python before unloading the
56+ DLL. During a hunt for memory leaks in an application a developer
57+ might want to free all memory allocated by Python before exiting
58+ from the application.
59+
60+ \strong{Bugs and caveats:} The destruction of modules and objects in
61+ modules is done in random order; this may cause destructors
62+ (\method{__del__()} methods) to fail when they depend on other
63+ objects (even functions) or modules. Dynamically loaded extension
64+ modules loaded by Python are not unloaded. Small amounts of memory
65+ allocated by the Python interpreter may not be freed (if you find a
66+ leak, please report it). Memory tied up in circular references
67+ between objects is not freed. Some memory allocated by extension
68+ modules may not be freed. Some extensions may not work properly if
69+ their initialization routine is called more than once; this can
70+ happen if an application calls \cfunction{Py_Initialize()} and
71+ \cfunction{Py_Finalize()} more than once.
72+\end{cfuncdesc}
73+
74+\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
75+ Create a new sub-interpreter. This is an (almost) totally separate
76+ environment for the execution of Python code. In particular, the
77+ new interpreter has separate, independent versions of all imported
78+ modules, including the fundamental modules
79+ \module{__builtin__}\refbimodindex{__builtin__},
80+ \module{__main__}\refbimodindex{__main__} and
81+ \module{sys}\refbimodindex{sys}. The table of loaded modules
82+ (\code{sys.modules}) and the module search path (\code{sys.path})
83+ are also separate. The new environment has no \code{sys.argv}
84+ variable. It has new standard I/O stream file objects
85+ \code{sys.stdin}, \code{sys.stdout} and \code{sys.stderr} (however
86+ these refer to the same underlying \ctype{FILE} structures in the C
87+ library).
88+ \withsubitem{(in module sys)}{
89+ \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
90+
91+ The return value points to the first thread state created in the new
92+ sub-interpreter. This thread state is made in the current thread
93+ state. Note that no actual thread is created; see the discussion of
94+ thread states below. If creation of the new interpreter is
95+ unsuccessful, \NULL{} is returned; no exception is set since the
96+ exception state is stored in the current thread state and there may
97+ not be a current thread state. (Like all other Python/C API
98+ functions, the global interpreter lock must be held before calling
99+ this function and is still held when it returns; however, unlike
100+ most other Python/C API functions, there needn't be a current thread
101+ state on entry.)
102+
103+ Extension modules are shared between (sub-)interpreters as follows:
104+ the first time a particular extension is imported, it is initialized
105+ normally, and a (shallow) copy of its module's dictionary is
106+ squirreled away. When the same extension is imported by another
107+ (sub-)interpreter, a new module is initialized and filled with the
108+ contents of this copy; the extension's \code{init} function is not
109+ called. Note that this is different from what happens when an
110+ extension is imported after the interpreter has been completely
111+ re-initialized by calling
112+ \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
113+ \cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
114+ the extension's \code{init\var{module}} function \emph{is} called
115+ again.
116+
117+ \strong{Bugs and caveats:} Because sub-interpreters (and the main
118+ interpreter) are part of the same process, the insulation between
119+ them isn't perfect --- for example, using low-level file operations
120+ like \withsubitem{(in module os)}{\ttindex{close()}}
121+ \function{os.close()} they can (accidentally or maliciously) affect
122+ each other's open files. Because of the way extensions are shared
123+ between (sub-)interpreters, some extensions may not work properly;
124+ this is especially likely when the extension makes use of (static)
125+ global variables, or when the extension manipulates its module's
126+ dictionary after its initialization. It is possible to insert
127+ objects created in one sub-interpreter into a namespace of another
128+ sub-interpreter; this should be done with great care to avoid
129+ sharing user-defined functions, methods, instances or classes
130+ between sub-interpreters, since import operations executed by such
131+ objects may affect the wrong (sub-)interpreter's dictionary of
132+ loaded modules. (XXX This is a hard-to-fix bug that will be
133+ addressed in a future release.)
134+
135+ Also note that the use of this functionality is incompatible with
136+ extension modules such as PyObjC and ctypes that use the
137+ \cfunction{PyGILState_*} APIs (and this is inherent in the way the
138+ \cfunction{PyGILState_*} functions work). Simple things may work,
139+ but confusing behavior will always be near.
140+\end{cfuncdesc}
141+
142+\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
143+ Destroy the (sub-)interpreter represented by the given thread state.
144+ The given thread state must be the current thread state. See the
145+ discussion of thread states below. When the call returns, the
146+ current thread state is \NULL. All thread states associated with
147+ this interpreter are destroyed. (The global interpreter lock must
148+ be held before calling this function and is still held when it
149+ returns.) \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will
150+ destroy all sub-interpreters that haven't been explicitly destroyed
151+ at that point.
152+\end{cfuncdesc}
153+
154+\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
155+ This function should be called before
156+ \cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
157+ for the first time, if it is called at all. It tells the
158+ interpreter the value of the \code{argv[0]} argument to the
159+ \cfunction{main()}\ttindex{main()} function of the program. This is
160+ used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some
161+ other functions below to find the Python run-time libraries relative
162+ to the interpreter executable. The default value is
163+ \code{'python'}. The argument should point to a zero-terminated
164+ character string in static storage whose contents will not change
165+ for the duration of the program's execution. No code in the Python
166+ interpreter will change the contents of this storage.
167+\end{cfuncdesc}
168+
169+\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
170+ Return the program name set with
171+ \cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
172+ default. The returned string points into static storage; the caller
173+ should not modify its value.
174+\end{cfuncdesc}
175+
176+\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
177+ Return the \emph{prefix} for installed platform-independent files.
178+ This is derived through a number of complicated rules from the
179+ program name set with \cfunction{Py_SetProgramName()} and some
180+ environment variables; for example, if the program name is
181+ \code{'/usr/local/bin/python'}, the prefix is \code{'/usr/local'}.
182+ The returned string points into static storage; the caller should
183+ not modify its value. This corresponds to the \makevar{prefix}
184+ variable in the top-level \file{Makefile} and the
185+ \longprogramopt{prefix} argument to the \program{configure} script
186+ at build time. The value is available to Python code as
187+ \code{sys.prefix}. It is only useful on \UNIX{}. See also the next
188+ function.
189+\end{cfuncdesc}
190+
191+\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
192+ Return the \emph{exec-prefix} for installed
193+ platform-\emph{de}pendent files. This is derived through a number
194+ of complicated rules from the program name set with
195+ \cfunction{Py_SetProgramName()} and some environment variables; for
196+ example, if the program name is \code{'/usr/local/bin/python'}, the
197+ exec-prefix is \code{'/usr/local'}. The returned string points into
198+ static storage; the caller should not modify its value. This
199+ corresponds to the \makevar{exec_prefix} variable in the top-level
200+ \file{Makefile} and the \longprogramopt{exec-prefix} argument to the
201+ \program{configure} script at build time. The value is available
202+ to Python code as \code{sys.exec_prefix}. It is only useful on
203+ \UNIX.
204+
205+ Background: The exec-prefix differs from the prefix when platform
206+ dependent files (such as executables and shared libraries) are
207+ installed in a different directory tree. In a typical installation,
208+ platform dependent files may be installed in the
209+ \file{/usr/local/plat} subtree while platform independent may be
210+ installed in \file{/usr/local}.
211+
212+ Generally speaking, a platform is a combination of hardware and
213+ software families, e.g. Sparc machines running the Solaris 2.x
214+ operating system are considered the same platform, but Intel
215+ machines running Solaris 2.x are another platform, and Intel
216+ machines running Linux are yet another platform. Different major
217+ revisions of the same operating system generally also form different
218+ platforms. Non-\UNIX{} operating systems are a different story; the
219+ installation strategies on those systems are so different that the
220+ prefix and exec-prefix are meaningless, and set to the empty string.
221+ Note that compiled Python bytecode files are platform independent
222+ (but not independent from the Python version by which they were
223+ compiled!).
224+
225+ System administrators will know how to configure the \program{mount}
226+ or \program{automount} programs to share \file{/usr/local} between
227+ platforms while having \file{/usr/local/plat} be a different
228+ filesystem for each platform.
229+\end{cfuncdesc}
230+
231+\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
232+ Return the full program name of the Python executable; this is
233+ computed as a side-effect of deriving the default module search path
234+ from the program name (set by
235+ \cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
236+ The returned string points into static storage; the caller should
237+ not modify its value. The value is available to Python code as
238+ \code{sys.executable}.
239+ \withsubitem{(in module sys)}{\ttindex{executable}}
240+\end{cfuncdesc}
241+
242+\begin{cfuncdesc}{char*}{Py_GetPath}{}
243+ \indexiii{module}{search}{path}
244+ Return the default module search path; this is computed from the
245+ program name (set by \cfunction{Py_SetProgramName()} above) and some
246+ environment variables. The returned string consists of a series of
247+ directory names separated by a platform dependent delimiter
248+ character. The delimiter character is \character{:} on \UNIX and Mac OS X,
249+ \character{;} on Windows. The returned string points into
250+ static storage; the caller should not modify its value. The value
251+ is available to Python code as the list
252+ \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}}, which
253+ may be modified to change the future search path for loaded
254+ modules.
255+
256+ % XXX should give the exact rules
257+\end{cfuncdesc}
258+
259+\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
260+ Return the version of this Python interpreter. This is a string
261+ that looks something like
262+
263+\begin{verbatim}
264+"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
265+\end{verbatim}
266+
267+ The first word (up to the first space character) is the current
268+ Python version; the first three characters are the major and minor
269+ version separated by a period. The returned string points into
270+ static storage; the caller should not modify its value. The value
271+ is available to Python code as \code{sys.version}.
272+ \withsubitem{(in module sys)}{\ttindex{version}}
273+\end{cfuncdesc}
274+
275+\begin{cfuncdesc}{const char*}{Py_GetBuildNumber}{}
276+ Return a string representing the Subversion revision that this Python
277+ executable was built from. This number is a string because it may contain a
278+ trailing 'M' if Python was built from a mixed revision source tree.
279+ \versionadded{2.5}
280+\end{cfuncdesc}
281+
282+\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
283+ Return the platform identifier for the current platform. On \UNIX,
284+ this is formed from the ``official'' name of the operating system,
285+ converted to lower case, followed by the major revision number;
286+ e.g., for Solaris 2.x, which is also known as SunOS 5.x, the value
287+ is \code{'sunos5'}. On Mac OS X, it is \code{'darwin'}. On Windows,
288+ it is \code{'win'}. The returned string points into static storage;
289+ the caller should not modify its value. The value is available to
290+ Python code as \code{sys.platform}.
291+ \withsubitem{(in module sys)}{\ttindex{platform}}
292+\end{cfuncdesc}
293+
294+\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
295+ Return the official copyright string for the current Python version,
296+ for example
297+
298+ \code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
299+
300+ The returned string points into static storage; the caller should
301+ not modify its value. The value is available to Python code as
302+ \code{sys.copyright}.
303+ \withsubitem{(in module sys)}{\ttindex{copyright}}
304+\end{cfuncdesc}
305+
306+\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
307+ Return an indication of the compiler used to build the current
308+ Python version, in square brackets, for example:
309+
310+\begin{verbatim}
311+"[GCC 2.7.2.2]"
312+\end{verbatim}
313+
314+ The returned string points into static storage; the caller should
315+ not modify its value. The value is available to Python code as part
316+ of the variable \code{sys.version}.
317+ \withsubitem{(in module sys)}{\ttindex{version}}
318+\end{cfuncdesc}
319+
320+\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
321+ Return information about the sequence number and build date and time
322+ of the current Python interpreter instance, for example
323+
324+\begin{verbatim}
325+"#67, Aug 1 1997, 22:34:28"
326+\end{verbatim}
327+
328+ The returned string points into static storage; the caller should
329+ not modify its value. The value is available to Python code as part
330+ of the variable \code{sys.version}.
331+ \withsubitem{(in module sys)}{\ttindex{version}}
332+\end{cfuncdesc}
333+
334+\begin{cfuncdesc}{void}{PySys_SetArgv}{int argc, char **argv}
335+ Set \code{sys.argv} based on \var{argc} and \var{argv}. These
336+ parameters are similar to those passed to the program's
337+ \cfunction{main()}\ttindex{main()} function with the difference that
338+ the first entry should refer to the script file to be executed
339+ rather than the executable hosting the Python interpreter. If there
340+ isn't a script that will be run, the first entry in \var{argv} can
341+ be an empty string. If this function fails to initialize
342+ \code{sys.argv}, a fatal condition is signalled using
343+ \cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
344+ \withsubitem{(in module sys)}{\ttindex{argv}}
345+ % XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
346+ % check w/ Guido.
347+\end{cfuncdesc}
348+
349+% XXX Other PySys thingies (doesn't really belong in this chapter)
350+
351+\section{Thread State and the Global Interpreter Lock
352+ \label{threads}}
353+
354+\index{global interpreter lock}
355+\index{interpreter lock}
356+\index{lock, interpreter}
357+
358+The Python interpreter is not fully thread safe. In order to support
359+multi-threaded Python programs, there's a global lock that must be
360+held by the current thread before it can safely access Python objects.
361+Without the lock, even the simplest operations could cause problems in
362+a multi-threaded program: for example, when two threads simultaneously
363+increment the reference count of the same object, the reference count
364+could end up being incremented only once instead of twice.
365+
366+Therefore, the rule exists that only the thread that has acquired the
367+global interpreter lock may operate on Python objects or call Python/C
368+API functions. In order to support multi-threaded Python programs,
369+the interpreter regularly releases and reacquires the lock --- by
370+default, every 100 bytecode instructions (this can be changed with
371+\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
372+\function{sys.setcheckinterval()}). The lock is also released and
373+reacquired around potentially blocking I/O operations like reading or
374+writing a file, so that other threads can run while the thread that
375+requests the I/O is waiting for the I/O operation to complete.
376+
377+The Python interpreter needs to keep some bookkeeping information
378+separate per thread --- for this it uses a data structure called
379+\ctype{PyThreadState}\ttindex{PyThreadState}. There's one global
380+variable, however: the pointer to the current
381+\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
382+thread packages have a way to store ``per-thread global data,''
383+Python's internal platform independent thread abstraction doesn't
384+support this yet. Therefore, the current thread state must be
385+manipulated explicitly.
386+
387+This is easy enough in most cases. Most code manipulating the global
388+interpreter lock has the following simple structure:
389+
390+\begin{verbatim}
391+Save the thread state in a local variable.
392+Release the interpreter lock.
393+...Do some blocking I/O operation...
394+Reacquire the interpreter lock.
395+Restore the thread state from the local variable.
396+\end{verbatim}
397+
398+This is so common that a pair of macros exists to simplify it:
399+
400+\begin{verbatim}
401+Py_BEGIN_ALLOW_THREADS
402+...Do some blocking I/O operation...
403+Py_END_ALLOW_THREADS
404+\end{verbatim}
405+
406+The
407+\csimplemacro{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS}
408+macro opens a new block and declares a hidden local variable; the
409+\csimplemacro{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS}
410+macro closes the block. Another advantage of using these two macros
411+is that when Python is compiled without thread support, they are
412+defined empty, thus saving the thread state and lock manipulations.
413+
414+When thread support is enabled, the block above expands to the
415+following code:
416+
417+\begin{verbatim}
418+ PyThreadState *_save;
419+
420+ _save = PyEval_SaveThread();
421+ ...Do some blocking I/O operation...
422+ PyEval_RestoreThread(_save);
423+\end{verbatim}
424+
425+Using even lower level primitives, we can get roughly the same effect
426+as follows:
427+
428+\begin{verbatim}
429+ PyThreadState *_save;
430+
431+ _save = PyThreadState_Swap(NULL);
432+ PyEval_ReleaseLock();
433+ ...Do some blocking I/O operation...
434+ PyEval_AcquireLock();
435+ PyThreadState_Swap(_save);
436+\end{verbatim}
437+
438+There are some subtle differences; in particular,
439+\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
440+and restores the value of the global variable
441+\cdata{errno}\ttindex{errno}, since the lock manipulation does not
442+guarantee that \cdata{errno} is left alone. Also, when thread support
443+is disabled,
444+\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
445+\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
446+case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
447+\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
448+available. This is done so that dynamically loaded extensions
449+compiled with thread support enabled can be loaded by an interpreter
450+that was compiled with disabled thread support.
451+
452+The global interpreter lock is used to protect the pointer to the
453+current thread state. When releasing the lock and saving the thread
454+state, the current thread state pointer must be retrieved before the
455+lock is released (since another thread could immediately acquire the
456+lock and store its own thread state in the global variable).
457+Conversely, when acquiring the lock and restoring the thread state,
458+the lock must be acquired before storing the thread state pointer.
459+
460+Why am I going on with so much detail about this? Because when
461+threads are created from C, they don't have the global interpreter
462+lock, nor is there a thread state data structure for them. Such
463+threads must bootstrap themselves into existence, by first creating a
464+thread state data structure, then acquiring the lock, and finally
465+storing their thread state pointer, before they can start using the
466+Python/C API. When they are done, they should reset the thread state
467+pointer, release the lock, and finally free their thread state data
468+structure.
469+
470+Beginning with version 2.3, threads can now take advantage of the
471+\cfunction{PyGILState_*()} functions to do all of the above
472+automatically. The typical idiom for calling into Python from a C
473+thread is now:
474+
475+\begin{verbatim}
476+ PyGILState_STATE gstate;
477+ gstate = PyGILState_Ensure();
478+
479+ /* Perform Python actions here. */
480+ result = CallSomeFunction();
481+ /* evaluate result */
482+
483+ /* Release the thread. No Python API allowed beyond this point. */
484+ PyGILState_Release(gstate);
485+\end{verbatim}
486+
487+Note that the \cfunction{PyGILState_*()} functions assume there is
488+only one global interpreter (created automatically by
489+\cfunction{Py_Initialize()}). Python still supports the creation of
490+additional interpreters (using \cfunction{Py_NewInterpreter()}), but
491+mixing multiple interpreters and the \cfunction{PyGILState_*()} API is
492+unsupported.
493+
494+\begin{ctypedesc}{PyInterpreterState}
495+ This data structure represents the state shared by a number of
496+ cooperating threads. Threads belonging to the same interpreter
497+ share their module administration and a few other internal items.
498+ There are no public members in this structure.
499+
500+ Threads belonging to different interpreters initially share nothing,
501+ except process state like available memory, open file descriptors
502+ and such. The global interpreter lock is also shared by all
503+ threads, regardless of to which interpreter they belong.
504+\end{ctypedesc}
505+
506+\begin{ctypedesc}{PyThreadState}
507+ This data structure represents the state of a single thread. The
508+ only public data member is \ctype{PyInterpreterState
509+ *}\member{interp}, which points to this thread's interpreter state.
510+\end{ctypedesc}
511+
512+\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
513+ Initialize and acquire the global interpreter lock. It should be
514+ called in the main thread before creating a second thread or
515+ engaging in any other thread operations such as
516+ \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
517+ \code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
518+ It is not needed before calling
519+ \cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
520+ \cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
521+
522+ This is a no-op when called for a second time. It is safe to call
523+ this function before calling
524+ \cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
525+
526+ When only the main thread exists, no lock operations are needed.
527+ This is a common situation (most Python programs do not use
528+ threads), and the lock operations slow the interpreter down a bit.
529+ Therefore, the lock is not created initially. This situation is
530+ equivalent to having acquired the lock: when there is only a single
531+ thread, all object accesses are safe. Therefore, when this function
532+ initializes the lock, it also acquires it. Before the Python
533+ \module{thread}\refbimodindex{thread} module creates a new thread,
534+ knowing that either it has the lock or the lock hasn't been created
535+ yet, it calls \cfunction{PyEval_InitThreads()}. When this call
536+ returns, it is guaranteed that the lock has been created and that the
537+ calling thread has acquired it.
538+
539+ It is \strong{not} safe to call this function when it is unknown
540+ which thread (if any) currently has the global interpreter lock.
541+
542+ This function is not available when thread support is disabled at
543+ compile time.
544+\end{cfuncdesc}
545+
546+\begin{cfuncdesc}{int}{PyEval_ThreadsInitialized}{}
547+ Returns a non-zero value if \cfunction{PyEval_InitThreads()} has been
548+ called. This function can be called without holding the lock, and
549+ therefore can be used to avoid calls to the locking API when running
550+ single-threaded. This function is not available when thread support
551+ is disabled at compile time. \versionadded{2.4}
552+\end{cfuncdesc}
553+
554+\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
555+ Acquire the global interpreter lock. The lock must have been
556+ created earlier. If this thread already has the lock, a deadlock
557+ ensues. This function is not available when thread support is
558+ disabled at compile time.
559+\end{cfuncdesc}
560+
561+\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
562+ Release the global interpreter lock. The lock must have been
563+ created earlier. This function is not available when thread support
564+ is disabled at compile time.
565+\end{cfuncdesc}
566+
567+\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
568+ Acquire the global interpreter lock and set the current thread
569+ state to \var{tstate}, which should not be \NULL. The lock must
570+ have been created earlier. If this thread already has the lock,
571+ deadlock ensues. This function is not available when thread support
572+ is disabled at compile time.
573+\end{cfuncdesc}
574+
575+\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
576+ Reset the current thread state to \NULL{} and release the global
577+ interpreter lock. The lock must have been created earlier and must
578+ be held by the current thread. The \var{tstate} argument, which
579+ must not be \NULL, is only used to check that it represents the
580+ current thread state --- if it isn't, a fatal error is reported.
581+ This function is not available when thread support is disabled at
582+ compile time.
583+\end{cfuncdesc}
584+
585+\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
586+ Release the interpreter lock (if it has been created and thread
587+ support is enabled) and reset the thread state to \NULL, returning
588+ the previous thread state (which is not \NULL). If the lock has
589+ been created, the current thread must have acquired it. (This
590+ function is available even when thread support is disabled at
591+ compile time.)
592+\end{cfuncdesc}
593+
594+\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
595+ Acquire the interpreter lock (if it has been created and thread
596+ support is enabled) and set the thread state to \var{tstate}, which
597+ must not be \NULL. If the lock has been created, the current thread
598+ must not have acquired it, otherwise deadlock ensues. (This
599+ function is available even when thread support is disabled at
600+ compile time.)
601+\end{cfuncdesc}
602+
603+The following macros are normally used without a trailing semicolon;
604+look for example usage in the Python source distribution.
605+
606+\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
607+ This macro expands to
608+ \samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
609+ Note that it contains an opening brace; it must be matched with a
610+ following \csimplemacro{Py_END_ALLOW_THREADS} macro. See above for
611+ further discussion of this macro. It is a no-op when thread support
612+ is disabled at compile time.
613+\end{csimplemacrodesc}
614+
615+\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
616+ This macro expands to \samp{PyEval_RestoreThread(_save); \}}.
617+ Note that it contains a closing brace; it must be matched with an
618+ earlier \csimplemacro{Py_BEGIN_ALLOW_THREADS} macro. See above for
619+ further discussion of this macro. It is a no-op when thread support
620+ is disabled at compile time.
621+\end{csimplemacrodesc}
622+
623+\begin{csimplemacrodesc}{Py_BLOCK_THREADS}
624+ This macro expands to \samp{PyEval_RestoreThread(_save);}: it is
625+ equivalent to \csimplemacro{Py_END_ALLOW_THREADS} without the
626+ closing brace. It is a no-op when thread support is disabled at
627+ compile time.
628+\end{csimplemacrodesc}
629+
630+\begin{csimplemacrodesc}{Py_UNBLOCK_THREADS}
631+ This macro expands to \samp{_save = PyEval_SaveThread();}: it is
632+ equivalent to \csimplemacro{Py_BEGIN_ALLOW_THREADS} without the
633+ opening brace and variable declaration. It is a no-op when thread
634+ support is disabled at compile time.
635+\end{csimplemacrodesc}
636+
637+All of the following functions are only available when thread support
638+is enabled at compile time, and must be called only when the
639+interpreter lock has been created.
640+
641+\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
642+ Create a new interpreter state object. The interpreter lock need
643+ not be held, but may be held if it is necessary to serialize calls
644+ to this function.
645+\end{cfuncdesc}
646+
647+\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
648+ Reset all information in an interpreter state object. The
649+ interpreter lock must be held.
650+\end{cfuncdesc}
651+
652+\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
653+ Destroy an interpreter state object. The interpreter lock need not
654+ be held. The interpreter state must have been reset with a previous
655+ call to \cfunction{PyInterpreterState_Clear()}.
656+\end{cfuncdesc}
657+
658+\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
659+ Create a new thread state object belonging to the given interpreter
660+ object. The interpreter lock need not be held, but may be held if
661+ it is necessary to serialize calls to this function.
662+\end{cfuncdesc}
663+
664+\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
665+ Reset all information in a thread state object. The interpreter lock
666+ must be held.
667+\end{cfuncdesc}
668+
669+\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
670+ Destroy a thread state object. The interpreter lock need not be
671+ held. The thread state must have been reset with a previous call to
672+ \cfunction{PyThreadState_Clear()}.
673+\end{cfuncdesc}
674+
675+\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
676+ Return the current thread state. The interpreter lock must be
677+ held. When the current thread state is \NULL, this issues a fatal
678+ error (so that the caller needn't check for \NULL).
679+\end{cfuncdesc}
680+
681+\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
682+ Swap the current thread state with the thread state given by the
683+ argument \var{tstate}, which may be \NULL. The interpreter lock
684+ must be held.
685+\end{cfuncdesc}
686+
687+\begin{cfuncdesc}{PyObject*}{PyThreadState_GetDict}{}
688+ Return a dictionary in which extensions can store thread-specific
689+ state information. Each extension should use a unique key to use to
690+ store state in the dictionary. It is okay to call this function
691+ when no current thread state is available.
692+ If this function returns \NULL, no exception has been raised and the
693+ caller should assume no current thread state is available.
694+ \versionchanged[Previously this could only be called when a current
695+ thread is active, and \NULL{} meant that an exception was raised]{2.3}
696+\end{cfuncdesc}
697+
698+\begin{cfuncdesc}{int}{PyThreadState_SetAsyncExc}{long id, PyObject *exc}
699+ Asynchronously raise an exception in a thread.
700+ The \var{id} argument is the thread id of the target thread;
701+ \var{exc} is the exception object to be raised.
702+ This function does not steal any references to \var{exc}.
703+ To prevent naive misuse, you must write your own C extension
704+ to call this. Must be called with the GIL held.
705+ Returns the number of thread states modified; this is normally one, but
706+ will be zero if the thread id isn't found. If \var{exc} is
707+ \constant{NULL}, the pending exception (if any) for the thread is cleared.
708+ This raises no exceptions.
709+ \versionadded{2.3}
710+\end{cfuncdesc}
711+
712+\begin{cfuncdesc}{PyGILState_STATE}{PyGILState_Ensure}{}
713+Ensure that the current thread is ready to call the Python C API
714+regardless of the current state of Python, or of its thread lock.
715+This may be called as many times as desired by a thread as long as
716+each call is matched with a call to \cfunction{PyGILState_Release()}.
717+In general, other thread-related APIs may be used between
718+\cfunction{PyGILState_Ensure()} and \cfunction{PyGILState_Release()}
719+calls as long as the thread state is restored to its previous state
720+before the Release(). For example, normal usage of the
721+\csimplemacro{Py_BEGIN_ALLOW_THREADS} and
722+\csimplemacro{Py_END_ALLOW_THREADS} macros is acceptable.
723+
724+The return value is an opaque "handle" to the thread state when
725+\cfunction{PyGILState_Acquire()} was called, and must be passed to
726+\cfunction{PyGILState_Release()} to ensure Python is left in the same
727+state. Even though recursive calls are allowed, these handles
728+\emph{cannot} be shared - each unique call to
729+\cfunction{PyGILState_Ensure} must save the handle for its call to
730+\cfunction{PyGILState_Release}.
731+
732+When the function returns, the current thread will hold the GIL.
733+Failure is a fatal error.
734+ \versionadded{2.3}
735+\end{cfuncdesc}
736+
737+\begin{cfuncdesc}{void}{PyGILState_Release}{PyGILState_STATE}
738+Release any resources previously acquired. After this call, Python's
739+state will be the same as it was prior to the corresponding
740+\cfunction{PyGILState_Ensure} call (but generally this state will be
741+unknown to the caller, hence the use of the GILState API.)
742+
743+Every call to \cfunction{PyGILState_Ensure()} must be matched by a call to
744+\cfunction{PyGILState_Release()} on the same thread.
745+ \versionadded{2.3}
746+\end{cfuncdesc}
747+
748+
749+\section{Profiling and Tracing \label{profiling}}
750+
751+\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
752+
753+The Python interpreter provides some low-level support for attaching
754+profiling and execution tracing facilities. These are used for
755+profiling, debugging, and coverage analysis tools.
756+
757+Starting with Python 2.2, the implementation of this facility was
758+substantially revised, and an interface from C was added. This C
759+interface allows the profiling or tracing code to avoid the overhead
760+of calling through Python-level callable objects, making a direct C
761+function call instead. The essential attributes of the facility have
762+not changed; the interface allows trace functions to be installed
763+per-thread, and the basic events reported to the trace function are
764+the same as had been reported to the Python-level trace functions in
765+previous versions.
766+
767+\begin{ctypedesc}[Py_tracefunc]{int (*Py_tracefunc)(PyObject *obj,
768+ PyFrameObject *frame, int what,
769+ PyObject *arg)}
770+ The type of the trace function registered using
771+ \cfunction{PyEval_SetProfile()} and \cfunction{PyEval_SetTrace()}.
772+ The first parameter is the object passed to the registration
773+ function as \var{obj}, \var{frame} is the frame object to which the
774+ event pertains, \var{what} is one of the constants
775+ \constant{PyTrace_CALL}, \constant{PyTrace_EXCEPTION},
776+ \constant{PyTrace_LINE}, \constant{PyTrace_RETURN},
777+ \constant{PyTrace_C_CALL}, \constant{PyTrace_C_EXCEPTION},
778+ or \constant{PyTrace_C_RETURN}, and \var{arg}
779+ depends on the value of \var{what}:
780+
781+ \begin{tableii}{l|l}{constant}{Value of \var{what}}{Meaning of \var{arg}}
782+ \lineii{PyTrace_CALL}{Always \NULL.}
783+ \lineii{PyTrace_EXCEPTION}{Exception information as returned by
784+ \function{sys.exc_info()}.}
785+ \lineii{PyTrace_LINE}{Always \NULL.}
786+ \lineii{PyTrace_RETURN}{Value being returned to the caller.}
787+ \lineii{PyTrace_C_CALL}{Name of function being called.}
788+ \lineii{PyTrace_C_EXCEPTION}{Always \NULL.}
789+ \lineii{PyTrace_C_RETURN}{Always \NULL.}
790+ \end{tableii}
791+\end{ctypedesc}
792+
793+\begin{cvardesc}{int}{PyTrace_CALL}
794+ The value of the \var{what} parameter to a \ctype{Py_tracefunc}
795+ function when a new call to a function or method is being reported,
796+ or a new entry into a generator. Note that the creation of the
797+ iterator for a generator function is not reported as there is no
798+ control transfer to the Python bytecode in the corresponding frame.
799+\end{cvardesc}
800+
801+\begin{cvardesc}{int}{PyTrace_EXCEPTION}
802+ The value of the \var{what} parameter to a \ctype{Py_tracefunc}
803+ function when an exception has been raised. The callback function
804+ is called with this value for \var{what} when after any bytecode is
805+ processed after which the exception becomes set within the frame
806+ being executed. The effect of this is that as exception propagation
807+ causes the Python stack to unwind, the callback is called upon
808+ return to each frame as the exception propagates. Only trace
809+ functions receives these events; they are not needed by the
810+ profiler.
811+\end{cvardesc}
812+
813+\begin{cvardesc}{int}{PyTrace_LINE}
814+ The value passed as the \var{what} parameter to a trace function
815+ (but not a profiling function) when a line-number event is being
816+ reported.
817+\end{cvardesc}
818+
819+\begin{cvardesc}{int}{PyTrace_RETURN}
820+ The value for the \var{what} parameter to \ctype{Py_tracefunc}
821+ functions when a call is returning without propagating an exception.
822+\end{cvardesc}
823+
824+\begin{cvardesc}{int}{PyTrace_C_CALL}
825+ The value for the \var{what} parameter to \ctype{Py_tracefunc}
826+ functions when a C function is about to be called.
827+\end{cvardesc}
828+
829+\begin{cvardesc}{int}{PyTrace_C_EXCEPTION}
830+ The value for the \var{what} parameter to \ctype{Py_tracefunc}
831+ functions when a C function has thrown an exception.
832+\end{cvardesc}
833+
834+\begin{cvardesc}{int}{PyTrace_C_RETURN}
835+ The value for the \var{what} parameter to \ctype{Py_tracefunc}
836+ functions when a C function has returned.
837+\end{cvardesc}
838+
839+\begin{cfuncdesc}{void}{PyEval_SetProfile}{Py_tracefunc func, PyObject *obj}
840+ Set the profiler function to \var{func}. The \var{obj} parameter is
841+ passed to the function as its first parameter, and may be any Python
842+ object, or \NULL. If the profile function needs to maintain state,
843+ using a different value for \var{obj} for each thread provides a
844+ convenient and thread-safe place to store it. The profile function
845+ is called for all monitored events except the line-number events.
846+\end{cfuncdesc}
847+
848+\begin{cfuncdesc}{void}{PyEval_SetTrace}{Py_tracefunc func, PyObject *obj}
849+ Set the tracing function to \var{func}. This is similar to
850+ \cfunction{PyEval_SetProfile()}, except the tracing function does
851+ receive line-number events.
852+\end{cfuncdesc}
853+
854+
855+\section{Advanced Debugger Support \label{advanced-debugging}}
856+\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
857+
858+These functions are only intended to be used by advanced debugging
859+tools.
860+
861+\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Head}{}
862+ Return the interpreter state object at the head of the list of all
863+ such objects.
864+ \versionadded{2.2}
865+\end{cfuncdesc}
866+
867+\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Next}{PyInterpreterState *interp}
868+ Return the next interpreter state object after \var{interp} from the
869+ list of all such objects.
870+ \versionadded{2.2}
871+\end{cfuncdesc}
872+
873+\begin{cfuncdesc}{PyThreadState *}{PyInterpreterState_ThreadHead}{PyInterpreterState *interp}
874+ Return the a pointer to the first \ctype{PyThreadState} object in
875+ the list of threads associated with the interpreter \var{interp}.
876+ \versionadded{2.2}
877+\end{cfuncdesc}
878+
879+\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Next}{PyThreadState *tstate}
880+ Return the next thread state object after \var{tstate} from the list
881+ of all such objects belonging to the same \ctype{PyInterpreterState}
882+ object.
883+ \versionadded{2.2}
884+\end{cfuncdesc}
sys/src/cmd/python/Doc/api/intro.tex+627−0
@@ -0,0 +1,627 @@
1+\chapter{Introduction \label{intro}}
2+
3+
4+The Application Programmer's Interface to Python gives C and
5+\Cpp{} programmers access to the Python interpreter at a variety of
6+levels. The API is equally usable from \Cpp, but for brevity it is
7+generally referred to as the Python/C API. There are two
8+fundamentally different reasons for using the Python/C API. The first
9+reason is to write \emph{extension modules} for specific purposes;
10+these are C modules that extend the Python interpreter. This is
11+probably the most common use. The second reason is to use Python as a
12+component in a larger application; this technique is generally
13+referred to as \dfn{embedding} Python in an application.
14+
15+Writing an extension module is a relatively well-understood process,
16+where a ``cookbook'' approach works well. There are several tools
17+that automate the process to some extent. While people have embedded
18+Python in other applications since its early existence, the process of
19+embedding Python is less straightforward than writing an extension.
20+
21+Many API functions are useful independent of whether you're embedding
22+or extending Python; moreover, most applications that embed Python
23+will need to provide a custom extension as well, so it's probably a
24+good idea to become familiar with writing an extension before
25+attempting to embed Python in a real application.
26+
27+
28+\section{Include Files \label{includes}}
29+
30+All function, type and macro definitions needed to use the Python/C
31+API are included in your code by the following line:
32+
33+\begin{verbatim}
34+#include "Python.h"
35+\end{verbatim}
36+
37+This implies inclusion of the following standard headers:
38+\code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>},
39+\code{<limits.h>}, and \code{<stdlib.h>} (if available).
40+
41+\begin{notice}[warning]
42+ Since Python may define some pre-processor definitions which affect
43+ the standard headers on some systems, you \emph{must} include
44+ \file{Python.h} before any standard headers are included.
45+\end{notice}
46+
47+All user visible names defined by Python.h (except those defined by
48+the included standard headers) have one of the prefixes \samp{Py} or
49+\samp{_Py}. Names beginning with \samp{_Py} are for internal use by
50+the Python implementation and should not be used by extension writers.
51+Structure member names do not have a reserved prefix.
52+
53+\strong{Important:} user code should never define names that begin
54+with \samp{Py} or \samp{_Py}. This confuses the reader, and
55+jeopardizes the portability of the user code to future Python
56+versions, which may define additional names beginning with one of
57+these prefixes.
58+
59+The header files are typically installed with Python. On \UNIX, these
60+are located in the directories
61+\file{\envvar{prefix}/include/python\var{version}/} and
62+\file{\envvar{exec_prefix}/include/python\var{version}/}, where
63+\envvar{prefix} and \envvar{exec_prefix} are defined by the
64+corresponding parameters to Python's \program{configure} script and
65+\var{version} is \code{sys.version[:3]}. On Windows, the headers are
66+installed in \file{\envvar{prefix}/include}, where \envvar{prefix} is
67+the installation directory specified to the installer.
68+
69+To include the headers, place both directories (if different) on your
70+compiler's search path for includes. Do \emph{not} place the parent
71+directories on the search path and then use
72+\samp{\#include <python\shortversion/Python.h>}; this will break on
73+multi-platform builds since the platform independent headers under
74+\envvar{prefix} include the platform specific headers from
75+\envvar{exec_prefix}.
76+
77+\Cpp{} users should note that though the API is defined entirely using
78+C, the header files do properly declare the entry points to be
79+\code{extern "C"}, so there is no need to do anything special to use
80+the API from \Cpp.
81+
82+
83+\section{Objects, Types and Reference Counts \label{objects}}
84+
85+Most Python/C API functions have one or more arguments as well as a
86+return value of type \ctype{PyObject*}. This type is a pointer
87+to an opaque data type representing an arbitrary Python
88+object. Since all Python object types are treated the same way by the
89+Python language in most situations (e.g., assignments, scope rules,
90+and argument passing), it is only fitting that they should be
91+represented by a single C type. Almost all Python objects live on the
92+heap: you never declare an automatic or static variable of type
93+\ctype{PyObject}, only pointer variables of type \ctype{PyObject*} can
94+be declared. The sole exception are the type objects\obindex{type};
95+since these must never be deallocated, they are typically static
96+\ctype{PyTypeObject} objects.
97+
98+All Python objects (even Python integers) have a \dfn{type} and a
99+\dfn{reference count}. An object's type determines what kind of object
100+it is (e.g., an integer, a list, or a user-defined function; there are
101+many more as explained in the \citetitle[../ref/ref.html]{Python
102+Reference Manual}). For each of the well-known types there is a macro
103+to check whether an object is of that type; for instance,
104+\samp{PyList_Check(\var{a})} is true if (and only if) the object
105+pointed to by \var{a} is a Python list.
106+
107+
108+\subsection{Reference Counts \label{refcounts}}
109+
110+The reference count is important because today's computers have a
111+finite (and often severely limited) memory size; it counts how many
112+different places there are that have a reference to an object. Such a
113+place could be another object, or a global (or static) C variable, or
114+a local variable in some C function. When an object's reference count
115+becomes zero, the object is deallocated. If it contains references to
116+other objects, their reference count is decremented. Those other
117+objects may be deallocated in turn, if this decrement makes their
118+reference count become zero, and so on. (There's an obvious problem
119+with objects that reference each other here; for now, the solution is
120+``don't do that.'')
121+
122+Reference counts are always manipulated explicitly. The normal way is
123+to use the macro \cfunction{Py_INCREF()}\ttindex{Py_INCREF()} to
124+increment an object's reference count by one, and
125+\cfunction{Py_DECREF()}\ttindex{Py_DECREF()} to decrement it by
126+one. The \cfunction{Py_DECREF()} macro is considerably more complex
127+than the incref one, since it must check whether the reference count
128+becomes zero and then cause the object's deallocator to be called.
129+The deallocator is a function pointer contained in the object's type
130+structure. The type-specific deallocator takes care of decrementing
131+the reference counts for other objects contained in the object if this
132+is a compound object type, such as a list, as well as performing any
133+additional finalization that's needed. There's no chance that the
134+reference count can overflow; at least as many bits are used to hold
135+the reference count as there are distinct memory locations in virtual
136+memory (assuming \code{sizeof(long) >= sizeof(char*)}). Thus, the
137+reference count increment is a simple operation.
138+
139+It is not necessary to increment an object's reference count for every
140+local variable that contains a pointer to an object. In theory, the
141+object's reference count goes up by one when the variable is made to
142+point to it and it goes down by one when the variable goes out of
143+scope. However, these two cancel each other out, so at the end the
144+reference count hasn't changed. The only real reason to use the
145+reference count is to prevent the object from being deallocated as
146+long as our variable is pointing to it. If we know that there is at
147+least one other reference to the object that lives at least as long as
148+our variable, there is no need to increment the reference count
149+temporarily. An important situation where this arises is in objects
150+that are passed as arguments to C functions in an extension module
151+that are called from Python; the call mechanism guarantees to hold a
152+reference to every argument for the duration of the call.
153+
154+However, a common pitfall is to extract an object from a list and
155+hold on to it for a while without incrementing its reference count.
156+Some other operation might conceivably remove the object from the
157+list, decrementing its reference count and possible deallocating it.
158+The real danger is that innocent-looking operations may invoke
159+arbitrary Python code which could do this; there is a code path which
160+allows control to flow back to the user from a \cfunction{Py_DECREF()},
161+so almost any operation is potentially dangerous.
162+
163+A safe approach is to always use the generic operations (functions
164+whose name begins with \samp{PyObject_}, \samp{PyNumber_},
165+\samp{PySequence_} or \samp{PyMapping_}). These operations always
166+increment the reference count of the object they return. This leaves
167+the caller with the responsibility to call
168+\cfunction{Py_DECREF()} when they are done with the result; this soon
169+becomes second nature.
170+
171+
172+\subsubsection{Reference Count Details \label{refcountDetails}}
173+
174+The reference count behavior of functions in the Python/C API is best
175+explained in terms of \emph{ownership of references}. Ownership
176+pertains to references, never to objects (objects are not owned: they
177+are always shared). "Owning a reference" means being responsible for
178+calling Py_DECREF on it when the reference is no longer needed.
179+Ownership can also be transferred, meaning that the code that receives
180+ownership of the reference then becomes responsible for eventually
181+decref'ing it by calling \cfunction{Py_DECREF()} or
182+\cfunction{Py_XDECREF()} when it's no longer needed---or passing on
183+this responsibility (usually to its caller).
184+When 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.
188+
189+Conversely, when a calling 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. \emph{Stealing a reference}
192+means that when you pass a reference to a function, that function
193+assumes that it now owns that reference, and you are not responsible
194+for it any longer.
195+
196+Few functions steal references; the two notable exceptions are
197+\cfunction{PyList_SetItem()}\ttindex{PyList_SetItem()} and
198+\cfunction{PyTuple_SetItem()}\ttindex{PyTuple_SetItem()}, which
199+steal a reference to the item (but not to the tuple or list into which
200+the item is put!). These functions were designed to steal a reference
201+because of a common idiom for populating a tuple or list with newly
202+created objects; for example, the code to create the tuple \code{(1,
203+2, "three")} could look like this (forgetting about error handling for
204+the moment; a better way to code this is shown below):
205+
206+\begin{verbatim}
207+PyObject *t;
208+
209+t = PyTuple_New(3);
210+PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
211+PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
212+PyTuple_SetItem(t, 2, PyString_FromString("three"));
213+\end{verbatim}
214+
215+Here, \cfunction{PyInt_FromLong()} returns a new reference which is
216+immediately stolen by \cfunction{PyTuple_SetItem()}. When you want to
217+keep using an object although the reference to it will be stolen,
218+use \cfunction{Py_INCREF()} to grab another reference before calling the
219+reference-stealing function.
220+
221+Incidentally, \cfunction{PyTuple_SetItem()} is the \emph{only} way to
222+set tuple items; \cfunction{PySequence_SetItem()} and
223+\cfunction{PyObject_SetItem()} refuse to do this since tuples are an
224+immutable data type. You should only use
225+\cfunction{PyTuple_SetItem()} for tuples that you are creating
226+yourself.
227+
228+Equivalent code for populating a list can be written using
229+\cfunction{PyList_New()} and \cfunction{PyList_SetItem()}.
230+
231+However, in practice, you will rarely use these ways of
232+creating and populating a tuple or list. There's a generic function,
233+\cfunction{Py_BuildValue()}, that can create most common objects from
234+C values, directed by a \dfn{format string}. For example, the
235+above two blocks of code could be replaced by the following (which
236+also takes care of the error checking):
237+
238+\begin{verbatim}
239+PyObject *tuple, *list;
240+
241+tuple = Py_BuildValue("(iis)", 1, 2, "three");
242+list = Py_BuildValue("[iis]", 1, 2, "three");
243+\end{verbatim}
244+
245+It is much more common to use \cfunction{PyObject_SetItem()} and
246+friends with items whose references you are only borrowing, like
247+arguments that were passed in to the function you are writing. In
248+that case, their behaviour regarding reference counts is much saner,
249+since you don't have to increment a reference count so you can give a
250+reference away (``have it be stolen''). For example, this function
251+sets all items of a list (actually, any mutable sequence) to a given
252+item:
253+
254+\begin{verbatim}
255+int
256+set_all(PyObject *target, PyObject *item)
257+{
258+ int i, n;
259+
260+ n = PyObject_Length(target);
261+ if (n < 0)
262+ return -1;
263+ for (i = 0; i < n; i++) {
264+ PyObject *index = PyInt_FromLong(i);
265+ if (!index)
266+ return -1;
267+ if (PyObject_SetItem(target, index, item) < 0)
268+ return -1;
269+ Py_DECREF(index);
270+ }
271+ return 0;
272+}
273+\end{verbatim}
274+\ttindex{set_all()}
275+
276+The situation is slightly different for function return values.
277+While passing a reference to most functions does not change your
278+ownership responsibilities for that reference, many functions that
279+return a reference to an object give you ownership of the reference.
280+The reason is simple: in many cases, the returned object is created
281+on the fly, and the reference you get is the only reference to the
282+object. Therefore, the generic functions that return object
283+references, like \cfunction{PyObject_GetItem()} and
284+\cfunction{PySequence_GetItem()}, always return a new reference (the
285+caller becomes the owner of the reference).
286+
287+It is important to realize that whether you own a reference returned
288+by a function depends on which function you call only --- \emph{the
289+plumage} (the type of the object passed as an
290+argument to the function) \emph{doesn't enter into it!} Thus, if you
291+extract an item from a list using \cfunction{PyList_GetItem()}, you
292+don't own the reference --- but if you obtain the same item from the
293+same list using \cfunction{PySequence_GetItem()} (which happens to
294+take exactly the same arguments), you do own a reference to the
295+returned object.
296+
297+Here is an example of how you could write a function that computes the
298+sum of the items in a list of integers; once using
299+\cfunction{PyList_GetItem()}\ttindex{PyList_GetItem()}, and once using
300+\cfunction{PySequence_GetItem()}\ttindex{PySequence_GetItem()}.
301+
302+\begin{verbatim}
303+long
304+sum_list(PyObject *list)
305+{
306+ int i, n;
307+ long total = 0;
308+ PyObject *item;
309+
310+ n = PyList_Size(list);
311+ if (n < 0)
312+ return -1; /* Not a list */
313+ for (i = 0; i < n; i++) {
314+ item = PyList_GetItem(list, i); /* Can't fail */
315+ if (!PyInt_Check(item)) continue; /* Skip non-integers */
316+ total += PyInt_AsLong(item);
317+ }
318+ return total;
319+}
320+\end{verbatim}
321+\ttindex{sum_list()}
322+
323+\begin{verbatim}
324+long
325+sum_sequence(PyObject *sequence)
326+{
327+ int i, n;
328+ long total = 0;
329+ PyObject *item;
330+ n = PySequence_Length(sequence);
331+ if (n < 0)
332+ return -1; /* Has no length */
333+ for (i = 0; i < n; i++) {
334+ item = PySequence_GetItem(sequence, i);
335+ if (item == NULL)
336+ return -1; /* Not a sequence, or other failure */
337+ if (PyInt_Check(item))
338+ total += PyInt_AsLong(item);
339+ Py_DECREF(item); /* Discard reference ownership */
340+ }
341+ return total;
342+}
343+\end{verbatim}
344+\ttindex{sum_sequence()}
345+
346+
347+\subsection{Types \label{types}}
348+
349+There are few other data types that play a significant role in
350+the Python/C API; most are simple C types such as \ctype{int},
351+\ctype{long}, \ctype{double} and \ctype{char*}. A few structure types
352+are used to describe static tables used to list the functions exported
353+by a module or the data attributes of a new object type, and another
354+is used to describe the value of a complex number. These will
355+be discussed together with the functions that use them.
356+
357+
358+\section{Exceptions \label{exceptions}}
359+
360+The Python programmer only needs to deal with exceptions if specific
361+error handling is required; unhandled exceptions are automatically
362+propagated to the caller, then to the caller's caller, and so on, until
363+they reach the top-level interpreter, where they are reported to the
364+user accompanied by a stack traceback.
365+
366+For C programmers, however, error checking always has to be explicit.
367+All functions in the Python/C API can raise exceptions, unless an
368+explicit claim is made otherwise in a function's documentation. In
369+general, when a function encounters an error, it sets an exception,
370+discards any object references that it owns, and returns an
371+error indicator --- usually \NULL{} or \code{-1}. A few functions
372+return a Boolean true/false result, with false indicating an error.
373+Very few functions return no explicit error indicator or have an
374+ambiguous return value, and require explicit testing for errors with
375+\cfunction{PyErr_Occurred()}\ttindex{PyErr_Occurred()}.
376+
377+Exception state is maintained in per-thread storage (this is
378+equivalent to using global storage in an unthreaded application). A
379+thread can be in one of two states: an exception has occurred, or not.
380+The function \cfunction{PyErr_Occurred()} can be used to check for
381+this: it returns a borrowed reference to the exception type object
382+when an exception has occurred, and \NULL{} otherwise. There are a
383+number of functions to set the exception state:
384+\cfunction{PyErr_SetString()}\ttindex{PyErr_SetString()} is the most
385+common (though not the most general) function to set the exception
386+state, and \cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} clears the
387+exception state.
388+
389+The full exception state consists of three objects (all of which can
390+be \NULL): the exception type, the corresponding exception
391+value, and the traceback. These have the same meanings as the Python
392+\withsubitem{(in module sys)}{
393+ \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
394+objects \code{sys.exc_type}, \code{sys.exc_value}, and
395+\code{sys.exc_traceback}; however, they are not the same: the Python
396+objects represent the last exception being handled by a Python
397+\keyword{try} \ldots\ \keyword{except} statement, while the C level
398+exception state only exists while an exception is being passed on
399+between C functions until it reaches the Python bytecode interpreter's
400+main loop, which takes care of transferring it to \code{sys.exc_type}
401+and friends.
402+
403+Note that starting with Python 1.5, the preferred, thread-safe way to
404+access the exception state from Python code is to call the function
405+\withsubitem{(in module sys)}{\ttindex{exc_info()}}
406+\function{sys.exc_info()}, which returns the per-thread exception state
407+for Python code. Also, the semantics of both ways to access the
408+exception state have changed so that a function which catches an
409+exception will save and restore its thread's exception state so as to
410+preserve the exception state of its caller. This prevents common bugs
411+in exception handling code caused by an innocent-looking function
412+overwriting the exception being handled; it also reduces the often
413+unwanted lifetime extension for objects that are referenced by the
414+stack frames in the traceback.
415+
416+As a general principle, a function that calls another function to
417+perform some task should check whether the called function raised an
418+exception, and if so, pass the exception state on to its caller. It
419+should discard any object references that it owns, and return an
420+error indicator, but it should \emph{not} set another exception ---
421+that would overwrite the exception that was just raised, and lose
422+important information about the exact cause of the error.
423+
424+A simple example of detecting exceptions and passing them on is shown
425+in the \cfunction{sum_sequence()}\ttindex{sum_sequence()} example
426+above. It so happens that that example doesn't need to clean up any
427+owned references when it detects an error. The following example
428+function shows some error cleanup. First, to remind you why you like
429+Python, we show the equivalent Python code:
430+
431+\begin{verbatim}
432+def incr_item(dict, key):
433+ try:
434+ item = dict[key]
435+ except KeyError:
436+ item = 0
437+ dict[key] = item + 1
438+\end{verbatim}
439+\ttindex{incr_item()}
440+
441+Here is the corresponding C code, in all its glory:
442+
443+\begin{verbatim}
444+int
445+incr_item(PyObject *dict, PyObject *key)
446+{
447+ /* Objects all initialized to NULL for Py_XDECREF */
448+ PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
449+ int rv = -1; /* Return value initialized to -1 (failure) */
450+
451+ item = PyObject_GetItem(dict, key);
452+ if (item == NULL) {
453+ /* Handle KeyError only: */
454+ if (!PyErr_ExceptionMatches(PyExc_KeyError))
455+ goto error;
456+
457+ /* Clear the error and use zero: */
458+ PyErr_Clear();
459+ item = PyInt_FromLong(0L);
460+ if (item == NULL)
461+ goto error;
462+ }
463+ const_one = PyInt_FromLong(1L);
464+ if (const_one == NULL)
465+ goto error;
466+
467+ incremented_item = PyNumber_Add(item, const_one);
468+ if (incremented_item == NULL)
469+ goto error;
470+
471+ if (PyObject_SetItem(dict, key, incremented_item) < 0)
472+ goto error;
473+ rv = 0; /* Success */
474+ /* Continue with cleanup code */
475+
476+ error:
477+ /* Cleanup code, shared by success and failure path */
478+
479+ /* Use Py_XDECREF() to ignore NULL references */
480+ Py_XDECREF(item);
481+ Py_XDECREF(const_one);
482+ Py_XDECREF(incremented_item);
483+
484+ return rv; /* -1 for error, 0 for success */
485+}
486+\end{verbatim}
487+\ttindex{incr_item()}
488+
489+This example represents an endorsed use of the \keyword{goto} statement
490+in C! It illustrates the use of
491+\cfunction{PyErr_ExceptionMatches()}\ttindex{PyErr_ExceptionMatches()} and
492+\cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} to
493+handle specific exceptions, and the use of
494+\cfunction{Py_XDECREF()}\ttindex{Py_XDECREF()} to
495+dispose of owned references that may be \NULL{} (note the
496+\character{X} in the name; \cfunction{Py_DECREF()} would crash when
497+confronted with a \NULL{} reference). It is important that the
498+variables used to hold owned references are initialized to \NULL{} for
499+this to work; likewise, the proposed return value is initialized to
500+\code{-1} (failure) and only set to success after the final call made
501+is successful.
502+
503+
504+\section{Embedding Python \label{embedding}}
505+
506+The one important task that only embedders (as opposed to extension
507+writers) of the Python interpreter have to worry about is the
508+initialization, and possibly the finalization, of the Python
509+interpreter. Most functionality of the interpreter can only be used
510+after the interpreter has been initialized.
511+
512+The basic initialization function is
513+\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
514+This initializes the table of loaded modules, and creates the
515+fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
516+\module{__main__}\refbimodindex{__main__}, \module{sys}\refbimodindex{sys},
517+and \module{exceptions}.\refbimodindex{exceptions} It also initializes
518+the module search path (\code{sys.path}).%
519+\indexiii{module}{search}{path}
520+\withsubitem{(in module sys)}{\ttindex{path}}
521+
522+\cfunction{Py_Initialize()} does not set the ``script argument list''
523+(\code{sys.argv}). If this variable is needed by Python code that
524+will be executed later, it must be set explicitly with a call to
525+\code{PySys_SetArgv(\var{argc},
526+\var{argv})}\ttindex{PySys_SetArgv()} subsequent to the call to
527+\cfunction{Py_Initialize()}.
528+
529+On most systems (in particular, on \UNIX{} and Windows, although the
530+details are slightly different),
531+\cfunction{Py_Initialize()} calculates the module search path based
532+upon its best guess for the location of the standard Python
533+interpreter executable, assuming that the Python library is found in a
534+fixed location relative to the Python interpreter executable. In
535+particular, it looks for a directory named
536+\file{lib/python\shortversion} relative to the parent directory where
537+the executable named \file{python} is found on the shell command
538+search path (the environment variable \envvar{PATH}).
539+
540+For instance, if the Python executable is found in
541+\file{/usr/local/bin/python}, it will assume that the libraries are in
542+\file{/usr/local/lib/python\shortversion}. (In fact, this particular path
543+is also the ``fallback'' location, used when no executable file named
544+\file{python} is found along \envvar{PATH}.) The user can override
545+this behavior by setting the environment variable \envvar{PYTHONHOME},
546+or insert additional directories in front of the standard path by
547+setting \envvar{PYTHONPATH}.
548+
549+The embedding application can steer the search by calling
550+\code{Py_SetProgramName(\var{file})}\ttindex{Py_SetProgramName()} \emph{before} calling
551+\cfunction{Py_Initialize()}. Note that \envvar{PYTHONHOME} still
552+overrides this and \envvar{PYTHONPATH} is still inserted in front of
553+the standard path. An application that requires total control has to
554+provide its own implementation of
555+\cfunction{Py_GetPath()}\ttindex{Py_GetPath()},
556+\cfunction{Py_GetPrefix()}\ttindex{Py_GetPrefix()},
557+\cfunction{Py_GetExecPrefix()}\ttindex{Py_GetExecPrefix()}, and
558+\cfunction{Py_GetProgramFullPath()}\ttindex{Py_GetProgramFullPath()} (all
559+defined in \file{Modules/getpath.c}).
560+
561+Sometimes, it is desirable to ``uninitialize'' Python. For instance,
562+the application may want to start over (make another call to
563+\cfunction{Py_Initialize()}) or the application is simply done with its
564+use of Python and wants to free memory allocated by Python. This
565+can be accomplished by calling \cfunction{Py_Finalize()}. The function
566+\cfunction{Py_IsInitialized()}\ttindex{Py_IsInitialized()} returns
567+true if Python is currently in the initialized state. More
568+information about these functions is given in a later chapter.
569+Notice that \cfunction{Py_Finalize} does \emph{not} free all memory
570+allocated by the Python interpreter, e.g. memory allocated by extension
571+modules currently cannot be released.
572+
573+
574+\section{Debugging Builds \label{debugging}}
575+
576+Python can be built with several macros to enable extra checks of the
577+interpreter and extension modules. These checks tend to add a large
578+amount of overhead to the runtime so they are not enabled by default.
579+
580+A full list of the various types of debugging builds is in the file
581+\file{Misc/SpecialBuilds.txt} in the Python source distribution.
582+Builds are available that support tracing of reference counts,
583+debugging the memory allocator, or low-level profiling of the main
584+interpreter loop. Only the most frequently-used builds will be
585+described in the remainder of this section.
586+
587+Compiling the interpreter with the \csimplemacro{Py_DEBUG} macro
588+defined produces what is generally meant by "a debug build" of Python.
589+\csimplemacro{Py_DEBUG} is enabled in the \UNIX{} build by adding
590+\longprogramopt{with-pydebug} to the \file{configure} command. It is also
591+implied by the presence of the not-Python-specific
592+\csimplemacro{_DEBUG} macro. When \csimplemacro{Py_DEBUG} is enabled
593+in the \UNIX{} build, compiler optimization is disabled.
594+
595+In addition to the reference count debugging described below, the
596+following extra checks are performed:
597+
598+\begin{itemize}
599+ \item Extra checks are added to the object allocator.
600+ \item Extra checks are added to the parser and compiler.
601+ \item Downcasts from wide types to narrow types are checked for
602+ loss of information.
603+ \item A number of assertions are added to the dictionary and set
604+ implementations. In addition, the set object acquires a
605+ \method{test_c_api} method.
606+ \item Sanity checks of the input arguments are added to frame
607+ creation.
608+ \item The storage for long ints is initialized with a known
609+ invalid pattern to catch reference to uninitialized
610+ digits.
611+ \item Low-level tracing and extra exception checking are added
612+ to the runtime virtual machine.
613+ \item Extra checks are added to the memory arena implementation.
614+ \item Extra debugging is added to the thread module.
615+\end{itemize}
616+
617+There may be additional checks not mentioned here.
618+
619+Defining \csimplemacro{Py_TRACE_REFS} enables reference tracing. When
620+defined, a circular doubly linked list of active objects is maintained
621+by adding two extra fields to every \ctype{PyObject}. Total
622+allocations are tracked as well. Upon exit, all existing references
623+are printed. (In interactive mode this happens after every statement
624+run by the interpreter.) Implied by \csimplemacro{Py_DEBUG}.
625+
626+Please refer to \file{Misc/SpecialBuilds.txt} in the Python source
627+distribution for more detailed information.
sys/src/cmd/python/Doc/api/memory.tex+204−0
@@ -0,0 +1,204 @@
1+\chapter{Memory Management \label{memory}}
2+\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
3+
4+
5+\section{Overview \label{memoryOverview}}
6+
7+Memory management in Python involves a private heap containing all
8+Python objects and data structures. The management of this private
9+heap is ensured internally by the \emph{Python memory manager}. The
10+Python memory manager has different components which deal with various
11+dynamic storage management aspects, like sharing, segmentation,
12+preallocation or caching.
13+
14+At the lowest level, a raw memory allocator ensures that there is
15+enough room in the private heap for storing all Python-related data
16+by interacting with the memory manager of the operating system. On top
17+of the raw memory allocator, several object-specific allocators
18+operate on the same heap and implement distinct memory management
19+policies adapted to the peculiarities of every object type. For
20+example, integer objects are managed differently within the heap than
21+strings, tuples or dictionaries because integers imply different
22+storage requirements and speed/space tradeoffs. The Python memory
23+manager thus delegates some of the work to the object-specific
24+allocators, but ensures that the latter operate within the bounds of
25+the private heap.
26+
27+It is important to understand that the management of the Python heap
28+is performed by the interpreter itself and that the user has no
29+control over it, even if she regularly manipulates object pointers to
30+memory blocks inside that heap. The allocation of heap space for
31+Python objects and other internal buffers is performed on demand by
32+the Python memory manager through the Python/C API functions listed in
33+this document.
34+
35+To avoid memory corruption, extension writers should never try to
36+operate on Python objects with the functions exported by the C
37+library: \cfunction{malloc()}\ttindex{malloc()},
38+\cfunction{calloc()}\ttindex{calloc()},
39+\cfunction{realloc()}\ttindex{realloc()} and
40+\cfunction{free()}\ttindex{free()}. This will result in
41+mixed calls between the C allocator and the Python memory manager
42+with fatal consequences, because they implement different algorithms
43+and operate on different heaps. However, one may safely allocate and
44+release memory blocks with the C library allocator for individual
45+purposes, as shown in the following example:
46+
47+\begin{verbatim}
48+ PyObject *res;
49+ char *buf = (char *) malloc(BUFSIZ); /* for I/O */
50+
51+ if (buf == NULL)
52+ return PyErr_NoMemory();
53+ ...Do some I/O operation involving buf...
54+ res = PyString_FromString(buf);
55+ free(buf); /* malloc'ed */
56+ return res;
57+\end{verbatim}
58+
59+In this example, the memory request for the I/O buffer is handled by
60+the C library allocator. The Python memory manager is involved only
61+in the allocation of the string object returned as a result.
62+
63+In most situations, however, it is recommended to allocate memory from
64+the Python heap specifically because the latter is under control of
65+the Python memory manager. For example, this is required when the
66+interpreter is extended with new object types written in C. Another
67+reason for using the Python heap is the desire to \emph{inform} the
68+Python memory manager about the memory needs of the extension module.
69+Even when the requested memory is used exclusively for internal,
70+highly-specific purposes, delegating all memory requests to the Python
71+memory manager causes the interpreter to have a more accurate image of
72+its memory footprint as a whole. Consequently, under certain
73+circumstances, the Python memory manager may or may not trigger
74+appropriate actions, like garbage collection, memory compaction or
75+other preventive procedures. Note that by using the C library
76+allocator as shown in the previous example, the allocated memory for
77+the I/O buffer escapes completely the Python memory manager.
78+
79+
80+\section{Memory Interface \label{memoryInterface}}
81+
82+The following function sets, modeled after the ANSI C standard,
83+but specifying behavior when requesting zero bytes,
84+are available for allocating and releasing memory from the Python heap:
85+
86+
87+\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
88+ Allocates \var{n} bytes and returns a pointer of type \ctype{void*}
89+ to the allocated memory, or \NULL{} if the request fails.
90+ Requesting zero bytes returns a distinct non-\NULL{} pointer if
91+ possible, as if \cfunction{PyMem_Malloc(1)} had been called instead.
92+ The memory will not have been initialized in any way.
93+\end{cfuncdesc}
94+
95+\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
96+ Resizes the memory block pointed to by \var{p} to \var{n} bytes.
97+ The contents will be unchanged to the minimum of the old and the new
98+ sizes. If \var{p} is \NULL, the call is equivalent to
99+ \cfunction{PyMem_Malloc(\var{n})}; else if \var{n} is equal to zero, the
100+ memory block is resized but is not freed, and the returned pointer
101+ is non-\NULL. Unless \var{p} is \NULL, it must have been
102+ returned by a previous call to \cfunction{PyMem_Malloc()} or
103+ \cfunction{PyMem_Realloc()}. If the request fails,
104+ \cfunction{PyMem_Realloc()} returns \NULL{} and \var{p} remains a
105+ valid pointer to the previous memory area.
106+\end{cfuncdesc}
107+
108+\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
109+ Frees the memory block pointed to by \var{p}, which must have been
110+ returned by a previous call to \cfunction{PyMem_Malloc()} or
111+ \cfunction{PyMem_Realloc()}. Otherwise, or if
112+ \cfunction{PyMem_Free(p)} has been called before, undefined
113+ behavior occurs. If \var{p} is \NULL, no operation is performed.
114+\end{cfuncdesc}
115+
116+The following type-oriented macros are provided for convenience. Note
117+that \var{TYPE} refers to any C type.
118+
119+\begin{cfuncdesc}{\var{TYPE}*}{PyMem_New}{TYPE, size_t n}
120+ Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
121+ sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
122+ \ctype{\var{TYPE}*}. The memory will not have been initialized in
123+ any way.
124+\end{cfuncdesc}
125+
126+\begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
127+ Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
128+ to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
129+ cast to \ctype{\var{TYPE}*}. On return, \var{p} will be a pointer to
130+ the new memory area, or \NULL{} in the event of failure.
131+\end{cfuncdesc}
132+
133+\begin{cfuncdesc}{void}{PyMem_Del}{void *p}
134+ Same as \cfunction{PyMem_Free()}.
135+\end{cfuncdesc}
136+
137+In addition, the following macro sets are provided for calling the
138+Python memory allocator directly, without involving the C API functions
139+listed above. However, note that their use does not preserve binary
140+compatibility across Python versions and is therefore deprecated in
141+extension modules.
142+
143+\cfunction{PyMem_MALLOC()}, \cfunction{PyMem_REALLOC()}, \cfunction{PyMem_FREE()}.
144+
145+\cfunction{PyMem_NEW()}, \cfunction{PyMem_RESIZE()}, \cfunction{PyMem_DEL()}.
146+
147+
148+\section{Examples \label{memoryExamples}}
149+
150+Here is the example from section \ref{memoryOverview}, rewritten so
151+that the I/O buffer is allocated from the Python heap by using the
152+first function set:
153+
154+\begin{verbatim}
155+ PyObject *res;
156+ char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
157+
158+ if (buf == NULL)
159+ return PyErr_NoMemory();
160+ /* ...Do some I/O operation involving buf... */
161+ res = PyString_FromString(buf);
162+ PyMem_Free(buf); /* allocated with PyMem_Malloc */
163+ return res;
164+\end{verbatim}
165+
166+The same code using the type-oriented function set:
167+
168+\begin{verbatim}
169+ PyObject *res;
170+ char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
171+
172+ if (buf == NULL)
173+ return PyErr_NoMemory();
174+ /* ...Do some I/O operation involving buf... */
175+ res = PyString_FromString(buf);
176+ PyMem_Del(buf); /* allocated with PyMem_New */
177+ return res;
178+\end{verbatim}
179+
180+Note that in the two examples above, the buffer is always
181+manipulated via functions belonging to the same set. Indeed, it
182+is required to use the same memory API family for a given
183+memory block, so that the risk of mixing different allocators is
184+reduced to a minimum. The following code sequence contains two errors,
185+one of which is labeled as \emph{fatal} because it mixes two different
186+allocators operating on different heaps.
187+
188+\begin{verbatim}
189+char *buf1 = PyMem_New(char, BUFSIZ);
190+char *buf2 = (char *) malloc(BUFSIZ);
191+char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
192+...
193+PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
194+free(buf2); /* Right -- allocated via malloc() */
195+free(buf1); /* Fatal -- should be PyMem_Del() */
196+\end{verbatim}
197+
198+In addition to the functions aimed at handling raw memory blocks from
199+the Python heap, objects in Python are allocated and released with
200+\cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()} and
201+\cfunction{PyObject_Del()}.
202+
203+These will be explained in the next chapter on defining and
204+implementing new object types in C.
sys/src/cmd/python/Doc/api/newtypes.tex+1780−0
@@ -0,0 +1,1780 @@
1+\chapter{Object Implementation Support \label{newTypes}}
2+
3+
4+This chapter describes the functions, types, and macros used when
5+defining new object types.
6+
7+
8+\section{Allocating Objects on the Heap
9+ \label{allocating-objects}}
10+
11+\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
12+\end{cfuncdesc}
13+
14+\begin{cfuncdesc}{PyVarObject*}{_PyObject_NewVar}{PyTypeObject *type, Py_ssize_t size}
15+\end{cfuncdesc}
16+
17+\begin{cfuncdesc}{void}{_PyObject_Del}{PyObject *op}
18+\end{cfuncdesc}
19+
20+\begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op,
21+ PyTypeObject *type}
22+ Initialize a newly-allocated object \var{op} with its type and
23+ initial reference. Returns the initialized object. If \var{type}
24+ indicates that the object participates in the cyclic garbage
25+ detector, it is added to the detector's set of observed objects.
26+ Other fields of the object are not affected.
27+\end{cfuncdesc}
28+
29+\begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op,
30+ PyTypeObject *type, Py_ssize_t size}
31+ This does everything \cfunction{PyObject_Init()} does, and also
32+ initializes the length information for a variable-size object.
33+\end{cfuncdesc}
34+
35+\begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type}
36+ Allocate a new Python object using the C structure type \var{TYPE}
37+ and the Python type object \var{type}. Fields not defined by the
38+ Python object header are not initialized; the object's reference
39+ count will be one. The size of the memory
40+ allocation is determined from the \member{tp_basicsize} field of the
41+ type object.
42+\end{cfuncdesc}
43+
44+\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type,
45+ Py_ssize_t size}
46+ Allocate a new Python object using the C structure type \var{TYPE}
47+ and the Python type object \var{type}. Fields not defined by the
48+ Python object header are not initialized. The allocated memory
49+ allows for the \var{TYPE} structure plus \var{size} fields of the
50+ size given by the \member{tp_itemsize} field of \var{type}. This is
51+ useful for implementing objects like tuples, which are able to
52+ determine their size at construction time. Embedding the array of
53+ fields into the same allocation decreases the number of allocations,
54+ improving the memory management efficiency.
55+\end{cfuncdesc}
56+
57+\begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op}
58+ Releases memory allocated to an object using
59+ \cfunction{PyObject_New()} or \cfunction{PyObject_NewVar()}. This
60+ is normally called from the \member{tp_dealloc} handler specified in
61+ the object's type. The fields of the object should not be accessed
62+ after this call as the memory is no longer a valid Python object.
63+\end{cfuncdesc}
64+
65+\begin{cfuncdesc}{PyObject*}{Py_InitModule}{char *name,
66+ PyMethodDef *methods}
67+ Create a new module object based on a name and table of functions,
68+ returning the new module object.
69+
70+ \versionchanged[Older versions of Python did not support \NULL{} as
71+ the value for the \var{methods} argument]{2.3}
72+\end{cfuncdesc}
73+
74+\begin{cfuncdesc}{PyObject*}{Py_InitModule3}{char *name,
75+ PyMethodDef *methods,
76+ char *doc}
77+ Create a new module object based on a name and table of functions,
78+ returning the new module object. If \var{doc} is non-\NULL, it will
79+ be used to define the docstring for the module.
80+
81+ \versionchanged[Older versions of Python did not support \NULL{} as
82+ the value for the \var{methods} argument]{2.3}
83+\end{cfuncdesc}
84+
85+\begin{cfuncdesc}{PyObject*}{Py_InitModule4}{char *name,
86+ PyMethodDef *methods,
87+ char *doc, PyObject *self,
88+ int apiver}
89+ Create a new module object based on a name and table of functions,
90+ returning the new module object. If \var{doc} is non-\NULL, it will
91+ be used to define the docstring for the module. If \var{self} is
92+ non-\NULL, it will passed to the functions of the module as their
93+ (otherwise \NULL) first parameter. (This was added as an
94+ experimental feature, and there are no known uses in the current
95+ version of Python.) For \var{apiver}, the only value which should
96+ be passed is defined by the constant \constant{PYTHON_API_VERSION}.
97+
98+ \note{Most uses of this function should probably be using
99+ the \cfunction{Py_InitModule3()} instead; only use this if you are
100+ sure you need it.}
101+
102+ \versionchanged[Older versions of Python did not support \NULL{} as
103+ the value for the \var{methods} argument]{2.3}
104+\end{cfuncdesc}
105+
106+\begin{cvardesc}{PyObject}{_Py_NoneStruct}
107+ Object which is visible in Python as \code{None}. This should only
108+ be accessed using the \code{Py_None} macro, which evaluates to a
109+ pointer to this object.
110+\end{cvardesc}
111+
112+
113+\section{Common Object Structures \label{common-structs}}
114+
115+There are a large number of structures which are used in the
116+definition of object types for Python. This section describes these
117+structures and how they are used.
118+
119+All Python objects ultimately share a small number of fields at the
120+beginning of the object's representation in memory. These are
121+represented by the \ctype{PyObject} and \ctype{PyVarObject} types,
122+which are defined, in turn, by the expansions of some macros also
123+used, whether directly or indirectly, in the definition of all other
124+Python objects.
125+
126+\begin{ctypedesc}{PyObject}
127+ All object types are extensions of this type. This is a type which
128+ contains the information Python needs to treat a pointer to an
129+ object as an object. In a normal ``release'' build, it contains
130+ only the objects reference count and a pointer to the corresponding
131+ type object. It corresponds to the fields defined by the
132+ expansion of the \code{PyObject_HEAD} macro.
133+\end{ctypedesc}
134+
135+\begin{ctypedesc}{PyVarObject}
136+ This is an extension of \ctype{PyObject} that adds the
137+ \member{ob_size} field. This is only used for objects that have
138+ some notion of \emph{length}. This type does not often appear in
139+ the Python/C API. It corresponds to the fields defined by the
140+ expansion of the \code{PyObject_VAR_HEAD} macro.
141+\end{ctypedesc}
142+
143+These macros are used in the definition of \ctype{PyObject} and
144+\ctype{PyVarObject}:
145+
146+\begin{csimplemacrodesc}{PyObject_HEAD}
147+ This is a macro which expands to the declarations of the fields of
148+ the \ctype{PyObject} type; it is used when declaring new types which
149+ represent objects without a varying length. The specific fields it
150+ expands to depend on the definition of
151+ \csimplemacro{Py_TRACE_REFS}. By default, that macro is not
152+ defined, and \csimplemacro{PyObject_HEAD} expands to:
153+ \begin{verbatim}
154+ Py_ssize_t ob_refcnt;
155+ PyTypeObject *ob_type;
156+ \end{verbatim}
157+ When \csimplemacro{Py_TRACE_REFS} is defined, it expands to:
158+ \begin{verbatim}
159+ PyObject *_ob_next, *_ob_prev;
160+ Py_ssize_t ob_refcnt;
161+ PyTypeObject *ob_type;
162+ \end{verbatim}
163+\end{csimplemacrodesc}
164+
165+\begin{csimplemacrodesc}{PyObject_VAR_HEAD}
166+ This is a macro which expands to the declarations of the fields of
167+ the \ctype{PyVarObject} type; it is used when declaring new types which
168+ represent objects with a length that varies from instance to
169+ instance. This macro always expands to:
170+ \begin{verbatim}
171+ PyObject_HEAD
172+ Py_ssize_t ob_size;
173+ \end{verbatim}
174+ Note that \csimplemacro{PyObject_HEAD} is part of the expansion, and
175+ that its own expansion varies depending on the definition of
176+ \csimplemacro{Py_TRACE_REFS}.
177+\end{csimplemacrodesc}
178+
179+PyObject_HEAD_INIT
180+
181+\begin{ctypedesc}{PyCFunction}
182+ Type of the functions used to implement most Python callables in C.
183+ Functions of this type take two \ctype{PyObject*} parameters and
184+ return one such value. If the return value is \NULL, an exception
185+ shall have been set. If not \NULL, the return value is interpreted
186+ as the return value of the function as exposed in Python. The
187+ function must return a new reference.
188+\end{ctypedesc}
189+
190+\begin{ctypedesc}{PyMethodDef}
191+ Structure used to describe a method of an extension type. This
192+ structure has four fields:
193+
194+ \begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
195+ \lineiii{ml_name}{char *}{name of the method}
196+ \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
197+ \lineiii{ml_flags}{int}{flag bits indicating how the call should be
198+ constructed}
199+ \lineiii{ml_doc}{char *}{points to the contents of the docstring}
200+ \end{tableiii}
201+\end{ctypedesc}
202+
203+The \member{ml_meth} is a C function pointer. The functions may be of
204+different types, but they always return \ctype{PyObject*}. If the
205+function is not of the \ctype{PyCFunction}, the compiler will require
206+a cast in the method table. Even though \ctype{PyCFunction} defines
207+the first parameter as \ctype{PyObject*}, it is common that the method
208+implementation uses a the specific C type of the \var{self} object.
209+
210+The \member{ml_flags} field is a bitfield which can include the
211+following flags. The individual flags indicate either a calling
212+convention or a binding convention. Of the calling convention flags,
213+only \constant{METH_VARARGS} and \constant{METH_KEYWORDS} can be
214+combined (but note that \constant{METH_KEYWORDS} alone is equivalent
215+to \code{\constant{METH_VARARGS} | \constant{METH_KEYWORDS}}).
216+Any of the calling convention flags can be combined with a
217+binding flag.
218+
219+\begin{datadesc}{METH_VARARGS}
220+ This is the typical calling convention, where the methods have the
221+ type \ctype{PyCFunction}. The function expects two
222+ \ctype{PyObject*} values. The first one is the \var{self} object for
223+ methods; for module functions, it has the value given to
224+ \cfunction{Py_InitModule4()} (or \NULL{} if
225+ \cfunction{Py_InitModule()} was used). The second parameter
226+ (often called \var{args}) is a tuple object representing all
227+ arguments. This parameter is typically processed using
228+ \cfunction{PyArg_ParseTuple()} or \cfunction{PyArg_UnpackTuple}.
229+\end{datadesc}
230+
231+\begin{datadesc}{METH_KEYWORDS}
232+ Methods with these flags must be of type
233+ \ctype{PyCFunctionWithKeywords}. The function expects three
234+ parameters: \var{self}, \var{args}, and a dictionary of all the
235+ keyword arguments. The flag is typically combined with
236+ \constant{METH_VARARGS}, and the parameters are typically processed
237+ using \cfunction{PyArg_ParseTupleAndKeywords()}.
238+\end{datadesc}
239+
240+\begin{datadesc}{METH_NOARGS}
241+ Methods without parameters don't need to check whether arguments are
242+ given if they are listed with the \constant{METH_NOARGS} flag. They
243+ need to be of type \ctype{PyCFunction}. When used with object
244+ methods, the first parameter is typically named \code{self} and will
245+ hold a reference to the object instance. In all cases the second
246+ parameter will be \NULL.
247+\end{datadesc}
248+
249+\begin{datadesc}{METH_O}
250+ Methods with a single object argument can be listed with the
251+ \constant{METH_O} flag, instead of invoking
252+ \cfunction{PyArg_ParseTuple()} with a \code{"O"} argument. They have
253+ the type \ctype{PyCFunction}, with the \var{self} parameter, and a
254+ \ctype{PyObject*} parameter representing the single argument.
255+\end{datadesc}
256+
257+\begin{datadesc}{METH_OLDARGS}
258+ This calling convention is deprecated. The method must be of type
259+ \ctype{PyCFunction}. The second argument is \NULL{} if no arguments
260+ are given, a single object if exactly one argument is given, and a
261+ tuple of objects if more than one argument is given. There is no
262+ way for a function using this convention to distinguish between a
263+ call with multiple arguments and a call with a tuple as the only
264+ argument.
265+\end{datadesc}
266+
267+These two constants are not used to indicate the calling convention
268+but the binding when use with methods of classes. These may not be
269+used for functions defined for modules. At most one of these flags
270+may be set for any given method.
271+
272+\begin{datadesc}{METH_CLASS}
273+ The method will be passed the type object as the first parameter
274+ rather than an instance of the type. This is used to create
275+ \emph{class methods}, similar to what is created when using the
276+ \function{classmethod()}\bifuncindex{classmethod} built-in
277+ function.
278+ \versionadded{2.3}
279+\end{datadesc}
280+
281+\begin{datadesc}{METH_STATIC}
282+ The method will be passed \NULL{} as the first parameter rather than
283+ an instance of the type. This is used to create \emph{static
284+ methods}, similar to what is created when using the
285+ \function{staticmethod()}\bifuncindex{staticmethod} built-in
286+ function.
287+ \versionadded{2.3}
288+\end{datadesc}
289+
290+One other constant controls whether a method is loaded in place of
291+another definition with the same method name.
292+
293+\begin{datadesc}{METH_COEXIST}
294+ The method will be loaded in place of existing definitions. Without
295+ \var{METH_COEXIST}, the default is to skip repeated definitions. Since
296+ slot wrappers are loaded before the method table, the existence of a
297+ \var{sq_contains} slot, for example, would generate a wrapped method
298+ named \method{__contains__()} and preclude the loading of a
299+ corresponding PyCFunction with the same name. With the flag defined,
300+ the PyCFunction will be loaded in place of the wrapper object and will
301+ co-exist with the slot. This is helpful because calls to PyCFunctions
302+ are optimized more than wrapper object calls.
303+ \versionadded{2.4}
304+\end{datadesc}
305+
306+\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef table[],
307+ PyObject *ob, char *name}
308+ Return a bound method object for an extension type implemented in
309+ C. This can be useful in the implementation of a
310+ \member{tp_getattro} or \member{tp_getattr} handler that does not
311+ use the \cfunction{PyObject_GenericGetAttr()} function.
312+\end{cfuncdesc}
313+
314+
315+\section{Type Objects \label{type-structs}}
316+
317+Perhaps one of the most important structures of the Python object
318+system is the structure that defines a new type: the
319+\ctype{PyTypeObject} structure. Type objects can be handled using any
320+of the \cfunction{PyObject_*()} or \cfunction{PyType_*()} functions,
321+but do not offer much that's interesting to most Python applications.
322+These objects are fundamental to how objects behave, so they are very
323+important to the interpreter itself and to any extension module that
324+implements new types.
325+
326+Type objects are fairly large compared to most of the standard types.
327+The reason for the size is that each type object stores a large number
328+of values, mostly C function pointers, each of which implements a
329+small part of the type's functionality. The fields of the type object
330+are examined in detail in this section. The fields will be described
331+in the order in which they occur in the structure.
332+
333+Typedefs:
334+unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
335+intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
336+destructor, freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc,
337+setattrofunc, cmpfunc, reprfunc, hashfunc
338+
339+The structure definition for \ctype{PyTypeObject} can be found in
340+\file{Include/object.h}. For convenience of reference, this repeats
341+the definition found there:
342+
343+\verbatiminput{typestruct.h}
344+
345+The type object structure extends the \ctype{PyVarObject} structure.
346+The \member{ob_size} field is used for dynamic types (created
347+by \function{type_new()}, usually called from a class statement).
348+Note that \cdata{PyType_Type} (the metatype) initializes
349+\member{tp_itemsize}, which means that its instances (i.e. type
350+objects) \emph{must} have the \member{ob_size} field.
351+
352+\begin{cmemberdesc}{PyObject}{PyObject*}{_ob_next}
353+\cmemberline{PyObject}{PyObject*}{_ob_prev}
354+ These fields are only present when the macro \code{Py_TRACE_REFS} is
355+ defined. Their initialization to \NULL{} is taken care of by the
356+ \code{PyObject_HEAD_INIT} macro. For statically allocated objects,
357+ these fields always remain \NULL. For dynamically allocated
358+ objects, these two fields are used to link the object into a
359+ doubly-linked list of \emph{all} live objects on the heap. This
360+ could be used for various debugging purposes; currently the only use
361+ is to print the objects that are still alive at the end of a run
362+ when the environment variable \envvar{PYTHONDUMPREFS} is set.
363+
364+ These fields are not inherited by subtypes.
365+\end{cmemberdesc}
366+
367+\begin{cmemberdesc}{PyObject}{Py_ssize_t}{ob_refcnt}
368+ This is the type object's reference count, initialized to \code{1}
369+ by the \code{PyObject_HEAD_INIT} macro. Note that for statically
370+ allocated type objects, the type's instances (objects whose
371+ \member{ob_type} points back to the type) do \emph{not} count as
372+ references. But for dynamically allocated type objects, the
373+ instances \emph{do} count as references.
374+
375+ This field is not inherited by subtypes.
376+\end{cmemberdesc}
377+
378+\begin{cmemberdesc}{PyObject}{PyTypeObject*}{ob_type}
379+ This is the type's type, in other words its metatype. It is
380+ initialized by the argument to the \code{PyObject_HEAD_INIT} macro,
381+ and its value should normally be \code{\&PyType_Type}. However, for
382+ dynamically loadable extension modules that must be usable on
383+ Windows (at least), the compiler complains that this is not a valid
384+ initializer. Therefore, the convention is to pass \NULL{} to the
385+ \code{PyObject_HEAD_INIT} macro and to initialize this field
386+ explicitly at the start of the module's initialization function,
387+ before doing anything else. This is typically done like this:
388+
389+\begin{verbatim}
390+Foo_Type.ob_type = &PyType_Type;
391+\end{verbatim}
392+
393+ This should be done before any instances of the type are created.
394+ \cfunction{PyType_Ready()} checks if \member{ob_type} is \NULL, and
395+ if so, initializes it: in Python 2.2, it is set to
396+ \code{\&PyType_Type}; in Python 2.2.1 and later it is
397+ initialized to the \member{ob_type} field of the base class.
398+ \cfunction{PyType_Ready()} will not change this field if it is
399+ non-zero.
400+
401+ In Python 2.2, this field is not inherited by subtypes. In 2.2.1,
402+ and in 2.3 and beyond, it is inherited by subtypes.
403+\end{cmemberdesc}
404+
405+\begin{cmemberdesc}{PyVarObject}{Py_ssize_t}{ob_size}
406+ For statically allocated type objects, this should be initialized
407+ to zero. For dynamically allocated type objects, this field has a
408+ special internal meaning.
409+
410+ This field is not inherited by subtypes.
411+\end{cmemberdesc}
412+
413+\begin{cmemberdesc}{PyTypeObject}{char*}{tp_name}
414+ Pointer to a NUL-terminated string containing the name of the type.
415+ For types that are accessible as module globals, the string should
416+ be the full module name, followed by a dot, followed by the type
417+ name; for built-in types, it should be just the type name. If the
418+ module is a submodule of a package, the full package name is part of
419+ the full module name. For example, a type named \class{T} defined
420+ in module \module{M} in subpackage \module{Q} in package \module{P}
421+ should have the \member{tp_name} initializer \code{"P.Q.M.T"}.
422+
423+ For dynamically allocated type objects, this should just be the type
424+ name, and the module name explicitly stored in the type dict as the
425+ value for key \code{'__module__'}.
426+
427+ For statically allocated type objects, the tp_name field should
428+ contain a dot. Everything before the last dot is made accessible as
429+ the \member{__module__} attribute, and everything after the last dot
430+ is made accessible as the \member{__name__} attribute.
431+
432+ If no dot is present, the entire \member{tp_name} field is made
433+ accessible as the \member{__name__} attribute, and the
434+ \member{__module__} attribute is undefined (unless explicitly set in
435+ the dictionary, as explained above). This means your type will be
436+ impossible to pickle.
437+
438+ This field is not inherited by subtypes.
439+\end{cmemberdesc}
440+
441+\begin{cmemberdesc}{PyTypeObject}{Py_ssize_t}{tp_basicsize}
442+\cmemberline{PyTypeObject}{Py_ssize_t}{tp_itemsize}
443+ These fields allow calculating the size in bytes of instances of
444+ the type.
445+
446+ There are two kinds of types: types with fixed-length instances have
447+ a zero \member{tp_itemsize} field, types with variable-length
448+ instances have a non-zero \member{tp_itemsize} field. For a type
449+ with fixed-length instances, all instances have the same size,
450+ given in \member{tp_basicsize}.
451+
452+ For a type with variable-length instances, the instances must have
453+ an \member{ob_size} field, and the instance size is
454+ \member{tp_basicsize} plus N times \member{tp_itemsize}, where N is
455+ the ``length'' of the object. The value of N is typically stored in
456+ the instance's \member{ob_size} field. There are exceptions: for
457+ example, long ints use a negative \member{ob_size} to indicate a
458+ negative number, and N is \code{abs(\member{ob_size})} there. Also,
459+ the presence of an \member{ob_size} field in the instance layout
460+ doesn't mean that the instance structure is variable-length (for
461+ example, the structure for the list type has fixed-length instances,
462+ yet those instances have a meaningful \member{ob_size} field).
463+
464+ The basic size includes the fields in the instance declared by the
465+ macro \csimplemacro{PyObject_HEAD} or
466+ \csimplemacro{PyObject_VAR_HEAD} (whichever is used to declare the
467+ instance struct) and this in turn includes the \member{_ob_prev} and
468+ \member{_ob_next} fields if they are present. This means that the
469+ only correct way to get an initializer for the \member{tp_basicsize}
470+ is to use the \keyword{sizeof} operator on the struct used to
471+ declare the instance layout. The basic size does not include the GC
472+ header size (this is new in Python 2.2; in 2.1 and 2.0, the GC
473+ header size was included in \member{tp_basicsize}).
474+
475+ These fields are inherited separately by subtypes. If the base type
476+ has a non-zero \member{tp_itemsize}, it is generally not safe to set
477+ \member{tp_itemsize} to a different non-zero value in a subtype
478+ (though this depends on the implementation of the base type).
479+
480+ A note about alignment: if the variable items require a particular
481+ alignment, this should be taken care of by the value of
482+ \member{tp_basicsize}. Example: suppose a type implements an array
483+ of \code{double}. \member{tp_itemsize} is \code{sizeof(double)}.
484+ It is the programmer's responsibility that \member{tp_basicsize} is
485+ a multiple of \code{sizeof(double)} (assuming this is the alignment
486+ requirement for \code{double}).
487+\end{cmemberdesc}
488+
489+\begin{cmemberdesc}{PyTypeObject}{destructor}{tp_dealloc}
490+ A pointer to the instance destructor function. This function must
491+ be defined unless the type guarantees that its instances will never
492+ be deallocated (as is the case for the singletons \code{None} and
493+ \code{Ellipsis}).
494+
495+ The destructor function is called by the \cfunction{Py_DECREF()} and
496+ \cfunction{Py_XDECREF()} macros when the new reference count is
497+ zero. At this point, the instance is still in existence, but there
498+ are no references to it. The destructor function should free all
499+ references which the instance owns, free all memory buffers owned by
500+ the instance (using the freeing function corresponding to the
501+ allocation function used to allocate the buffer), and finally (as
502+ its last action) call the type's \member{tp_free} function. If the
503+ type is not subtypable (doesn't have the
504+ \constant{Py_TPFLAGS_BASETYPE} flag bit set), it is permissible to
505+ call the object deallocator directly instead of via
506+ \member{tp_free}. The object deallocator should be the one used to
507+ allocate the instance; this is normally \cfunction{PyObject_Del()}
508+ if the instance was allocated using \cfunction{PyObject_New()} or
509+ \cfunction{PyObject_VarNew()}, or \cfunction{PyObject_GC_Del()} if
510+ the instance was allocated using \cfunction{PyObject_GC_New()} or
511+ \cfunction{PyObject_GC_VarNew()}.
512+
513+ This field is inherited by subtypes.
514+\end{cmemberdesc}
515+
516+\begin{cmemberdesc}{PyTypeObject}{printfunc}{tp_print}
517+ An optional pointer to the instance print function.
518+
519+ The print function is only called when the instance is printed to a
520+ \emph{real} file; when it is printed to a pseudo-file (like a
521+ \class{StringIO} instance), the instance's \member{tp_repr} or
522+ \member{tp_str} function is called to convert it to a string. These
523+ are also called when the type's \member{tp_print} field is \NULL. A
524+ type should never implement \member{tp_print} in a way that produces
525+ different output than \member{tp_repr} or \member{tp_str} would.
526+
527+ The print function is called with the same signature as
528+ \cfunction{PyObject_Print()}: \code{int tp_print(PyObject *self, FILE
529+ *file, int flags)}. The \var{self} argument is the instance to be
530+ printed. The \var{file} argument is the stdio file to which it is
531+ to be printed. The \var{flags} argument is composed of flag bits.
532+ The only flag bit currently defined is \constant{Py_PRINT_RAW}.
533+ When the \constant{Py_PRINT_RAW} flag bit is set, the instance
534+ should be printed the same way as \member{tp_str} would format it;
535+ when the \constant{Py_PRINT_RAW} flag bit is clear, the instance
536+ should be printed the same was as \member{tp_repr} would format it.
537+ It should return \code{-1} and set an exception condition when an
538+ error occurred during the comparison.
539+
540+ It is possible that the \member{tp_print} field will be deprecated.
541+ In any case, it is recommended not to define \member{tp_print}, but
542+ instead to rely on \member{tp_repr} and \member{tp_str} for
543+ printing.
544+
545+ This field is inherited by subtypes.
546+\end{cmemberdesc}
547+
548+\begin{cmemberdesc}{PyTypeObject}{getattrfunc}{tp_getattr}
549+ An optional pointer to the get-attribute-string function.
550+
551+ This field is deprecated. When it is defined, it should point to a
552+ function that acts the same as the \member{tp_getattro} function,
553+ but taking a C string instead of a Python string object to give the
554+ attribute name. The signature is the same as for
555+ \cfunction{PyObject_GetAttrString()}.
556+
557+ This field is inherited by subtypes together with
558+ \member{tp_getattro}: a subtype inherits both \member{tp_getattr}
559+ and \member{tp_getattro} from its base type when the subtype's
560+ \member{tp_getattr} and \member{tp_getattro} are both \NULL.
561+\end{cmemberdesc}
562+
563+\begin{cmemberdesc}{PyTypeObject}{setattrfunc}{tp_setattr}
564+ An optional pointer to the set-attribute-string function.
565+
566+ This field is deprecated. When it is defined, it should point to a
567+ function that acts the same as the \member{tp_setattro} function,
568+ but taking a C string instead of a Python string object to give the
569+ attribute name. The signature is the same as for
570+ \cfunction{PyObject_SetAttrString()}.
571+
572+ This field is inherited by subtypes together with
573+ \member{tp_setattro}: a subtype inherits both \member{tp_setattr}
574+ and \member{tp_setattro} from its base type when the subtype's
575+ \member{tp_setattr} and \member{tp_setattro} are both \NULL.
576+\end{cmemberdesc}
577+
578+\begin{cmemberdesc}{PyTypeObject}{cmpfunc}{tp_compare}
579+ An optional pointer to the three-way comparison function.
580+
581+ The signature is the same as for \cfunction{PyObject_Compare()}.
582+ The function should return \code{1} if \var{self} greater than
583+ \var{other}, \code{0} if \var{self} is equal to \var{other}, and
584+ \code{-1} if \var{self} less than \var{other}. It should return
585+ \code{-1} and set an exception condition when an error occurred
586+ during the comparison.
587+
588+ This field is inherited by subtypes together with
589+ \member{tp_richcompare} and \member{tp_hash}: a subtypes inherits
590+ all three of \member{tp_compare}, \member{tp_richcompare}, and
591+ \member{tp_hash} when the subtype's \member{tp_compare},
592+ \member{tp_richcompare}, and \member{tp_hash} are all \NULL.
593+\end{cmemberdesc}
594+
595+\begin{cmemberdesc}{PyTypeObject}{reprfunc}{tp_repr}
596+ An optional pointer to a function that implements the built-in
597+ function \function{repr()}.\bifuncindex{repr}
598+
599+ The signature is the same as for \cfunction{PyObject_Repr()}; it
600+ must return a string or a Unicode object. Ideally, this function
601+ should return a string that, when passed to \function{eval()}, given
602+ a suitable environment, returns an object with the same value. If
603+ this is not feasible, it should return a string starting with
604+ \character{\textless} and ending with \character{\textgreater} from
605+ which both the type and the value of the object can be deduced.
606+
607+ When this field is not set, a string of the form \samp{<\%s object
608+ at \%p>} is returned, where \code{\%s} is replaced by the type name,
609+ and \code{\%p} by the object's memory address.
610+
611+ This field is inherited by subtypes.
612+\end{cmemberdesc}
613+
614+PyNumberMethods *tp_as_number;
615+
616+ XXX
617+
618+PySequenceMethods *tp_as_sequence;
619+
620+ XXX
621+
622+PyMappingMethods *tp_as_mapping;
623+
624+ XXX
625+
626+\begin{cmemberdesc}{PyTypeObject}{hashfunc}{tp_hash}
627+ An optional pointer to a function that implements the built-in
628+ function \function{hash()}.\bifuncindex{hash}
629+
630+ The signature is the same as for \cfunction{PyObject_Hash()}; it
631+ must return a C long. The value \code{-1} should not be returned as
632+ a normal return value; when an error occurs during the computation
633+ of the hash value, the function should set an exception and return
634+ \code{-1}.
635+
636+ When this field is not set, two possibilities exist: if the
637+ \member{tp_compare} and \member{tp_richcompare} fields are both
638+ \NULL, a default hash value based on the object's address is
639+ returned; otherwise, a \exception{TypeError} is raised.
640+
641+ This field is inherited by subtypes together with
642+ \member{tp_richcompare} and \member{tp_compare}: a subtypes inherits
643+ all three of \member{tp_compare}, \member{tp_richcompare}, and
644+ \member{tp_hash}, when the subtype's \member{tp_compare},
645+ \member{tp_richcompare} and \member{tp_hash} are all \NULL.
646+\end{cmemberdesc}
647+
648+\begin{cmemberdesc}{PyTypeObject}{ternaryfunc}{tp_call}
649+ An optional pointer to a function that implements calling the
650+ object. This should be \NULL{} if the object is not callable. The
651+ signature is the same as for \cfunction{PyObject_Call()}.
652+
653+ This field is inherited by subtypes.
654+\end{cmemberdesc}
655+
656+\begin{cmemberdesc}{PyTypeObject}{reprfunc}{tp_str}
657+ An optional pointer to a function that implements the built-in
658+ operation \function{str()}. (Note that \class{str} is a type now,
659+ and \function{str()} calls the constructor for that type. This
660+ constructor calls \cfunction{PyObject_Str()} to do the actual work,
661+ and \cfunction{PyObject_Str()} will call this handler.)
662+
663+ The signature is the same as for \cfunction{PyObject_Str()}; it must
664+ return a string or a Unicode object. This function should return a
665+ ``friendly'' string representation of the object, as this is the
666+ representation that will be used by the print statement.
667+
668+ When this field is not set, \cfunction{PyObject_Repr()} is called to
669+ return a string representation.
670+
671+ This field is inherited by subtypes.
672+\end{cmemberdesc}
673+
674+\begin{cmemberdesc}{PyTypeObject}{getattrofunc}{tp_getattro}
675+ An optional pointer to the get-attribute function.
676+
677+ The signature is the same as for \cfunction{PyObject_GetAttr()}. It
678+ is usually convenient to set this field to
679+ \cfunction{PyObject_GenericGetAttr()}, which implements the normal
680+ way of looking for object attributes.
681+
682+ This field is inherited by subtypes together with
683+ \member{tp_getattr}: a subtype inherits both \member{tp_getattr} and
684+ \member{tp_getattro} from its base type when the subtype's
685+ \member{tp_getattr} and \member{tp_getattro} are both \NULL.
686+\end{cmemberdesc}
687+
688+\begin{cmemberdesc}{PyTypeObject}{setattrofunc}{tp_setattro}
689+ An optional pointer to the set-attribute function.
690+
691+ The signature is the same as for \cfunction{PyObject_SetAttr()}. It
692+ is usually convenient to set this field to
693+ \cfunction{PyObject_GenericSetAttr()}, which implements the normal
694+ way of setting object attributes.
695+
696+ This field is inherited by subtypes together with
697+ \member{tp_setattr}: a subtype inherits both \member{tp_setattr} and
698+ \member{tp_setattro} from its base type when the subtype's
699+ \member{tp_setattr} and \member{tp_setattro} are both \NULL.
700+\end{cmemberdesc}
701+
702+\begin{cmemberdesc}{PyTypeObject}{PyBufferProcs*}{tp_as_buffer}
703+ Pointer to an additional structure that contains fields relevant only to
704+ objects which implement the buffer interface. These fields are
705+ documented in ``Buffer Object Structures'' (section
706+ \ref{buffer-structs}).
707+
708+ The \member{tp_as_buffer} field is not inherited, but the contained
709+ fields are inherited individually.
710+\end{cmemberdesc}
711+
712+\begin{cmemberdesc}{PyTypeObject}{long}{tp_flags}
713+ This field is a bit mask of various flags. Some flags indicate
714+ variant semantics for certain situations; others are used to
715+ indicate that certain fields in the type object (or in the extension
716+ structures referenced via \member{tp_as_number},
717+ \member{tp_as_sequence}, \member{tp_as_mapping}, and
718+ \member{tp_as_buffer}) that were historically not always present are
719+ valid; if such a flag bit is clear, the type fields it guards must
720+ not be accessed and must be considered to have a zero or \NULL{}
721+ value instead.
722+
723+ Inheritance of this field is complicated. Most flag bits are
724+ inherited individually, i.e. if the base type has a flag bit set,
725+ the subtype inherits this flag bit. The flag bits that pertain to
726+ extension structures are strictly inherited if the extension
727+ structure is inherited, i.e. the base type's value of the flag bit
728+ is copied into the subtype together with a pointer to the extension
729+ structure. The \constant{Py_TPFLAGS_HAVE_GC} flag bit is inherited
730+ together with the \member{tp_traverse} and \member{tp_clear} fields,
731+ i.e. if the \constant{Py_TPFLAGS_HAVE_GC} flag bit is clear in the
732+ subtype and the \member{tp_traverse} and \member{tp_clear} fields in
733+ the subtype exist (as indicated by the
734+ \constant{Py_TPFLAGS_HAVE_RICHCOMPARE} flag bit) and have \NULL{}
735+ values.
736+
737+ The following bit masks are currently defined; these can be or-ed
738+ together using the \code{|} operator to form the value of the
739+ \member{tp_flags} field. The macro \cfunction{PyType_HasFeature()}
740+ takes a type and a flags value, \var{tp} and \var{f}, and checks
741+ whether \code{\var{tp}->tp_flags \& \var{f}} is non-zero.
742+
743+ \begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
744+ If this bit is set, the \ctype{PyBufferProcs} struct referenced by
745+ \member{tp_as_buffer} has the \member{bf_getcharbuffer} field.
746+ \end{datadesc}
747+
748+ \begin{datadesc}{Py_TPFLAGS_HAVE_SEQUENCE_IN}
749+ If this bit is set, the \ctype{PySequenceMethods} struct
750+ referenced by \member{tp_as_sequence} has the \member{sq_contains}
751+ field.
752+ \end{datadesc}
753+
754+ \begin{datadesc}{Py_TPFLAGS_GC}
755+ This bit is obsolete. The bit it used to name is no longer in
756+ use. The symbol is now defined as zero.
757+ \end{datadesc}
758+
759+ \begin{datadesc}{Py_TPFLAGS_HAVE_INPLACEOPS}
760+ If this bit is set, the \ctype{PySequenceMethods} struct
761+ referenced by \member{tp_as_sequence} and the
762+ \ctype{PyNumberMethods} structure referenced by
763+ \member{tp_as_number} contain the fields for in-place operators.
764+ In particular, this means that the \ctype{PyNumberMethods}
765+ structure has the fields \member{nb_inplace_add},
766+ \member{nb_inplace_subtract}, \member{nb_inplace_multiply},
767+ \member{nb_inplace_divide}, \member{nb_inplace_remainder},
768+ \member{nb_inplace_power}, \member{nb_inplace_lshift},
769+ \member{nb_inplace_rshift}, \member{nb_inplace_and},
770+ \member{nb_inplace_xor}, and \member{nb_inplace_or}; and the
771+ \ctype{PySequenceMethods} struct has the fields
772+ \member{sq_inplace_concat} and \member{sq_inplace_repeat}.
773+ \end{datadesc}
774+
775+ \begin{datadesc}{Py_TPFLAGS_CHECKTYPES}
776+ If this bit is set, the binary and ternary operations in the
777+ \ctype{PyNumberMethods} structure referenced by
778+ \member{tp_as_number} accept arguments of arbitrary object types,
779+ and do their own type conversions if needed. If this bit is
780+ clear, those operations require that all arguments have the
781+ current type as their type, and the caller is supposed to perform
782+ a coercion operation first. This applies to \member{nb_add},
783+ \member{nb_subtract}, \member{nb_multiply}, \member{nb_divide},
784+ \member{nb_remainder}, \member{nb_divmod}, \member{nb_power},
785+ \member{nb_lshift}, \member{nb_rshift}, \member{nb_and},
786+ \member{nb_xor}, and \member{nb_or}.
787+ \end{datadesc}
788+
789+ \begin{datadesc}{Py_TPFLAGS_HAVE_RICHCOMPARE}
790+ If this bit is set, the type object has the
791+ \member{tp_richcompare} field, as well as the \member{tp_traverse}
792+ and the \member{tp_clear} fields.
793+ \end{datadesc}
794+
795+ \begin{datadesc}{Py_TPFLAGS_HAVE_WEAKREFS}
796+ If this bit is set, the \member{tp_weaklistoffset} field is
797+ defined. Instances of a type are weakly referenceable if the
798+ type's \member{tp_weaklistoffset} field has a value greater than
799+ zero.
800+ \end{datadesc}
801+
802+ \begin{datadesc}{Py_TPFLAGS_HAVE_ITER}
803+ If this bit is set, the type object has the \member{tp_iter} and
804+ \member{tp_iternext} fields.
805+ \end{datadesc}
806+
807+ \begin{datadesc}{Py_TPFLAGS_HAVE_CLASS}
808+ If this bit is set, the type object has several new fields defined
809+ starting in Python 2.2: \member{tp_methods}, \member{tp_members},
810+ \member{tp_getset}, \member{tp_base}, \member{tp_dict},
811+ \member{tp_descr_get}, \member{tp_descr_set},
812+ \member{tp_dictoffset}, \member{tp_init}, \member{tp_alloc},
813+ \member{tp_new}, \member{tp_free}, \member{tp_is_gc},
814+ \member{tp_bases}, \member{tp_mro}, \member{tp_cache},
815+ \member{tp_subclasses}, and \member{tp_weaklist}.
816+ \end{datadesc}
817+
818+ \begin{datadesc}{Py_TPFLAGS_HEAPTYPE}
819+ This bit is set when the type object itself is allocated on the
820+ heap. In this case, the \member{ob_type} field of its instances
821+ is considered a reference to the type, and the type object is
822+ INCREF'ed when a new instance is created, and DECREF'ed when an
823+ instance is destroyed (this does not apply to instances of
824+ subtypes; only the type referenced by the instance's ob_type gets
825+ INCREF'ed or DECREF'ed).
826+ \end{datadesc}
827+
828+ \begin{datadesc}{Py_TPFLAGS_BASETYPE}
829+ This bit is set when the type can be used as the base type of
830+ another type. If this bit is clear, the type cannot be subtyped
831+ (similar to a "final" class in Java).
832+ \end{datadesc}
833+
834+ \begin{datadesc}{Py_TPFLAGS_READY}
835+ This bit is set when the type object has been fully initialized by
836+ \cfunction{PyType_Ready()}.
837+ \end{datadesc}
838+
839+ \begin{datadesc}{Py_TPFLAGS_READYING}
840+ This bit is set while \cfunction{PyType_Ready()} is in the process
841+ of initializing the type object.
842+ \end{datadesc}
843+
844+ \begin{datadesc}{Py_TPFLAGS_HAVE_GC}
845+ This bit is set when the object supports garbage collection. If
846+ this bit is set, instances must be created using
847+ \cfunction{PyObject_GC_New()} and destroyed using
848+ \cfunction{PyObject_GC_Del()}. More information in section XXX
849+ about garbage collection. This bit also implies that the
850+ GC-related fields \member{tp_traverse} and \member{tp_clear} are
851+ present in the type object; but those fields also exist when
852+ \constant{Py_TPFLAGS_HAVE_GC} is clear but
853+ \constant{Py_TPFLAGS_HAVE_RICHCOMPARE} is set.
854+ \end{datadesc}
855+
856+ \begin{datadesc}{Py_TPFLAGS_DEFAULT}
857+ This is a bitmask of all the bits that pertain to the existence of
858+ certain fields in the type object and its extension structures.
859+ Currently, it includes the following bits:
860+ \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER},
861+ \constant{Py_TPFLAGS_HAVE_SEQUENCE_IN},
862+ \constant{Py_TPFLAGS_HAVE_INPLACEOPS},
863+ \constant{Py_TPFLAGS_HAVE_RICHCOMPARE},
864+ \constant{Py_TPFLAGS_HAVE_WEAKREFS},
865+ \constant{Py_TPFLAGS_HAVE_ITER}, and
866+ \constant{Py_TPFLAGS_HAVE_CLASS}.
867+ \end{datadesc}
868+\end{cmemberdesc}
869+
870+\begin{cmemberdesc}{PyTypeObject}{char*}{tp_doc}
871+ An optional pointer to a NUL-terminated C string giving the
872+ docstring for this type object. This is exposed as the
873+ \member{__doc__} attribute on the type and instances of the type.
874+
875+ This field is \emph{not} inherited by subtypes.
876+\end{cmemberdesc}
877+
878+The following three fields only exist if the
879+\constant{Py_TPFLAGS_HAVE_RICHCOMPARE} flag bit is set.
880+
881+\begin{cmemberdesc}{PyTypeObject}{traverseproc}{tp_traverse}
882+ An optional pointer to a traversal function for the garbage
883+ collector. This is only used if the \constant{Py_TPFLAGS_HAVE_GC}
884+ flag bit is set. More information about Python's garbage collection
885+ scheme can be found in section \ref{supporting-cycle-detection}.
886+
887+ The \member{tp_traverse} pointer is used by the garbage collector
888+ to detect reference cycles. A typical implementation of a
889+ \member{tp_traverse} function simply calls \cfunction{Py_VISIT()} on
890+ each of the instance's members that are Python objects. For exampe, this
891+ is function \cfunction{local_traverse} from the \module{thread} extension
892+ module:
893+
894+ \begin{verbatim}
895+ static int
896+ local_traverse(localobject *self, visitproc visit, void *arg)
897+ {
898+ Py_VISIT(self->args);
899+ Py_VISIT(self->kw);
900+ Py_VISIT(self->dict);
901+ return 0;
902+ }
903+ \end{verbatim}
904+
905+ Note that \cfunction{Py_VISIT()} is called only on those members that can
906+ participate in reference cycles. Although there is also a
907+ \samp{self->key} member, it can only be \NULL{} or a Python string and
908+ therefore cannot be part of a reference cycle.
909+
910+ On the other hand, even if you know a member can never be part of a cycle,
911+ as a debugging aid you may want to visit it anyway just so the
912+ \module{gc} module's \function{get_referents()} function will include it.
913+
914+ Note that \cfunction{Py_VISIT()} requires the \var{visit} and \var{arg}
915+ parameters to \cfunction{local_traverse} to have these specific names;
916+ don't name them just anything.
917+
918+ This field is inherited by subtypes together with \member{tp_clear}
919+ and the \constant{Py_TPFLAGS_HAVE_GC} flag bit: the flag bit,
920+ \member{tp_traverse}, and \member{tp_clear} are all inherited from
921+ the base type if they are all zero in the subtype \emph{and} the
922+ subtype has the \constant{Py_TPFLAGS_HAVE_RICHCOMPARE} flag bit set.
923+\end{cmemberdesc}
924+
925+\begin{cmemberdesc}{PyTypeObject}{inquiry}{tp_clear}
926+ An optional pointer to a clear function for the garbage collector.
927+ This is only used if the \constant{Py_TPFLAGS_HAVE_GC} flag bit is
928+ set.
929+
930+ The \member{tp_clear} member function is used to break reference
931+ cycles in cyclic garbage detected by the garbage collector. Taken
932+ together, all \member{tp_clear} functions in the system must combine to
933+ break all reference cycles. This is subtle, and if in any doubt supply a
934+ \member{tp_clear} function. For example, the tuple type does not
935+ implement a \member{tp_clear} function, because it's possible to prove
936+ that no reference cycle can be composed entirely of tuples. Therefore
937+ the \member{tp_clear} functions of other types must be sufficient to
938+ break any cycle containing a tuple. This isn't immediately obvious, and
939+ there's rarely a good reason to avoid implementing \member{tp_clear}.
940+
941+ Implementations of \member{tp_clear} should drop the instance's
942+ references to those of its members that may be Python objects, and set
943+ its pointers to those members to \NULL{}, as in the following example:
944+
945+ \begin{verbatim}
946+ static int
947+ local_clear(localobject *self)
948+ {
949+ Py_CLEAR(self->key);
950+ Py_CLEAR(self->args);
951+ Py_CLEAR(self->kw);
952+ Py_CLEAR(self->dict);
953+ return 0;
954+ }
955+ \end{verbatim}
956+
957+ The \cfunction{Py_CLEAR()} macro should be used, because clearing
958+ references is delicate: the reference to the contained object must not be
959+ decremented until after the pointer to the contained object is set to
960+ \NULL{}. This is because decrementing the reference count may cause
961+ the contained object to become trash, triggering a chain of reclamation
962+ activity that may include invoking arbitrary Python code (due to
963+ finalizers, or weakref callbacks, associated with the contained object).
964+ If it's possible for such code to reference \var{self} again, it's
965+ important that the pointer to the contained object be \NULL{} at that
966+ time, so that \var{self} knows the contained object can no longer be
967+ used. The \cfunction{Py_CLEAR()} macro performs the operations in a
968+ safe order.
969+
970+ Because the goal of \member{tp_clear} functions is to break reference
971+ cycles, it's not necessary to clear contained objects like Python strings
972+ or Python integers, which can't participate in reference cycles.
973+ On the other hand, it may be convenient to clear all contained Python
974+ objects, and write the type's \member{tp_dealloc} function to
975+ invoke \member{tp_clear}.
976+
977+ More information about Python's garbage collection
978+ scheme can be found in section \ref{supporting-cycle-detection}.
979+
980+ This field is inherited by subtypes together with \member{tp_traverse}
981+ and the \constant{Py_TPFLAGS_HAVE_GC} flag bit: the flag bit,
982+ \member{tp_traverse}, and \member{tp_clear} are all inherited from
983+ the base type if they are all zero in the subtype \emph{and} the
984+ subtype has the \constant{Py_TPFLAGS_HAVE_RICHCOMPARE} flag bit set.
985+\end{cmemberdesc}
986+
987+\begin{cmemberdesc}{PyTypeObject}{richcmpfunc}{tp_richcompare}
988+ An optional pointer to the rich comparison function.
989+
990+ The signature is the same as for \cfunction{PyObject_RichCompare()}.
991+ The function should return the result of the comparison (usually
992+ \code{Py_True} or \code{Py_False}). If the comparison is undefined,
993+ it must return \code{Py_NotImplemented}, if another error occurred
994+ it must return \code{NULL} and set an exception condition.
995+
996+ This field is inherited by subtypes together with
997+ \member{tp_compare} and \member{tp_hash}: a subtype inherits all
998+ three of \member{tp_compare}, \member{tp_richcompare}, and
999+ \member{tp_hash}, when the subtype's \member{tp_compare},
1000+ \member{tp_richcompare}, and \member{tp_hash} are all \NULL.
1001+
1002+ The following constants are defined to be used as the third argument
1003+ for \member{tp_richcompare} and for \cfunction{PyObject_RichCompare()}:
1004+
1005+ \begin{tableii}{l|c}{constant}{Constant}{Comparison}
1006+ \lineii{Py_LT}{\code{<}}
1007+ \lineii{Py_LE}{\code{<=}}
1008+ \lineii{Py_EQ}{\code{==}}
1009+ \lineii{Py_NE}{\code{!=}}
1010+ \lineii{Py_GT}{\code{>}}
1011+ \lineii{Py_GE}{\code{>=}}
1012+ \end{tableii}
1013+\end{cmemberdesc}
1014+
1015+The next field only exists if the \constant{Py_TPFLAGS_HAVE_WEAKREFS}
1016+flag bit is set.
1017+
1018+\begin{cmemberdesc}{PyTypeObject}{long}{tp_weaklistoffset}
1019+ If the instances of this type are weakly referenceable, this field
1020+ is greater than zero and contains the offset in the instance
1021+ structure of the weak reference list head (ignoring the GC header,
1022+ if present); this offset is used by
1023+ \cfunction{PyObject_ClearWeakRefs()} and the
1024+ \cfunction{PyWeakref_*()} functions. The instance structure needs
1025+ to include a field of type \ctype{PyObject*} which is initialized to
1026+ \NULL.
1027+
1028+ Do not confuse this field with \member{tp_weaklist}; that is the
1029+ list head for weak references to the type object itself.
1030+
1031+ This field is inherited by subtypes, but see the rules listed below.
1032+ A subtype may override this offset; this means that the subtype uses
1033+ a different weak reference list head than the base type. Since the
1034+ list head is always found via \member{tp_weaklistoffset}, this
1035+ should not be a problem.
1036+
1037+ When a type defined by a class statement has no \member{__slots__}
1038+ declaration, and none of its base types are weakly referenceable,
1039+ the type is made weakly referenceable by adding a weak reference
1040+ list head slot to the instance layout and setting the
1041+ \member{tp_weaklistoffset} of that slot's offset.
1042+
1043+ When a type's \member{__slots__} declaration contains a slot named
1044+ \member{__weakref__}, that slot becomes the weak reference list head
1045+ for instances of the type, and the slot's offset is stored in the
1046+ type's \member{tp_weaklistoffset}.
1047+
1048+ When a type's \member{__slots__} declaration does not contain a slot
1049+ named \member{__weakref__}, the type inherits its
1050+ \member{tp_weaklistoffset} from its base type.
1051+\end{cmemberdesc}
1052+
1053+The next two fields only exist if the
1054+\constant{Py_TPFLAGS_HAVE_CLASS} flag bit is set.
1055+
1056+\begin{cmemberdesc}{PyTypeObject}{getiterfunc}{tp_iter}
1057+ An optional pointer to a function that returns an iterator for the
1058+ object. Its presence normally signals that the instances of this
1059+ type are iterable (although sequences may be iterable without this
1060+ function, and classic instances always have this function, even if
1061+ they don't define an \method{__iter__()} method).
1062+
1063+ This function has the same signature as
1064+ \cfunction{PyObject_GetIter()}.
1065+
1066+ This field is inherited by subtypes.
1067+\end{cmemberdesc}
1068+
1069+\begin{cmemberdesc}{PyTypeObject}{iternextfunc}{tp_iternext}
1070+ An optional pointer to a function that returns the next item in an
1071+ iterator, or raises \exception{StopIteration} when the iterator is
1072+ exhausted. Its presence normally signals that the instances of this
1073+ type are iterators (although classic instances always have this
1074+ function, even if they don't define a \method{next()} method).
1075+
1076+ Iterator types should also define the \member{tp_iter} function, and
1077+ that function should return the iterator instance itself (not a new
1078+ iterator instance).
1079+
1080+ This function has the same signature as \cfunction{PyIter_Next()}.
1081+
1082+ This field is inherited by subtypes.
1083+\end{cmemberdesc}
1084+
1085+The next fields, up to and including \member{tp_weaklist}, only exist
1086+if the \constant{Py_TPFLAGS_HAVE_CLASS} flag bit is set.
1087+
1088+\begin{cmemberdesc}{PyTypeObject}{struct PyMethodDef*}{tp_methods}
1089+ An optional pointer to a static \NULL-terminated array of
1090+ \ctype{PyMethodDef} structures, declaring regular methods of this
1091+ type.
1092+
1093+ For each entry in the array, an entry is added to the type's
1094+ dictionary (see \member{tp_dict} below) containing a method
1095+ descriptor.
1096+
1097+ This field is not inherited by subtypes (methods are
1098+ inherited through a different mechanism).
1099+\end{cmemberdesc}
1100+
1101+\begin{cmemberdesc}{PyTypeObject}{struct PyMemberDef*}{tp_members}
1102+ An optional pointer to a static \NULL-terminated array of
1103+ \ctype{PyMemberDef} structures, declaring regular data members
1104+ (fields or slots) of instances of this type.
1105+
1106+ For each entry in the array, an entry is added to the type's
1107+ dictionary (see \member{tp_dict} below) containing a member
1108+ descriptor.
1109+
1110+ This field is not inherited by subtypes (members are inherited
1111+ through a different mechanism).
1112+\end{cmemberdesc}
1113+
1114+\begin{cmemberdesc}{PyTypeObject}{struct PyGetSetDef*}{tp_getset}
1115+ An optional pointer to a static \NULL-terminated array of
1116+ \ctype{PyGetSetDef} structures, declaring computed attributes of
1117+ instances of this type.
1118+
1119+ For each entry in the array, an entry is added to the type's
1120+ dictionary (see \member{tp_dict} below) containing a getset
1121+ descriptor.
1122+
1123+ This field is not inherited by subtypes (computed attributes are
1124+ inherited through a different mechanism).
1125+
1126+ Docs for PyGetSetDef (XXX belong elsewhere):
1127+
1128+\begin{verbatim}
1129+typedef PyObject *(*getter)(PyObject *, void *);
1130+typedef int (*setter)(PyObject *, PyObject *, void *);
1131+
1132+typedef struct PyGetSetDef {
1133+ char *name; /* attribute name */
1134+ getter get; /* C function to get the attribute */
1135+ setter set; /* C function to set the attribute */
1136+ char *doc; /* optional doc string */
1137+ void *closure; /* optional additional data for getter and setter */
1138+} PyGetSetDef;
1139+\end{verbatim}
1140+\end{cmemberdesc}
1141+
1142+\begin{cmemberdesc}{PyTypeObject}{PyTypeObject*}{tp_base}
1143+ An optional pointer to a base type from which type properties are
1144+ inherited. At this level, only single inheritance is supported;
1145+ multiple inheritance require dynamically creating a type object by
1146+ calling the metatype.
1147+
1148+ This field is not inherited by subtypes (obviously), but it defaults
1149+ to \code{\&PyBaseObject_Type} (which to Python programmers is known
1150+ as the type \class{object}).
1151+\end{cmemberdesc}
1152+
1153+\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_dict}
1154+ The type's dictionary is stored here by \cfunction{PyType_Ready()}.
1155+
1156+ This field should normally be initialized to \NULL{} before
1157+ PyType_Ready is called; it may also be initialized to a dictionary
1158+ containing initial attributes for the type. Once
1159+ \cfunction{PyType_Ready()} has initialized the type, extra
1160+ attributes for the type may be added to this dictionary only if they
1161+ don't correspond to overloaded operations (like \method{__add__()}).
1162+
1163+ This field is not inherited by subtypes (though the attributes
1164+ defined in here are inherited through a different mechanism).
1165+\end{cmemberdesc}
1166+
1167+\begin{cmemberdesc}{PyTypeObject}{descrgetfunc}{tp_descr_get}
1168+ An optional pointer to a "descriptor get" function.
1169+
1170+
1171+ The function signature is
1172+
1173+\begin{verbatim}
1174+PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
1175+\end{verbatim}
1176+
1177+ XXX blah, blah.
1178+
1179+ This field is inherited by subtypes.
1180+\end{cmemberdesc}
1181+
1182+\begin{cmemberdesc}{PyTypeObject}{descrsetfunc}{tp_descr_set}
1183+ An optional pointer to a "descriptor set" function.
1184+
1185+ The function signature is
1186+
1187+\begin{verbatim}
1188+int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);
1189+\end{verbatim}
1190+
1191+ This field is inherited by subtypes.
1192+
1193+ XXX blah, blah.
1194+
1195+\end{cmemberdesc}
1196+
1197+\begin{cmemberdesc}{PyTypeObject}{long}{tp_dictoffset}
1198+ If the instances of this type have a dictionary containing instance
1199+ variables, this field is non-zero and contains the offset in the
1200+ instances of the type of the instance variable dictionary; this
1201+ offset is used by \cfunction{PyObject_GenericGetAttr()}.
1202+
1203+ Do not confuse this field with \member{tp_dict}; that is the
1204+ dictionary for attributes of the type object itself.
1205+
1206+ If the value of this field is greater than zero, it specifies the
1207+ offset from the start of the instance structure. If the value is
1208+ less than zero, it specifies the offset from the \emph{end} of the
1209+ instance structure. A negative offset is more expensive to use, and
1210+ should only be used when the instance structure contains a
1211+ variable-length part. This is used for example to add an instance
1212+ variable dictionary to subtypes of \class{str} or \class{tuple}.
1213+ Note that the \member{tp_basicsize} field should account for the
1214+ dictionary added to the end in that case, even though the dictionary
1215+ is not included in the basic object layout. On a system with a
1216+ pointer size of 4 bytes, \member{tp_dictoffset} should be set to
1217+ \code{-4} to indicate that the dictionary is at the very end of the
1218+ structure.
1219+
1220+ The real dictionary offset in an instance can be computed from a
1221+ negative \member{tp_dictoffset} as follows:
1222+
1223+\begin{verbatim}
1224+dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
1225+if dictoffset is not aligned on sizeof(void*):
1226+ round up to sizeof(void*)
1227+\end{verbatim}
1228+
1229+ where \member{tp_basicsize}, \member{tp_itemsize} and
1230+ \member{tp_dictoffset} are taken from the type object, and
1231+ \member{ob_size} is taken from the instance. The absolute value is
1232+ taken because long ints use the sign of \member{ob_size} to store
1233+ the sign of the number. (There's never a need to do this
1234+ calculation yourself; it is done for you by
1235+ \cfunction{_PyObject_GetDictPtr()}.)
1236+
1237+ This field is inherited by subtypes, but see the rules listed below.
1238+ A subtype may override this offset; this means that the subtype
1239+ instances store the dictionary at a difference offset than the base
1240+ type. Since the dictionary is always found via
1241+ \member{tp_dictoffset}, this should not be a problem.
1242+
1243+ When a type defined by a class statement has no \member{__slots__}
1244+ declaration, and none of its base types has an instance variable
1245+ dictionary, a dictionary slot is added to the instance layout and
1246+ the \member{tp_dictoffset} is set to that slot's offset.
1247+
1248+ When a type defined by a class statement has a \member{__slots__}
1249+ declaration, the type inherits its \member{tp_dictoffset} from its
1250+ base type.
1251+
1252+ (Adding a slot named \member{__dict__} to the \member{__slots__}
1253+ declaration does not have the expected effect, it just causes
1254+ confusion. Maybe this should be added as a feature just like
1255+ \member{__weakref__} though.)
1256+\end{cmemberdesc}
1257+
1258+\begin{cmemberdesc}{PyTypeObject}{initproc}{tp_init}
1259+ An optional pointer to an instance initialization function.
1260+
1261+ This function corresponds to the \method{__init__()} method of
1262+ classes. Like \method{__init__()}, it is possible to create an
1263+ instance without calling \method{__init__()}, and it is possible to
1264+ reinitialize an instance by calling its \method{__init__()} method
1265+ again.
1266+
1267+ The function signature is
1268+
1269+\begin{verbatim}
1270+int tp_init(PyObject *self, PyObject *args, PyObject *kwds)
1271+\end{verbatim}
1272+
1273+ The self argument is the instance to be initialized; the \var{args}
1274+ and \var{kwds} arguments represent positional and keyword arguments
1275+ of the call to \method{__init__()}.
1276+
1277+ The \member{tp_init} function, if not \NULL, is called when an
1278+ instance is created normally by calling its type, after the type's
1279+ \member{tp_new} function has returned an instance of the type. If
1280+ the \member{tp_new} function returns an instance of some other type
1281+ that is not a subtype of the original type, no \member{tp_init}
1282+ function is called; if \member{tp_new} returns an instance of a
1283+ subtype of the original type, the subtype's \member{tp_init} is
1284+ called. (VERSION NOTE: described here is what is implemented in
1285+ Python 2.2.1 and later. In Python 2.2, the \member{tp_init} of the
1286+ type of the object returned by \member{tp_new} was always called, if
1287+ not \NULL.)
1288+
1289+ This field is inherited by subtypes.
1290+\end{cmemberdesc}
1291+
1292+\begin{cmemberdesc}{PyTypeObject}{allocfunc}{tp_alloc}
1293+ An optional pointer to an instance allocation function.
1294+
1295+ The function signature is
1296+
1297+\begin{verbatim}
1298+PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems)
1299+\end{verbatim}
1300+
1301+ The purpose of this function is to separate memory allocation from
1302+ memory initialization. It should return a pointer to a block of
1303+ memory of adequate length for the instance, suitably aligned, and
1304+ initialized to zeros, but with \member{ob_refcnt} set to \code{1}
1305+ and \member{ob_type} set to the type argument. If the type's
1306+ \member{tp_itemsize} is non-zero, the object's \member{ob_size} field
1307+ should be initialized to \var{nitems} and the length of the
1308+ allocated memory block should be \code{tp_basicsize +
1309+ \var{nitems}*tp_itemsize}, rounded up to a multiple of
1310+ \code{sizeof(void*)}; otherwise, \var{nitems} is not used and the
1311+ length of the block should be \member{tp_basicsize}.
1312+
1313+ Do not use this function to do any other instance initialization,
1314+ not even to allocate additional memory; that should be done by
1315+ \member{tp_new}.
1316+
1317+ This field is inherited by static subtypes, but not by dynamic
1318+ subtypes (subtypes created by a class statement); in the latter,
1319+ this field is always set to \cfunction{PyType_GenericAlloc()}, to
1320+ force a standard heap allocation strategy. That is also the
1321+ recommended value for statically defined types.
1322+\end{cmemberdesc}
1323+
1324+\begin{cmemberdesc}{PyTypeObject}{newfunc}{tp_new}
1325+ An optional pointer to an instance creation function.
1326+
1327+ If this function is \NULL{} for a particular type, that type cannot
1328+ be called to create new instances; presumably there is some other
1329+ way to create instances, like a factory function.
1330+
1331+ The function signature is
1332+
1333+\begin{verbatim}
1334+PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
1335+\end{verbatim}
1336+
1337+ The subtype argument is the type of the object being created; the
1338+ \var{args} and \var{kwds} arguments represent positional and keyword
1339+ arguments of the call to the type. Note that subtype doesn't have
1340+ to equal the type whose \member{tp_new} function is called; it may
1341+ be a subtype of that type (but not an unrelated type).
1342+
1343+ The \member{tp_new} function should call
1344+ \code{\var{subtype}->tp_alloc(\var{subtype}, \var{nitems})} to
1345+ allocate space for the object, and then do only as much further
1346+ initialization as is absolutely necessary. Initialization that can
1347+ safely be ignored or repeated should be placed in the
1348+ \member{tp_init} handler. A good rule of thumb is that for
1349+ immutable types, all initialization should take place in
1350+ \member{tp_new}, while for mutable types, most initialization should
1351+ be deferred to \member{tp_init}.
1352+
1353+ This field is inherited by subtypes, except it is not inherited by
1354+ static types whose \member{tp_base} is \NULL{} or
1355+ \code{\&PyBaseObject_Type}. The latter exception is a precaution so
1356+ that old extension types don't become callable simply by being
1357+ linked with Python 2.2.
1358+\end{cmemberdesc}
1359+
1360+\begin{cmemberdesc}{PyTypeObject}{destructor}{tp_free}
1361+ An optional pointer to an instance deallocation function.
1362+
1363+ The signature of this function has changed slightly: in Python
1364+ 2.2 and 2.2.1, its signature is \ctype{destructor}:
1365+
1366+\begin{verbatim}
1367+void tp_free(PyObject *)
1368+\end{verbatim}
1369+
1370+ In Python 2.3 and beyond, its signature is \ctype{freefunc}:
1371+
1372+\begin{verbatim}
1373+void tp_free(void *)
1374+\end{verbatim}
1375+
1376+ The only initializer that is compatible with both versions is
1377+ \code{_PyObject_Del}, whose definition has suitably adapted in
1378+ Python 2.3.
1379+
1380+ This field is inherited by static subtypes, but not by dynamic
1381+ subtypes (subtypes created by a class statement); in the latter,
1382+ this field is set to a deallocator suitable to match
1383+ \cfunction{PyType_GenericAlloc()} and the value of the
1384+ \constant{Py_TPFLAGS_HAVE_GC} flag bit.
1385+\end{cmemberdesc}
1386+
1387+\begin{cmemberdesc}{PyTypeObject}{inquiry}{tp_is_gc}
1388+ An optional pointer to a function called by the garbage collector.
1389+
1390+ The garbage collector needs to know whether a particular object is
1391+ collectible or not. Normally, it is sufficient to look at the
1392+ object's type's \member{tp_flags} field, and check the
1393+ \constant{Py_TPFLAGS_HAVE_GC} flag bit. But some types have a
1394+ mixture of statically and dynamically allocated instances, and the
1395+ statically allocated instances are not collectible. Such types
1396+ should define this function; it should return \code{1} for a
1397+ collectible instance, and \code{0} for a non-collectible instance.
1398+ The signature is
1399+
1400+\begin{verbatim}
1401+int tp_is_gc(PyObject *self)
1402+\end{verbatim}
1403+
1404+ (The only example of this are types themselves. The metatype,
1405+ \cdata{PyType_Type}, defines this function to distinguish between
1406+ statically and dynamically allocated types.)
1407+
1408+ This field is inherited by subtypes. (VERSION NOTE: in Python
1409+ 2.2, it was not inherited. It is inherited in 2.2.1 and later
1410+ versions.)
1411+\end{cmemberdesc}
1412+
1413+\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_bases}
1414+ Tuple of base types.
1415+
1416+ This is set for types created by a class statement. It should be
1417+ \NULL{} for statically defined types.
1418+
1419+ This field is not inherited.
1420+\end{cmemberdesc}
1421+
1422+\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_mro}
1423+ Tuple containing the expanded set of base types, starting with the
1424+ type itself and ending with \class{object}, in Method Resolution
1425+ Order.
1426+
1427+ This field is not inherited; it is calculated fresh by
1428+ \cfunction{PyType_Ready()}.
1429+\end{cmemberdesc}
1430+
1431+\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_cache}
1432+ Unused. Not inherited. Internal use only.
1433+\end{cmemberdesc}
1434+
1435+\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_subclasses}
1436+ List of weak references to subclasses. Not inherited. Internal
1437+ use only.
1438+\end{cmemberdesc}
1439+
1440+\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_weaklist}
1441+ Weak reference list head, for weak references to this type
1442+ object. Not inherited. Internal use only.
1443+\end{cmemberdesc}
1444+
1445+The remaining fields are only defined if the feature test macro
1446+\constant{COUNT_ALLOCS} is defined, and are for internal use only.
1447+They are documented here for completeness. None of these fields are
1448+inherited by subtypes.
1449+
1450+\begin{cmemberdesc}{PyTypeObject}{Py_ssize_t}{tp_allocs}
1451+ Number of allocations.
1452+\end{cmemberdesc}
1453+
1454+\begin{cmemberdesc}{PyTypeObject}{Py_ssize_t}{tp_frees}
1455+ Number of frees.
1456+\end{cmemberdesc}
1457+
1458+\begin{cmemberdesc}{PyTypeObject}{Py_ssize_t}{tp_maxalloc}
1459+ Maximum simultaneously allocated objects.
1460+\end{cmemberdesc}
1461+
1462+\begin{cmemberdesc}{PyTypeObject}{PyTypeObject*}{tp_next}
1463+ Pointer to the next type object with a non-zero \member{tp_allocs}
1464+ field.
1465+\end{cmemberdesc}
1466+
1467+Also, note that, in a garbage collected Python, tp_dealloc may be
1468+called from any Python thread, not just the thread which created the
1469+object (if the object becomes part of a refcount cycle, that cycle
1470+might be collected by a garbage collection on any thread). This is
1471+not a problem for Python API calls, since the thread on which
1472+tp_dealloc is called will own the Global Interpreter Lock (GIL).
1473+However, if the object being destroyed in turn destroys objects from
1474+some other C or \Cpp{} library, care should be taken to ensure that
1475+destroying those objects on the thread which called tp_dealloc will
1476+not violate any assumptions of the library.
1477+
1478+\section{Mapping Object Structures \label{mapping-structs}}
1479+
1480+\begin{ctypedesc}{PyMappingMethods}
1481+ Structure used to hold pointers to the functions used to implement
1482+ the mapping protocol for an extension type.
1483+\end{ctypedesc}
1484+
1485+
1486+\section{Number Object Structures \label{number-structs}}
1487+
1488+\begin{ctypedesc}{PyNumberMethods}
1489+ Structure used to hold pointers to the functions an extension type
1490+ uses to implement the number protocol.
1491+\end{ctypedesc}
1492+
1493+
1494+\section{Sequence Object Structures \label{sequence-structs}}
1495+
1496+\begin{ctypedesc}{PySequenceMethods}
1497+ Structure used to hold pointers to the functions which an object
1498+ uses to implement the sequence protocol.
1499+\end{ctypedesc}
1500+
1501+
1502+\section{Buffer Object Structures \label{buffer-structs}}
1503+\sectionauthor{Greg J. Stein}{greg@lyra.org}
1504+
1505+The buffer interface exports a model where an object can expose its
1506+internal data as a set of chunks of data, where each chunk is
1507+specified as a pointer/length pair. These chunks are called
1508+\dfn{segments} and are presumed to be non-contiguous in memory.
1509+
1510+If an object does not export the buffer interface, then its
1511+\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
1512+should be \NULL. Otherwise, the \member{tp_as_buffer} will point to
1513+a \ctype{PyBufferProcs} structure.
1514+
1515+\note{It is very important that your \ctype{PyTypeObject} structure
1516+uses \constant{Py_TPFLAGS_DEFAULT} for the value of the
1517+\member{tp_flags} member rather than \code{0}. This tells the Python
1518+runtime that your \ctype{PyBufferProcs} structure contains the
1519+\member{bf_getcharbuffer} slot. Older versions of Python did not have
1520+this member, so a new Python interpreter using an old extension needs
1521+to be able to test for its presence before using it.}
1522+
1523+\begin{ctypedesc}{PyBufferProcs}
1524+ Structure used to hold the function pointers which define an
1525+ implementation of the buffer protocol.
1526+
1527+ The first slot is \member{bf_getreadbuffer}, of type
1528+ \ctype{getreadbufferproc}. If this slot is \NULL, then the object
1529+ does not support reading from the internal data. This is
1530+ non-sensical, so implementors should fill this in, but callers
1531+ should test that the slot contains a non-\NULL{} value.
1532+
1533+ The next slot is \member{bf_getwritebuffer} having type
1534+ \ctype{getwritebufferproc}. This slot may be \NULL{} if the object
1535+ does not allow writing into its returned buffers.
1536+
1537+ The third slot is \member{bf_getsegcount}, with type
1538+ \ctype{getsegcountproc}. This slot must not be \NULL{} and is used
1539+ to inform the caller how many segments the object contains. Simple
1540+ objects such as \ctype{PyString_Type} and \ctype{PyBuffer_Type}
1541+ objects contain a single segment.
1542+
1543+ The last slot is \member{bf_getcharbuffer}, of type
1544+ \ctype{getcharbufferproc}. This slot will only be present if the
1545+ \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
1546+ \member{tp_flags} field of the object's \ctype{PyTypeObject}.
1547+ Before using this slot, the caller should test whether it is present
1548+ by using the
1549+ \cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()}
1550+ function. If the flag is present, \member{bf_getcharbuffer} may be
1551+ \NULL,
1552+ indicating that the object's
1553+ contents cannot be used as \emph{8-bit characters}.
1554+ The slot function may also raise an error if the object's contents
1555+ cannot be interpreted as 8-bit characters. For example, if the
1556+ object is an array which is configured to hold floating point
1557+ values, an exception may be raised if a caller attempts to use
1558+ \member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
1559+ This notion of exporting the internal buffers as ``text'' is used to
1560+ distinguish between objects that are binary in nature, and those
1561+ which have character-based content.
1562+
1563+ \note{The current policy seems to state that these characters
1564+ may be multi-byte characters. This implies that a buffer size of
1565+ \var{N} does not mean there are \var{N} characters present.}
1566+\end{ctypedesc}
1567+
1568+\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
1569+ Flag bit set in the type structure to indicate that the
1570+ \member{bf_getcharbuffer} slot is known. This being set does not
1571+ indicate that the object supports the buffer interface or that the
1572+ \member{bf_getcharbuffer} slot is non-\NULL.
1573+\end{datadesc}
1574+
1575+\begin{ctypedesc}[getreadbufferproc]{Py_ssize_t (*readbufferproc)
1576+ (PyObject *self, Py_ssize_t segment, void **ptrptr)}
1577+ Return a pointer to a readable segment of the buffer in
1578+ \code{*\var{ptrptr}}. This function
1579+ is allowed to raise an exception, in which case it must return
1580+ \code{-1}. The \var{segment} which is specified must be zero or
1581+ positive, and strictly less than the number of segments returned by
1582+ the \member{bf_getsegcount} slot function. On success, it returns
1583+ the length of the segment, and sets \code{*\var{ptrptr}} to a
1584+ pointer to that memory.
1585+\end{ctypedesc}
1586+
1587+\begin{ctypedesc}[getwritebufferproc]{Py_ssize_t (*writebufferproc)
1588+ (PyObject *self, Py_ssize_t segment, void **ptrptr)}
1589+ Return a pointer to a writable memory buffer in
1590+ \code{*\var{ptrptr}}, and the length of that segment as the function
1591+ return value. The memory buffer must correspond to buffer segment
1592+ \var{segment}. Must return \code{-1} and set an exception on
1593+ error. \exception{TypeError} should be raised if the object only
1594+ supports read-only buffers, and \exception{SystemError} should be
1595+ raised when \var{segment} specifies a segment that doesn't exist.
1596+% Why doesn't it raise ValueError for this one?
1597+% GJS: because you shouldn't be calling it with an invalid
1598+% segment. That indicates a blatant programming error in the C
1599+% code.
1600+\end{ctypedesc}
1601+
1602+\begin{ctypedesc}[getsegcountproc]{Py_ssize_t (*segcountproc)
1603+ (PyObject *self, Py_ssize_t *lenp)}
1604+ Return the number of memory segments which comprise the buffer. If
1605+ \var{lenp} is not \NULL, the implementation must report the sum of
1606+ the sizes (in bytes) of all segments in \code{*\var{lenp}}.
1607+ The function cannot fail.
1608+\end{ctypedesc}
1609+
1610+\begin{ctypedesc}[getcharbufferproc]{Py_ssize_t (*charbufferproc)
1611+ (PyObject *self, Py_ssize_t segment, const char **ptrptr)}
1612+ Return the size of the segment \var{segment} that \var{ptrptr}
1613+ is set to. \code{*\var{ptrptr}} is set to the memory buffer.
1614+ Returns \code{-1} on error.
1615+\end{ctypedesc}
1616+
1617+
1618+\section{Supporting the Iterator Protocol
1619+ \label{supporting-iteration}}
1620+
1621+
1622+\section{Supporting Cyclic Garbage Collection
1623+ \label{supporting-cycle-detection}}
1624+
1625+Python's support for detecting and collecting garbage which involves
1626+circular references requires support from object types which are
1627+``containers'' for other objects which may also be containers. Types
1628+which do not store references to other objects, or which only store
1629+references to atomic types (such as numbers or strings), do not need
1630+to provide any explicit support for garbage collection.
1631+
1632+An example showing the use of these interfaces can be found in
1633+``\ulink{Supporting the Cycle
1634+Collector}{../ext/example-cycle-support.html}'' in
1635+\citetitle[../ext/ext.html]{Extending and Embedding the Python
1636+Interpreter}.
1637+
1638+To create a container type, the \member{tp_flags} field of the type
1639+object must include the \constant{Py_TPFLAGS_HAVE_GC} and provide an
1640+implementation of the \member{tp_traverse} handler. If instances of the
1641+type are mutable, a \member{tp_clear} implementation must also be
1642+provided.
1643+
1644+\begin{datadesc}{Py_TPFLAGS_HAVE_GC}
1645+ Objects with a type with this flag set must conform with the rules
1646+ documented here. For convenience these objects will be referred to
1647+ as container objects.
1648+\end{datadesc}
1649+
1650+Constructors for container types must conform to two rules:
1651+
1652+\begin{enumerate}
1653+\item The memory for the object must be allocated using
1654+ \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_VarNew()}.
1655+
1656+\item Once all the fields which may contain references to other
1657+ containers are initialized, it must call
1658+ \cfunction{PyObject_GC_Track()}.
1659+\end{enumerate}
1660+
1661+\begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_New}{TYPE, PyTypeObject *type}
1662+ Analogous to \cfunction{PyObject_New()} but for container objects with
1663+ the \constant{Py_TPFLAGS_HAVE_GC} flag set.
1664+\end{cfuncdesc}
1665+
1666+\begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_NewVar}{TYPE, PyTypeObject *type,
1667+ Py_ssize_t size}
1668+ Analogous to \cfunction{PyObject_NewVar()} but for container objects
1669+ with the \constant{Py_TPFLAGS_HAVE_GC} flag set.
1670+\end{cfuncdesc}
1671+
1672+\begin{cfuncdesc}{PyVarObject *}{PyObject_GC_Resize}{PyVarObject *op, Py_ssize_t}
1673+ Resize an object allocated by \cfunction{PyObject_NewVar()}. Returns
1674+ the resized object or \NULL{} on failure.
1675+\end{cfuncdesc}
1676+
1677+\begin{cfuncdesc}{void}{PyObject_GC_Track}{PyObject *op}
1678+ Adds the object \var{op} to the set of container objects tracked by
1679+ the collector. The collector can run at unexpected times so objects
1680+ must be valid while being tracked. This should be called once all
1681+ the fields followed by the \member{tp_traverse} handler become valid,
1682+ usually near the end of the constructor.
1683+\end{cfuncdesc}
1684+
1685+\begin{cfuncdesc}{void}{_PyObject_GC_TRACK}{PyObject *op}
1686+ A macro version of \cfunction{PyObject_GC_Track()}. It should not be
1687+ used for extension modules.
1688+\end{cfuncdesc}
1689+
1690+Similarly, the deallocator for the object must conform to a similar
1691+pair of rules:
1692+
1693+\begin{enumerate}
1694+\item Before fields which refer to other containers are invalidated,
1695+ \cfunction{PyObject_GC_UnTrack()} must be called.
1696+
1697+\item The object's memory must be deallocated using
1698+ \cfunction{PyObject_GC_Del()}.
1699+\end{enumerate}
1700+
1701+\begin{cfuncdesc}{void}{PyObject_GC_Del}{void *op}
1702+ Releases memory allocated to an object using
1703+ \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_NewVar()}.
1704+\end{cfuncdesc}
1705+
1706+\begin{cfuncdesc}{void}{PyObject_GC_UnTrack}{void *op}
1707+ Remove the object \var{op} from the set of container objects tracked
1708+ by the collector. Note that \cfunction{PyObject_GC_Track()} can be
1709+ called again on this object to add it back to the set of tracked
1710+ objects. The deallocator (\member{tp_dealloc} handler) should call
1711+ this for the object before any of the fields used by the
1712+ \member{tp_traverse} handler become invalid.
1713+\end{cfuncdesc}
1714+
1715+\begin{cfuncdesc}{void}{_PyObject_GC_UNTRACK}{PyObject *op}
1716+ A macro version of \cfunction{PyObject_GC_UnTrack()}. It should not be
1717+ used for extension modules.
1718+\end{cfuncdesc}
1719+
1720+The \member{tp_traverse} handler accepts a function parameter of this
1721+type:
1722+
1723+\begin{ctypedesc}[visitproc]{int (*visitproc)(PyObject *object, void *arg)}
1724+ Type of the visitor function passed to the \member{tp_traverse}
1725+ handler. The function should be called with an object to traverse
1726+ as \var{object} and the third parameter to the \member{tp_traverse}
1727+ handler as \var{arg}. The Python core uses several visitor functions
1728+ to implement cyclic garbage detection; it's not expected that users will
1729+ need to write their own visitor functions.
1730+\end{ctypedesc}
1731+
1732+The \member{tp_traverse} handler must have the following type:
1733+
1734+\begin{ctypedesc}[traverseproc]{int (*traverseproc)(PyObject *self,
1735+ visitproc visit, void *arg)}
1736+ Traversal function for a container object. Implementations must
1737+ call the \var{visit} function for each object directly contained by
1738+ \var{self}, with the parameters to \var{visit} being the contained
1739+ object and the \var{arg} value passed to the handler. The \var{visit}
1740+ function must not be called with a \NULL{} object argument. If
1741+ \var{visit} returns a non-zero value
1742+ that value should be returned immediately.
1743+\end{ctypedesc}
1744+
1745+To simplify writing \member{tp_traverse} handlers, a
1746+\cfunction{Py_VISIT()} macro is provided. In order to use this macro,
1747+the \member{tp_traverse} implementation must name its arguments
1748+exactly \var{visit} and \var{arg}:
1749+
1750+\begin{cfuncdesc}{void}{Py_VISIT}{PyObject *o}
1751+ Call the \var{visit} callback, with arguments \var{o} and \var{arg}.
1752+ If \var{visit} returns a non-zero value, then return it. Using this
1753+ macro, \member{tp_traverse} handlers look like:
1754+
1755+\begin{verbatim}
1756+static int
1757+my_traverse(Noddy *self, visitproc visit, void *arg)
1758+{
1759+ Py_VISIT(self->foo);
1760+ Py_VISIT(self->bar);
1761+ return 0;
1762+}
1763+\end{verbatim}
1764+
1765+\versionadded{2.4}
1766+\end{cfuncdesc}
1767+
1768+
1769+The \member{tp_clear} handler must be of the \ctype{inquiry} type, or
1770+\NULL{} if the object is immutable.
1771+
1772+\begin{ctypedesc}[inquiry]{int (*inquiry)(PyObject *self)}
1773+ Drop references that may have created reference cycles. Immutable
1774+ objects do not have to define this method since they can never
1775+ directly create reference cycles. Note that the object must still
1776+ be valid after calling this method (don't just call
1777+ \cfunction{Py_DECREF()} on a reference). The collector will call
1778+ this method if it detects that this object is involved in a
1779+ reference cycle.
1780+\end{ctypedesc}
sys/src/cmd/python/Doc/api/refcounting.tex+69−0
@@ -0,0 +1,69 @@
1+\chapter{Reference Counting \label{countingRefs}}
2+
3+
4+The macros in this section are used for managing reference counts
5+of Python objects.
6+
7+
8+\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
9+ Increment the reference count for object \var{o}. The object must
10+ not be \NULL; if you aren't sure that it isn't \NULL, use
11+ \cfunction{Py_XINCREF()}.
12+\end{cfuncdesc}
13+
14+\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
15+ Increment the reference count for object \var{o}. The object may be
16+ \NULL, in which case the macro has no effect.
17+\end{cfuncdesc}
18+
19+\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
20+ Decrement the reference count for object \var{o}. The object must
21+ not be \NULL; if you aren't sure that it isn't \NULL, use
22+ \cfunction{Py_XDECREF()}. If the reference count reaches zero, the
23+ object's type's deallocation function (which must not be \NULL) is
24+ invoked.
25+
26+ \warning{The deallocation function can cause arbitrary Python code
27+ to be invoked (e.g. when a class instance with a \method{__del__()}
28+ method is deallocated). While exceptions in such code are not
29+ propagated, the executed code has free access to all Python global
30+ variables. This means that any object that is reachable from a
31+ global variable should be in a consistent state before
32+ \cfunction{Py_DECREF()} is invoked. For example, code to delete an
33+ object from a list should copy a reference to the deleted object in
34+ a temporary variable, update the list data structure, and then call
35+ \cfunction{Py_DECREF()} for the temporary variable.}
36+\end{cfuncdesc}
37+
38+\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
39+ Decrement the reference count for object \var{o}. The object may be
40+ \NULL, in which case the macro has no effect; otherwise the effect
41+ is the same as for \cfunction{Py_DECREF()}, and the same warning
42+ applies.
43+\end{cfuncdesc}
44+
45+\begin{cfuncdesc}{void}{Py_CLEAR}{PyObject *o}
46+ Decrement the reference count for object \var{o}. The object may be
47+ \NULL, in which case the macro has no effect; otherwise the effect
48+ is the same as for \cfunction{Py_DECREF()}, except that the argument
49+ is also set to \NULL. The warning for \cfunction{Py_DECREF()} does
50+ not apply with respect to the object passed because the macro
51+ carefully uses a temporary variable and sets the argument to \NULL
52+ before decrementing its reference count.
53+
54+ It is a good idea to use this macro whenever decrementing the value
55+ of a variable that might be traversed during garbage collection.
56+
57+\versionadded{2.4}
58+\end{cfuncdesc}
59+
60+
61+The following functions are for runtime dynamic embedding of Python:
62+\cfunction{Py_IncRef(PyObject *o)}, \cfunction{Py_DecRef(PyObject *o)}.
63+They are simply exported function versions of \cfunction{Py_XINCREF()} and
64+\cfunction{Py_XDECREF()}, respectively.
65+
66+The following functions or macros are only for use within the
67+interpreter core: \cfunction{_Py_Dealloc()},
68+\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
69+well as the global variable \cdata{_Py_RefTotal}.
sys/src/cmd/python/Doc/api/refcounts.dat+1756−0
@@ -0,0 +1,1756 @@
1+# Created by Skip Montanaro <skip@mojam.com>.
2+
3+# Format:
4+# function ':' type ':' [param name] ':' [refcount effect] ':' [comment]
5+# If the param name slot is empty, that line corresponds to the function's
6+# return value, otherwise it's the type of the named parameter.
7+
8+# The first line of a function block gives type/refcount information for the
9+# function's return value. Successive lines with the same function name
10+# correspond to the function's parameter list and appear in the order the
11+# parameters appear in the function's prototype.
12+
13+# For readability, each function's lines are surrounded by a blank line.
14+# The blocks are sorted alphabetically by function name.
15+
16+# Refcount behavior is given for all PyObject* types: 0 (no change), +1
17+# (increment) and -1 (decrement). A blank refcount field indicates the
18+# parameter or function value is not a PyObject* and is therefore not
19+# subject to reference counting. A special case for the value "null"
20+# (without quotes) is used for functions which return a PyObject* type but
21+# always return NULL. This is used by some of the PyErr_*() functions, in
22+# particular.
23+
24+# XXX NOTE: the 0/+1/-1 refcount information for arguments is
25+# confusing! Much more useful would be to indicate whether the
26+# function "steals" a reference to the argument or not. Take for
27+# example PyList_SetItem(list, i, item). This lists as a 0 change for
28+# both the list and the item arguments. However, in fact it steals a
29+# reference to the item argument!
30+
31+# The parameter names are as they appear in the API manual, not the source
32+# code.
33+
34+PyBool_FromLong:PyObject*::+1:
35+PyBool_FromLong:long:v:0:
36+
37+PyBuffer_FromObject:PyObject*::+1:
38+PyBuffer_FromObject:PyObject*:base:+1:
39+PyBuffer_FromObject:int:offset::
40+PyBuffer_FromObject:int:size::
41+
42+PyBuffer_FromReadWriteObject:PyObject*::+1:
43+PyBuffer_FromReadWriteObject:PyObject*:base:+1:
44+PyBuffer_FromReadWriteObject:int:offset::
45+PyBuffer_FromReadWriteObject:int:size::
46+
47+PyBuffer_FromMemory:PyObject*::+1:
48+PyBuffer_FromMemory:void*:ptr::
49+PyBuffer_FromMemory:int:size::
50+
51+PyBuffer_FromReadWriteMemory:PyObject*::+1:
52+PyBuffer_FromReadWriteMemory:void*:ptr::
53+PyBuffer_FromReadWriteMemory:int:size::
54+
55+PyBuffer_New:PyObject*::+1:
56+PyBuffer_New:int:size::
57+
58+PyCObject_AsVoidPtr:void*:::
59+PyCObject_AsVoidPtr:PyObject*:self:0:
60+
61+PyCObject_FromVoidPtr:PyObject*::+1:
62+PyCObject_FromVoidPtr:void*:cobj::
63+PyCObject_FromVoidPtr::void (* destr)(void* )::
64+
65+PyCObject_FromVoidPtrAndDesc:PyObject*::+1:
66+PyCObject_FromVoidPtrAndDesc:void*:cobj::
67+PyCObject_FromVoidPtrAndDesc:void*:desc::
68+PyCObject_FromVoidPtrAndDesc:void(*)(void*,void*):destr::
69+
70+PyCObject_GetDesc:void*:::
71+PyCObject_GetDesc:PyObject*:self:0:
72+
73+PyCell_New:PyObject*::+1:
74+PyCell_New:PyObject*:ob:0:
75+
76+PyCell_GET:PyObject*::0:
77+PyCell_GET:PyObject*:ob:0:
78+
79+PyCell_Get:PyObject*::+1:
80+PyCell_Get:PyObject*:cell:0:
81+
82+PyCell_SET:void:::
83+PyCell_SET:PyObject*:cell:0:
84+PyCell_SET:PyObject*:value:0:
85+
86+PyCell_Set:int:::
87+PyCell_Set:PyObject*:cell:0:
88+PyCell_Set:PyObject*:value:0:
89+
90+PyCallIter_New:PyObject*::+1:
91+PyCallIter_New:PyObject*:callable::
92+PyCallIter_New:PyObject*:sentinel::
93+
94+PyCallable_Check:int:::
95+PyCallable_Check:PyObject*:o:0:
96+
97+PyComplex_AsCComplex:Py_complex:::
98+PyComplex_AsCComplex:PyObject*:op:0:
99+
100+PyComplex_Check:int:::
101+PyComplex_Check:PyObject*:p:0:
102+
103+PyComplex_FromCComplex:PyObject*::+1:
104+PyComplex_FromCComplex::Py_complex v::
105+
106+PyComplex_FromDoubles:PyObject*::+1:
107+PyComplex_FromDoubles::double real::
108+PyComplex_FromDoubles::double imag::
109+
110+PyComplex_ImagAsDouble:double:::
111+PyComplex_ImagAsDouble:PyObject*:op:0:
112+
113+PyComplex_RealAsDouble:double:::
114+PyComplex_RealAsDouble:PyObject*:op:0:
115+
116+PyDate_FromDate:PyObject*::+1:
117+PyDate_FromDate:int:year::
118+PyDate_FromDate:int:month::
119+PyDate_FromDate:int:day::
120+
121+PyDate_FromTimestamp:PyObject*::+1:
122+PyDate_FromTimestamp:PyObject*:args:0:
123+
124+PyDateTime_FromDateAndTime:PyObject*::+1:
125+PyDateTime_FromDateAndTime:int:year::
126+PyDateTime_FromDateAndTime:int:month::
127+PyDateTime_FromDateAndTime:int:day::
128+PyDateTime_FromDateAndTime:int:hour::
129+PyDateTime_FromDateAndTime:int:minute::
130+PyDateTime_FromDateAndTime:int:second::
131+PyDateTime_FromDateAndTime:int:usecond::
132+
133+PyDateTime_FromTimestamp:PyObject*::+1:
134+PyDateTime_FromTimestamp:PyObject*:args:0:
135+
136+PyDelta_FromDSU:PyObject*::+1:
137+PyDelta_FromDSU:int:days::
138+PyDelta_FromDSU:int:seconds::
139+PyDelta_FromDSU:int:useconds::
140+
141+PyDescr_NewClassMethod:PyObject*::+1:
142+PyDescr_NewClassMethod:PyTypeObject*:type::
143+PyDescr_NewClassMethod:PyMethodDef*:method::
144+
145+PyDescr_NewGetSet:PyObject*::+1:
146+PyDescr_NewGetSet:PyTypeObject*:type::
147+PyDescr_NewGetSet:PyGetSetDef*:getset::
148+
149+PyDescr_NewMember:PyObject*::+1:
150+PyDescr_NewMember:PyTypeObject*:type::
151+PyDescr_NewMember:PyMemberDef*:member::
152+
153+PyDescr_NewMethod:PyObject*::+1:
154+PyDescr_NewMethod:PyTypeObject*:type::
155+PyDescr_NewMethod:PyMethodDef*:meth::
156+
157+PyDescr_NewWrapper:PyObject*::+1:
158+PyDescr_NewWrapper:PyTypeObject*:type::
159+PyDescr_NewWrapper:struct wrapperbase*:base::
160+PyDescr_NewWrapper:void*:wrapped::
161+
162+PyDict_Check:int:::
163+PyDict_Check:PyObject*:p:0:
164+
165+PyDict_Clear:void:::
166+PyDict_Clear:PyObject*:p:0:
167+
168+PyDict_DelItem:int:::
169+PyDict_DelItem:PyObject*:p:0:
170+PyDict_DelItem:PyObject*:key:0:
171+
172+PyDict_DelItemString:int:::
173+PyDict_DelItemString:PyObject*:p:0:
174+PyDict_DelItemString:char*:key::
175+
176+PyDict_GetItem:PyObject*::0:0
177+PyDict_GetItem:PyObject*:p:0:
178+PyDict_GetItem:PyObject*:key:0:
179+
180+PyDict_GetItemString:PyObject*::0:
181+PyDict_GetItemString:PyObject*:p:0:
182+PyDict_GetItemString:char*:key::
183+
184+PyDict_Items:PyObject*::+1:
185+PyDict_Items:PyObject*:p:0:
186+
187+PyDict_Keys:PyObject*::+1:
188+PyDict_Keys:PyObject*:p:0:
189+
190+PyDict_New:PyObject*::+1:
191+
192+PyDict_Copy:PyObject*::+1:
193+PyDict_Copy:PyObject*:p:0:
194+
195+PyDict_Next:int:::
196+PyDict_Next:PyObject*:p:0:
197+PyDict_Next:int:ppos::
198+PyDict_Next:PyObject**:pkey:0:
199+PyDict_Next:PyObject**:pvalue:0:
200+
201+PyDict_SetItem:int:::
202+PyDict_SetItem:PyObject*:p:0:
203+PyDict_SetItem:PyObject*:key:+1:
204+PyDict_SetItem:PyObject*:val:+1:
205+
206+PyDict_SetItemString:int:::
207+PyDict_SetItemString:PyObject*:p:0:
208+PyDict_SetItemString:char*:key::
209+PyDict_SetItemString:PyObject*:val:+1:
210+
211+PyDict_Size:int:::
212+PyDict_Size:PyObject*:p::
213+
214+PyDict_Values:PyObject*::+1:
215+PyDict_Values:PyObject*:p:0:
216+
217+PyDictProxy_New:PyObject*::+1:
218+PyDictProxy_New:PyObject*:dict:0:
219+
220+PyErr_BadArgument:int:::
221+
222+PyErr_BadInternalCall:void:::
223+
224+PyErr_CheckSignals:int:::
225+
226+PyErr_Clear:void:::
227+
228+PyErr_ExceptionMatches:int:::
229+PyErr_ExceptionMatches:PyObject*:exc:0:
230+
231+PyErr_Fetch:void:::
232+PyErr_Fetch:PyObject**:ptype:0:
233+PyErr_Fetch:PyObject**:pvalue:0:
234+PyErr_Fetch:PyObject**:ptraceback:0:
235+
236+PyErr_GivenExceptionMatches:int:::
237+PyErr_GivenExceptionMatches:PyObject*:given:0:
238+PyErr_GivenExceptionMatches:PyObject*:exc:0:
239+
240+PyErr_NewException:PyObject*::+1:
241+PyErr_NewException:char*:name::
242+PyErr_NewException:PyObject*:base:0:
243+PyErr_NewException:PyObject*:dict:0:
244+
245+PyErr_NoMemory:PyObject*::null:
246+
247+PyErr_NormalizeException:void:::
248+PyErr_NormalizeException:PyObject**:exc::???
249+PyErr_NormalizeException:PyObject**:val::???
250+PyErr_NormalizeException:PyObject**:tb::???
251+
252+PyErr_Occurred:PyObject*::0:
253+
254+PyErr_Print:void:::
255+
256+PyErr_Restore:void:::
257+PyErr_Restore:PyObject*:type:-1:
258+PyErr_Restore:PyObject*:value:-1:
259+PyErr_Restore:PyObject*:traceback:-1:
260+
261+PyErr_SetExcFromWindowsErr:PyObject*::null:
262+PyErr_SetExcFromWindowsErr:PyObject*:type:0:
263+PyErr_SetExcFromWindowsErr:int:ierr::
264+
265+PyErr_SetExcFromWindowsErrWithFilename:PyObject*::null:
266+PyErr_SetExcFromWindowsErrWithFilename:PyObject*:type:0:
267+PyErr_SetExcFromWindowsErrWithFilename:int:ierr::
268+PyErr_SetExcFromWindowsErrWithFilename:char*:filename::
269+
270+PyErr_SetFromErrno:PyObject*::null:
271+PyErr_SetFromErrno:PyObject*:type:0:
272+
273+PyErr_SetFromErrnoWithFilename:PyObject*::null:
274+PyErr_SetFromErrnoWithFilename:PyObject*:type:0:
275+PyErr_SetFromErrnoWithFilename:char*:filename::
276+
277+PyErr_SetFromWindowsErr:PyObject*::null:
278+PyErr_SetFromWindowsErr:int:ierr::
279+
280+PyErr_SetFromWindowsErrWithFilename:PyObject*::null:
281+PyErr_SetFromWindowsErrWithFilename:int:ierr::
282+PyErr_SetFromWindowsErrWithFilename:char*:filename::
283+
284+PyErr_SetInterrupt:void:::
285+
286+PyErr_SetNone:void:::
287+PyErr_SetNone:PyObject*:type:+1:
288+
289+PyErr_SetObject:void:::
290+PyErr_SetObject:PyObject*:type:+1:
291+PyErr_SetObject:PyObject*:value:+1:
292+
293+PyErr_SetString:void:::
294+PyErr_SetString:PyObject*:type:+1:
295+PyErr_SetString:char*:message::
296+
297+PyErr_Format:PyObject*::null:
298+PyErr_Format:PyObject*:exception:+1:
299+PyErr_Format:char*:format::
300+PyErr_Format::...::
301+
302+PyErr_Warn:int:::
303+PyErr_Warn:PyObject*:category:0:
304+PyErr_Warn:char*:message::
305+
306+PyErr_WarnEx:int:::
307+PyErr_WarnEx:PyObject*:category:0:
308+PyErr_WarnEx:const char*:message::
309+PyErr_WarnEx:Py_ssize_t:stack_level::
310+
311+PyEval_AcquireLock:void:::
312+
313+PyEval_AcquireThread:void:::
314+PyEval_AcquireThread:PyThreadState*:tstate::
315+
316+PyEval_InitThreads:void:::
317+
318+PyEval_ReleaseLock:void:::
319+
320+PyEval_ReleaseThread:void:::
321+PyEval_ReleaseThread:PyThreadState*:tstate::
322+
323+PyEval_RestoreThread:void:::
324+PyEval_RestoreThread:PyThreadState*:tstate::
325+
326+PyEval_SaveThread:PyThreadState*:::
327+
328+PyEval_EvalCode:PyObject*::+1:
329+PyEval_EvalCode:PyCodeObject*:co:0:
330+PyEval_EvalCode:PyObject*:globals:0:
331+PyEval_EvalCode:PyObject*:locals:0:
332+
333+PyFile_AsFile:FILE*:::
334+PyFile_AsFile:PyFileObject*:p:0:
335+
336+PyFile_Check:int:::
337+PyFile_Check:PyObject*:p:0:
338+
339+PyFile_FromFile:PyObject*::+1:
340+PyFile_FromFile:FILE*:fp::
341+PyFile_FromFile:char*:name::
342+PyFile_FromFile:char*:mode::
343+PyFile_FromFile:int(*:close)::
344+
345+PyFile_FromString:PyObject*::+1:
346+PyFile_FromString:char*:name::
347+PyFile_FromString:char*:mode::
348+
349+PyFile_GetLine:PyObject*::+1:
350+PyFile_GetLine:PyObject*:p::
351+PyFile_GetLine:int:n::
352+
353+PyFile_Name:PyObject*::0:
354+PyFile_Name:PyObject*:p:0:
355+
356+PyFile_SetBufSize:void:::
357+PyFile_SetBufSize:PyFileObject*:p:0:
358+PyFile_SetBufSize:int:n::
359+
360+PyFile_SoftSpace:int:::
361+PyFile_SoftSpace:PyFileObject*:p:0:
362+PyFile_SoftSpace:int:newflag::
363+
364+PyFile_WriteObject:int:::
365+PyFile_WriteObject:PyObject*:obj:0:
366+PyFile_WriteObject:PyFileObject*:p:0:
367+PyFile_WriteObject:int:flags::
368+
369+PyFile_WriteString:int:::
370+PyFile_WriteString:const char*:s::
371+PyFile_WriteString:PyFileObject*:p:0:
372+PyFile_WriteString:int:flags::
373+
374+PyFloat_AS_DOUBLE:double:::
375+PyFloat_AS_DOUBLE:PyObject*:pyfloat:0:
376+
377+PyFloat_AsDouble:double:::
378+PyFloat_AsDouble:PyObject*:pyfloat:0:
379+
380+PyFloat_Check:int:::
381+PyFloat_Check:PyObject*:p:0:
382+
383+PyFloat_FromDouble:PyObject*::+1:
384+PyFloat_FromDouble:double:v::
385+
386+PyFloat_FromString:PyObject*::+1:
387+PyFloat_FromString:PyObject*:str:0:
388+PyFloat_FromString:char**:pend:0:ignored
389+
390+PyFrozenSet_New:PyObject*::+1:
391+PyFrozenSet_New:PyObject*:iterable:0:
392+
393+PyFunction_GetClosure:PyObject*::0:
394+PyFunction_GetClosure:PyObject*:op:0:
395+
396+PyFunction_GetCode:PyObject*::0:
397+PyFunction_GetCode:PyObject*:op:0:
398+
399+PyFunction_GetDefaults:PyObject*::0:
400+PyFunction_GetDefaults:PyObject*:op:0:
401+
402+PyFunction_GetGlobals:PyObject*::0:
403+PyFunction_GetGlobals:PyObject*:op:0:
404+
405+PyFunction_GetModule:PyObject*::0:
406+PyFunction_GetModule:PyObject*:op:0:
407+
408+PyFunction_New:PyObject*::+1:
409+PyFunction_New:PyObject*:code:+1:
410+PyFunction_New:PyObject*:globals:+1:
411+
412+PyFunction_SetClosure:int:::
413+PyFunction_SetClosure:PyObject*:op:0:
414+PyFunction_SetClosure:PyObject*:closure:+1:
415+
416+PyFunction_SetDefaults:int:::
417+PyFunction_SetDefaults:PyObject*:op:0:
418+PyFunction_SetDefaults:PyObject*:defaults:+1:
419+
420+PyGen_New:PyObject*::+1:
421+PyGen_New:PyFrameObject*:frame:0:
422+
423+Py_InitModule:PyObject*::0:
424+Py_InitModule:char*:name::
425+Py_InitModule:PyMethodDef[]:methods::
426+
427+Py_InitModule3:PyObject*::0:
428+Py_InitModule3:char*:name::
429+Py_InitModule3:PyMethodDef[]:methods::
430+Py_InitModule3:char*:doc::
431+
432+Py_InitModule4:PyObject*::0:
433+Py_InitModule4:char*:name::
434+Py_InitModule4:PyMethodDef[]:methods::
435+Py_InitModule4:char*:doc::
436+Py_InitModule4:PyObject*:self::
437+Py_InitModule4:int:apiver::usually provided by Py_InitModule or Py_InitModule3
438+
439+PyImport_AddModule:PyObject*::0:reference borrowed from sys.modules
440+PyImport_AddModule:char*:name::
441+
442+PyImport_Cleanup:void:::
443+
444+PyImport_ExecCodeModule:PyObject*::+1:
445+PyImport_ExecCodeModule:char*:name::
446+PyImport_ExecCodeModule:PyObject*:co:0:
447+
448+PyImport_GetMagicNumber:long:::
449+
450+PyImport_GetModuleDict:PyObject*::0:
451+
452+PyImport_Import:PyObject*::+1:
453+PyImport_Import:PyObject*:name:0:
454+
455+PyImport_ImportFrozenModule:int:::
456+PyImport_ImportFrozenModule:char*:::
457+
458+PyImport_ImportModule:PyObject*::+1:
459+PyImport_ImportModule:char*:name::
460+
461+PyImport_ImportModuleEx:PyObject*::+1:
462+PyImport_ImportModuleEx:char*:name::
463+PyImport_ImportModuleEx:PyObject*:globals:0:???
464+PyImport_ImportModuleEx:PyObject*:locals:0:???
465+PyImport_ImportModuleEx:PyObject*:fromlist:0:???
466+
467+PyImport_ReloadModule:PyObject*::+1:
468+PyImport_ReloadModule:PyObject*:m:0:
469+
470+PyInstance_New:PyObject*::+1:
471+PyInstance_New:PyObject*:klass:+1:
472+PyInstance_New:PyObject*:arg:0:
473+PyInstance_New:PyObject*:kw:0:
474+
475+PyInstance_NewRaw:PyObject*::+1:
476+PyInstance_NewRaw:PyObject*:klass:+1:
477+PyInstance_NewRaw:PyObject*:dict:+1:
478+
479+PyInt_AS_LONG:long:::
480+PyInt_AS_LONG:PyIntObject*:io:0:
481+
482+PyInt_AsLong:long:::
483+PyInt_AsLong:PyObject*:io:0:
484+
485+PyInt_Check:int:::
486+PyInt_Check:PyObject*:op:0:
487+
488+PyInt_FromLong:PyObject*::+1:
489+PyInt_FromLong:long:ival::
490+
491+PyInt_FromString:PyObject*::+1:
492+PyInt_FromString:char*:str:0:
493+PyInt_FromString:char**:pend:0:
494+PyInt_FromString:int:base:0:
495+
496+PyInt_FromSsize_t:PyObject*::+1:
497+PyInt_FromSsize_t:Py_ssize_t:ival::
498+
499+PyInt_GetMax:long:::
500+
501+PyInterpreterState_Clear:void:::
502+PyInterpreterState_Clear:PyInterpreterState*:interp::
503+
504+PyInterpreterState_Delete:void:::
505+PyInterpreterState_Delete:PyInterpreterState*:interp::
506+
507+PyInterpreterState_New:PyInterpreterState*:::
508+
509+PyIter_Check:int:o:0:
510+
511+PyIter_Next:PyObject*::+1:
512+PyIter_Next:PyObject*:o:0:
513+
514+PyList_Append:int:::
515+PyList_Append:PyObject*:list:0:
516+PyList_Append:PyObject*:item:+1:
517+
518+PyList_AsTuple:PyObject*::+1:
519+PyList_AsTuple:PyObject*:list:0:
520+
521+PyList_Check:int:::
522+PyList_Check:PyObject*:p:0:
523+
524+PyList_GET_ITEM:PyObject*::0:
525+PyList_GET_ITEM:PyObject*:list:0:
526+PyList_GET_ITEM:int:i:0:
527+
528+PyList_GET_SIZE:int:::
529+PyList_GET_SIZE:PyObject*:list:0:
530+
531+PyList_GetItem:PyObject*::0:
532+PyList_GetItem:PyObject*:list:0:
533+PyList_GetItem:int:index::
534+
535+PyList_GetSlice:PyObject*::+1:
536+PyList_GetSlice:PyObject*:list:0:
537+PyList_GetSlice:int:low::
538+PyList_GetSlice:int:high::
539+
540+PyList_Insert:int:::
541+PyList_Insert:PyObject*:list:0:
542+PyList_Insert:int:index::
543+PyList_Insert:PyObject*:item:+1:
544+
545+PyList_New:PyObject*::+1:
546+PyList_New:int:len::
547+
548+PyList_Reverse:int:::
549+PyList_Reverse:PyObject*:list:0:
550+
551+PyList_SET_ITEM:void:::
552+PyList_SET_ITEM:PyObject*:list:0:
553+PyList_SET_ITEM:int:i::
554+PyList_SET_ITEM:PyObject*:o:0:
555+
556+PyList_SetItem:int:::
557+PyList_SetItem:PyObject*:list:0:
558+PyList_SetItem:int:index::
559+PyList_SetItem:PyObject*:item:0:
560+
561+PyList_SetSlice:int:::
562+PyList_SetSlice:PyObject*:list:0:
563+PyList_SetSlice:int:low::
564+PyList_SetSlice:int:high::
565+PyList_SetSlice:PyObject*:itemlist:0:but increfs its elements?
566+
567+PyList_Size:int:::
568+PyList_Size:PyObject*:list:0:
569+
570+PyList_Sort:int:::
571+PyList_Sort:PyObject*:list:0:
572+
573+PyLong_AsDouble:double:::
574+PyLong_AsDouble:PyObject*:pylong:0:
575+
576+PyLong_AsLong:long:::
577+PyLong_AsLong:PyObject*:pylong:0:
578+
579+PyLong_AsUnsignedLong:unsigned long:::
580+PyLong_AsUnsignedLong:PyObject*:pylong:0:
581+
582+PyLong_Check:int:::
583+PyLong_Check:PyObject*:p:0:
584+
585+PyLong_FromDouble:PyObject*::+1:
586+PyLong_FromDouble:double:v::
587+
588+PyLong_FromLong:PyObject*::+1:
589+PyLong_FromLong:long:v::
590+
591+PyLong_FromLongLong:PyObject*::+1:
592+PyLong_FromLongLong:long long:v::
593+
594+PyLong_FromUnsignedLongLong:PyObject*::+1:
595+PyLong_FromUnsignedLongLong:unsigned long long:v::
596+
597+PyLong_FromString:PyObject*::+1:
598+PyLong_FromString:char*:str::
599+PyLong_FromString:char**:pend::
600+PyLong_FromString:int:base::
601+
602+PyLong_FromUnicode:PyObject*::+1:
603+PyLong_FromUnicode:Py_UNICODE:u::
604+PyLong_FromUnicode:int:length::
605+PyLong_FromUnicode:int:base::
606+
607+PyLong_FromUnsignedLong:PyObject*::+1:
608+PyLong_FromUnsignedLong:unsignedlong:v::
609+
610+PyLong_FromVoidPtr:PyObject*::+1:
611+PyLong_FromVoidPtr:void*:p::
612+
613+PyMapping_Check:int:::
614+PyMapping_Check:PyObject*:o:0:
615+
616+PyMapping_DelItem:int:::
617+PyMapping_DelItem:PyObject*:o:0:
618+PyMapping_DelItem:PyObject*:key:0:
619+
620+PyMapping_DelItemString:int:::
621+PyMapping_DelItemString:PyObject*:o:0:
622+PyMapping_DelItemString:char*:key::
623+
624+PyMapping_GetItemString:PyObject*::+1:
625+PyMapping_GetItemString:PyObject*:o:0:
626+PyMapping_GetItemString:char*:key::
627+
628+PyMapping_HasKey:int:::
629+PyMapping_HasKey:PyObject*:o:0:
630+PyMapping_HasKey:PyObject*:key::
631+
632+PyMapping_HasKeyString:int:::
633+PyMapping_HasKeyString:PyObject*:o:0:
634+PyMapping_HasKeyString:char*:key::
635+
636+PyMapping_Items:PyObject*::+1:
637+PyMapping_Items:PyObject*:o:0:
638+
639+PyMapping_Keys:PyObject*::+1:
640+PyMapping_Keys:PyObject*:o:0:
641+
642+PyMapping_Length:int:::
643+PyMapping_Length:PyObject*:o:0:
644+
645+PyMapping_SetItemString:int:::
646+PyMapping_SetItemString:PyObject*:o:0:
647+PyMapping_SetItemString:char*:key::
648+PyMapping_SetItemString:PyObject*:v:+1:
649+
650+PyMapping_Values:PyObject*::+1:
651+PyMapping_Values:PyObject*:o:0:
652+
653+PyMarshal_ReadLastObjectFromFile:PyObject*::+1:
654+PyMarshal_ReadLastObjectFromFile:FILE*:file::
655+
656+PyMarshal_ReadObjectFromFile:PyObject*::+1:
657+PyMarshal_ReadObjectFromFile:FILE*:file::
658+
659+PyMarshal_ReadObjectFromString:PyObject*::+1:
660+PyMarshal_ReadObjectFromString:char*:string::
661+PyMarshal_ReadObjectFromString:int:len::
662+
663+PyMarshal_WriteObjectToString:PyObject*::+1:
664+PyMarshal_WriteObjectToString:PyObject*:value:0:
665+
666+PyMethod_Class:PyObject*::0:
667+PyMethod_Class:PyObject*:im:0:
668+
669+PyMethod_Function:PyObject*::0:
670+PyMethod_Function:PyObject*:im:0:
671+
672+PyMethod_GET_CLASS:PyObject*::0:
673+PyMethod_GET_CLASS:PyObject*:im:0:
674+
675+PyMethod_GET_FUNCTION:PyObject*::0:
676+PyMethod_GET_FUNCTION:PyObject*:im:0:
677+
678+PyMethod_GET_SELF:PyObject*::0:
679+PyMethod_GET_SELF:PyObject*:im:0:
680+
681+PyMethod_New:PyObject*::+1:
682+PyMethod_New:PyObject*:func:0:
683+PyMethod_New:PyObject*:self:0:
684+PyMethod_New:PyObject*:class:0:
685+
686+PyMethod_Self:PyObject*::0:
687+PyMethod_Self:PyObject*:im:0:
688+
689+PyModule_GetDict:PyObject*::0:
690+PyModule_GetDict::PyObject* module:0:
691+
692+PyModule_GetFilename:char*:::
693+PyModule_GetFilename:PyObject*:module:0:
694+
695+PyModule_GetName:char*:::
696+PyModule_GetName:PyObject*:module:0:
697+
698+PyModule_New:PyObject*::+1:
699+PyModule_New::char* name::
700+
701+PyNumber_Absolute:PyObject*::+1:
702+PyNumber_Absolute:PyObject*:o:0:
703+
704+PyNumber_Add:PyObject*::+1:
705+PyNumber_Add:PyObject*:o1:0:
706+PyNumber_Add:PyObject*:o2:0:
707+
708+PyNumber_And:PyObject*::+1:
709+PyNumber_And:PyObject*:o1:0:
710+PyNumber_And:PyObject*:o2:0:
711+
712+PyNumber_Check:PyObject*:o:0:
713+PyNumber_Check:int:::
714+
715+PyNumber_Coerce:int:::
716+PyNumber_Coerce:PyObject**:p1:+1:
717+PyNumber_Coerce:PyObject**:p2:+1:
718+
719+PyNumber_Divide:PyObject*::+1:
720+PyNumber_Divide:PyObject*:o1:0:
721+PyNumber_Divide:PyObject*:o2:0:
722+
723+PyNumber_Divmod:PyObject*::+1:
724+PyNumber_Divmod:PyObject*:o1:0:
725+PyNumber_Divmod:PyObject*:o2:0:
726+
727+PyNumber_Float:PyObject*::+1:
728+PyNumber_Float:PyObject*:o:0:
729+
730+PyNumber_FloorDivide:PyObject*::+1:
731+PyNumber_FloorDivide:PyObject*:v:0:
732+PyNumber_FloorDivide:PyObject*:w:0:
733+
734+PyNumber_InPlaceAdd:PyObject*::+1:
735+PyNumber_InPlaceAdd:PyObject*:v:0:
736+PyNumber_InPlaceAdd:PyObject*:w:0:
737+
738+PyNumber_InPlaceAnd:PyObject*::+1:
739+PyNumber_InPlaceAnd:PyObject*:v:0:
740+PyNumber_InPlaceAnd:PyObject*:w:0:
741+
742+PyNumber_InPlaceDivide:PyObject*::+1:
743+PyNumber_InPlaceDivide:PyObject*:v:0:
744+PyNumber_InPlaceDivide:PyObject*:w:0:
745+
746+PyNumber_InPlaceFloorDivide:PyObject*::+1:
747+PyNumber_InPlaceFloorDivide:PyObject*:v:0:
748+PyNumber_InPlaceFloorDivide:PyObject*:w:0:
749+
750+PyNumber_InPlaceLshift:PyObject*::+1:
751+PyNumber_InPlaceLshift:PyObject*:v:0:
752+PyNumber_InPlaceLshift:PyObject*:w:0:
753+
754+PyNumber_InPlaceMultiply:PyObject*::+1:
755+PyNumber_InPlaceMultiply:PyObject*:v:0:
756+PyNumber_InPlaceMultiply:PyObject*:w:0:
757+
758+PyNumber_InPlaceOr:PyObject*::+1:
759+PyNumber_InPlaceOr:PyObject*:v:0:
760+PyNumber_InPlaceOr:PyObject*:w:0:
761+
762+PyNumber_InPlacePower:PyObject*::+1:
763+PyNumber_InPlacePower:PyObject*:v:0:
764+PyNumber_InPlacePower:PyObject*:w:0:
765+PyNumber_InPlacePower:PyObject*:z:0:
766+
767+PyNumber_InPlaceRemainder:PyObject*::+1:
768+PyNumber_InPlaceRemainder:PyObject*:v:0:
769+PyNumber_InPlaceRemainder:PyObject*:w:0:
770+
771+PyNumber_InPlaceRshift:PyObject*::+1:
772+PyNumber_InPlaceRshift:PyObject*:v:0:
773+PyNumber_InPlaceRshift:PyObject*:w:0:
774+
775+PyNumber_InPlaceSubtract:PyObject*::+1:
776+PyNumber_InPlaceSubtract:PyObject*:v:0:
777+PyNumber_InPlaceSubtract:PyObject*:w:0:
778+
779+PyNumber_InPlaceTrueDivide:PyObject*::+1:
780+PyNumber_InPlaceTrueDivide:PyObject*:v:0:
781+PyNumber_InPlaceTrueDivide:PyObject*:w:0:
782+
783+PyNumber_InPlaceXor:PyObject*::+1:
784+PyNumber_InPlaceXor:PyObject*:v:0:
785+PyNumber_InPlaceXor:PyObject*:w:0:
786+
787+PyNumber_Int:PyObject*::+1:
788+PyNumber_Int:PyObject*:o:0:
789+
790+PyNumber_Invert:PyObject*::+1:
791+PyNumber_Invert:PyObject*:o:0:
792+
793+PyNumber_Long:PyObject*::+1:
794+PyNumber_Long:PyObject*:o:0:
795+
796+PyNumber_Lshift:PyObject*::+1:
797+PyNumber_Lshift:PyObject*:o1:0:
798+PyNumber_Lshift:PyObject*:o2:0:
799+
800+PyNumber_Multiply:PyObject*::+1:
801+PyNumber_Multiply:PyObject*:o1:0:
802+PyNumber_Multiply:PyObject*:o2:0:
803+
804+PyNumber_Negative:PyObject*::+1:
805+PyNumber_Negative:PyObject*:o:0:
806+
807+PyNumber_Or:PyObject*::+1:
808+PyNumber_Or:PyObject*:o1:0:
809+PyNumber_Or:PyObject*:o2:0:
810+
811+PyNumber_Positive:PyObject*::+1:
812+PyNumber_Positive:PyObject*:o:0:
813+
814+PyNumber_Power:PyObject*::+1:
815+PyNumber_Power:PyObject*:o1:0:
816+PyNumber_Power:PyObject*:o2:0:
817+PyNumber_Power:PyObject*:o3:0:
818+
819+PyNumber_Remainder:PyObject*::+1:
820+PyNumber_Remainder:PyObject*:o1:0:
821+PyNumber_Remainder:PyObject*:o2:0:
822+
823+PyNumber_Rshift:PyObject*::+1:
824+PyNumber_Rshift:PyObject*:o1:0:
825+PyNumber_Rshift:PyObject*:o2:0:
826+
827+PyNumber_Subtract:PyObject*::+1:
828+PyNumber_Subtract:PyObject*:o1:0:
829+PyNumber_Subtract:PyObject*:o2:0:
830+
831+PyNumber_TrueDivide:PyObject*::+1:
832+PyNumber_TrueDivide:PyObject*:v:0:
833+PyNumber_TrueDivide:PyObject*:w:0:
834+
835+PyNumber_Xor:PyObject*::+1:
836+PyNumber_Xor:PyObject*:o1:0:
837+PyNumber_Xor:PyObject*:o2:0:
838+
839+PyOS_GetLastModificationTime:long:::
840+PyOS_GetLastModificationTime:char*:filename::
841+
842+PyObject_AsFileDescriptor:int:::
843+PyObject_AsFileDescriptor:PyObject*:o:0:
844+
845+PyObject_Call:PyObject*::+1:
846+PyObject_Call:PyObject*:callable_object:0:
847+PyObject_Call:PyObject*:args:0:
848+PyObject_Call:PyObject*:kw:0:
849+
850+PyObject_CallFunction:PyObject*::+1:
851+PyObject_CallFunction:PyObject*:callable_object:0:
852+PyObject_CallFunction:char*:format::
853+PyObject_CallFunction::...::
854+
855+PyObject_CallFunctionObjArgs:PyObject*::+1:
856+PyObject_CallFunctionObjArgs:PyObject*:callable:0:
857+PyObject_CallFunctionObjArgs::...::
858+
859+PyObject_CallMethod:PyObject*::+1:
860+PyObject_CallMethod:PyObject*:o:0:
861+PyObject_CallMethod:char*:m::
862+PyObject_CallMethod:char*:format::
863+PyObject_CallMethod::...::
864+
865+PyObject_CallMethodObjArgs:PyObject*::+1:
866+PyObject_CallMethodObjArgs:PyObject*:o:0:
867+PyObject_CallMethodObjArgs:char*:name::
868+PyObject_CallMethodObjArgs::...::
869+
870+PyObject_CallObject:PyObject*::+1:
871+PyObject_CallObject:PyObject*:callable_object:0:
872+PyObject_CallObject:PyObject*:args:0:
873+
874+PyObject_Cmp:int:::
875+PyObject_Cmp:PyObject*:o1:0:
876+PyObject_Cmp:PyObject*:o2:0:
877+PyObject_Cmp:int*:result::
878+
879+PyObject_Compare:int:::
880+PyObject_Compare:PyObject*:o1:0:
881+PyObject_Compare:PyObject*:o2:0:
882+
883+PyObject_DelAttr:int:::
884+PyObject_DelAttr:PyObject*:o:0:
885+PyObject_DelAttr:PyObject*:attr_name:0:
886+
887+PyObject_DelAttrString:int:::
888+PyObject_DelAttrString:PyObject*:o:0:
889+PyObject_DelAttrString:char*:attr_name::
890+
891+PyObject_DelItem:int:::
892+PyObject_DelItem:PyObject*:o:0:
893+PyObject_DelItem:PyObject*:key:0:
894+
895+PyObject_Dir:PyObject*::+1:
896+PyObject_Dir:PyObject*:o:0:
897+
898+PyObject_GetAttr:PyObject*::+1:
899+PyObject_GetAttr:PyObject*:o:0:
900+PyObject_GetAttr:PyObject*:attr_name:0:
901+
902+PyObject_GetAttrString:PyObject*::+1:
903+PyObject_GetAttrString:PyObject*:o:0:
904+PyObject_GetAttrString:char*:attr_name::
905+
906+PyObject_GetItem:PyObject*::+1:
907+PyObject_GetItem:PyObject*:o:0:
908+PyObject_GetItem:PyObject*:key:0:
909+
910+PyObject_GetIter:PyObject*::+1:
911+PyObject_GetIter:PyObject*:o:0:
912+
913+PyObject_HasAttr:int:::
914+PyObject_HasAttr:PyObject*:o:0:
915+PyObject_HasAttr:PyObject*:attr_name:0:
916+
917+PyObject_HasAttrString:int:::
918+PyObject_HasAttrString:PyObject*:o:0:
919+PyObject_HasAttrString:char*:attr_name:0:
920+
921+PyObject_Hash:int:::
922+PyObject_Hash:PyObject*:o:0:
923+
924+PyObject_IsTrue:int:::
925+PyObject_IsTrue:PyObject*:o:0:
926+
927+PyObject_Init:PyObject*::0:
928+PyObject_Init:PyObject*:op:0:
929+
930+PyObject_InitVar:PyVarObject*::0:
931+PyObject_InitVar:PyVarObject*:op:0:
932+
933+PyObject_Length:int:::
934+PyObject_Length:PyObject*:o:0:
935+
936+PyObject_NEW:PyObject*::+1:
937+
938+PyObject_New:PyObject*::+1:
939+
940+PyObject_NEW_VAR:PyObject*::+1:
941+
942+PyObject_NewVar:PyObject*::+1:
943+
944+PyObject_Print:int:::
945+PyObject_Print:PyObject*:o:0:
946+PyObject_Print:FILE*:fp::
947+PyObject_Print:int:flags::
948+
949+PyObject_Repr:PyObject*::+1:
950+PyObject_Repr:PyObject*:o:0:
951+
952+PyObject_RichCompare:PyObject*::+1:
953+PyObject_RichCompare:PyObject*:o1:0:
954+PyObject_RichCompare:PyObject*:o2:0:
955+PyObject_RichCompare:int:opid::
956+
957+PyObject_RichCompareBool:int:::
958+PyObject_RichCompareBool:PyObject*:o1:0:
959+PyObject_RichCompareBool:PyObject*:o2:0:
960+PyObject_RichCompareBool:int:opid::
961+
962+PyObject_SetAttr:int:::
963+PyObject_SetAttr:PyObject*:o:0:
964+PyObject_SetAttr:PyObject*:attr_name:0:
965+PyObject_SetAttr:PyObject*:v:+1:
966+
967+PyObject_SetAttrString:int:::
968+PyObject_SetAttrString:PyObject*:o:0:
969+PyObject_SetAttrString:char*:attr_name::
970+PyObject_SetAttrString:PyObject*:v:+1:
971+
972+PyObject_SetItem:int:::
973+PyObject_SetItem:PyObject*:o:0:
974+PyObject_SetItem:PyObject*:key:0:
975+PyObject_SetItem:PyObject*:v:+1:
976+
977+PyObject_Str:PyObject*::+1:
978+PyObject_Str:PyObject*:o:0:
979+
980+PyObject_Type:PyObject*::+1:
981+PyObject_Type:PyObject*:o:0:
982+
983+PyObject_Unicode:PyObject*::+1:
984+PyObject_Unicode:PyObject*:o:0:
985+
986+PyParser_SimpleParseFile:struct _node*:::
987+PyParser_SimpleParseFile:FILE*:fp::
988+PyParser_SimpleParseFile:char*:filename::
989+PyParser_SimpleParseFile:int:start::
990+
991+PyParser_SimpleParseString:struct _node*:::
992+PyParser_SimpleParseString:char*:str::
993+PyParser_SimpleParseString:int:start::
994+
995+PyRun_AnyFile:int:::
996+PyRun_AnyFile:FILE*:fp::
997+PyRun_AnyFile:char*:filename::
998+
999+PyRun_File:PyObject*::+1:??? -- same as eval_code2()
1000+PyRun_File:FILE*:fp::
1001+PyRun_File:char*:filename::
1002+PyRun_File:int:start::
1003+PyRun_File:PyObject*:globals:0:
1004+PyRun_File:PyObject*:locals:0:
1005+
1006+PyRun_FileEx:PyObject*::+1:??? -- same as eval_code2()
1007+PyRun_FileEx:FILE*:fp::
1008+PyRun_FileEx:char*:filename::
1009+PyRun_FileEx:int:start::
1010+PyRun_FileEx:PyObject*:globals:0:
1011+PyRun_FileEx:PyObject*:locals:0:
1012+PyRun_FileEx:int:closeit::
1013+
1014+PyRun_FileFlags:PyObject*::+1:??? -- same as eval_code2()
1015+PyRun_FileFlags:FILE*:fp::
1016+PyRun_FileFlags:char*:filename::
1017+PyRun_FileFlags:int:start::
1018+PyRun_FileFlags:PyObject*:globals:0:
1019+PyRun_FileFlags:PyObject*:locals:0:
1020+PyRun_FileFlags:PyCompilerFlags*:flags::
1021+
1022+PyRun_FileExFlags:PyObject*::+1:??? -- same as eval_code2()
1023+PyRun_FileExFlags:FILE*:fp::
1024+PyRun_FileExFlags:char*:filename::
1025+PyRun_FileExFlags:int:start::
1026+PyRun_FileExFlags:PyObject*:globals:0:
1027+PyRun_FileExFlags:PyObject*:locals:0:
1028+PyRun_FileExFlags:int:closeit::
1029+PyRun_FileExFlags:PyCompilerFlags*:flags::
1030+
1031+PyRun_InteractiveLoop:int:::
1032+PyRun_InteractiveLoop:FILE*:fp::
1033+PyRun_InteractiveLoop:char*:filename::
1034+
1035+PyRun_InteractiveOne:int:::
1036+PyRun_InteractiveOne:FILE*:fp::
1037+PyRun_InteractiveOne:char*:filename::
1038+
1039+PyRun_SimpleFile:int:::
1040+PyRun_SimpleFile:FILE*:fp::
1041+PyRun_SimpleFile:char*:filename::
1042+
1043+PyRun_SimpleString:int:::
1044+PyRun_SimpleString:char*:command::
1045+
1046+PyRun_String:PyObject*::+1:??? -- same as eval_code2()
1047+PyRun_String:char*:str::
1048+PyRun_String:int:start::
1049+PyRun_String:PyObject*:globals:0:
1050+PyRun_String:PyObject*:locals:0:
1051+
1052+PyRun_StringFlags:PyObject*::+1:??? -- same as eval_code2()
1053+PyRun_StringFlags:char*:str::
1054+PyRun_StringFlags:int:start::
1055+PyRun_StringFlags:PyObject*:globals:0:
1056+PyRun_StringFlags:PyObject*:locals:0:
1057+PyRun_StringFlags:PyCompilerFlags*:flags::
1058+
1059+PySeqIter_New:PyObject*::+1:
1060+PySeqIter_New:PyObject*:seq::
1061+
1062+PySequence_Check:int:::
1063+PySequence_Check:PyObject*:o:0:
1064+
1065+PySequence_Concat:PyObject*::+1:
1066+PySequence_Concat:PyObject*:o1:0:
1067+PySequence_Concat:PyObject*:o2:0:
1068+
1069+PySequence_Count:int:::
1070+PySequence_Count:PyObject*:o:0:
1071+PySequence_Count:PyObject*:value:0:
1072+
1073+PySequence_DelItem:int:::
1074+PySequence_DelItem:PyObject*:o:0:
1075+PySequence_DelItem:int:i::
1076+
1077+PySequence_DelSlice:int:::
1078+PySequence_DelSlice:PyObject*:o:0:
1079+PySequence_DelSlice:int:i1::
1080+PySequence_DelSlice:int:i2::
1081+
1082+PySequence_Fast:PyObject*::+1:
1083+PySequence_Fast:PyObject*:v:0:
1084+PySequence_Fast:const char*:m::
1085+
1086+PySequence_Fast_GET_ITEM:PyObject*::0:
1087+PySequence_Fast_GET_ITEM:PyObject*:o:0:
1088+PySequence_Fast_GET_ITEM:int:i::
1089+
1090+PySequence_GetItem:PyObject*::+1:
1091+PySequence_GetItem:PyObject*:o:0:
1092+PySequence_GetItem:int:i::
1093+
1094+PySequence_GetSlice:PyObject*::+1:
1095+PySequence_GetSlice:PyObject*:o:0:
1096+PySequence_GetSlice:int:i1::
1097+PySequence_GetSlice:int:i2::
1098+
1099+PySequence_In:int:::
1100+PySequence_In:PyObject*:o:0:
1101+PySequence_In:PyObject*:value:0:
1102+
1103+PySequence_Index:int:::
1104+PySequence_Index:PyObject*:o:0:
1105+PySequence_Index:PyObject*:value:0:
1106+
1107+PySequence_InPlaceConcat:PyObject*::+1:
1108+PySequence_InPlaceConcat:PyObject*:s:0:
1109+PySequence_InPlaceConcat:PyObject*:o:0:
1110+
1111+PySequence_InPlaceRepeat:PyObject*::+1:
1112+PySequence_InPlaceRepeat:PyObject*:s:0:
1113+PySequence_InPlaceRepeat:PyObject*:o:0:
1114+
1115+PySequence_ITEM:PyObject*::+1:
1116+PySequence_ITEM:PyObject*:o:0:
1117+PySequence_ITEM:int:i::
1118+
1119+PySequence_Repeat:PyObject*::+1:
1120+PySequence_Repeat:PyObject*:o:0:
1121+PySequence_Repeat:int:count::
1122+
1123+PySequence_SetItem:int:::
1124+PySequence_SetItem:PyObject*:o:0:
1125+PySequence_SetItem:int:i::
1126+PySequence_SetItem:PyObject*:v:+1:
1127+
1128+PySequence_SetSlice:int:::
1129+PySequence_SetSlice:PyObject*:o:0:
1130+PySequence_SetSlice:int:i1::
1131+PySequence_SetSlice:int:i2::
1132+PySequence_SetSlice:PyObject*:v:+1:
1133+
1134+PySequence_List:PyObject*::+1:
1135+PySequence_List:PyObject*:o:0:
1136+
1137+PySequence_Tuple:PyObject*::+1:
1138+PySequence_Tuple:PyObject*:o:0:
1139+
1140+PySet_Append:int:::
1141+PySet_Append:PyObject*:set:0:
1142+PySet_Append:PyObject*:key:+1:
1143+
1144+PySet_Contains:int:::
1145+PySet_Contains:PyObject*:anyset:0:
1146+PySet_Contains:PyObject*:key:0:
1147+
1148+PySet_Discard:int:::
1149+PySet_Discard:PyObject*:set:0:
1150+PySet_Discard:PyObject*:key:-1:no effect if key not found
1151+
1152+PySet_New:PyObject*::+1:
1153+PySet_New:PyObject*:iterable:0:
1154+
1155+PySet_Pop:PyObject*::+1:or returns NULL and raises KeyError if set is empty
1156+PySet_Pop:PyObject*:set:0:
1157+
1158+PySet_Size:int:::
1159+PySet_Size:PyObject*:anyset:0:
1160+
1161+PySlice_Check:int:::
1162+PySlice_Check:PyObject*:ob:0:
1163+
1164+PySlice_New:PyObject*::+1:
1165+PySlice_New:PyObject*:start:0:
1166+PySlice_New:PyObject*:stop:0:
1167+PySlice_New:PyObject*:step:0:
1168+
1169+PyString_AS_STRING:char*:::
1170+PyString_AS_STRING:PyObject*:string:0:
1171+
1172+PyString_AsDecodedObject:PyObject*::+1:
1173+PyString_AsDecodedObject:PyObject*:str:0:
1174+PyString_AsDecodedObject:const char*:encoding::
1175+PyString_AsDecodedObject:const char*:errors::
1176+
1177+PyString_AsEncodedObject:PyObject*::+1:
1178+PyString_AsEncodedObject:PyObject*:str:0:
1179+PyString_AsEncodedObject:const char*:encoding::
1180+PyString_AsEncodedObject:const char*:errors::
1181+
1182+PyString_AsString:char*:::
1183+PyString_AsString:PyObject*:string:0:
1184+
1185+PyString_AsStringAndSize:int:::
1186+PyString_AsStringAndSize:PyObject*:obj:0:
1187+PyString_AsStringAndSize:char**:buffer::
1188+PyString_AsStringAndSize:int*:length::
1189+
1190+PyString_Check:int:::
1191+PyString_Check:PyObject*:o:0:
1192+
1193+PyString_Concat:void:::
1194+PyString_Concat:PyObject**:string:0:??? -- replaces w/ new string or NULL
1195+PyString_Concat:PyObject*:newpart:0:
1196+
1197+PyString_ConcatAndDel:void:::
1198+PyString_ConcatAndDel:PyObject**:string:0:??? -- replaces w/ new string or NULL
1199+PyString_ConcatAndDel:PyObject*:newpart:-1:
1200+
1201+PyString_Format:PyObject*::+1:
1202+PyString_Format:PyObject*:format:0:
1203+PyString_Format:PyObject*:args:0:
1204+
1205+PyString_FromString:PyObject*::+1:
1206+PyString_FromString:const char*:v::
1207+
1208+PyString_FromStringAndSize:PyObject*::+1:
1209+PyString_FromStringAndSize:const char*:v::
1210+PyString_FromStringAndSize:int:len::
1211+
1212+PyString_FromFormat:PyObject*::+1:
1213+PyString_FromFormat:const char*:format::
1214+PyString_FromFormat::...::
1215+
1216+PyString_FromFormatV:PyObject*::+1:
1217+PyString_FromFormatV:const char*:format::
1218+PyString_FromFormatV:va_list:vargs::
1219+
1220+PyString_GET_SIZE:int:::
1221+PyString_GET_SIZE:PyObject*:string:0:
1222+
1223+PyString_InternFromString:PyObject*::+1:
1224+PyString_InternFromString:const char*:v::
1225+
1226+PyString_InternInPlace:void:::
1227+PyString_InternInPlace:PyObject**:string:+1:???
1228+
1229+PyString_Size:int:::
1230+PyString_Size:PyObject*:string:0:
1231+
1232+PyString_Decode:PyObject*::+1:
1233+PyString_Decode:const char*:s::
1234+PyString_Decode:int:size::
1235+PyString_Decode:const char*:encoding::
1236+PyString_Decode:const char*:errors::
1237+
1238+PyString_Encode:PyObject*::+1:
1239+PyString_Encode:const char*:s::
1240+PyString_Encode:int:size::
1241+PyString_Encode:const char*:encoding::
1242+PyString_Encode:const char*:errors::
1243+
1244+PyString_AsEncodedString:PyObject*::+1:
1245+PyString_AsEncodedString:PyObject*:str::
1246+PyString_AsEncodedString:const char*:encoding::
1247+PyString_AsEncodedString:const char*:errors::
1248+
1249+PySys_SetArgv:int:::
1250+PySys_SetArgv:int:argc::
1251+PySys_SetArgv:char**:argv::
1252+
1253+PyThreadState_Clear:void:::
1254+PyThreadState_Clear:PyThreadState*:tstate::
1255+
1256+PyThreadState_Delete:void:::
1257+PyThreadState_Delete:PyThreadState*:tstate::
1258+
1259+PyThreadState_Get:PyThreadState*:::
1260+
1261+PyThreadState_GetDict:PyObject*::0:
1262+
1263+PyThreadState_New:PyThreadState*:::
1264+PyThreadState_New:PyInterpreterState*:interp::
1265+
1266+PyThreadState_Swap:PyThreadState*:::
1267+PyThreadState_Swap:PyThreadState*:tstate::
1268+
1269+PyTime_FromTime:PyObject*::+1:
1270+PyTime_FromTime:int:hour::
1271+PyTime_FromTime:int:minute::
1272+PyTime_FromTime:int:second::
1273+PyTime_FromTime:int:usecond::
1274+
1275+PyTuple_Check:int:::
1276+PyTuple_Check:PyObject*:p:0:
1277+
1278+PyTuple_GET_ITEM:PyObject*::0:
1279+PyTuple_GET_ITEM:PyTupleObject*:p:0:
1280+PyTuple_GET_ITEM:int:pos::
1281+
1282+PyTuple_GetItem:PyObject*::0:
1283+PyTuple_GetItem:PyTupleObject*:p:0:
1284+PyTuple_GetItem:int:pos::
1285+
1286+PyTuple_GetSlice:PyObject*::+1:
1287+PyTuple_GetSlice:PyTupleObject*:p:0:
1288+PyTuple_GetSlice:int:low::
1289+PyTuple_GetSlice:int:high::
1290+
1291+PyTuple_New:PyObject*::+1:
1292+PyTuple_New:int:len::
1293+
1294+PyTuple_Pack:PyObject*::+1:
1295+PyTuple_Pack:int:len::
1296+PyTuple_Pack:PyObject*:...:0:
1297+
1298+PyTuple_SET_ITEM:void:::
1299+PyTuple_SET_ITEM:PyTupleObject*:p:0:
1300+PyTuple_SET_ITEM:int:pos::
1301+PyTuple_SET_ITEM:PyObject*:o:0:
1302+
1303+PyTuple_SetItem:int:::
1304+PyTuple_SetItem:PyTupleObject*:p:0:
1305+PyTuple_SetItem:int:pos::
1306+PyTuple_SetItem:PyObject*:o:0:
1307+
1308+PyTuple_Size:int:::
1309+PyTuple_Size:PyTupleObject*:p:0:
1310+
1311+PyType_GenericAlloc:PyObject*::+1:
1312+PyType_GenericAlloc:PyObject*:type:0:
1313+PyType_GenericAlloc:int:nitems:0:
1314+
1315+PyType_GenericNew:PyObject*::+1:
1316+PyType_GenericNew:PyObject*:type:0:
1317+PyType_GenericNew:PyObject*:args:0:
1318+PyType_GenericNew:PyObject*:kwds:0:
1319+
1320+PyUnicode_Check:int:::
1321+PyUnicode_Check:PyObject*:o:0:
1322+
1323+PyUnicode_GET_SIZE:int:::
1324+PyUnicode_GET_SIZE:PyObject*:o:0:
1325+
1326+PyUnicode_GET_DATA_SIZE:int:::
1327+PyUnicode_GET_DATA_SIZE:PyObject*:o:0:
1328+
1329+PyUnicode_AS_UNICODE:Py_UNICODE*:::
1330+PyUnicode_AS_UNICODE:PyObject*:o:0:
1331+
1332+PyUnicode_AS_DATA:const char*:::
1333+PyUnicode_AS_DATA:PyObject*:o:0:
1334+
1335+Py_UNICODE_ISSPACE:int:::
1336+Py_UNICODE_ISSPACE:Py_UNICODE:ch::
1337+
1338+Py_UNICODE_ISLOWER:int:::
1339+Py_UNICODE_ISLOWER:Py_UNICODE:ch::
1340+
1341+Py_UNICODE_ISUPPER:int:::
1342+Py_UNICODE_ISUPPER:Py_UNICODE:ch::
1343+
1344+Py_UNICODE_ISTITLE:int:::
1345+Py_UNICODE_ISTITLE:Py_UNICODE:ch::
1346+
1347+Py_UNICODE_ISLINEBREAK:int:::
1348+Py_UNICODE_ISLINEBREAK:Py_UNICODE:ch::
1349+
1350+Py_UNICODE_ISDECIMAL:int:::
1351+Py_UNICODE_ISDECIMAL:Py_UNICODE:ch::
1352+
1353+Py_UNICODE_ISDIGIT:int:::
1354+Py_UNICODE_ISDIGIT:Py_UNICODE:ch::
1355+
1356+Py_UNICODE_ISNUMERIC:int:::
1357+Py_UNICODE_ISNUMERIC:Py_UNICODE:ch::
1358+
1359+Py_UNICODE_TOLOWER:Py_UNICODE:::
1360+Py_UNICODE_TOLOWER:Py_UNICODE:ch::
1361+
1362+Py_UNICODE_TOUPPER:Py_UNICODE:::
1363+Py_UNICODE_TOUPPER:Py_UNICODE:ch::
1364+
1365+Py_UNICODE_TOTITLE:Py_UNICODE:::
1366+Py_UNICODE_TOTITLE:Py_UNICODE:ch::
1367+
1368+Py_UNICODE_TODECIMAL:int:::
1369+Py_UNICODE_TODECIMAL:Py_UNICODE:ch::
1370+
1371+Py_UNICODE_TODIGIT:int:::
1372+Py_UNICODE_TODIGIT:Py_UNICODE:ch::
1373+
1374+Py_UNICODE_TONUMERIC:double:::
1375+Py_UNICODE_TONUMERIC:Py_UNICODE:ch::
1376+
1377+PyUnicode_FromUnicode:PyObject*::+1:
1378+PyUnicode_FromUnicode:const Py_UNICODE*:u::
1379+PyUnicode_FromUnicode:int:size::
1380+
1381+PyUnicode_AsUnicode:Py_UNICODE*:::
1382+PyUnicode_AsUnicode:PyObject :*unicode:0:
1383+
1384+PyUnicode_GetSize:int:::
1385+PyUnicode_GetSize:PyObject :*unicode:0:
1386+
1387+PyUnicode_FromObject:PyObject*::+1:
1388+PyUnicode_FromObject:PyObject*:*obj:0:
1389+
1390+PyUnicode_FromEncodedObject:PyObject*::+1:
1391+PyUnicode_FromEncodedObject:PyObject*:*obj:0:
1392+PyUnicode_FromEncodedObject:const char*:encoding::
1393+PyUnicode_FromEncodedObject:const char*:errors::
1394+
1395+PyUnicode_FromWideChar:PyObject*::+1:
1396+PyUnicode_FromWideChar:const wchar_t*:w::
1397+PyUnicode_FromWideChar:int:size::
1398+
1399+PyUnicode_AsWideChar:int:::
1400+PyUnicode_AsWideChar:PyObject*:*unicode:0:
1401+PyUnicode_AsWideChar:wchar_t*:w::
1402+PyUnicode_AsWideChar:int:size::
1403+
1404+PyUnicode_Decode:PyObject*::+1:
1405+PyUnicode_Decode:const char*:s::
1406+PyUnicode_Decode:int:size::
1407+PyUnicode_Decode:const char*:encoding::
1408+PyUnicode_Decode:const char*:errors::
1409+
1410+PyUnicode_DecodeUTF16Stateful:PyObject*::+1:
1411+PyUnicode_DecodeUTF16Stateful:const char*:s::
1412+PyUnicode_DecodeUTF16Stateful:int:size::
1413+PyUnicode_DecodeUTF16Stateful:const char*:errors::
1414+PyUnicode_DecodeUTF16Stateful:int*:byteorder::
1415+PyUnicode_DecodeUTF16Stateful:int*:consumed::
1416+
1417+PyUnicode_DecodeUTF8Stateful:PyObject*::+1:
1418+PyUnicode_DecodeUTF8Stateful:const char*:s::
1419+PyUnicode_DecodeUTF8Stateful:int:size::
1420+PyUnicode_DecodeUTF8Stateful:const char*:errors::
1421+PyUnicode_DecodeUTF8Stateful:int*:consumed::
1422+
1423+PyUnicode_Encode:PyObject*::+1:
1424+PyUnicode_Encode:const Py_UNICODE*:s::
1425+PyUnicode_Encode:int:size::
1426+PyUnicode_Encode:const char*:encoding::
1427+PyUnicode_Encode:const char*:errors::
1428+
1429+PyUnicode_AsEncodedString:PyObject*::+1:
1430+PyUnicode_AsEncodedString:PyObject*:unicode::
1431+PyUnicode_AsEncodedString:const char*:encoding::
1432+PyUnicode_AsEncodedString:const char*:errors::
1433+
1434+PyUnicode_DecodeUTF8:PyObject*::+1:
1435+PyUnicode_DecodeUTF8:const char*:s::
1436+PyUnicode_DecodeUTF8:int:size::
1437+PyUnicode_DecodeUTF8:const char*:errors::
1438+
1439+PyUnicode_EncodeUTF8:PyObject*::+1:
1440+PyUnicode_EncodeUTF8:const Py_UNICODE*:s::
1441+PyUnicode_EncodeUTF8:int:size::
1442+PyUnicode_EncodeUTF8:const char*:errors::
1443+
1444+PyUnicode_AsUTF8String:PyObject*::+1:
1445+PyUnicode_AsUTF8String:PyObject*:unicode::
1446+
1447+PyUnicode_DecodeUTF16:PyObject*::+1:
1448+PyUnicode_DecodeUTF16:const char*:s::
1449+PyUnicode_DecodeUTF16:int:size::
1450+PyUnicode_DecodeUTF16:const char*:errors::
1451+PyUnicode_DecodeUTF16:int*:byteorder::
1452+
1453+PyUnicode_EncodeUTF16:PyObject*::+1:
1454+PyUnicode_EncodeUTF16:const Py_UNICODE*:s::
1455+PyUnicode_EncodeUTF16:int:size::
1456+PyUnicode_EncodeUTF16:const char*:errors::
1457+PyUnicode_EncodeUTF16:int:byteorder::
1458+
1459+PyUnicode_AsUTF16String:PyObject*::+1:
1460+PyUnicode_AsUTF16String:PyObject*:unicode::
1461+
1462+PyUnicode_DecodeUnicodeEscape:PyObject*::+1:
1463+PyUnicode_DecodeUnicodeEscape:const char*:s::
1464+PyUnicode_DecodeUnicodeEscape:int:size::
1465+PyUnicode_DecodeUnicodeEscape:const char*:errors::
1466+
1467+PyUnicode_EncodeUnicodeEscape:PyObject*::+1:
1468+PyUnicode_EncodeUnicodeEscape:const Py_UNICODE*:s::
1469+PyUnicode_EncodeUnicodeEscape:int:size::
1470+PyUnicode_EncodeUnicodeEscape:const char*:errors::
1471+
1472+PyUnicode_AsUnicodeEscapeString:PyObject*::+1:
1473+PyUnicode_AsUnicodeEscapeString:PyObject*:unicode::
1474+
1475+PyUnicode_DecodeRawUnicodeEscape:PyObject*::+1:
1476+PyUnicode_DecodeRawUnicodeEscape:const char*:s::
1477+PyUnicode_DecodeRawUnicodeEscape:int:size::
1478+PyUnicode_DecodeRawUnicodeEscape:const char*:errors::
1479+
1480+PyUnicode_EncodeRawUnicodeEscape:PyObject*::+1:
1481+PyUnicode_EncodeRawUnicodeEscape:const Py_UNICODE*:s::
1482+PyUnicode_EncodeRawUnicodeEscape:int:size::
1483+PyUnicode_EncodeRawUnicodeEscape:const char*:errors::
1484+
1485+PyUnicode_AsRawUnicodeEscapeString:PyObject*::+1:
1486+PyUnicode_AsRawUnicodeEscapeString:PyObject*:unicode::
1487+
1488+PyUnicode_DecodeLatin1:PyObject*::+1:
1489+PyUnicode_DecodeLatin1:const char*:s::
1490+PyUnicode_DecodeLatin1:int:size::
1491+PyUnicode_DecodeLatin1:const char*:errors::
1492+
1493+PyUnicode_EncodeLatin1:PyObject*::+1:
1494+PyUnicode_EncodeLatin1:const Py_UNICODE*:s::
1495+PyUnicode_EncodeLatin1:int:size::
1496+PyUnicode_EncodeLatin1:const char*:errors::
1497+
1498+PyUnicode_AsLatin1String:PyObject*::+1:
1499+PyUnicode_AsLatin1String:PyObject*:unicode::
1500+
1501+PyUnicode_DecodeASCII:PyObject*::+1:
1502+PyUnicode_DecodeASCII:const char*:s::
1503+PyUnicode_DecodeASCII:int:size::
1504+PyUnicode_DecodeASCII:const char*:errors::
1505+
1506+PyUnicode_EncodeASCII:PyObject*::+1:
1507+PyUnicode_EncodeASCII:const Py_UNICODE*:s::
1508+PyUnicode_EncodeASCII:int:size::
1509+PyUnicode_EncodeASCII:const char*:errors::
1510+
1511+PyUnicode_AsASCIIString:PyObject*::+1:
1512+PyUnicode_AsASCIIString:PyObject*:unicode::
1513+
1514+PyUnicode_DecodeCharmap:PyObject*::+1:
1515+PyUnicode_DecodeCharmap:const char*:s::
1516+PyUnicode_DecodeCharmap:int:size::
1517+PyUnicode_DecodeCharmap:PyObject*:mapping:0:
1518+PyUnicode_DecodeCharmap:const char*:errors::
1519+
1520+PyUnicode_EncodeCharmap:PyObject*::+1:
1521+PyUnicode_EncodeCharmap:const Py_UNICODE*:s::
1522+PyUnicode_EncodeCharmap:int:size::
1523+PyUnicode_EncodeCharmap:PyObject*:mapping:0:
1524+PyUnicode_EncodeCharmap:const char*:errors::
1525+
1526+PyUnicode_AsCharmapString:PyObject*::+1:
1527+PyUnicode_AsCharmapString:PyObject*:unicode:0:
1528+PyUnicode_AsCharmapString:PyObject*:mapping:0:
1529+
1530+PyUnicode_TranslateCharmap:PyObject*::+1:
1531+PyUnicode_TranslateCharmap:const Py_UNICODE*:s::
1532+PyUnicode_TranslateCharmap:int:size::
1533+PyUnicode_TranslateCharmap:PyObject*:table:0:
1534+PyUnicode_TranslateCharmap:const char*:errors::
1535+
1536+PyUnicode_DecodeMBCS:PyObject*::+1:
1537+PyUnicode_DecodeMBCS:const char*:s::
1538+PyUnicode_DecodeMBCS:int:size::
1539+PyUnicode_DecodeMBCS:const char*:errors::
1540+
1541+PyUnicode_EncodeMBCS:PyObject*::+1:
1542+PyUnicode_EncodeMBCS:const Py_UNICODE*:s::
1543+PyUnicode_EncodeMBCS:int:size::
1544+PyUnicode_EncodeMBCS:const char*:errors::
1545+
1546+PyUnicode_AsMBCSString:PyObject*::+1:
1547+PyUnicode_AsMBCSString:PyObject*:unicode::
1548+
1549+PyUnicode_Concat:PyObject*::+1:
1550+PyUnicode_Concat:PyObject*:left:0:
1551+PyUnicode_Concat:PyObject*:right:0:
1552+
1553+PyUnicode_Split:PyObject*::+1:
1554+PyUnicode_Split:PyObject*:left:0:
1555+PyUnicode_Split:PyObject*:right:0:
1556+PyUnicode_Split:int:maxsplit::
1557+
1558+PyUnicode_Splitlines:PyObject*::+1:
1559+PyUnicode_Splitlines:PyObject*:s:0:
1560+PyUnicode_Splitlines:int:maxsplit::
1561+
1562+PyUnicode_Translate:PyObject*::+1:
1563+PyUnicode_Translate:PyObject*:str:0:
1564+PyUnicode_Translate:PyObject*:table:0:
1565+PyUnicode_Translate:const char*:errors::
1566+
1567+PyUnicode_Join:PyObject*::+1:
1568+PyUnicode_Join:PyObject*:separator:0:
1569+PyUnicode_Join:PyObject*:seq:0:
1570+
1571+PyUnicode_Tailmatch:PyObject*::+1:
1572+PyUnicode_Tailmatch:PyObject*:str:0:
1573+PyUnicode_Tailmatch:PyObject*:substr:0:
1574+PyUnicode_Tailmatch:int:start::
1575+PyUnicode_Tailmatch:int:end::
1576+PyUnicode_Tailmatch:int:direction::
1577+
1578+PyUnicode_Find:int:::
1579+PyUnicode_Find:PyObject*:str:0:
1580+PyUnicode_Find:PyObject*:substr:0:
1581+PyUnicode_Find:int:start::
1582+PyUnicode_Find:int:end::
1583+PyUnicode_Find:int:direction::
1584+
1585+PyUnicode_Count:int:::
1586+PyUnicode_Count:PyObject*:str:0:
1587+PyUnicode_Count:PyObject*:substr:0:
1588+PyUnicode_Count:int:start::
1589+PyUnicode_Count:int:end::
1590+
1591+PyUnicode_Replace:PyObject*::+1:
1592+PyUnicode_Replace:PyObject*:str:0:
1593+PyUnicode_Replace:PyObject*:substr:0:
1594+PyUnicode_Replace:PyObject*:replstr:0:
1595+PyUnicode_Replace:int:maxcount::
1596+
1597+PyUnicode_Compare:int:::
1598+PyUnicode_Compare:PyObject*:left:0:
1599+PyUnicode_Compare:PyObject*:right:0:
1600+
1601+PyUnicode_Format:PyObject*::+1:
1602+PyUnicode_Format:PyObject*:format:0:
1603+PyUnicode_Format:PyObject*:args:0:
1604+
1605+PyUnicode_Contains:int:::
1606+PyUnicode_Contains:PyObject*:container:0:
1607+PyUnicode_Contains:PyObject*:element:0:
1608+
1609+PyWeakref_GET_OBJECT:PyObject*::0:
1610+PyWeakref_GET_OBJECT:PyObject*:ref:0:
1611+
1612+PyWeakref_GetObject:PyObject*::0:
1613+PyWeakref_GetObject:PyObject*:ref:0:
1614+
1615+PyWeakref_NewProxy:PyObject*::+1:
1616+PyWeakref_NewProxy:PyObject*:ob:0:
1617+PyWeakref_NewProxy:PyObject*:callback:0:
1618+
1619+PyWeakref_NewRef:PyObject*::+1:
1620+PyWeakref_NewRef:PyObject*:ob:0:
1621+PyWeakref_NewRef:PyObject*:callback:0:
1622+
1623+PyWrapper_New:PyObject*::+1:
1624+PyWrapper_New:PyObject*:d:0:
1625+PyWrapper_New:PyObject*:self:0:
1626+
1627+Py_AtExit:int:::
1628+Py_AtExit:void (*)():func::
1629+
1630+Py_BuildValue:PyObject*::+1:
1631+Py_BuildValue:char*:format::
1632+
1633+Py_CompileString:PyObject*::+1:
1634+Py_CompileString:char*:str::
1635+Py_CompileString:char*:filename::
1636+Py_CompileString:int:start::
1637+
1638+Py_CompileStringFlags:PyObject*::+1:
1639+Py_CompileStringFlags:char*:str::
1640+Py_CompileStringFlags:char*:filename::
1641+Py_CompileStringFlags:int:start::
1642+Py_CompileStringFlags:PyCompilerFlags*:flags::
1643+
1644+Py_DECREF:void:::
1645+Py_DECREF:PyObject*:o:-1:
1646+
1647+Py_EndInterpreter:void:::
1648+Py_EndInterpreter:PyThreadState*:tstate::
1649+
1650+Py_Exit:void:::
1651+Py_Exit:int:status::
1652+
1653+Py_FatalError:void:::
1654+Py_FatalError:char*:message::
1655+
1656+Py_FdIsInteractive:int:::
1657+Py_FdIsInteractive:FILE*:fp::
1658+Py_FdIsInteractive:char*:filename::
1659+
1660+Py_Finalize:void:::
1661+
1662+Py_FindMethod:PyObject*::+1:
1663+Py_FindMethod:PyMethodDef[]:methods::
1664+Py_FindMethod:PyObject*:self:+1:
1665+Py_FindMethod:char*:name::
1666+
1667+Py_GetBuildInfoconst:char*:::
1668+
1669+Py_GetCompilerconst:char*:::
1670+
1671+Py_GetCopyrightconst:char*:::
1672+
1673+Py_GetExecPrefix:char*:::
1674+
1675+Py_GetPath:char*:::
1676+
1677+Py_GetPlatformconst:char*:::
1678+
1679+Py_GetPrefix:char*:::
1680+
1681+Py_GetProgramFullPath:char*:::
1682+
1683+Py_GetProgramName:char*:::
1684+
1685+Py_GetVersionconst:char*:::
1686+
1687+Py_INCREF:void:::
1688+Py_INCREF:PyObject*:o:+1:
1689+
1690+Py_Initialize:void:::
1691+
1692+Py_IsInitialized:int:::
1693+
1694+Py_NewInterpreter:PyThreadState*:::
1695+
1696+Py_SetProgramName:void:::
1697+Py_SetProgramName:char*:name::
1698+
1699+Py_XDECREF:void:::
1700+Py_XDECREF:PyObject*:o:-1:if o is not NULL
1701+
1702+Py_XINCREF:void:::
1703+Py_XINCREF:PyObject*:o:+1:if o is not NULL
1704+
1705+_PyImport_FindExtension:PyObject*::0:??? see PyImport_AddModule
1706+_PyImport_FindExtension:char*:::
1707+_PyImport_FindExtension:char*:::
1708+
1709+_PyImport_Fini:void:::
1710+
1711+_PyImport_FixupExtension:PyObject*:::???
1712+_PyImport_FixupExtension:char*:::
1713+_PyImport_FixupExtension:char*:::
1714+
1715+_PyImport_Init:void:::
1716+
1717+_PyObject_Del:void:::
1718+_PyObject_Del:PyObject*:op:0:
1719+
1720+_PyObject_New:PyObject*::+1:
1721+_PyObject_New:PyTypeObject*:type:0:
1722+
1723+_PyObject_NewVar:PyObject*::+1:
1724+_PyObject_NewVar:PyTypeObject*:type:0:
1725+_PyObject_NewVar:int:size::
1726+
1727+_PyString_Resize:int:::
1728+_PyString_Resize:PyObject**:string:+1:
1729+_PyString_Resize:int:newsize::
1730+
1731+_PyTuple_Resize:int:::
1732+_PyTuple_Resize:PyTupleObject**:p:+1:
1733+_PyTuple_Resize:int:new::
1734+
1735+_Py_c_diff:Py_complex:::
1736+_Py_c_diff:Py_complex:left::
1737+_Py_c_diff:Py_complex:right::
1738+
1739+_Py_c_neg:Py_complex:::
1740+_Py_c_neg:Py_complex:complex::
1741+
1742+_Py_c_pow:Py_complex:::
1743+_Py_c_pow:Py_complex:num::
1744+_Py_c_pow:Py_complex:exp::
1745+
1746+_Py_c_prod:Py_complex:::
1747+_Py_c_prod:Py_complex:left::
1748+_Py_c_prod:Py_complex:right::
1749+
1750+_Py_c_quot:Py_complex:::
1751+_Py_c_quot:Py_complex:dividend::
1752+_Py_c_quot:Py_complex:divisor::
1753+
1754+_Py_c_sum:Py_complex:::
1755+_Py_c_sum:Py_complex:left::
1756+_Py_c_sum:Py_complex:right::
sys/src/cmd/python/Doc/api/utilities.tex+1023−0
@@ -0,0 +1,1023 @@
1+\chapter{Utilities \label{utilities}}
2+
3+The functions in this chapter perform various utility tasks, ranging
4+from helping C code be more portable across platforms, using Python
5+modules from C, and parsing function arguments and constructing Python
6+values from C values.
7+
8+
9+\section{Operating System Utilities \label{os}}
10+
11+\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, const char *filename}
12+ Return true (nonzero) if the standard I/O file \var{fp} with name
13+ \var{filename} is deemed interactive. This is the case for files
14+ for which \samp{isatty(fileno(\var{fp}))} is true. If the global
15+ flag \cdata{Py_InteractiveFlag} is true, this function also returns
16+ true if the \var{filename} pointer is \NULL{} or if the name is
17+ equal to one of the strings \code{'<stdin>'} or \code{'???'}.
18+\end{cfuncdesc}
19+
20+\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
21+ Return the time of last modification of the file \var{filename}.
22+ The result is encoded in the same way as the timestamp returned by
23+ the standard C library function \cfunction{time()}.
24+\end{cfuncdesc}
25+
26+\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
27+ Function to update some internal state after a process fork; this
28+ should be called in the new process if the Python interpreter will
29+ continue to be used. If a new executable is loaded into the new
30+ process, this function does not need to be called.
31+\end{cfuncdesc}
32+
33+\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
34+ Return true when the interpreter runs out of stack space. This is a
35+ reliable check, but is only available when \constant{USE_STACKCHECK}
36+ is defined (currently on Windows using the Microsoft Visual \Cpp{}
37+ compiler). \constant{USE_STACKCHECK} will be
38+ defined automatically; you should never change the definition in
39+ your own code.
40+\end{cfuncdesc}
41+
42+\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i}
43+ Return the current signal handler for signal \var{i}. This is a
44+ thin wrapper around either \cfunction{sigaction()} or
45+ \cfunction{signal()}. Do not call those functions directly!
46+ \ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void
47+ (*)(int)}.
48+\end{cfuncdesc}
49+
50+\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h}
51+ Set the signal handler for signal \var{i} to be \var{h}; return the
52+ old signal handler. This is a thin wrapper around either
53+ \cfunction{sigaction()} or \cfunction{signal()}. Do not call those
54+ functions directly! \ctype{PyOS_sighandler_t} is a typedef alias
55+ for \ctype{void (*)(int)}.
56+\end{cfuncdesc}
57+
58+
59+\section{Process Control \label{processControl}}
60+
61+\begin{cfuncdesc}{void}{Py_FatalError}{const char *message}
62+ Print a fatal error message and kill the process. No cleanup is
63+ performed. This function should only be invoked when a condition is
64+ detected that would make it dangerous to continue using the Python
65+ interpreter; e.g., when the object administration appears to be
66+ corrupted. On \UNIX, the standard C library function
67+ \cfunction{abort()}\ttindex{abort()} is called which will attempt to
68+ produce a \file{core} file.
69+\end{cfuncdesc}
70+
71+\begin{cfuncdesc}{void}{Py_Exit}{int status}
72+ Exit the current process. This calls
73+ \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and then calls the
74+ standard C library function
75+ \code{exit(\var{status})}\ttindex{exit()}.
76+\end{cfuncdesc}
77+
78+\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
79+ Register a cleanup function to be called by
80+ \cfunction{Py_Finalize()}\ttindex{Py_Finalize()}. The cleanup
81+ function will be called with no arguments and should return no
82+ value. At most 32 \index{cleanup functions}cleanup functions can be
83+ registered. When the registration is successful,
84+ \cfunction{Py_AtExit()} returns \code{0}; on failure, it returns
85+ \code{-1}. The cleanup function registered last is called first.
86+ Each cleanup function will be called at most once. Since Python's
87+ internal finalization will have completed before the cleanup
88+ function, no Python APIs should be called by \var{func}.
89+\end{cfuncdesc}
90+
91+
92+\section{Importing Modules \label{importing}}
93+
94+\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{const char *name}
95+ This is a simplified interface to
96+ \cfunction{PyImport_ImportModuleEx()} below, leaving the
97+ \var{globals} and \var{locals} arguments set to \NULL. When the
98+ \var{name} argument contains a dot (when it specifies a submodule of
99+ a package), the \var{fromlist} argument is set to the list
100+ \code{['*']} so that the return value is the named module rather
101+ than the top-level package containing it as would otherwise be the
102+ case. (Unfortunately, this has an additional side effect when
103+ \var{name} in fact specifies a subpackage instead of a submodule:
104+ the submodules specified in the package's \code{__all__} variable
105+ are \index{package variable!\code{__all__}}
106+ \withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return
107+ a new reference to the imported module, or \NULL{} with an exception
108+ set on failure. Before Python 2.4, the module may still be created in
109+ the failure case --- examine \code{sys.modules} to find out. Starting
110+ with Python 2.4, a failing import of a module no longer leaves the
111+ module in \code{sys.modules}.
112+ \versionchanged[failing imports remove incomplete module objects]{2.4}
113+ \withsubitem{(in module sys)}{\ttindex{modules}}
114+\end{cfuncdesc}
115+
116+\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name,
117+ PyObject *globals, PyObject *locals, PyObject *fromlist}
118+ Import a module. This is best described by referring to the
119+ built-in Python function
120+ \function{__import__()}\bifuncindex{__import__}, as the standard
121+ \function{__import__()} function calls this function directly.
122+
123+ The return value is a new reference to the imported module or
124+ top-level package, or \NULL{} with an exception set on failure (before
125+ Python 2.4, the
126+ module may still be created in this case). Like for
127+ \function{__import__()}, the return value when a submodule of a
128+ package was requested is normally the top-level package, unless a
129+ non-empty \var{fromlist} was given.
130+ \versionchanged[failing imports remove incomplete module objects]{2.4}
131+\end{cfuncdesc}
132+
133+\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
134+ This is a higher-level interface that calls the current ``import
135+ hook function''. It invokes the \function{__import__()} function
136+ from the \code{__builtins__} of the current globals. This means
137+ that the import is done using whatever import hooks are installed in
138+ the current environment, e.g. by \module{rexec}\refstmodindex{rexec}
139+ or \module{ihooks}\refstmodindex{ihooks}.
140+\end{cfuncdesc}
141+
142+\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
143+ Reload a module. This is best described by referring to the
144+ built-in Python function \function{reload()}\bifuncindex{reload}, as
145+ the standard \function{reload()} function calls this function
146+ directly. Return a new reference to the reloaded module, or \NULL{}
147+ with an exception set on failure (the module still exists in this
148+ case).
149+\end{cfuncdesc}
150+
151+\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{const char *name}
152+ Return the module object corresponding to a module name. The
153+ \var{name} argument may be of the form \code{package.module}.
154+ First check the modules dictionary if there's one there, and if not,
155+ create a new one and insert it in the modules dictionary.
156+ Return \NULL{} with an exception set on failure.
157+ \note{This function does not load or import the module; if the
158+ module wasn't already loaded, you will get an empty module object.
159+ Use \cfunction{PyImport_ImportModule()} or one of its variants to
160+ import a module. Package structures implied by a dotted name for
161+ \var{name} are not created if not already present.}
162+\end{cfuncdesc}
163+
164+\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
165+ Given a module name (possibly of the form \code{package.module}) and
166+ a code object read from a Python bytecode file or obtained from the
167+ built-in function \function{compile()}\bifuncindex{compile}, load
168+ the module. Return a new reference to the module object, or \NULL{}
169+ with an exception set if an error occurred. Before Python 2.4, the module
170+ could still be created in error cases. Starting with Python 2.4,
171+ \var{name} is removed from \code{sys.modules} in error cases, and even
172+ if \var{name} was already in \code{sys.modules} on entry to
173+ \cfunction{PyImport_ExecCodeModule()}. Leaving incompletely initialized
174+ modules in \code{sys.modules} is dangerous, as imports of such modules
175+ have no way to know that the module object is an unknown (and probably
176+ damaged with respect to the module author's intents) state.
177+
178+ This function will reload the module if it was already imported. See
179+ \cfunction{PyImport_ReloadModule()} for the intended way to reload a
180+ module.
181+
182+ If \var{name} points to a dotted name of the
183+ form \code{package.module}, any package structures not already
184+ created will still not be created.
185+
186+ \versionchanged[\var{name} is removed from \code{sys.modules} in error cases]{2.4}
187+
188+\end{cfuncdesc}
189+
190+\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
191+ Return the magic number for Python bytecode files
192+ (a.k.a. \file{.pyc} and \file{.pyo} files). The magic number should
193+ be present in the first four bytes of the bytecode file, in
194+ little-endian byte order.
195+\end{cfuncdesc}
196+
197+\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
198+ Return the dictionary used for the module administration
199+ (a.k.a.\ \code{sys.modules}). Note that this is a per-interpreter
200+ variable.
201+\end{cfuncdesc}
202+
203+\begin{cfuncdesc}{void}{_PyImport_Init}{}
204+ Initialize the import mechanism. For internal use only.
205+\end{cfuncdesc}
206+
207+\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
208+ Empty the module table. For internal use only.
209+\end{cfuncdesc}
210+
211+\begin{cfuncdesc}{void}{_PyImport_Fini}{}
212+ Finalize the import mechanism. For internal use only.
213+\end{cfuncdesc}
214+
215+\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
216+ For internal use only.
217+\end{cfuncdesc}
218+
219+\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
220+ For internal use only.
221+\end{cfuncdesc}
222+
223+\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
224+ Load a frozen module named \var{name}. Return \code{1} for success,
225+ \code{0} if the module is not found, and \code{-1} with an exception
226+ set if the initialization failed. To access the imported module on
227+ a successful load, use \cfunction{PyImport_ImportModule()}. (Note
228+ the misnomer --- this function would reload the module if it was
229+ already imported.)
230+\end{cfuncdesc}
231+
232+\begin{ctypedesc}[_frozen]{struct _frozen}
233+ This is the structure type definition for frozen module descriptors,
234+ as generated by the \program{freeze}\index{freeze utility} utility
235+ (see \file{Tools/freeze/} in the Python source distribution). Its
236+ definition, found in \file{Include/import.h}, is:
237+
238+\begin{verbatim}
239+struct _frozen {
240+ char *name;
241+ unsigned char *code;
242+ int size;
243+};
244+\end{verbatim}
245+\end{ctypedesc}
246+
247+\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
248+ This pointer is initialized to point to an array of \ctype{struct
249+ _frozen} records, terminated by one whose members are all \NULL{} or
250+ zero. When a frozen module is imported, it is searched in this
251+ table. Third-party code could play tricks with this to provide a
252+ dynamically created collection of frozen modules.
253+\end{cvardesc}
254+
255+\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
256+ void (*initfunc)(void)}
257+ Add a single module to the existing table of built-in modules. This
258+ is a convenience wrapper around
259+ \cfunction{PyImport_ExtendInittab()}, returning \code{-1} if the
260+ table could not be extended. The new module can be imported by the
261+ name \var{name}, and uses the function \var{initfunc} as the
262+ initialization function called on the first attempted import. This
263+ should be called before \cfunction{Py_Initialize()}.
264+\end{cfuncdesc}
265+
266+\begin{ctypedesc}[_inittab]{struct _inittab}
267+ Structure describing a single entry in the list of built-in
268+ modules. Each of these structures gives the name and initialization
269+ function for a module built into the interpreter. Programs which
270+ embed Python may use an array of these structures in conjunction
271+ with \cfunction{PyImport_ExtendInittab()} to provide additional
272+ built-in modules. The structure is defined in
273+ \file{Include/import.h} as:
274+
275+\begin{verbatim}
276+struct _inittab {
277+ char *name;
278+ void (*initfunc)(void);
279+};
280+\end{verbatim}
281+\end{ctypedesc}
282+
283+\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
284+ Add a collection of modules to the table of built-in modules. The
285+ \var{newtab} array must end with a sentinel entry which contains
286+ \NULL{} for the \member{name} field; failure to provide the sentinel
287+ value can result in a memory fault. Returns \code{0} on success or
288+ \code{-1} if insufficient memory could be allocated to extend the
289+ internal table. In the event of failure, no modules are added to
290+ the internal table. This should be called before
291+ \cfunction{Py_Initialize()}.
292+\end{cfuncdesc}
293+
294+
295+\section{Data marshalling support \label{marshalling-utils}}
296+
297+These routines allow C code to work with serialized objects using the
298+same data format as the \module{marshal} module. There are functions
299+to write data into the serialization format, and additional functions
300+that can be used to read the data back. Files used to store marshalled
301+data must be opened in binary mode.
302+
303+Numeric values are stored with the least significant byte first.
304+
305+The module supports two versions of the data format: version 0 is the
306+historical version, version 1 (new in Python 2.4) shares interned
307+strings in the file, and upon unmarshalling. \var{Py_MARSHAL_VERSION}
308+indicates the current file format (currently 1).
309+
310+\begin{cfuncdesc}{void}{PyMarshal_WriteLongToFile}{long value, FILE *file, int version}
311+ Marshal a \ctype{long} integer, \var{value}, to \var{file}. This
312+ will only write the least-significant 32 bits of \var{value};
313+ regardless of the size of the native \ctype{long} type.
314+
315+ \versionchanged[\var{version} indicates the file format]{2.4}
316+\end{cfuncdesc}
317+
318+\begin{cfuncdesc}{void}{PyMarshal_WriteObjectToFile}{PyObject *value,
319+ FILE *file, int version}
320+ Marshal a Python object, \var{value}, to \var{file}.
321+
322+ \versionchanged[\var{version} indicates the file format]{2.4}
323+\end{cfuncdesc}
324+
325+\begin{cfuncdesc}{PyObject*}{PyMarshal_WriteObjectToString}{PyObject *value, int version}
326+ Return a string object containing the marshalled representation of
327+ \var{value}.
328+
329+ \versionchanged[\var{version} indicates the file format]{2.4}
330+\end{cfuncdesc}
331+
332+The following functions allow marshalled values to be read back in.
333+
334+XXX What about error detection? It appears that reading past the end
335+of the file will always result in a negative numeric value (where
336+that's relevant), but it's not clear that negative values won't be
337+handled properly when there's no error. What's the right way to tell?
338+Should only non-negative values be written using these routines?
339+
340+\begin{cfuncdesc}{long}{PyMarshal_ReadLongFromFile}{FILE *file}
341+ Return a C \ctype{long} from the data stream in a \ctype{FILE*}
342+ opened for reading. Only a 32-bit value can be read in using
343+ this function, regardless of the native size of \ctype{long}.
344+\end{cfuncdesc}
345+
346+\begin{cfuncdesc}{int}{PyMarshal_ReadShortFromFile}{FILE *file}
347+ Return a C \ctype{short} from the data stream in a \ctype{FILE*}
348+ opened for reading. Only a 16-bit value can be read in using
349+ this function, regardless of the native size of \ctype{short}.
350+\end{cfuncdesc}
351+
352+\begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromFile}{FILE *file}
353+ Return a Python object from the data stream in a \ctype{FILE*}
354+ opened for reading. On error, sets the appropriate exception
355+ (\exception{EOFError} or \exception{TypeError}) and returns \NULL.
356+\end{cfuncdesc}
357+
358+\begin{cfuncdesc}{PyObject*}{PyMarshal_ReadLastObjectFromFile}{FILE *file}
359+ Return a Python object from the data stream in a \ctype{FILE*}
360+ opened for reading. Unlike
361+ \cfunction{PyMarshal_ReadObjectFromFile()}, this function assumes
362+ that no further objects will be read from the file, allowing it to
363+ aggressively load file data into memory so that the de-serialization
364+ can operate from data in memory rather than reading a byte at a time
365+ from the file. Only use these variant if you are certain that you
366+ won't be reading anything else from the file. On error, sets the
367+ appropriate exception (\exception{EOFError} or
368+ \exception{TypeError}) and returns \NULL.
369+\end{cfuncdesc}
370+
371+\begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromString}{char *string,
372+ Py_ssize_t len}
373+ Return a Python object from the data stream in a character buffer
374+ containing \var{len} bytes pointed to by \var{string}. On error,
375+ sets the appropriate exception (\exception{EOFError} or
376+ \exception{TypeError}) and returns \NULL.
377+\end{cfuncdesc}
378+
379+
380+\section{Parsing arguments and building values
381+ \label{arg-parsing}}
382+
383+These functions are useful when creating your own extensions functions
384+and methods. Additional information and examples are available in
385+\citetitle[../ext/ext.html]{Extending and Embedding the Python
386+Interpreter}.
387+
388+The first three of these functions described,
389+\cfunction{PyArg_ParseTuple()},
390+\cfunction{PyArg_ParseTupleAndKeywords()}, and
391+\cfunction{PyArg_Parse()}, all use \emph{format strings} which are
392+used to tell the function about the expected arguments. The format
393+strings use the same syntax for each of these functions.
394+
395+A format string consists of zero or more ``format units.'' A format
396+unit describes one Python object; it is usually a single character or
397+a parenthesized sequence of format units. With a few exceptions, a
398+format unit that is not a parenthesized sequence normally corresponds
399+to a single address argument to these functions. In the following
400+description, the quoted form is the format unit; the entry in (round)
401+parentheses is the Python object type that matches the format unit;
402+and the entry in [square] brackets is the type of the C variable(s)
403+whose address should be passed.
404+
405+\begin{description}
406+ \item[\samp{s} (string or Unicode object) {[const char *]}]
407+ Convert a Python string or Unicode object to a C pointer to a
408+ character string. You must not provide storage for the string
409+ itself; a pointer to an existing string is stored into the character
410+ pointer variable whose address you pass. The C string is
411+ NUL-terminated. The Python string must not contain embedded NUL
412+ bytes; if it does, a \exception{TypeError} exception is raised.
413+ Unicode objects are converted to C strings using the default
414+ encoding. If this conversion fails, a \exception{UnicodeError} is
415+ raised.
416+
417+ \item[\samp{s\#} (string, Unicode or any read buffer compatible object)
418+ {[const char *, int]}]
419+ This variant on \samp{s} stores into two C variables, the first one
420+ a pointer to a character string, the second one its length. In this
421+ case the Python string may contain embedded null bytes. Unicode
422+ objects pass back a pointer to the default encoded string version of
423+ the object if such a conversion is possible. All other read-buffer
424+ compatible objects pass back a reference to the raw internal data
425+ representation.
426+
427+ \item[\samp{z} (string or \code{None}) {[const char *]}]
428+ Like \samp{s}, but the Python object may also be \code{None}, in
429+ which case the C pointer is set to \NULL.
430+
431+ \item[\samp{z\#} (string or \code{None} or any read buffer
432+ compatible object) {[const char *, int]}]
433+ This is to \samp{s\#} as \samp{z} is to \samp{s}.
434+
435+ \item[\samp{u} (Unicode object) {[Py_UNICODE *]}]
436+ Convert a Python Unicode object to a C pointer to a NUL-terminated
437+ buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is
438+ no need to provide storage for the Unicode data buffer; a pointer to
439+ the existing Unicode data is stored into the \ctype{Py_UNICODE}
440+ pointer variable whose address you pass.
441+
442+ \item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}]
443+ This variant on \samp{u} stores into two C variables, the first one
444+ a pointer to a Unicode data buffer, the second one its length.
445+ Non-Unicode objects are handled by interpreting their read-buffer
446+ pointer as pointer to a \ctype{Py_UNICODE} array.
447+
448+ \item[\samp{es} (string, Unicode object or character buffer
449+ compatible object) {[const char *encoding, char **buffer]}]
450+ This variant on \samp{s} is used for encoding Unicode and objects
451+ convertible to Unicode into a character buffer. It only works for
452+ encoded data without embedded NUL bytes.
453+
454+ This format requires two arguments. The first is only used as
455+ input, and must be a \ctype{const char*} which points to the name of an
456+ encoding as a NUL-terminated string, or \NULL, in which case the
457+ default encoding is used. An exception is raised if the named
458+ encoding is not known to Python. The second argument must be a
459+ \ctype{char**}; the value of the pointer it references will be set
460+ to a buffer with the contents of the argument text. The text will
461+ be encoded in the encoding specified by the first argument.
462+
463+ \cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
464+ size, copy the encoded data into this buffer and adjust
465+ \var{*buffer} to reference the newly allocated storage. The caller
466+ is responsible for calling \cfunction{PyMem_Free()} to free the
467+ allocated buffer after use.
468+
469+ \item[\samp{et} (string, Unicode object or character buffer
470+ compatible object) {[const char *encoding, char **buffer]}]
471+ Same as \samp{es} except that 8-bit string objects are passed
472+ through without recoding them. Instead, the implementation assumes
473+ that the string object uses the encoding passed in as parameter.
474+
475+ \item[\samp{es\#} (string, Unicode object or character buffer compatible
476+ object) {[const char *encoding, char **buffer, int *buffer_length]}]
477+ This variant on \samp{s\#} is used for encoding Unicode and objects
478+ convertible to Unicode into a character buffer. Unlike the
479+ \samp{es} format, this variant allows input data which contains NUL
480+ characters.
481+
482+ It requires three arguments. The first is only used as input, and
483+ must be a \ctype{const char*} which points to the name of an encoding as a
484+ NUL-terminated string, or \NULL, in which case the default encoding
485+ is used. An exception is raised if the named encoding is not known
486+ to Python. The second argument must be a \ctype{char**}; the value
487+ of the pointer it references will be set to a buffer with the
488+ contents of the argument text. The text will be encoded in the
489+ encoding specified by the first argument. The third argument must
490+ be a pointer to an integer; the referenced integer will be set to
491+ the number of bytes in the output buffer.
492+
493+ There are two modes of operation:
494+
495+ If \var{*buffer} points a \NULL{} pointer, the function will
496+ allocate a buffer of the needed size, copy the encoded data into
497+ this buffer and set \var{*buffer} to reference the newly allocated
498+ storage. The caller is responsible for calling
499+ \cfunction{PyMem_Free()} to free the allocated buffer after usage.
500+
501+ If \var{*buffer} points to a non-\NULL{} pointer (an already
502+ allocated buffer), \cfunction{PyArg_ParseTuple()} will use this
503+ location as the buffer and interpret the initial value of
504+ \var{*buffer_length} as the buffer size. It will then copy the
505+ encoded data into the buffer and NUL-terminate it. If the buffer
506+ is not large enough, a \exception{ValueError} will be set.
507+
508+ In both cases, \var{*buffer_length} is set to the length of the
509+ encoded data without the trailing NUL byte.
510+
511+ \item[\samp{et\#} (string, Unicode object or character buffer compatible
512+ object) {[const char *encoding, char **buffer]}]
513+ Same as \samp{es\#} except that string objects are passed through
514+ without recoding them. Instead, the implementation assumes that the
515+ string object uses the encoding passed in as parameter.
516+
517+ \item[\samp{b} (integer) {[char]}]
518+ Convert a Python integer to a tiny int, stored in a C \ctype{char}.
519+
520+ \item[\samp{B} (integer) {[unsigned char]}]
521+ Convert a Python integer to a tiny int without overflow checking,
522+ stored in a C \ctype{unsigned char}. \versionadded{2.3}
523+
524+ \item[\samp{h} (integer) {[short int]}]
525+ Convert a Python integer to a C \ctype{short int}.
526+
527+ \item[\samp{H} (integer) {[unsigned short int]}]
528+ Convert a Python integer to a C \ctype{unsigned short int}, without
529+ overflow checking. \versionadded{2.3}
530+
531+ \item[\samp{i} (integer) {[int]}]
532+ Convert a Python integer to a plain C \ctype{int}.
533+
534+ \item[\samp{I} (integer) {[unsigned int]}]
535+ Convert a Python integer to a C \ctype{unsigned int}, without
536+ overflow checking. \versionadded{2.3}
537+
538+ \item[\samp{l} (integer) {[long int]}]
539+ Convert a Python integer to a C \ctype{long int}.
540+
541+ \item[\samp{k} (integer) {[unsigned long]}]
542+ Convert a Python integer or long integer to a C \ctype{unsigned long} without
543+ overflow checking. \versionadded{2.3}
544+
545+ \item[\samp{L} (integer) {[PY_LONG_LONG]}]
546+ Convert a Python integer to a C \ctype{long long}. This format is
547+ only available on platforms that support \ctype{long long} (or
548+ \ctype{_int64} on Windows).
549+
550+ \item[\samp{K} (integer) {[unsigned PY_LONG_LONG]}]
551+ Convert a Python integer or long integer to a C \ctype{unsigned long long}
552+ without overflow checking. This format is only available on
553+ platforms that support \ctype{unsigned long long} (or
554+ \ctype{unsigned _int64} on Windows). \versionadded{2.3}
555+
556+ \item[\samp{n} (integer) {[Py_ssize_t]}]
557+ Convert a Python integer or long integer to a C \ctype{Py_ssize_t}.
558+ \versionadded{2.5}
559+
560+ \item[\samp{c} (string of length 1) {[char]}]
561+ Convert a Python character, represented as a string of length 1, to
562+ a C \ctype{char}.
563+
564+ \item[\samp{f} (float) {[float]}]
565+ Convert a Python floating point number to a C \ctype{float}.
566+
567+ \item[\samp{d} (float) {[double]}]
568+ Convert a Python floating point number to a C \ctype{double}.
569+
570+ \item[\samp{D} (complex) {[Py_complex]}]
571+ Convert a Python complex number to a C \ctype{Py_complex} structure.
572+
573+ \item[\samp{O} (object) {[PyObject *]}]
574+ Store a Python object (without any conversion) in a C object
575+ pointer. The C program thus receives the actual object that was
576+ passed. The object's reference count is not increased. The pointer
577+ stored is not \NULL.
578+
579+ \item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}]
580+ Store a Python object in a C object pointer. This is similar to
581+ \samp{O}, but takes two C arguments: the first is the address of a
582+ Python type object, the second is the address of the C variable (of
583+ type \ctype{PyObject*}) into which the object pointer is stored. If
584+ the Python object does not have the required type,
585+ \exception{TypeError} is raised.
586+
587+ \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
588+ Convert a Python object to a C variable through a \var{converter}
589+ function. This takes two arguments: the first is a function, the
590+ second is the address of a C variable (of arbitrary type), converted
591+ to \ctype{void *}. The \var{converter} function in turn is called
592+ as follows:
593+
594+ \var{status}\code{ = }\var{converter}\code{(}\var{object},
595+ \var{address}\code{);}
596+
597+ where \var{object} is the Python object to be converted and
598+ \var{address} is the \ctype{void*} argument that was passed to the
599+ \cfunction{PyArg_Parse*()} function. The returned \var{status}
600+ should be \code{1} for a successful conversion and \code{0} if the
601+ conversion has failed. When the conversion fails, the
602+ \var{converter} function should raise an exception.
603+
604+ \item[\samp{S} (string) {[PyStringObject *]}]
605+ Like \samp{O} but requires that the Python object is a string
606+ object. Raises \exception{TypeError} if the object is not a string
607+ object. The C variable may also be declared as \ctype{PyObject*}.
608+
609+ \item[\samp{U} (Unicode string) {[PyUnicodeObject *]}]
610+ Like \samp{O} but requires that the Python object is a Unicode
611+ object. Raises \exception{TypeError} if the object is not a Unicode
612+ object. The C variable may also be declared as \ctype{PyObject*}.
613+
614+ \item[\samp{t\#} (read-only character buffer) {[char *, int]}]
615+ Like \samp{s\#}, but accepts any object which implements the
616+ read-only buffer interface. The \ctype{char*} variable is set to
617+ point to the first byte of the buffer, and the \ctype{int} is set to
618+ the length of the buffer. Only single-segment buffer objects are
619+ accepted; \exception{TypeError} is raised for all others.
620+
621+ \item[\samp{w} (read-write character buffer) {[char *]}]
622+ Similar to \samp{s}, but accepts any object which implements the
623+ read-write buffer interface. The caller must determine the length
624+ of the buffer by other means, or use \samp{w\#} instead. Only
625+ single-segment buffer objects are accepted; \exception{TypeError} is
626+ raised for all others.
627+
628+ \item[\samp{w\#} (read-write character buffer) {[char *, int]}]
629+ Like \samp{s\#}, but accepts any object which implements the
630+ read-write buffer interface. The \ctype{char *} variable is set to
631+ point to the first byte of the buffer, and the \ctype{int} is set to
632+ the length of the buffer. Only single-segment buffer objects are
633+ accepted; \exception{TypeError} is raised for all others.
634+
635+ \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
636+ The object must be a Python sequence whose length is the number of
637+ format units in \var{items}. The C arguments must correspond to the
638+ individual format units in \var{items}. Format units for sequences
639+ may be nested.
640+
641+ \note{Prior to Python version 1.5.2, this format specifier only
642+ accepted a tuple containing the individual parameters, not an
643+ arbitrary sequence. Code which previously caused
644+ \exception{TypeError} to be raised here may now proceed without an
645+ exception. This is not expected to be a problem for existing code.}
646+\end{description}
647+
648+It is possible to pass Python long integers where integers are
649+requested; however no proper range checking is done --- the most
650+significant bits are silently truncated when the receiving field is
651+too small to receive the value (actually, the semantics are inherited
652+from downcasts in C --- your mileage may vary).
653+
654+A few other characters have a meaning in a format string. These may
655+not occur inside nested parentheses. They are:
656+
657+\begin{description}
658+ \item[\samp{|}]
659+ Indicates that the remaining arguments in the Python argument list
660+ are optional. The C variables corresponding to optional arguments
661+ should be initialized to their default value --- when an optional
662+ argument is not specified, \cfunction{PyArg_ParseTuple()} does not
663+ touch the contents of the corresponding C variable(s).
664+
665+ \item[\samp{:}]
666+ The list of format units ends here; the string after the colon is
667+ used as the function name in error messages (the ``associated
668+ value'' of the exception that \cfunction{PyArg_ParseTuple()}
669+ raises).
670+
671+ \item[\samp{;}]
672+ The list of format units ends here; the string after the semicolon
673+ is used as the error message \emph{instead} of the default error
674+ message. Clearly, \samp{:} and \samp{;} mutually exclude each
675+ other.
676+\end{description}
677+
678+Note that any Python object references which are provided to the
679+caller are \emph{borrowed} references; do not decrement their
680+reference count!
681+
682+Additional arguments passed to these functions must be addresses of
683+variables whose type is determined by the format string; these are
684+used to store values from the input tuple. There are a few cases, as
685+described in the list of format units above, where these parameters
686+are used as input values; they should match what is specified for the
687+corresponding format unit in that case.
688+
689+For the conversion to succeed, the \var{arg} object must match the
690+format and the format must be exhausted. On success, the
691+\cfunction{PyArg_Parse*()} functions return true, otherwise they
692+return false and raise an appropriate exception.
693+
694+\begin{cfuncdesc}{int}{PyArg_ParseTuple}{PyObject *args, const char *format,
695+ \moreargs}
696+ Parse the parameters of a function that takes only positional
697+ parameters into local variables. Returns true on success; on
698+ failure, it returns false and raises the appropriate exception.
699+\end{cfuncdesc}
700+
701+\begin{cfuncdesc}{int}{PyArg_VaParse}{PyObject *args, const char *format,
702+ va_list vargs}
703+ Identical to \cfunction{PyArg_ParseTuple()}, except that it accepts a
704+ va_list rather than a variable number of arguments.
705+\end{cfuncdesc}
706+
707+\begin{cfuncdesc}{int}{PyArg_ParseTupleAndKeywords}{PyObject *args,
708+ PyObject *kw, const char *format, char *keywords[],
709+ \moreargs}
710+ Parse the parameters of a function that takes both positional and
711+ keyword parameters into local variables. Returns true on success;
712+ on failure, it returns false and raises the appropriate exception.
713+\end{cfuncdesc}
714+
715+\begin{cfuncdesc}{int}{PyArg_VaParseTupleAndKeywords}{PyObject *args,
716+ PyObject *kw, const char *format, char *keywords[],
717+ va_list vargs}
718+ Identical to \cfunction{PyArg_ParseTupleAndKeywords()}, except that it
719+ accepts a va_list rather than a variable number of arguments.
720+\end{cfuncdesc}
721+
722+\begin{cfuncdesc}{int}{PyArg_Parse}{PyObject *args, const char *format,
723+ \moreargs}
724+ Function used to deconstruct the argument lists of ``old-style''
725+ functions --- these are functions which use the
726+ \constant{METH_OLDARGS} parameter parsing method. This is not
727+ recommended for use in parameter parsing in new code, and most code
728+ in the standard interpreter has been modified to no longer use this
729+ for that purpose. It does remain a convenient way to decompose
730+ other tuples, however, and may continue to be used for that
731+ purpose.
732+\end{cfuncdesc}
733+
734+\begin{cfuncdesc}{int}{PyArg_UnpackTuple}{PyObject *args, const char *name,
735+ Py_ssize_t min, Py_ssize_t max, \moreargs}
736+ A simpler form of parameter retrieval which does not use a format
737+ string to specify the types of the arguments. Functions which use
738+ this method to retrieve their parameters should be declared as
739+ \constant{METH_VARARGS} in function or method tables. The tuple
740+ containing the actual parameters should be passed as \var{args}; it
741+ must actually be a tuple. The length of the tuple must be at least
742+ \var{min} and no more than \var{max}; \var{min} and \var{max} may be
743+ equal. Additional arguments must be passed to the function, each of
744+ which should be a pointer to a \ctype{PyObject*} variable; these
745+ will be filled in with the values from \var{args}; they will contain
746+ borrowed references. The variables which correspond to optional
747+ parameters not given by \var{args} will not be filled in; these
748+ should be initialized by the caller.
749+ This function returns true on success and false if \var{args} is not
750+ a tuple or contains the wrong number of elements; an exception will
751+ be set if there was a failure.
752+
753+ This is an example of the use of this function, taken from the
754+ sources for the \module{_weakref} helper module for weak references:
755+
756+\begin{verbatim}
757+static PyObject *
758+weakref_ref(PyObject *self, PyObject *args)
759+{
760+ PyObject *object;
761+ PyObject *callback = NULL;
762+ PyObject *result = NULL;
763+
764+ if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
765+ result = PyWeakref_NewRef(object, callback);
766+ }
767+ return result;
768+}
769+\end{verbatim}
770+
771+ The call to \cfunction{PyArg_UnpackTuple()} in this example is
772+ entirely equivalent to this call to \cfunction{PyArg_ParseTuple()}:
773+
774+\begin{verbatim}
775+PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
776+\end{verbatim}
777+
778+ \versionadded{2.2}
779+\end{cfuncdesc}
780+
781+\begin{cfuncdesc}{PyObject*}{Py_BuildValue}{const char *format,
782+ \moreargs}
783+ Create a new value based on a format string similar to those
784+ accepted by the \cfunction{PyArg_Parse*()} family of functions and a
785+ sequence of values. Returns the value or \NULL{} in the case of an
786+ error; an exception will be raised if \NULL{} is returned.
787+
788+ \cfunction{Py_BuildValue()} does not always build a tuple. It
789+ builds a tuple only if its format string contains two or more format
790+ units. If the format string is empty, it returns \code{None}; if it
791+ contains exactly one format unit, it returns whatever object is
792+ described by that format unit. To force it to return a tuple of
793+ size 0 or one, parenthesize the format string.
794+
795+ When memory buffers are passed as parameters to supply data to build
796+ objects, as for the \samp{s} and \samp{s\#} formats, the required
797+ data is copied. Buffers provided by the caller are never referenced
798+ by the objects created by \cfunction{Py_BuildValue()}. In other
799+ words, if your code invokes \cfunction{malloc()} and passes the
800+ allocated memory to \cfunction{Py_BuildValue()}, your code is
801+ responsible for calling \cfunction{free()} for that memory once
802+ \cfunction{Py_BuildValue()} returns.
803+
804+ In the following description, the quoted form is the format unit;
805+ the entry in (round) parentheses is the Python object type that the
806+ format unit will return; and the entry in [square] brackets is the
807+ type of the C value(s) to be passed.
808+
809+ The characters space, tab, colon and comma are ignored in format
810+ strings (but not within format units such as \samp{s\#}). This can
811+ be used to make long format strings a tad more readable.
812+
813+ \begin{description}
814+ \item[\samp{s} (string) {[char *]}]
815+ Convert a null-terminated C string to a Python object. If the C
816+ string pointer is \NULL, \code{None} is used.
817+
818+ \item[\samp{s\#} (string) {[char *, int]}]
819+ Convert a C string and its length to a Python object. If the C
820+ string pointer is \NULL, the length is ignored and \code{None} is
821+ returned.
822+
823+ \item[\samp{z} (string or \code{None}) {[char *]}]
824+ Same as \samp{s}.
825+
826+ \item[\samp{z\#} (string or \code{None}) {[char *, int]}]
827+ Same as \samp{s\#}.
828+
829+ \item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
830+ Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4)
831+ data to a Python Unicode object. If the Unicode buffer pointer
832+ is \NULL, \code{None} is returned.
833+
834+ \item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
835+ Convert a Unicode (UCS-2 or UCS-4) data buffer and its length
836+ to a Python Unicode object. If the Unicode buffer pointer
837+ is \NULL, the length is ignored and \code{None} is returned.
838+
839+ \item[\samp{i} (integer) {[int]}]
840+ Convert a plain C \ctype{int} to a Python integer object.
841+
842+ \item[\samp{b} (integer) {[char]}]
843+ Convert a plain C \ctype{char} to a Python integer object.
844+
845+ \item[\samp{h} (integer) {[short int]}]
846+ Convert a plain C \ctype{short int} to a Python integer object.
847+
848+ \item[\samp{l} (integer) {[long int]}]
849+ Convert a C \ctype{long int} to a Python integer object.
850+
851+ \item[\samp{B} (integer) {[unsigned char]}]
852+ Convert a C \ctype{unsigned char} to a Python integer object.
853+
854+ \item[\samp{H} (integer) {[unsigned short int]}]
855+ Convert a C \ctype{unsigned short int} to a Python integer object.
856+
857+ \item[\samp{I} (integer/long) {[unsigned int]}]
858+ Convert a C \ctype{unsigned int} to a Python integer object
859+ or a Python long integer object, if it is larger than \code{sys.maxint}.
860+
861+ \item[\samp{k} (integer/long) {[unsigned long]}]
862+ Convert a C \ctype{unsigned long} to a Python integer object
863+ or a Python long integer object, if it is larger than \code{sys.maxint}.
864+
865+ \item[\samp{L} (long) {[PY_LONG_LONG]}]
866+ Convert a C \ctype{long long} to a Python long integer object. Only
867+ available on platforms that support \ctype{long long}.
868+
869+ \item[\samp{K} (long) {[unsigned PY_LONG_LONG]}]
870+ Convert a C \ctype{unsigned long long} to a Python long integer object.
871+ Only available on platforms that support \ctype{unsigned long long}.
872+
873+ \item[\samp{n} (int) {[Py_ssize_t]}]
874+ Convert a C \ctype{Py_ssize_t} to a Python integer or long integer.
875+ \versionadded{2.5}
876+
877+ \item[\samp{c} (string of length 1) {[char]}]
878+ Convert a C \ctype{int} representing a character to a Python
879+ string of length 1.
880+
881+ \item[\samp{d} (float) {[double]}]
882+ Convert a C \ctype{double} to a Python floating point number.
883+
884+ \item[\samp{f} (float) {[float]}]
885+ Same as \samp{d}.
886+
887+ \item[\samp{D} (complex) {[Py_complex *]}]
888+ Convert a C \ctype{Py_complex} structure to a Python complex
889+ number.
890+
891+ \item[\samp{O} (object) {[PyObject *]}]
892+ Pass a Python object untouched (except for its reference count,
893+ which is incremented by one). If the object passed in is a
894+ \NULL{} pointer, it is assumed that this was caused because the
895+ call producing the argument found an error and set an exception.
896+ Therefore, \cfunction{Py_BuildValue()} will return \NULL{} but
897+ won't raise an exception. If no exception has been raised yet,
898+ \exception{SystemError} is set.
899+
900+ \item[\samp{S} (object) {[PyObject *]}]
901+ Same as \samp{O}.
902+
903+ \item[\samp{N} (object) {[PyObject *]}]
904+ Same as \samp{O}, except it doesn't increment the reference count
905+ on the object. Useful when the object is created by a call to an
906+ object constructor in the argument list.
907+
908+ \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
909+ Convert \var{anything} to a Python object through a
910+ \var{converter} function. The function is called with
911+ \var{anything} (which should be compatible with \ctype{void *}) as
912+ its argument and should return a ``new'' Python object, or \NULL{}
913+ if an error occurred.
914+
915+ \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
916+ Convert a sequence of C values to a Python tuple with the same
917+ number of items.
918+
919+ \item[\samp{[\var{items}]} (list) {[\var{matching-items}]}]
920+ Convert a sequence of C values to a Python list with the same
921+ number of items.
922+
923+ \item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}]
924+ Convert a sequence of C values to a Python dictionary. Each pair
925+ of consecutive C values adds one item to the dictionary, serving
926+ as key and value, respectively.
927+
928+ \end{description}
929+
930+ If there is an error in the format string, the
931+ \exception{SystemError} exception is set and \NULL{} returned.
932+\end{cfuncdesc}
933+
934+\section{String conversion and formatting \label{string-formatting}}
935+
936+Functions for number conversion and formatted string output.
937+
938+\begin{cfuncdesc}{int}{PyOS_snprintf}{char *str, size_t size,
939+ const char *format, \moreargs}
940+Output not more than \var{size} bytes to \var{str} according to the format
941+string \var{format} and the extra arguments. See the \UNIX{} man
942+page \manpage{snprintf}{2}.
943+\end{cfuncdesc}
944+
945+\begin{cfuncdesc}{int}{PyOS_vsnprintf}{char *str, size_t size,
946+ const char *format, va_list va}
947+Output not more than \var{size} bytes to \var{str} according to the format
948+string \var{format} and the variable argument list \var{va}. \UNIX{}
949+man page \manpage{vsnprintf}{2}.
950+\end{cfuncdesc}
951+
952+\cfunction{PyOS_snprintf} and \cfunction{PyOS_vsnprintf} wrap the
953+Standard C library functions \cfunction{snprintf()} and
954+\cfunction{vsnprintf()}. Their purpose is to guarantee consistent
955+behavior in corner cases, which the Standard C functions do not.
956+
957+The wrappers ensure that \var{str}[\var{size}-1] is always
958+\character{\textbackslash0} upon return. They never write more than
959+\var{size} bytes (including the trailing \character{\textbackslash0}
960+into str. Both functions require that \code{\var{str} != NULL},
961+\code{\var{size} > 0} and \code{\var{format} != NULL}.
962+
963+If the platform doesn't have \cfunction{vsnprintf()} and the buffer
964+size needed to avoid truncation exceeds \var{size} by more than 512
965+bytes, Python aborts with a \var{Py_FatalError}.
966+
967+The return value (\var{rv}) for these functions should be interpreted
968+as follows:
969+
970+\begin{itemize}
971+
972+\item When \code{0 <= \var{rv} < \var{size}}, the output conversion
973+ was successful and \var{rv} characters were written to \var{str}
974+ (excluding the trailing \character{\textbackslash0} byte at
975+ \var{str}[\var{rv}]).
976+
977+\item When \code{\var{rv} >= \var{size}}, the output conversion was
978+ truncated and a buffer with \code{\var{rv} + 1} bytes would have
979+ been needed to succeed. \var{str}[\var{size}-1] is
980+ \character{\textbackslash0} in this case.
981+
982+\item When \code{\var{rv} < 0}, ``something bad happened.''
983+ \var{str}[\var{size}-1] is \character{\textbackslash0} in this case
984+ too, but the rest of \var{str} is undefined. The exact cause of the
985+ error depends on the underlying platform.
986+
987+\end{itemize}
988+
989+The following functions provide locale-independent string to number
990+conversions.
991+
992+\begin{cfuncdesc}{double}{PyOS_ascii_strtod}{const char *nptr, char **endptr}
993+Convert a string to a \ctype{double}. This function behaves like the
994+Standard C function \cfunction{strtod()} does in the C locale. It does
995+this without changing the current locale, since that would not be
996+thread-safe.
997+
998+\cfunction{PyOS_ascii_strtod} should typically be used for reading
999+configuration files or other non-user input that should be locale
1000+independent. \versionadded{2.4}
1001+
1002+See the \UNIX{} man page \manpage{strtod}{2} for details.
1003+
1004+\end{cfuncdesc}
1005+
1006+\begin{cfuncdesc}{char *}{PyOS_ascii_formatd}{char *buffer, size_t buf_len,
1007+ const char *format, double d}
1008+Convert a \ctype{double} to a string using the \character{.} as the
1009+decimal separator. \var{format} is a \cfunction{printf()}-style format
1010+string specifying the number format. Allowed conversion characters are
1011+\character{e}, \character{E}, \character{f}, \character{F},
1012+\character{g} and \character{G}.
1013+
1014+The return value is a pointer to \var{buffer} with the converted
1015+string or NULL if the conversion failed. \versionadded{2.4}
1016+\end{cfuncdesc}
1017+
1018+\begin{cfuncdesc}{double}{PyOS_ascii_atof}{const char *nptr}
1019+Convert a string to a \ctype{double} in a locale-independent
1020+way. \versionadded{2.4}
1021+
1022+See the \UNIX{} man page \manpage{atof}{2} for details.
1023+\end{cfuncdesc}
sys/src/cmd/python/Doc/api/veryhigh.tex+287−0
@@ -0,0 +1,287 @@
1+\chapter{The Very High Level Layer \label{veryhigh}}
2+
3+
4+The functions in this chapter will let you execute Python source code
5+given in a file or a buffer, but they will not let you interact in a
6+more detailed way with the interpreter.
7+
8+Several of these functions accept a start symbol from the grammar as a
9+parameter. The available start symbols are \constant{Py_eval_input},
10+\constant{Py_file_input}, and \constant{Py_single_input}. These are
11+described following the functions which accept them as parameters.
12+
13+Note also that several of these functions take \ctype{FILE*}
14+parameters. On particular issue which needs to be handled carefully
15+is that the \ctype{FILE} structure for different C libraries can be
16+different and incompatible. Under Windows (at least), it is possible
17+for dynamically linked extensions to actually use different libraries,
18+so care should be taken that \ctype{FILE*} parameters are only passed
19+to these functions if it is certain that they were created by the same
20+library that the Python runtime is using.
21+
22+
23+\begin{cfuncdesc}{int}{Py_Main}{int argc, char **argv}
24+ The main program for the standard interpreter. This is made
25+ available for programs which embed Python. The \var{argc} and
26+ \var{argv} parameters should be prepared exactly as those which are
27+ passed to a C program's \cfunction{main()} function. It is
28+ important to note that the argument list may be modified (but the
29+ contents of the strings pointed to by the argument list are not).
30+ The return value will be the integer passed to the
31+ \function{sys.exit()} function, \code{1} if the interpreter exits
32+ due to an exception, or \code{2} if the parameter list does not
33+ represent a valid Python command line.
34+\end{cfuncdesc}
35+
36+\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, const char *filename}
37+ This is a simplified interface to \cfunction{PyRun_AnyFileExFlags()}
38+ below, leaving \var{closeit} set to \code{0} and \var{flags} set to \NULL.
39+\end{cfuncdesc}
40+
41+\begin{cfuncdesc}{int}{PyRun_AnyFileFlags}{FILE *fp, const char *filename,
42+ PyCompilerFlags *flags}
43+ This is a simplified interface to \cfunction{PyRun_AnyFileExFlags()}
44+ below, leaving the \var{closeit} argument set to \code{0}.
45+\end{cfuncdesc}
46+
47+\begin{cfuncdesc}{int}{PyRun_AnyFileEx}{FILE *fp, const char *filename,
48+ int closeit}
49+ This is a simplified interface to \cfunction{PyRun_AnyFileExFlags()}
50+ below, leaving the \var{flags} argument set to \NULL.
51+\end{cfuncdesc}
52+
53+\begin{cfuncdesc}{int}{PyRun_AnyFileExFlags}{FILE *fp, const char *filename,
54+ int closeit,
55+ PyCompilerFlags *flags}
56+ If \var{fp} refers to a file associated with an interactive device
57+ (console or terminal input or \UNIX{} pseudo-terminal), return the
58+ value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
59+ result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
60+ \NULL, this function uses \code{"???"} as the filename.
61+\end{cfuncdesc}
62+
63+\begin{cfuncdesc}{int}{PyRun_SimpleString}{const char *command}
64+ This is a simplified interface to \cfunction{PyRun_SimpleStringFlags()}
65+ below, leaving the \var{PyCompilerFlags*} argument set to NULL.
66+\end{cfuncdesc}
67+
68+\begin{cfuncdesc}{int}{PyRun_SimpleStringFlags}{const char *command,
69+ PyCompilerFlags *flags}
70+ Executes the Python source code from \var{command} in the
71+ \module{__main__} module according to the \var{flags} argument.
72+ If \module{__main__} does not already exist, it is created. Returns
73+ \code{0} on success or \code{-1} if an exception was raised. If there
74+ was an error, there is no way to get the exception information.
75+ For the meaning of \var{flags}, see below.
76+\end{cfuncdesc}
77+
78+\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, const char *filename}
79+ This is a simplified interface to \cfunction{PyRun_SimpleFileExFlags()}
80+ below, leaving \var{closeit} set to \code{0} and \var{flags} set to
81+ \NULL.
82+\end{cfuncdesc}
83+
84+\begin{cfuncdesc}{int}{PyRun_SimpleFileFlags}{FILE *fp, const char *filename,
85+ PyCompilerFlags *flags}
86+ This is a simplified interface to \cfunction{PyRun_SimpleFileExFlags()}
87+ below, leaving \var{closeit} set to \code{0}.
88+\end{cfuncdesc}
89+
90+\begin{cfuncdesc}{int}{PyRun_SimpleFileEx}{FILE *fp, const char *filename,
91+ int closeit}
92+ This is a simplified interface to \cfunction{PyRun_SimpleFileExFlags()}
93+ below, leaving \var{flags} set to \NULL.
94+\end{cfuncdesc}
95+
96+\begin{cfuncdesc}{int}{PyRun_SimpleFileExFlags}{FILE *fp, const char *filename,
97+ int closeit,
98+ PyCompilerFlags *flags}
99+ Similar to \cfunction{PyRun_SimpleStringFlags()}, but the Python source
100+ code is read from \var{fp} instead of an in-memory string.
101+ \var{filename} should be the name of the file. If \var{closeit} is
102+ true, the file is closed before PyRun_SimpleFileExFlags returns.
103+\end{cfuncdesc}
104+
105+\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, const char *filename}
106+ This is a simplified interface to \cfunction{PyRun_InteractiveOneFlags()}
107+ below, leaving \var{flags} set to \NULL.
108+\end{cfuncdesc}
109+
110+\begin{cfuncdesc}{int}{PyRun_InteractiveOneFlags}{FILE *fp,
111+ const char *filename,
112+ PyCompilerFlags *flags}
113+ Read and execute a single statement from a file associated with an
114+ interactive device according to the \var{flags} argument. If
115+ \var{filename} is \NULL, \code{"???"} is used instead. The user will
116+ be prompted using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0}
117+ when the input was executed successfully, \code{-1} if there was an
118+ exception, or an error code from the \file{errcode.h} include file
119+ distributed as part of Python if there was a parse error. (Note that
120+ \file{errcode.h} is not included by \file{Python.h}, so must be included
121+ specifically if needed.)
122+\end{cfuncdesc}
123+
124+\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, const char *filename}
125+ This is a simplified interface to \cfunction{PyRun_InteractiveLoopFlags()}
126+ below, leaving \var{flags} set to \NULL.
127+\end{cfuncdesc}
128+
129+\begin{cfuncdesc}{int}{PyRun_InteractiveLoopFlags}{FILE *fp,
130+ const char *filename,
131+ PyCompilerFlags *flags}
132+ Read and execute statements from a file associated with an
133+ interactive device until \EOF{} is reached. If \var{filename} is
134+ \NULL, \code{"???"} is used instead. The user will be prompted
135+ using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
136+\end{cfuncdesc}
137+
138+\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{const char *str,
139+ int start}
140+ This is a simplified interface to
141+ \cfunction{PyParser_SimpleParseStringFlagsFilename()} below, leaving
142+ \var{filename} set to \NULL{} and \var{flags} set to \code{0}.
143+\end{cfuncdesc}
144+
145+\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseStringFlags}{
146+ const char *str, int start, int flags}
147+ This is a simplified interface to
148+ \cfunction{PyParser_SimpleParseStringFlagsFilename()} below, leaving
149+ \var{filename} set to \NULL.
150+\end{cfuncdesc}
151+
152+\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseStringFlagsFilename}{
153+ const char *str, const char *filename,
154+ int start, int flags}
155+ Parse Python source code from \var{str} using the start token
156+ \var{start} according to the \var{flags} argument. The result can
157+ be used to create a code object which can be evaluated efficiently.
158+ This is useful if a code fragment must be evaluated many times.
159+\end{cfuncdesc}
160+
161+\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
162+ const char *filename, int start}
163+ This is a simplified interface to \cfunction{PyParser_SimpleParseFileFlags()}
164+ below, leaving \var{flags} set to \code{0}
165+\end{cfuncdesc}
166+
167+\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFileFlags}{FILE *fp,
168+ const char *filename, int start, int flags}
169+ Similar to \cfunction{PyParser_SimpleParseStringFlagsFilename()}, but
170+ the Python source code is read from \var{fp} instead of an in-memory
171+ string.
172+\end{cfuncdesc}
173+
174+\begin{cfuncdesc}{PyObject*}{PyRun_String}{const char *str, int start,
175+ PyObject *globals,
176+ PyObject *locals}
177+ This is a simplified interface to \cfunction{PyRun_StringFlags()} below,
178+ leaving \var{flags} set to \NULL.
179+\end{cfuncdesc}
180+
181+\begin{cfuncdesc}{PyObject*}{PyRun_StringFlags}{const char *str, int start,
182+ PyObject *globals,
183+ PyObject *locals,
184+ PyCompilerFlags *flags}
185+ Execute Python source code from \var{str} in the context specified
186+ by the dictionaries \var{globals} and \var{locals} with the compiler
187+ flags specified by \var{flags}. The parameter \var{start} specifies
188+ the start token that should be used to parse the source code.
189+
190+ Returns the result of executing the code as a Python object, or
191+ \NULL{} if an exception was raised.
192+\end{cfuncdesc}
193+
194+\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, const char *filename,
195+ int start, PyObject *globals,
196+ PyObject *locals}
197+ This is a simplified interface to \cfunction{PyRun_FileExFlags()} below,
198+ leaving \var{closeit} set to \code{0} and \var{flags} set to \NULL.
199+\end{cfuncdesc}
200+
201+\begin{cfuncdesc}{PyObject*}{PyRun_FileEx}{FILE *fp, const char *filename,
202+ int start, PyObject *globals,
203+ PyObject *locals, int closeit}
204+ This is a simplified interface to \cfunction{PyRun_FileExFlags()} below,
205+ leaving \var{flags} set to \NULL.
206+\end{cfuncdesc}
207+
208+\begin{cfuncdesc}{PyObject*}{PyRun_FileFlags}{FILE *fp, const char *filename,
209+ int start, PyObject *globals,
210+ PyObject *locals,
211+ PyCompilerFlags *flags}
212+ This is a simplified interface to \cfunction{PyRun_FileExFlags()} below,
213+ leaving \var{closeit} set to \code{0}.
214+\end{cfuncdesc}
215+
216+\begin{cfuncdesc}{PyObject*}{PyRun_FileExFlags}{FILE *fp, const char *filename,
217+ int start, PyObject *globals,
218+ PyObject *locals, int closeit,
219+ PyCompilerFlags *flags}
220+ Similar to \cfunction{PyRun_StringFlags()}, but the Python source code is
221+ read from \var{fp} instead of an in-memory string.
222+ \var{filename} should be the name of the file.
223+ If \var{closeit} is true, the file is closed before
224+ \cfunction{PyRun_FileExFlags()} returns.
225+\end{cfuncdesc}
226+
227+\begin{cfuncdesc}{PyObject*}{Py_CompileString}{const char *str,
228+ const char *filename,
229+ int start}
230+ This is a simplified interface to \cfunction{Py_CompileStringFlags()} below,
231+ leaving \var{flags} set to \NULL.
232+\end{cfuncdesc}
233+
234+\begin{cfuncdesc}{PyObject*}{Py_CompileStringFlags}{const char *str,
235+ const char *filename,
236+ int start,
237+ PyCompilerFlags *flags}
238+ Parse and compile the Python source code in \var{str}, returning the
239+ resulting code object. The start token is given by \var{start};
240+ this can be used to constrain the code which can be compiled and should
241+ be \constant{Py_eval_input}, \constant{Py_file_input}, or
242+ \constant{Py_single_input}. The filename specified by
243+ \var{filename} is used to construct the code object and may appear
244+ in tracebacks or \exception{SyntaxError} exception messages. This
245+ returns \NULL{} if the code cannot be parsed or compiled.
246+\end{cfuncdesc}
247+
248+\begin{cvardesc}{int}{Py_eval_input}
249+ The start symbol from the Python grammar for isolated expressions;
250+ for use with
251+ \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
252+\end{cvardesc}
253+
254+\begin{cvardesc}{int}{Py_file_input}
255+ The start symbol from the Python grammar for sequences of statements
256+ as read from a file or other source; for use with
257+ \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
258+ the symbol to use when compiling arbitrarily long Python source code.
259+\end{cvardesc}
260+
261+\begin{cvardesc}{int}{Py_single_input}
262+ The start symbol from the Python grammar for a single statement; for
263+ use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
264+ This is the symbol used for the interactive interpreter loop.
265+\end{cvardesc}
266+
267+\begin{ctypedesc}[PyCompilerFlags]{struct PyCompilerFlags}
268+ This is the structure used to hold compiler flags. In cases where
269+ code is only being compiled, it is passed as \code{int flags}, and in
270+ cases where code is being executed, it is passed as
271+ \code{PyCompilerFlags *flags}. In this case, \code{from __future__
272+ import} can modify \var{flags}.
273+
274+ Whenever \code{PyCompilerFlags *flags} is \NULL, \member{cf_flags}
275+ is treated as equal to \code{0}, and any modification due to
276+ \code{from __future__ import} is discarded.
277+\begin{verbatim}
278+struct PyCompilerFlags {
279+ int cf_flags;
280+}
281+\end{verbatim}
282+\end{ctypedesc}
283+
284+\begin{cvardesc}{int}{CO_FUTURE_DIVISION}
285+ This bit can be set in \var{flags} to cause division operator \code{/}
286+ to be interpreted as ``true division'' according to \pep{238}.
287+\end{cvardesc}