blob: 50405ffd2701d1f33a52f61267fafbaf0c2b92e3 [file] [log] [blame]
Fred Drake3adf79e2001-10-12 19:01:43 +00001\chapter{Concrete Objects Layer \label{concrete}}
2
3
4The functions in this chapter are specific to certain Python object
5types. Passing them an object of the wrong type is not a good idea;
6if you receive an object from a Python program and you are not sure
7that it has the right type, you must perform a type check first;
8for 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
13the type of the objects which are passed in, many of them do not check
14for \NULL{} being passed instead of a valid object. Allowing \NULL{}
15to be passed in can cause memory access violations and immediate
16termination of the interpreter.}
17
18
19\section{Fundamental Objects \label{fundamental}}
20
Tim Petersf582b822001-12-11 18:51:08 +000021This section describes Python type objects and the singleton object
Fred Drake3adf79e2001-10-12 19:01:43 +000022\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{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 Returns true is the object \var{o} is a type object.
40\end{cfuncdesc}
41
42\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
43 Returns true if the type object \var{o} sets the feature
44 \var{feature}. Type features are denoted by single bit flags.
45\end{cfuncdesc}
46
47\begin{cfuncdesc}{int}{PyType_IsSubtype}{PyTypeObject *a, PyTypeObject *b}
48 Returns true if \var{a} is a subtype of \var{b}.
49 \versionadded{2.2}
50\end{cfuncdesc}
51
52\begin{cfuncdesc}{PyObject*}{PyType_GenericAlloc}{PyTypeObject *type,
53 int nitems}
54 \versionadded{2.2}
55\end{cfuncdesc}
56
57\begin{cfuncdesc}{PyObject*}{PyType_GenericNew}{PyTypeObject *type,
58 PyObject *args, PyObject *kwds}
59 \versionadded{2.2}
60\end{cfuncdesc}
61
62\begin{cfuncdesc}{int}{PyType_Ready}{PyTypeObject *type}
63 \versionadded{2.2}
64\end{cfuncdesc}
65
66
67\subsection{The None Object \label{noneObject}}
68
69\obindex{None@\texttt{None}}
70Note that the \ctype{PyTypeObject} for \code{None} is not directly
71exposed in the Python/C API. Since \code{None} is a singleton,
72testing for object identity (using \samp{==} in C) is sufficient.
73There is no \cfunction{PyNone_Check()} function for the same reason.
74
75\begin{cvardesc}{PyObject*}{Py_None}
76 The Python \code{None} object, denoting lack of value. This object
Fred Drake6ccdccd2002-03-12 20:12:54 +000077 has no methods. It needs to be treated just like any other object
78 with respect to reference counts.
Fred Drake3adf79e2001-10-12 19:01:43 +000079\end{cvardesc}
80
81
82\section{Numeric Objects \label{numericObjects}}
83
84\obindex{numeric}
85
86
87\subsection{Plain Integer Objects \label{intObjects}}
88
89\obindex{integer}
90\begin{ctypedesc}{PyIntObject}
91 This subtype of \ctype{PyObject} represents a Python integer
92 object.
93\end{ctypedesc}
94
95\begin{cvardesc}{PyTypeObject}{PyInt_Type}
Tim Petersf582b822001-12-11 18:51:08 +000096 This instance of \ctype{PyTypeObject} represents the Python plain
Fred Drake3adf79e2001-10-12 19:01:43 +000097 integer type. This is the same object as \code{types.IntType}.
98 \withsubitem{(in modules types)}{\ttindex{IntType}}
99\end{cvardesc}
100
101\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
102 Returns true if \var{o} is of type \cdata{PyInt_Type} or a subtype
103 of \cdata{PyInt_Type}.
104 \versionchanged[Allowed subtypes to be accepted]{2.2}
105\end{cfuncdesc}
106
107\begin{cfuncdesc}{int}{PyInt_CheckExact}{PyObject* o}
108 Returns true if \var{o} is of type \cdata{PyInt_Type}, but not a
109 subtype of \cdata{PyInt_Type}.
110 \versionadded{2.2}
111\end{cfuncdesc}
112
113\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
114 Creates a new integer object with a value of \var{ival}.
115
116 The current implementation keeps an array of integer objects for all
117 integers between \code{-1} and \code{100}, when you create an int in
118 that range you actually just get back a reference to the existing
119 object. So it should be possible to change the value of \code{1}. I
120 suspect the behaviour of Python in this case is undefined. :-)
121\end{cfuncdesc}
122
123\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
124 Will first attempt to cast the object to a \ctype{PyIntObject}, if
125 it is not already one, and then return its value.
126\end{cfuncdesc}
127
128\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
129 Returns the value of the object \var{io}. No error checking is
130 performed.
131\end{cfuncdesc}
132
133\begin{cfuncdesc}{long}{PyInt_GetMax}{}
134 Returns the system's idea of the largest integer it can handle
135 (\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
136 header files).
137\end{cfuncdesc}
138
139
140\subsection{Long Integer Objects \label{longObjects}}
141
142\obindex{long integer}
143\begin{ctypedesc}{PyLongObject}
144 This subtype of \ctype{PyObject} represents a Python long integer
145 object.
146\end{ctypedesc}
147
148\begin{cvardesc}{PyTypeObject}{PyLong_Type}
149 This instance of \ctype{PyTypeObject} represents the Python long
150 integer type. This is the same object as \code{types.LongType}.
151 \withsubitem{(in modules types)}{\ttindex{LongType}}
152\end{cvardesc}
153
154\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
155 Returns true if its argument is a \ctype{PyLongObject} or a subtype
156 of \ctype{PyLongObject}.
157 \versionchanged[Allowed subtypes to be accepted]{2.2}
158\end{cfuncdesc}
159
160\begin{cfuncdesc}{int}{PyLong_CheckExact}{PyObject *p}
161 Returns true if its argument is a \ctype{PyLongObject}, but not a
162 subtype of \ctype{PyLongObject}.
163 \versionadded{2.2}
164\end{cfuncdesc}
165
166\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
167 Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{}
168 on failure.
169\end{cfuncdesc}
170
171\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
172 Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
173 long}, or \NULL{} on failure.
174\end{cfuncdesc}
175
176\begin{cfuncdesc}{PyObject*}{PyLong_FromLongLong}{long long v}
177 Returns a new \ctype{PyLongObject} object from a C \ctype{long long},
178 or \NULL{} on failure.
179\end{cfuncdesc}
180
181\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLongLong}{unsigned long long v}
182 Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
183 long long}, or \NULL{} on failure.
184\end{cfuncdesc}
185
186\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
187 Returns a new \ctype{PyLongObject} object from the integer part of
188 \var{v}, or \NULL{} on failure.
189\end{cfuncdesc}
190
191\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
192 int base}
193 Return a new \ctype{PyLongObject} based on the string value in
194 \var{str}, which is interpreted according to the radix in
195 \var{base}. If \var{pend} is non-\NULL, \code{*\var{pend}} will
196 point to the first character in \var{str} which follows the
197 representation of the number. If \var{base} is \code{0}, the radix
198 will be determined base on the leading characters of \var{str}: if
199 \var{str} starts with \code{'0x'} or \code{'0X'}, radix 16 will be
200 used; if \var{str} starts with \code{'0'}, radix 8 will be used;
201 otherwise radix 10 will be used. If \var{base} is not \code{0}, it
202 must be between \code{2} and \code{36}, inclusive. Leading spaces
203 are ignored. If there are no digits, \exception{ValueError} will be
204 raised.
205\end{cfuncdesc}
206
207\begin{cfuncdesc}{PyObject*}{PyLong_FromUnicode}{Py_UNICODE *u,
208 int length, int base}
209 Convert a sequence of Unicode digits to a Python long integer
210 value. The first parameter, \var{u}, points to the first character
211 of the Unicode string, \var{length} gives the number of characters,
212 and \var{base} is the radix for the conversion. The radix must be
213 in the range [2, 36]; if it is out of range, \exception{ValueError}
214 will be raised.
215 \versionadded{1.6}
216\end{cfuncdesc}
217
218\begin{cfuncdesc}{PyObject*}{PyLong_FromVoidPtr}{void *p}
219 Create a Python integer or long integer from the pointer \var{p}.
220 The pointer value can be retrieved from the resulting value using
221 \cfunction{PyLong_AsVoidPtr()}.
222 \versionadded{1.5.2}
223\end{cfuncdesc}
224
225\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
226 Returns a C \ctype{long} representation of the contents of
227 \var{pylong}. If \var{pylong} is greater than
228 \constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError}
229 is raised.
230 \withsubitem{(built-in exception)}{\ttindex{OverflowError}}
231\end{cfuncdesc}
232
233\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
234 Returns a C \ctype{unsigned long} representation of the contents of
235 \var{pylong}. If \var{pylong} is greater than
236 \constant{ULONG_MAX}\ttindex{ULONG_MAX}, an
237 \exception{OverflowError} is raised.
Tim Petersf582b822001-12-11 18:51:08 +0000238 \withsubitem{(built-in exception)}{\ttindex{OverflowError}}
Fred Drake3adf79e2001-10-12 19:01:43 +0000239\end{cfuncdesc}
240
241\begin{cfuncdesc}{long long}{PyLong_AsLongLong}{PyObject *pylong}
242 Return a C \ctype{long long} from a Python long integer. If
243 \var{pylong} cannot be represented as a \ctype{long long}, an
244 \exception{OverflowError} will be raised.
245 \versionadded{2.2}
246\end{cfuncdesc}
247
248\begin{cfuncdesc}{unsigned long long}{PyLong_AsUnsignedLongLong}{PyObject
249 *pylong}
250 Return a C \ctype{unsigned long long} from a Python long integer.
251 If \var{pylong} cannot be represented as an \ctype{unsigned long
252 long}, an \exception{OverflowError} will be raised if the value is
253 positive, or a \exception{TypeError} will be raised if the value is
254 negative.
255 \versionadded{2.2}
256\end{cfuncdesc}
257
258\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
259 Returns a C \ctype{double} representation of the contents of
260 \var{pylong}. If \var{pylong} cannot be approximately represented
261 as a \ctype{double}, an \exception{OverflowError} exception is
262 raised and \code{-1.0} will be returned.
263\end{cfuncdesc}
264
265\begin{cfuncdesc}{void*}{PyLong_AsVoidPtr}{PyObject *pylong}
266 Convert a Python integer or long integer \var{pylong} to a C
267 \ctype{void} pointer. If \var{pylong} cannot be converted, an
268 \exception{OverflowError} will be raised. This is only assured to
269 produce a usable \ctype{void} pointer for values created with
270 \cfunction{PyLong_FromVoidPtr()}.
271 \versionadded{1.5.2}
272\end{cfuncdesc}
273
274
275\subsection{Floating Point Objects \label{floatObjects}}
276
277\obindex{floating point}
278\begin{ctypedesc}{PyFloatObject}
279 This subtype of \ctype{PyObject} represents a Python floating point
280 object.
281\end{ctypedesc}
282
283\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
284 This instance of \ctype{PyTypeObject} represents the Python floating
285 point type. This is the same object as \code{types.FloatType}.
286 \withsubitem{(in modules types)}{\ttindex{FloatType}}
287\end{cvardesc}
288
289\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
290 Returns true if its argument is a \ctype{PyFloatObject} or a subtype
291 of \ctype{PyFloatObject}.
292 \versionchanged[Allowed subtypes to be accepted]{2.2}
293\end{cfuncdesc}
294
295\begin{cfuncdesc}{int}{PyFloat_CheckExact}{PyObject *p}
296 Returns true if its argument is a \ctype{PyFloatObject}, but not a
297 subtype of \ctype{PyFloatObject}.
298 \versionadded{2.2}
299\end{cfuncdesc}
300
301\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
302 Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
303 failure.
304\end{cfuncdesc}
305
306\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
307 Returns a C \ctype{double} representation of the contents of
308 \var{pyfloat}.
309\end{cfuncdesc}
310
311\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
312 Returns a C \ctype{double} representation of the contents of
313 \var{pyfloat}, but without error checking.
314\end{cfuncdesc}
315
316
317\subsection{Complex Number Objects \label{complexObjects}}
318
319\obindex{complex number}
320Python's complex number objects are implemented as two distinct types
321when viewed from the C API: one is the Python object exposed to
322Python programs, and the other is a C structure which represents the
323actual complex number value. The API provides functions for working
324with both.
325
326\subsubsection{Complex Numbers as C Structures}
327
328Note that the functions which accept these structures as parameters
329and return them as results do so \emph{by value} rather than
330dereferencing them through pointers. This is consistent throughout
331the API.
332
333\begin{ctypedesc}{Py_complex}
334 The C structure which corresponds to the value portion of a Python
335 complex number object. Most of the functions for dealing with
336 complex number objects use structures of this type as input or
337 output values, as appropriate. It is defined as:
338
339\begin{verbatim}
340typedef struct {
341 double real;
342 double imag;
343} Py_complex;
344\end{verbatim}
345\end{ctypedesc}
346
347\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
348 Return the sum of two complex numbers, using the C
349 \ctype{Py_complex} representation.
350\end{cfuncdesc}
351
352\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
353 Return the difference between two complex numbers, using the C
354 \ctype{Py_complex} representation.
355\end{cfuncdesc}
356
357\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
358 Return the negation of the complex number \var{complex}, using the C
359 \ctype{Py_complex} representation.
360\end{cfuncdesc}
361
362\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
363 Return the product of two complex numbers, using the C
364 \ctype{Py_complex} representation.
365\end{cfuncdesc}
366
367\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
368 Py_complex divisor}
369 Return the quotient of two complex numbers, using the C
370 \ctype{Py_complex} representation.
371\end{cfuncdesc}
372
373\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
374 Return the exponentiation of \var{num} by \var{exp}, using the C
375 \ctype{Py_complex} representation.
376\end{cfuncdesc}
377
378
379\subsubsection{Complex Numbers as Python Objects}
380
381\begin{ctypedesc}{PyComplexObject}
382 This subtype of \ctype{PyObject} represents a Python complex number
383 object.
384\end{ctypedesc}
385
386\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
387 This instance of \ctype{PyTypeObject} represents the Python complex
388 number type.
389\end{cvardesc}
390
391\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
392 Returns true if its argument is a \ctype{PyComplexObject} or a
393 subtype of \ctype{PyComplexObject}.
394 \versionchanged[Allowed subtypes to be accepted]{2.2}
395\end{cfuncdesc}
396
397\begin{cfuncdesc}{int}{PyComplex_CheckExact}{PyObject *p}
398 Returns true if its argument is a \ctype{PyComplexObject}, but not a
399 subtype of \ctype{PyComplexObject}.
400 \versionadded{2.2}
401\end{cfuncdesc}
402
403\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
404 Create a new Python complex number object from a C
405 \ctype{Py_complex} value.
406\end{cfuncdesc}
407
408\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
409 Returns a new \ctype{PyComplexObject} object from \var{real} and
410 \var{imag}.
411\end{cfuncdesc}
412
413\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
414 Returns the real part of \var{op} as a C \ctype{double}.
415\end{cfuncdesc}
416
417\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
418 Returns the imaginary part of \var{op} as a C \ctype{double}.
419\end{cfuncdesc}
420
421\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
422 Returns the \ctype{Py_complex} value of the complex number
423 \var{op}.
424\end{cfuncdesc}
425
426
427
428\section{Sequence Objects \label{sequenceObjects}}
429
430\obindex{sequence}
Tim Petersf582b822001-12-11 18:51:08 +0000431Generic operations on sequence objects were discussed in the previous
432chapter; this section deals with the specific kinds of sequence
Fred Drake3adf79e2001-10-12 19:01:43 +0000433objects that are intrinsic to the Python language.
434
435
436\subsection{String Objects \label{stringObjects}}
437
438These functions raise \exception{TypeError} when expecting a string
439parameter and are called with a non-string parameter.
440
441\obindex{string}
442\begin{ctypedesc}{PyStringObject}
443 This subtype of \ctype{PyObject} represents a Python string object.
444\end{ctypedesc}
445
446\begin{cvardesc}{PyTypeObject}{PyString_Type}
447 This instance of \ctype{PyTypeObject} represents the Python string
448 type; it is the same object as \code{types.TypeType} in the Python
449 layer.
450 \withsubitem{(in module types)}{\ttindex{StringType}}.
451\end{cvardesc}
452
453\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
454 Returns true if the object \var{o} is a string object or an instance
455 of a subtype of the string type.
456 \versionchanged[Allowed subtypes to be accepted]{2.2}
457\end{cfuncdesc}
458
459\begin{cfuncdesc}{int}{PyString_CheckExact}{PyObject *o}
460 Returns true if the object \var{o} is a string object, but not an
461 instance of a subtype of the string type.
462 \versionadded{2.2}
463\end{cfuncdesc}
464
465\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
466 Returns a new string object with the value \var{v} on success, and
Fred Drake32a35872001-12-06 20:38:15 +0000467 \NULL{} on failure. The parameter \var{v} must not be \NULL; it
468 will not be checked.
Fred Drake3adf79e2001-10-12 19:01:43 +0000469\end{cfuncdesc}
470
471\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
472 int len}
473 Returns a new string object with the value \var{v} and length
474 \var{len} on success, and \NULL{} on failure. If \var{v} is
475 \NULL, the contents of the string are uninitialized.
476\end{cfuncdesc}
477
478\begin{cfuncdesc}{PyObject*}{PyString_FromFormat}{const char *format, ...}
479 Takes a C \cfunction{printf()}-style \var{format} string and a
480 variable number of arguments, calculates the size of the resulting
481 Python string and returns a string with the values formatted into
482 it. The variable arguments must be C types and must correspond
483 exactly to the format characters in the \var{format} string. The
484 following format characters are allowed:
485
486 \begin{tableiii}{l|l|l}{member}{Format Characters}{Type}{Comment}
487 \lineiii{\%\%}{\emph{n/a}}{The literal \% character.}
488 \lineiii{\%c}{int}{A single character, represented as an C int.}
489 \lineiii{\%d}{int}{Exactly equivalent to \code{printf("\%d")}.}
490 \lineiii{\%ld}{long}{Exactly equivalent to \code{printf("\%ld")}.}
491 \lineiii{\%i}{int}{Exactly equivalent to \code{printf("\%i")}.}
492 \lineiii{\%x}{int}{Exactly equivalent to \code{printf("\%x")}.}
493 \lineiii{\%s}{char*}{A null-terminated C character array.}
494 \lineiii{\%p}{void*}{The hex representation of a C pointer.
495 Mostly equivalent to \code{printf("\%p")} except that it is
496 guaranteed to start with the literal \code{0x} regardless of
497 what the platform's \code{printf} yields.}
498 \end{tableiii}
499\end{cfuncdesc}
500
501\begin{cfuncdesc}{PyObject*}{PyString_FromFormatV}{const char *format,
502 va_list vargs}
503 Identical to \function{PyString_FromFormat()} except that it takes
504 exactly two arguments.
505\end{cfuncdesc}
506
507\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
508 Returns the length of the string in string object \var{string}.
509\end{cfuncdesc}
510
511\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
512 Macro form of \cfunction{PyString_Size()} but without error
513 checking.
514\end{cfuncdesc}
515
516\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
517 Returns a null-terminated representation of the contents of
518 \var{string}. The pointer refers to the internal buffer of
519 \var{string}, not a copy. The data must not be modified in any way,
520 unless the string was just created using
521 \code{PyString_FromStringAndSize(NULL, \var{size})}.
522 It must not be deallocated.
523\end{cfuncdesc}
524
525\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
526 Macro form of \cfunction{PyString_AsString()} but without error
527 checking.
528\end{cfuncdesc}
529
530\begin{cfuncdesc}{int}{PyString_AsStringAndSize}{PyObject *obj,
531 char **buffer,
532 int *length}
533 Returns a null-terminated representation of the contents of the
534 object \var{obj} through the output variables \var{buffer} and
535 \var{length}.
536
537 The function accepts both string and Unicode objects as input. For
538 Unicode objects it returns the default encoded version of the
539 object. If \var{length} is set to \NULL, the resulting buffer may
540 not contain null characters; if it does, the function returns -1 and
541 a \exception{TypeError} is raised.
542
543 The buffer refers to an internal string buffer of \var{obj}, not a
544 copy. The data must not be modified in any way, unless the string
545 was just created using \code{PyString_FromStringAndSize(NULL,
546 \var{size})}. It must not be deallocated.
547\end{cfuncdesc}
548
549\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
550 PyObject *newpart}
551 Creates a new string object in \var{*string} containing the contents
552 of \var{newpart} appended to \var{string}; the caller will own the
553 new reference. The reference to the old value of \var{string} will
554 be stolen. If the new string cannot be created, the old reference
555 to \var{string} will still be discarded and the value of
556 \var{*string} will be set to \NULL; the appropriate exception will
557 be set.
558\end{cfuncdesc}
559
560\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
561 PyObject *newpart}
562 Creates a new string object in \var{*string} containing the contents
563 of \var{newpart} appended to \var{string}. This version decrements
564 the reference count of \var{newpart}.
565\end{cfuncdesc}
566
567\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
568 A way to resize a string object even though it is ``immutable''.
569 Only use this to build up a brand new string object; don't use this
570 if the string may already be known in other parts of the code.
571\end{cfuncdesc}
572
573\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
574 PyObject *args}
575 Returns a new string object from \var{format} and \var{args}.
576 Analogous to \code{\var{format} \%\ \var{args}}. The \var{args}
577 argument must be a tuple.
578\end{cfuncdesc}
579
580\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
581 Intern the argument \var{*string} in place. The argument must be
582 the address of a pointer variable pointing to a Python string
583 object. If there is an existing interned string that is the same as
584 \var{*string}, it sets \var{*string} to it (decrementing the
585 reference count of the old string object and incrementing the
586 reference count of the interned string object), otherwise it leaves
587 \var{*string} alone and interns it (incrementing its reference
588 count). (Clarification: even though there is a lot of talk about
589 reference counts, think of this function as reference-count-neutral;
590 you own the object after the call if and only if you owned it before
591 the call.)
592\end{cfuncdesc}
593
594\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
595 A combination of \cfunction{PyString_FromString()} and
596 \cfunction{PyString_InternInPlace()}, returning either a new string
597 object that has been interned, or a new (``owned'') reference to an
598 earlier interned string object with the same value.
599\end{cfuncdesc}
600
601\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
602 int size,
603 const char *encoding,
604 const char *errors}
605 Creates an object by decoding \var{size} bytes of the encoded
606 buffer \var{s} using the codec registered for
607 \var{encoding}. \var{encoding} and \var{errors} have the same
608 meaning as the parameters of the same name in the
609 \function{unicode()} built-in function. The codec to be used is
610 looked up using the Python codec registry. Returns \NULL{} if
611 an exception was raised by the codec.
612\end{cfuncdesc}
613
614\begin{cfuncdesc}{PyObject*}{PyString_AsDecodedObject}{PyObject *str,
615 const char *encoding,
616 const char *errors}
617 Decodes a string object by passing it to the codec registered for
618 \var{encoding} and returns the result as Python
619 object. \var{encoding} and \var{errors} have the same meaning as the
620 parameters of the same name in the string \method{encode()} method.
621 The codec to be used is looked up using the Python codec registry.
622 Returns \NULL{} if an exception was raised by the codec.
623\end{cfuncdesc}
624
625\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const char *s,
626 int size,
627 const char *encoding,
628 const char *errors}
629 Encodes the \ctype{char} buffer of the given size by passing it to
630 the codec registered for \var{encoding} and returns a Python object.
631 \var{encoding} and \var{errors} have the same meaning as the
632 parameters of the same name in the string \method{encode()} method.
633 The codec to be used is looked up using the Python codec
634 registry. Returns \NULL{} if an exception was raised by the
635 codec.
636\end{cfuncdesc}
637
638\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedObject}{PyObject *str,
639 const char *encoding,
640 const char *errors}
641 Encodes a string object using the codec registered for
642 \var{encoding} and returns the result as Python object.
643 \var{encoding} and \var{errors} have the same meaning as the
644 parameters of the same name in the string \method{encode()} method.
645 The codec to be used is looked up using the Python codec registry.
646 Returns \NULL{} if an exception was raised by the codec.
647\end{cfuncdesc}
648
649
650\subsection{Unicode Objects \label{unicodeObjects}}
651\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
652
653%--- Unicode Type -------------------------------------------------------
654
655These are the basic Unicode object types used for the Unicode
656implementation in Python:
657
658\begin{ctypedesc}{Py_UNICODE}
659 This type represents a 16-bit unsigned storage type which is used by
660 Python internally as basis for holding Unicode ordinals. On
661 platforms where \ctype{wchar_t} is available and also has 16-bits,
662 \ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
663 native platform compatibility. On all other platforms,
664 \ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
665\end{ctypedesc}
666
667\begin{ctypedesc}{PyUnicodeObject}
668 This subtype of \ctype{PyObject} represents a Python Unicode object.
669\end{ctypedesc}
670
671\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
672 This instance of \ctype{PyTypeObject} represents the Python Unicode
673 type.
674\end{cvardesc}
675
676The following APIs are really C macros and can be used to do fast
677checks and to access internal read-only data of Unicode objects:
678
679\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
680 Returns true if the object \var{o} is a Unicode object or an
681 instance of a Unicode subtype.
682 \versionchanged[Allowed subtypes to be accepted]{2.2}
683\end{cfuncdesc}
684
685\begin{cfuncdesc}{int}{PyUnicode_CheckExact}{PyObject *o}
686 Returns true if the object \var{o} is a Unicode object, but not an
687 instance of a subtype.
688 \versionadded{2.2}
689\end{cfuncdesc}
690
691\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
692 Returns the size of the object. \var{o} has to be a
693 \ctype{PyUnicodeObject} (not checked).
694\end{cfuncdesc}
695
696\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
697 Returns the size of the object's internal buffer in bytes. \var{o}
698 has to be a \ctype{PyUnicodeObject} (not checked).
699\end{cfuncdesc}
700
701\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
702 Returns a pointer to the internal \ctype{Py_UNICODE} buffer of the
703 object. \var{o} has to be a \ctype{PyUnicodeObject} (not checked).
704\end{cfuncdesc}
705
706\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
707 Returns a pointer to the internal buffer of the object.
708 \var{o} has to be a \ctype{PyUnicodeObject} (not checked).
709\end{cfuncdesc}
710
711% --- Unicode character properties ---------------------------------------
712
713Unicode provides many different character properties. The most often
714needed ones are available through these macros which are mapped to C
715functions depending on the Python configuration.
716
717\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
718 Returns 1/0 depending on whether \var{ch} is a whitespace
719 character.
720\end{cfuncdesc}
721
722\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
723 Returns 1/0 depending on whether \var{ch} is a lowercase character.
724\end{cfuncdesc}
725
726\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
727 Returns 1/0 depending on whether \var{ch} is an uppercase
728 character.
729\end{cfuncdesc}
730
731\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
732 Returns 1/0 depending on whether \var{ch} is a titlecase character.
733\end{cfuncdesc}
734
735\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
736 Returns 1/0 depending on whether \var{ch} is a linebreak character.
737\end{cfuncdesc}
738
739\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
740 Returns 1/0 depending on whether \var{ch} is a decimal character.
741\end{cfuncdesc}
742
743\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
744 Returns 1/0 depending on whether \var{ch} is a digit character.
745\end{cfuncdesc}
746
747\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
748 Returns 1/0 depending on whether \var{ch} is a numeric character.
749\end{cfuncdesc}
750
751\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
752 Returns 1/0 depending on whether \var{ch} is an alphabetic
753 character.
754\end{cfuncdesc}
755
756\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
757 Returns 1/0 depending on whether \var{ch} is an alphanumeric
758 character.
759\end{cfuncdesc}
760
761These APIs can be used for fast direct character conversions:
762
763\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
764 Returns the character \var{ch} converted to lower case.
765\end{cfuncdesc}
766
767\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
768 Returns the character \var{ch} converted to upper case.
769\end{cfuncdesc}
770
771\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
772 Returns the character \var{ch} converted to title case.
773\end{cfuncdesc}
774
775\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
776 Returns the character \var{ch} converted to a decimal positive
777 integer. Returns \code{-1} if this is not possible. Does not raise
778 exceptions.
779\end{cfuncdesc}
780
781\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
782 Returns the character \var{ch} converted to a single digit integer.
783 Returns \code{-1} if this is not possible. Does not raise
784 exceptions.
785\end{cfuncdesc}
786
787\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
788 Returns the character \var{ch} converted to a (positive) double.
789 Returns \code{-1.0} if this is not possible. Does not raise
790 exceptions.
791\end{cfuncdesc}
792
793% --- Plain Py_UNICODE ---------------------------------------------------
794
795To create Unicode objects and access their basic sequence properties,
796use these APIs:
797
798\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
Tim Petersf582b822001-12-11 18:51:08 +0000799 int size}
Fred Drake3adf79e2001-10-12 19:01:43 +0000800 Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
801 given size. \var{u} may be \NULL{} which causes the contents to be
802 undefined. It is the user's responsibility to fill in the needed
803 data. The buffer is copied into the new object. If the buffer is
804 not \NULL, the return value might be a shared object. Therefore,
805 modification of the resulting Unicode object is only allowed when
806 \var{u} is \NULL.
807\end{cfuncdesc}
808
809\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
810 Return a read-only pointer to the Unicode object's internal
811 \ctype{Py_UNICODE} buffer, \NULL{} if \var{unicode} is not a Unicode
812 object.
813\end{cfuncdesc}
814
815\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
816 Return the length of the Unicode object.
817\end{cfuncdesc}
818
819\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
820 const char *encoding,
821 const char *errors}
822 Coerce an encoded object \var{obj} to an Unicode object and return a
823 reference with incremented refcount.
824
825 Coercion is done in the following way:
826
827\begin{enumerate}
828\item Unicode objects are passed back as-is with incremented
829 refcount. \note{These cannot be decoded; passing a non-\NULL{}
830 value for encoding will result in a \exception{TypeError}.}
831
832\item String and other char buffer compatible objects are decoded
833 according to the given encoding and using the error handling
834 defined by errors. Both can be \NULL{} to have the interface
835 use the default values (see the next section for details).
836
837\item All other objects cause an exception.
838\end{enumerate}
839
840 The API returns \NULL{} if there was an error. The caller is
841 responsible for decref'ing the returned objects.
842\end{cfuncdesc}
843
844\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
845 Shortcut for \code{PyUnicode_FromEncodedObject(obj, NULL, "strict")}
846 which is used throughout the interpreter whenever coercion to
847 Unicode is needed.
848\end{cfuncdesc}
849
850% --- wchar_t support for platforms which support it ---------------------
851
852If the platform supports \ctype{wchar_t} and provides a header file
853wchar.h, Python can interface directly to this type using the
854following functions. Support is optimized if Python's own
855\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
856
857\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
858 int size}
859 Create a Unicode object from the \ctype{whcar_t} buffer \var{w} of
860 the given size. Returns \NULL{} on failure.
861\end{cfuncdesc}
862
863\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
864 wchar_t *w,
865 int size}
866 Copies the Unicode object contents into the \ctype{whcar_t} buffer
867 \var{w}. At most \var{size} \ctype{whcar_t} characters are copied.
868 Returns the number of \ctype{whcar_t} characters copied or -1 in
869 case of an error.
870\end{cfuncdesc}
871
872
873\subsubsection{Built-in Codecs \label{builtinCodecs}}
874
875Python provides a set of builtin codecs which are written in C
876for speed. All of these codecs are directly usable via the
877following functions.
878
879Many of the following APIs take two arguments encoding and
880errors. These parameters encoding and errors have the same semantics
881as the ones of the builtin unicode() Unicode object constructor.
882
883Setting encoding to \NULL{} causes the default encoding to be used
884which is \ASCII. The file system calls should use
885\cdata{Py_FileSystemDefaultEncoding} as the encoding for file
886names. This variable should be treated as read-only: On some systems,
887it will be a pointer to a static string, on others, it will change at
888run-time, e.g. when the application invokes setlocale.
889
890Error handling is set by errors which may also be set to \NULL{}
891meaning to use the default handling defined for the codec. Default
892error handling for all builtin codecs is ``strict''
893(\exception{ValueError} is raised).
894
895The codecs all use a similar interface. Only deviation from the
896following generic ones are documented for simplicity.
897
898% --- Generic Codecs -----------------------------------------------------
899
900These are the generic codec APIs:
901
902\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
903 int size,
904 const char *encoding,
905 const char *errors}
906 Create a Unicode object by decoding \var{size} bytes of the encoded
907 string \var{s}. \var{encoding} and \var{errors} have the same
908 meaning as the parameters of the same name in the
909 \function{unicode()} builtin function. The codec to be used is
910 looked up using the Python codec registry. Returns \NULL{} if an
911 exception was raised by the codec.
912\end{cfuncdesc}
913
914\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
915 int size,
916 const char *encoding,
917 const char *errors}
918 Encodes the \ctype{Py_UNICODE} buffer of the given size and returns
919 a Python string object. \var{encoding} and \var{errors} have the
920 same meaning as the parameters of the same name in the Unicode
921 \method{encode()} method. The codec to be used is looked up using
922 the Python codec registry. Returns \NULL{} if an exception was
923 raised by the codec.
924\end{cfuncdesc}
925
926\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
927 const char *encoding,
928 const char *errors}
929 Encodes a Unicode object and returns the result as Python string
930 object. \var{encoding} and \var{errors} have the same meaning as the
931 parameters of the same name in the Unicode \method{encode()} method.
932 The codec to be used is looked up using the Python codec registry.
933 Returns \NULL{} if an exception was raised by the codec.
934\end{cfuncdesc}
935
936% --- UTF-8 Codecs -------------------------------------------------------
937
938These are the UTF-8 codec APIs:
939
940\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
941 int size,
942 const char *errors}
943 Creates a Unicode object by decoding \var{size} bytes of the UTF-8
944 encoded string \var{s}. Returns \NULL{} if an exception was raised
945 by the codec.
946\end{cfuncdesc}
947
948\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
949 int size,
950 const char *errors}
951 Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
952 and returns a Python string object. Returns \NULL{} if an exception
953 was raised by the codec.
954\end{cfuncdesc}
955
956\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
957 Encodes a Unicode objects using UTF-8 and returns the result as
958 Python string object. Error handling is ``strict''. Returns
959 \NULL{} if an exception was raised by the codec.
960\end{cfuncdesc}
961
962% --- UTF-16 Codecs ------------------------------------------------------ */
963
964These are the UTF-16 codec APIs:
965
966\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
967 int size,
968 const char *errors,
969 int *byteorder}
970 Decodes \var{length} bytes from a UTF-16 encoded buffer string and
971 returns the corresponding Unicode object. \var{errors} (if
972 non-\NULL) defines the error handling. It defaults to ``strict''.
973
974 If \var{byteorder} is non-\NULL, the decoder starts decoding using
975 the given byte order:
976
977\begin{verbatim}
978 *byteorder == -1: little endian
979 *byteorder == 0: native order
980 *byteorder == 1: big endian
981\end{verbatim}
982
983 and then switches according to all byte order marks (BOM) it finds
984 in the input data. BOMs are not copied into the resulting Unicode
985 string. After completion, \var{*byteorder} is set to the current
986 byte order at the end of input data.
987
988 If \var{byteorder} is \NULL, the codec starts in native order mode.
989
990 Returns \NULL{} if an exception was raised by the codec.
991\end{cfuncdesc}
992
993\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
994 int size,
995 const char *errors,
996 int byteorder}
997 Returns a Python string object holding the UTF-16 encoded value of
998 the Unicode data in \var{s}. If \var{byteorder} is not \code{0},
999 output is written according to the following byte order:
1000
1001\begin{verbatim}
1002 byteorder == -1: little endian
1003 byteorder == 0: native byte order (writes a BOM mark)
1004 byteorder == 1: big endian
1005\end{verbatim}
1006
1007 If byteorder is \code{0}, the output string will always start with
1008 the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark
1009 is prepended.
1010
1011 Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
1012 reduced to UCS-2. This trick makes it possible to add full UTF-16
1013 capabilities at a later point without comprimising the APIs.
1014
1015 Returns \NULL{} if an exception was raised by the codec.
1016\end{cfuncdesc}
1017
1018\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
1019 Returns a Python string using the UTF-16 encoding in native byte
1020 order. The string always starts with a BOM mark. Error handling is
1021 ``strict''. Returns \NULL{} if an exception was raised by the
1022 codec.
1023\end{cfuncdesc}
1024
1025% --- Unicode-Escape Codecs ----------------------------------------------
1026
1027These are the ``Unicode Esacpe'' codec APIs:
1028
1029\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
1030 int size,
1031 const char *errors}
1032 Creates a Unicode object by decoding \var{size} bytes of the
1033 Unicode-Escape encoded string \var{s}. Returns \NULL{} if an
1034 exception was raised by the codec.
1035\end{cfuncdesc}
1036
1037\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
1038 int size,
1039 const char *errors}
1040 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1041 Unicode-Escape and returns a Python string object. Returns \NULL{}
1042 if an exception was raised by the codec.
1043\end{cfuncdesc}
1044
1045\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
1046 Encodes a Unicode objects using Unicode-Escape and returns the
1047 result as Python string object. Error handling is ``strict''.
1048 Returns \NULL{} if an exception was raised by the codec.
1049\end{cfuncdesc}
1050
1051% --- Raw-Unicode-Escape Codecs ------------------------------------------
1052
1053These are the ``Raw Unicode Esacpe'' codec APIs:
1054
1055\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
1056 int size,
1057 const char *errors}
1058 Creates a Unicode object by decoding \var{size} bytes of the
1059 Raw-Unicode-Esacpe encoded string \var{s}. Returns \NULL{} if an
1060 exception was raised by the codec.
1061\end{cfuncdesc}
1062
1063\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
1064 int size,
1065 const char *errors}
1066 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1067 Raw-Unicode-Escape and returns a Python string object. Returns
1068 \NULL{} if an exception was raised by the codec.
1069\end{cfuncdesc}
1070
1071\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
1072 Encodes a Unicode objects using Raw-Unicode-Escape and returns the
1073 result as Python string object. Error handling is ``strict''.
1074 Returns \NULL{} if an exception was raised by the codec.
1075\end{cfuncdesc}
1076
Tim Petersf582b822001-12-11 18:51:08 +00001077% --- Latin-1 Codecs -----------------------------------------------------
Fred Drake3adf79e2001-10-12 19:01:43 +00001078
1079These are the Latin-1 codec APIs:
1080Latin-1 corresponds to the first 256 Unicode ordinals and only these
1081are accepted by the codecs during encoding.
1082
1083\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
1084 int size,
1085 const char *errors}
1086 Creates a Unicode object by decoding \var{size} bytes of the Latin-1
1087 encoded string \var{s}. Returns \NULL{} if an exception was raised
1088 by the codec.
1089\end{cfuncdesc}
1090
1091\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
1092 int size,
1093 const char *errors}
1094 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1095 Latin-1 and returns a Python string object. Returns \NULL{} if an
1096 exception was raised by the codec.
1097\end{cfuncdesc}
1098
1099\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
1100 Encodes a Unicode objects using Latin-1 and returns the result as
1101 Python string object. Error handling is ``strict''. Returns
1102 \NULL{} if an exception was raised by the codec.
1103\end{cfuncdesc}
1104
Tim Petersf582b822001-12-11 18:51:08 +00001105% --- ASCII Codecs -------------------------------------------------------
Fred Drake3adf79e2001-10-12 19:01:43 +00001106
1107These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
1108accepted. All other codes generate errors.
1109
1110\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
1111 int size,
1112 const char *errors}
1113 Creates a Unicode object by decoding \var{size} bytes of the
1114 \ASCII{} encoded string \var{s}. Returns \NULL{} if an exception
1115 was raised by the codec.
1116\end{cfuncdesc}
1117
1118\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
1119 int size,
1120 const char *errors}
1121 Encodes the \ctype{Py_UNICODE} buffer of the given size using
1122 \ASCII{} and returns a Python string object. Returns \NULL{} if an
1123 exception was raised by the codec.
1124\end{cfuncdesc}
1125
1126\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
1127 Encodes a Unicode objects using \ASCII{} and returns the result as
1128 Python string object. Error handling is ``strict''. Returns
1129 \NULL{} if an exception was raised by the codec.
1130\end{cfuncdesc}
1131
Tim Petersf582b822001-12-11 18:51:08 +00001132% --- Character Map Codecs -----------------------------------------------
Fred Drake3adf79e2001-10-12 19:01:43 +00001133
1134These are the mapping codec APIs:
1135
1136This codec is special in that it can be used to implement many
1137different codecs (and this is in fact what was done to obtain most of
1138the standard codecs included in the \module{encodings} package). The
1139codec uses mapping to encode and decode characters.
1140
1141Decoding mappings must map single string characters to single Unicode
1142characters, integers (which are then interpreted as Unicode ordinals)
Tim Petersf582b822001-12-11 18:51:08 +00001143or None (meaning "undefined mapping" and causing an error).
Fred Drake3adf79e2001-10-12 19:01:43 +00001144
1145Encoding mappings must map single Unicode characters to single string
1146characters, integers (which are then interpreted as Latin-1 ordinals)
1147or None (meaning "undefined mapping" and causing an error).
1148
1149The mapping objects provided must only support the __getitem__ mapping
1150interface.
1151
1152If a character lookup fails with a LookupError, the character is
1153copied as-is meaning that its ordinal value will be interpreted as
1154Unicode or Latin-1 ordinal resp. Because of this, mappings only need
1155to contain those mappings which map characters to different code
1156points.
1157
1158\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
1159 int size,
1160 PyObject *mapping,
1161 const char *errors}
1162 Creates a Unicode object by decoding \var{size} bytes of the encoded
1163 string \var{s} using the given \var{mapping} object. Returns
1164 \NULL{} if an exception was raised by the codec.
1165\end{cfuncdesc}
1166
1167\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
1168 int size,
1169 PyObject *mapping,
1170 const char *errors}
1171 Encodes the \ctype{Py_UNICODE} buffer of the given size using the
1172 given \var{mapping} object and returns a Python string object.
1173 Returns \NULL{} if an exception was raised by the codec.
1174\end{cfuncdesc}
1175
1176\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
1177 PyObject *mapping}
1178 Encodes a Unicode objects using the given \var{mapping} object and
1179 returns the result as Python string object. Error handling is
1180 ``strict''. Returns \NULL{} if an exception was raised by the
1181 codec.
1182\end{cfuncdesc}
1183
1184The following codec API is special in that maps Unicode to Unicode.
1185
1186\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
1187 int size,
1188 PyObject *table,
1189 const char *errors}
1190 Translates a \ctype{Py_UNICODE} buffer of the given length by
1191 applying a character mapping \var{table} to it and returns the
1192 resulting Unicode object. Returns \NULL{} when an exception was
1193 raised by the codec.
1194
1195 The \var{mapping} table must map Unicode ordinal integers to Unicode
1196 ordinal integers or None (causing deletion of the character).
1197
1198 Mapping tables need only provide the method{__getitem__()}
1199 interface; dictionaries and sequences work well. Unmapped character
1200 ordinals (ones which cause a \exception{LookupError}) are left
1201 untouched and are copied as-is.
1202\end{cfuncdesc}
1203
1204% --- MBCS codecs for Windows --------------------------------------------
1205
1206These are the MBCS codec APIs. They are currently only available on
1207Windows and use the Win32 MBCS converters to implement the
1208conversions. Note that MBCS (or DBCS) is a class of encodings, not
1209just one. The target encoding is defined by the user settings on the
1210machine running the codec.
1211
1212\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
1213 int size,
1214 const char *errors}
1215 Creates a Unicode object by decoding \var{size} bytes of the MBCS
1216 encoded string \var{s}. Returns \NULL{} if an exception was
1217 raised by the codec.
1218\end{cfuncdesc}
1219
1220\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
1221 int size,
1222 const char *errors}
1223 Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
1224 and returns a Python string object. Returns \NULL{} if an exception
1225 was raised by the codec.
1226\end{cfuncdesc}
1227
1228\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
1229 Encodes a Unicode objects using MBCS and returns the result as
1230 Python string object. Error handling is ``strict''. Returns
1231 \NULL{} if an exception was raised by the codec.
1232\end{cfuncdesc}
1233
1234% --- Methods & Slots ----------------------------------------------------
1235
1236\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
1237
1238The following APIs are capable of handling Unicode objects and strings
1239on input (we refer to them as strings in the descriptions) and return
1240Unicode objects or integers as apporpriate.
1241
1242They all return \NULL{} or \code{-1} if an exception occurs.
1243
1244\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
1245 PyObject *right}
1246 Concat two strings giving a new Unicode string.
1247\end{cfuncdesc}
1248
1249\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
1250 PyObject *sep,
1251 int maxsplit}
1252 Split a string giving a list of Unicode strings. If sep is \NULL,
1253 splitting will be done at all whitespace substrings. Otherwise,
1254 splits occur at the given separator. At most \var{maxsplit} splits
1255 will be done. If negative, no limit is set. Separators are not
1256 included in the resulting list.
1257\end{cfuncdesc}
1258
1259\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
1260 int maxsplit}
1261 Split a Unicode string at line breaks, returning a list of Unicode
1262 strings. CRLF is considered to be one line break. The Line break
1263 characters are not included in the resulting strings.
1264\end{cfuncdesc}
1265
1266\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
1267 PyObject *table,
1268 const char *errors}
1269 Translate a string by applying a character mapping table to it and
1270 return the resulting Unicode object.
1271
1272 The mapping table must map Unicode ordinal integers to Unicode
1273 ordinal integers or None (causing deletion of the character).
1274
1275 Mapping tables need only provide the \method{__getitem__()}
1276 interface; dictionaries and sequences work well. Unmapped character
1277 ordinals (ones which cause a \exception{LookupError}) are left
1278 untouched and are copied as-is.
1279
1280 \var{errors} has the usual meaning for codecs. It may be \NULL{}
1281 which indicates to use the default error handling.
1282\end{cfuncdesc}
1283
1284\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
1285 PyObject *seq}
1286 Join a sequence of strings using the given separator and return the
1287 resulting Unicode string.
1288\end{cfuncdesc}
1289
1290\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
1291 PyObject *substr,
1292 int start,
1293 int end,
1294 int direction}
1295 Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
1296 the given tail end (\var{direction} == -1 means to do a prefix
1297 match, \var{direction} == 1 a suffix match), 0 otherwise.
1298\end{cfuncdesc}
1299
1300\begin{cfuncdesc}{PyObject*}{PyUnicode_Find}{PyObject *str,
1301 PyObject *substr,
1302 int start,
1303 int end,
1304 int direction}
1305 Return the first position of \var{substr} in
1306 \var{str}[\var{start}:\var{end}] using the given \var{direction}
1307 (\var{direction} == 1 means to do a forward search,
1308 \var{direction} == -1 a backward search), 0 otherwise.
1309\end{cfuncdesc}
1310
1311\begin{cfuncdesc}{PyObject*}{PyUnicode_Count}{PyObject *str,
1312 PyObject *substr,
1313 int start,
1314 int end}
1315 Count the number of occurrences of \var{substr} in
1316 \var{str}[\var{start}:\var{end}]
1317\end{cfuncdesc}
1318
1319\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
1320 PyObject *substr,
1321 PyObject *replstr,
1322 int maxcount}
1323 Replace at most \var{maxcount} occurrences of \var{substr} in
1324 \var{str} with \var{replstr} and return the resulting Unicode object.
1325 \var{maxcount} == -1 means replace all occurrences.
1326\end{cfuncdesc}
1327
1328\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
1329 Compare two strings and return -1, 0, 1 for less than, equal, and
1330 greater than, respectively.
1331\end{cfuncdesc}
1332
1333\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
1334 PyObject *args}
1335 Returns a new string object from \var{format} and \var{args}; this
1336 is analogous to \code{\var{format} \%\ \var{args}}. The
1337 \var{args} argument must be a tuple.
1338\end{cfuncdesc}
1339
1340\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
1341 PyObject *element}
1342 Checks whether \var{element} is contained in \var{container} and
1343 returns true or false accordingly.
1344
1345 \var{element} has to coerce to a one element Unicode
1346 string. \code{-1} is returned if there was an error.
1347\end{cfuncdesc}
1348
1349
1350\subsection{Buffer Objects \label{bufferObjects}}
1351\sectionauthor{Greg Stein}{gstein@lyra.org}
1352
1353\obindex{buffer}
1354Python objects implemented in C can export a group of functions called
1355the ``buffer\index{buffer interface} interface.'' These functions can
1356be used by an object to expose its data in a raw, byte-oriented
1357format. Clients of the object can use the buffer interface to access
1358the object data directly, without needing to copy it first.
1359
Tim Petersf582b822001-12-11 18:51:08 +00001360Two examples of objects that support
1361the buffer interface are strings and arrays. The string object exposes
Fred Drake3adf79e2001-10-12 19:01:43 +00001362the character contents in the buffer interface's byte-oriented
1363form. An array can also expose its contents, but it should be noted
1364that array elements may be multi-byte values.
1365
1366An example user of the buffer interface is the file object's
1367\method{write()} method. Any object that can export a series of bytes
1368through the buffer interface can be written to a file. There are a
Tim Petersf582b822001-12-11 18:51:08 +00001369number of format codes to \cfunction{PyArg_ParseTuple()} that operate
Fred Drake3adf79e2001-10-12 19:01:43 +00001370against an object's buffer interface, returning data from the target
1371object.
1372
1373More information on the buffer interface is provided in the section
Fred Drake54e62942001-12-11 19:40:16 +00001374``Buffer Object Structures'' (section~\ref{buffer-structs}), under
Fred Drake3adf79e2001-10-12 19:01:43 +00001375the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
1376
1377A ``buffer object'' is defined in the \file{bufferobject.h} header
1378(included by \file{Python.h}). These objects look very similar to
1379string objects at the Python programming level: they support slicing,
1380indexing, concatenation, and some other standard string
1381operations. However, their data can come from one of two sources: from
1382a block of memory, or from another object which exports the buffer
1383interface.
1384
1385Buffer objects are useful as a way to expose the data from another
1386object's buffer interface to the Python programmer. They can also be
1387used as a zero-copy slicing mechanism. Using their ability to
1388reference a block of memory, it is possible to expose any data to the
1389Python programmer quite easily. The memory could be a large, constant
1390array in a C extension, it could be a raw block of memory for
1391manipulation before passing to an operating system library, or it
1392could be used to pass around structured data in its native, in-memory
1393format.
1394
1395\begin{ctypedesc}{PyBufferObject}
1396 This subtype of \ctype{PyObject} represents a buffer object.
1397\end{ctypedesc}
1398
1399\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
1400 The instance of \ctype{PyTypeObject} which represents the Python
1401 buffer type; it is the same object as \code{types.BufferType} in the
1402 Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
1403\end{cvardesc}
1404
1405\begin{cvardesc}{int}{Py_END_OF_BUFFER}
1406 This constant may be passed as the \var{size} parameter to
1407 \cfunction{PyBuffer_FromObject()} or
1408 \cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the
1409 new \ctype{PyBufferObject} should refer to \var{base} object from
1410 the specified \var{offset} to the end of its exported buffer. Using
1411 this enables the caller to avoid querying the \var{base} object for
1412 its length.
1413\end{cvardesc}
1414
1415\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
1416 Return true if the argument has type \cdata{PyBuffer_Type}.
1417\end{cfuncdesc}
1418
1419\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
1420 int offset, int size}
1421 Return a new read-only buffer object. This raises
1422 \exception{TypeError} if \var{base} doesn't support the read-only
1423 buffer protocol or doesn't provide exactly one buffer segment, or it
1424 raises \exception{ValueError} if \var{offset} is less than zero. The
1425 buffer will hold a reference to the \var{base} object, and the
1426 buffer's contents will refer to the \var{base} object's buffer
1427 interface, starting as position \var{offset} and extending for
1428 \var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
1429 the new buffer's contents extend to the length of the \var{base}
1430 object's exported buffer data.
1431\end{cfuncdesc}
1432
1433\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
1434 int offset,
1435 int size}
1436 Return a new writable buffer object. Parameters and exceptions are
1437 similar to those for \cfunction{PyBuffer_FromObject()}. If the
1438 \var{base} object does not export the writeable buffer protocol,
1439 then \exception{TypeError} is raised.
1440\end{cfuncdesc}
1441
1442\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
1443 Return a new read-only buffer object that reads from a specified
1444 location in memory, with a specified size. The caller is
1445 responsible for ensuring that the memory buffer, passed in as
1446 \var{ptr}, is not deallocated while the returned buffer object
1447 exists. Raises \exception{ValueError} if \var{size} is less than
1448 zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be
1449 passed for the \var{size} parameter; \exception{ValueError} will be
1450 raised in that case.
1451\end{cfuncdesc}
1452
1453\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
1454 Similar to \cfunction{PyBuffer_FromMemory()}, but the returned
1455 buffer is writable.
1456\end{cfuncdesc}
1457
1458\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
1459 Returns a new writable buffer object that maintains its own memory
1460 buffer of \var{size} bytes. \exception{ValueError} is returned if
1461 \var{size} is not zero or positive.
1462\end{cfuncdesc}
1463
1464
1465\subsection{Tuple Objects \label{tupleObjects}}
1466
1467\obindex{tuple}
1468\begin{ctypedesc}{PyTupleObject}
1469 This subtype of \ctype{PyObject} represents a Python tuple object.
1470\end{ctypedesc}
1471
1472\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
1473 This instance of \ctype{PyTypeObject} represents the Python tuple
1474 type; it is the same object as \code{types.TupleType} in the Python
1475 layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
1476\end{cvardesc}
1477
1478\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
1479 Return true if \var{p} is a tuple object or an instance of a subtype
1480 of the tuple type.
1481 \versionchanged[Allowed subtypes to be accepted]{2.2}
1482\end{cfuncdesc}
1483
1484\begin{cfuncdesc}{int}{PyTuple_CheckExact}{PyObject *p}
1485 Return true if \var{p} is a tuple object, but not an instance of a
1486 subtype of the tuple type.
1487 \versionadded{2.2}
1488\end{cfuncdesc}
1489
1490\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
1491 Return a new tuple object of size \var{len}, or \NULL{} on failure.
1492\end{cfuncdesc}
1493
1494\begin{cfuncdesc}{int}{PyTuple_Size}{PyObject *p}
1495 Takes a pointer to a tuple object, and returns the size of that
1496 tuple.
1497\end{cfuncdesc}
1498
1499\begin{cfuncdesc}{int}{PyTuple_GET_SIZE}{PyObject *p}
1500 Return the size of the tuple \var{p}, which must be non-\NULL{} and
1501 point to a tuple; no error checking is performed.
1502\end{cfuncdesc}
1503
1504\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyObject *p, int pos}
1505 Returns the object at position \var{pos} in the tuple pointed to by
1506 \var{p}. If \var{pos} is out of bounds, returns \NULL{} and sets an
1507 \exception{IndexError} exception.
1508\end{cfuncdesc}
1509
1510\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyObject *p, int pos}
1511 Like \cfunction{PyTuple_GetItem()}, but does no checking of its
1512 arguments.
1513\end{cfuncdesc}
1514
1515\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyObject *p,
1516 int low, int high}
1517 Takes a slice of the tuple pointed to by \var{p} from \var{low} to
1518 \var{high} and returns it as a new tuple.
1519\end{cfuncdesc}
1520
1521\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
1522 int pos, PyObject *o}
1523 Inserts a reference to object \var{o} at position \var{pos} of the
1524 tuple pointed to by \var{p}. It returns \code{0} on success.
1525 \note{This function ``steals'' a reference to \var{o}.}
1526\end{cfuncdesc}
1527
1528\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
1529 int pos, PyObject *o}
1530 Like \cfunction{PyTuple_SetItem()}, but does no error checking, and
1531 should \emph{only} be used to fill in brand new tuples. \note{This
1532 function ``steals'' a reference to \var{o}.}
1533\end{cfuncdesc}
1534
1535\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyObject **p, int newsize}
1536 Can be used to resize a tuple. \var{newsize} will be the new length
1537 of the tuple. Because tuples are \emph{supposed} to be immutable,
1538 this should only be used if there is only one reference to the
1539 object. Do \emph{not} use this if the tuple may already be known to
1540 some other part of the code. The tuple will always grow or shrink
1541 at the end. Think of this as destroying the old tuple and creating
1542 a new one, only more efficiently. Returns \code{0} on success.
1543 Client code should never assume that the resulting value of
1544 \code{*\var{p}} will be the same as before calling this function.
1545 If the object referenced by \code{*\var{p}} is replaced, the
1546 original \code{*\var{p}} is destroyed. On failure, returns
1547 \code{-1} and sets \code{*\var{p}} to \NULL, and raises
1548 \exception{MemoryError} or
1549 \exception{SystemError}.
Tim Petersf582b822001-12-11 18:51:08 +00001550 \versionchanged[Removed unused third parameter, \var{last_is_sticky}]{2.2}
Fred Drake3adf79e2001-10-12 19:01:43 +00001551\end{cfuncdesc}
1552
1553
1554\subsection{List Objects \label{listObjects}}
1555
1556\obindex{list}
1557\begin{ctypedesc}{PyListObject}
1558 This subtype of \ctype{PyObject} represents a Python list object.
1559\end{ctypedesc}
1560
1561\begin{cvardesc}{PyTypeObject}{PyList_Type}
1562 This instance of \ctype{PyTypeObject} represents the Python list
1563 type. This is the same object as \code{types.ListType}.
1564 \withsubitem{(in module types)}{\ttindex{ListType}}
1565\end{cvardesc}
1566
1567\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
1568 Returns true if its argument is a \ctype{PyListObject}.
1569\end{cfuncdesc}
1570
1571\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
1572 Returns a new list of length \var{len} on success, or \NULL{} on
1573 failure.
1574\end{cfuncdesc}
1575
1576\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
1577 Returns the length of the list object in \var{list}; this is
1578 equivalent to \samp{len(\var{list})} on a list object.
1579 \bifuncindex{len}
1580\end{cfuncdesc}
1581
1582\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
1583 Macro form of \cfunction{PyList_Size()} without error checking.
1584\end{cfuncdesc}
1585
1586\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
1587 Returns the object at position \var{pos} in the list pointed to by
1588 \var{p}. If \var{pos} is out of bounds, returns \NULL{} and sets an
1589 \exception{IndexError} exception.
1590\end{cfuncdesc}
1591
1592\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
1593 Macro form of \cfunction{PyList_GetItem()} without error checking.
1594\end{cfuncdesc}
1595
1596\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
1597 PyObject *item}
1598 Sets the item at index \var{index} in list to \var{item}. Returns
1599 \code{0} on success or \code{-1} on failure. \note{This function
1600 ``steals'' a reference to \var{item} and discards a reference to an
1601 item already in the list at the affected position.}
1602\end{cfuncdesc}
1603
1604\begin{cfuncdesc}{void}{PyList_SET_ITEM}{PyObject *list, int i,
1605 PyObject *o}
1606 Macro form of \cfunction{PyList_SetItem()} without error checking.
1607 This is normally only used to fill in new lists where there is no
1608 previous content.
1609 \note{This function ``steals'' a reference to \var{item}, and,
1610 unlike \cfunction{PyList_SetItem()}, does \emph{not} discard a
1611 reference to any item that it being replaced; any reference in
1612 \var{list} at position \var{i} will be leaked.}
1613\end{cfuncdesc}
1614
1615\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
1616 PyObject *item}
1617 Inserts the item \var{item} into list \var{list} in front of index
1618 \var{index}. Returns \code{0} if successful; returns \code{-1} and
1619 raises an exception if unsuccessful. Analogous to
1620 \code{\var{list}.insert(\var{index}, \var{item})}.
1621\end{cfuncdesc}
1622
1623\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
1624 Appends the object \var{item} at the end of list \var{list}.
1625 Returns \code{0} if successful; returns \code{-1} and sets an
1626 exception if unsuccessful. Analogous to
1627 \code{\var{list}.append(\var{item})}.
1628\end{cfuncdesc}
1629
1630\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
1631 int low, int high}
1632 Returns a list of the objects in \var{list} containing the objects
1633 \emph{between} \var{low} and \var{high}. Returns \NULL{} and sets
1634 an exception if unsuccessful.
1635 Analogous to \code{\var{list}[\var{low}:\var{high}]}.
1636\end{cfuncdesc}
1637
1638\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
1639 int low, int high,
1640 PyObject *itemlist}
1641 Sets the slice of \var{list} between \var{low} and \var{high} to the
1642 contents of \var{itemlist}. Analogous to
1643 \code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
1644 \code{0} on success, \code{-1} on failure.
1645\end{cfuncdesc}
1646
1647\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
1648 Sorts the items of \var{list} in place. Returns \code{0} on
1649 success, \code{-1} on failure. This is equivalent to
1650 \samp{\var{list}.sort()}.
1651\end{cfuncdesc}
1652
1653\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
1654 Reverses the items of \var{list} in place. Returns \code{0} on
1655 success, \code{-1} on failure. This is the equivalent of
1656 \samp{\var{list}.reverse()}.
1657\end{cfuncdesc}
1658
1659\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
1660 Returns a new tuple object containing the contents of \var{list};
1661 equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
1662\end{cfuncdesc}
1663
1664
1665\section{Mapping Objects \label{mapObjects}}
1666
1667\obindex{mapping}
1668
1669
1670\subsection{Dictionary Objects \label{dictObjects}}
1671
1672\obindex{dictionary}
1673\begin{ctypedesc}{PyDictObject}
1674 This subtype of \ctype{PyObject} represents a Python dictionary
1675 object.
1676\end{ctypedesc}
1677
1678\begin{cvardesc}{PyTypeObject}{PyDict_Type}
1679 This instance of \ctype{PyTypeObject} represents the Python
1680 dictionary type. This is exposed to Python programs as
1681 \code{types.DictType} and \code{types.DictionaryType}.
1682 \withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
1683\end{cvardesc}
1684
1685\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
1686 Returns true if its argument is a \ctype{PyDictObject}.
1687\end{cfuncdesc}
1688
1689\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
1690 Returns a new empty dictionary, or \NULL{} on failure.
1691\end{cfuncdesc}
1692
1693\begin{cfuncdesc}{PyObject*}{PyDictProxy_New}{PyObject *dict}
1694 Return a proxy object for a mapping which enforces read-only
1695 behavior. This is normally used to create a proxy to prevent
1696 modification of the dictionary for non-dynamic class types.
1697 \versionadded{2.2}
1698\end{cfuncdesc}
1699
1700\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
1701 Empties an existing dictionary of all key-value pairs.
1702\end{cfuncdesc}
1703
1704\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
1705 Returns a new dictionary that contains the same key-value pairs as
1706 \var{p}.
1707 \versionadded{1.6}
1708\end{cfuncdesc}
1709
1710\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
1711 PyObject *val}
1712 Inserts \var{value} into the dictionary \var{p} with a key of
1713 \var{key}. \var{key} must be hashable; if it isn't,
1714 \exception{TypeError} will be raised.
1715 Returns \code{0} on success or \code{-1} on failure.
1716\end{cfuncdesc}
1717
1718\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p,
1719 char *key,
1720 PyObject *val}
1721 Inserts \var{value} into the dictionary \var{p} using \var{key} as a
1722 key. \var{key} should be a \ctype{char*}. The key object is created
1723 using \code{PyString_FromString(\var{key})}. Returns \code{0} on
1724 success or \code{-1} on failure.
1725 \ttindex{PyString_FromString()}
1726\end{cfuncdesc}
1727
1728\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
1729 Removes the entry in dictionary \var{p} with key \var{key}.
1730 \var{key} must be hashable; if it isn't, \exception{TypeError} is
Skip Montanaroa23bc422002-01-23 08:18:30 +00001731 raised. Returns \code{0} on success or \code{-1} on failure.
Fred Drake3adf79e2001-10-12 19:01:43 +00001732\end{cfuncdesc}
1733
1734\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
1735 Removes the entry in dictionary \var{p} which has a key specified by
1736 the string \var{key}. Returns \code{0} on success or \code{-1} on
1737 failure.
1738\end{cfuncdesc}
1739
1740\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
1741 Returns the object from dictionary \var{p} which has a key
1742 \var{key}. Returns \NULL{} if the key \var{key} is not present, but
1743 \emph{without} setting an exception.
1744\end{cfuncdesc}
1745
1746\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
1747 This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
1748 specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
1749\end{cfuncdesc}
1750
1751\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
1752 Returns a \ctype{PyListObject} containing all the items from the
1753 dictionary, as in the dictinoary method \method{items()} (see the
1754 \citetitle[../lib/lib.html]{Python Library Reference}).
1755\end{cfuncdesc}
1756
1757\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
1758 Returns a \ctype{PyListObject} containing all the keys from the
1759 dictionary, as in the dictionary method \method{keys()} (see the
1760 \citetitle[../lib/lib.html]{Python Library Reference}).
1761\end{cfuncdesc}
1762
1763\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
1764 Returns a \ctype{PyListObject} containing all the values from the
1765 dictionary \var{p}, as in the dictionary method \method{values()}
1766 (see the \citetitle[../lib/lib.html]{Python Library Reference}).
1767\end{cfuncdesc}
1768
1769\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
1770 Returns the number of items in the dictionary. This is equivalent
1771 to \samp{len(\var{p})} on a dictionary.\bifuncindex{len}
1772\end{cfuncdesc}
1773
1774\begin{cfuncdesc}{int}{PyDict_Next}{PyObject *p, int *ppos,
1775 PyObject **pkey, PyObject **pvalue}
1776 Iterate over all key-value pairs in the dictionary \var{p}. The
1777 \ctype{int} referred to by \var{ppos} must be initialized to
1778 \code{0} prior to the first call to this function to start the
1779 iteration; the function returns true for each pair in the
1780 dictionary, and false once all pairs have been reported. The
1781 parameters \var{pkey} and \var{pvalue} should either point to
1782 \ctype{PyObject*} variables that will be filled in with each key and
Skip Montanaroea3ceaa2002-01-23 10:54:41 +00001783 value, respectively, or may be \NULL. Any references returned through
1784 them are borrowed.
Fred Drake3adf79e2001-10-12 19:01:43 +00001785
1786 For example:
1787
1788\begin{verbatim}
1789PyObject *key, *value;
1790int pos = 0;
1791
1792while (PyDict_Next(self->dict, &pos, &key, &value)) {
1793 /* do something interesting with the values... */
1794 ...
1795}
1796\end{verbatim}
1797
1798 The dictionary \var{p} should not be mutated during iteration. It
1799 is safe (since Python 2.1) to modify the values of the keys as you
1800 iterate over the dictionary, but only so long as the set of keys
1801 does not change. For example:
1802
1803\begin{verbatim}
1804PyObject *key, *value;
1805int pos = 0;
1806
1807while (PyDict_Next(self->dict, &pos, &key, &value)) {
1808 int i = PyInt_AS_LONG(value) + 1;
1809 PyObject *o = PyInt_FromLong(i);
1810 if (o == NULL)
1811 return -1;
1812 if (PyDict_SetItem(self->dict, key, o) < 0) {
1813 Py_DECREF(o);
1814 return -1;
1815 }
1816 Py_DECREF(o);
1817}
1818\end{verbatim}
1819\end{cfuncdesc}
1820
1821\begin{cfuncdesc}{int}{PyDict_Merge}{PyObject *a, PyObject *b, int override}
Tim Petersf582b822001-12-11 18:51:08 +00001822 Iterate over mapping object \var{b} adding key-value pairs to dictionary
1823 \var{a}.
1824 \var{b} may be a dictionary, or any object supporting
1825 \function{PyMapping_Keys()} and \function{PyObject_GetItem()}.
1826 If \var{override} is true, existing pairs in \var{a} will
Fred Drake3adf79e2001-10-12 19:01:43 +00001827 be replaced if a matching key is found in \var{b}, otherwise pairs
1828 will only be added if there is not a matching key in \var{a}.
Tim Petersf582b822001-12-11 18:51:08 +00001829 Return \code{0} on success or \code{-1} if an exception was
Fred Drake3adf79e2001-10-12 19:01:43 +00001830 raised.
1831\versionadded{2.2}
1832\end{cfuncdesc}
1833
1834\begin{cfuncdesc}{int}{PyDict_Update}{PyObject *a, PyObject *b}
1835 This is the same as \code{PyDict_Merge(\var{a}, \var{b}, 1)} in C,
Tim Petersf582b822001-12-11 18:51:08 +00001836 or \code{\var{a}.update(\var{b})} in Python. Return \code{0} on
Fred Drake3adf79e2001-10-12 19:01:43 +00001837 success or \code{-1} if an exception was raised.
1838 \versionadded{2.2}
1839\end{cfuncdesc}
1840
Tim Petersf582b822001-12-11 18:51:08 +00001841\begin{cfuncdesc}{int}{PyDict_MergeFromSeq2}{PyObject *a, PyObject *seq2,
1842 int override}
1843 Update or merge into dictionary \var{a}, from the key-value pairs in
1844 \var{seq2}. \var{seq2} must be an iterable object producing
1845 iterable objects of length 2, viewed as key-value pairs. In case of
1846 duplicate keys, the last wins if \var{override} is true, else the
1847 first wins.
1848 Return \code{0} on success or \code{-1} if an exception
1849 was raised.
1850 Equivalent Python (except for the return value):
1851
1852\begin{verbatim}
1853def PyDict_MergeFromSeq2(a, seq2, override):
1854 for key, value in seq2:
1855 if override or key not in a:
1856 a[key] = value
1857\end{verbatim}
1858
1859 \versionadded{2.2}
1860\end{cfuncdesc}
Fred Drake3adf79e2001-10-12 19:01:43 +00001861
Fred Drake54e62942001-12-11 19:40:16 +00001862
Fred Drake3adf79e2001-10-12 19:01:43 +00001863\section{Other Objects \label{otherObjects}}
1864
1865\subsection{File Objects \label{fileObjects}}
1866
1867\obindex{file}
1868Python's built-in file objects are implemented entirely on the
1869\ctype{FILE*} support from the C standard library. This is an
1870implementation detail and may change in future releases of Python.
1871
1872\begin{ctypedesc}{PyFileObject}
1873 This subtype of \ctype{PyObject} represents a Python file object.
1874\end{ctypedesc}
1875
1876\begin{cvardesc}{PyTypeObject}{PyFile_Type}
1877 This instance of \ctype{PyTypeObject} represents the Python file
1878 type. This is exposed to Python programs as \code{types.FileType}.
1879 \withsubitem{(in module types)}{\ttindex{FileType}}
1880\end{cvardesc}
1881
1882\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
1883 Returns true if its argument is a \ctype{PyFileObject} or a subtype
1884 of \ctype{PyFileObject}.
1885 \versionchanged[Allowed subtypes to be accepted]{2.2}
1886\end{cfuncdesc}
1887
1888\begin{cfuncdesc}{int}{PyFile_CheckExact}{PyObject *p}
1889 Returns true if its argument is a \ctype{PyFileObject}, but not a
1890 subtype of \ctype{PyFileObject}.
1891 \versionadded{2.2}
1892\end{cfuncdesc}
1893
1894\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
1895 On success, returns a new file object that is opened on the file
1896 given by \var{filename}, with a file mode given by \var{mode}, where
1897 \var{mode} has the same semantics as the standard C routine
1898 \cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
1899\end{cfuncdesc}
1900
1901\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
1902 char *name, char *mode,
1903 int (*close)(FILE*)}
1904 Creates a new \ctype{PyFileObject} from the already-open standard C
1905 file pointer, \var{fp}. The function \var{close} will be called
1906 when the file should be closed. Returns \NULL{} on failure.
1907\end{cfuncdesc}
1908
1909\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
1910 Returns the file object associated with \var{p} as a \ctype{FILE*}.
1911\end{cfuncdesc}
1912
1913\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
1914 Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
1915 function reads one line from the object \var{p}. \var{p} may be a
1916 file object or any object with a \method{readline()} method. If
1917 \var{n} is \code{0}, exactly one line is read, regardless of the
1918 length of the line. If \var{n} is greater than \code{0}, no more
1919 than \var{n} bytes will be read from the file; a partial line can be
1920 returned. In both cases, an empty string is returned if the end of
1921 the file is reached immediately. If \var{n} is less than \code{0},
1922 however, one line is read regardless of length, but
1923 \exception{EOFError} is raised if the end of the file is reached
1924 immediately.
1925 \withsubitem{(built-in exception)}{\ttindex{EOFError}}
1926\end{cfuncdesc}
1927
1928\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
1929 Returns the name of the file specified by \var{p} as a string
1930 object.
1931\end{cfuncdesc}
1932
1933\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
1934 Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
1935 only. This should only be called immediately after file object
1936 creation.
1937\end{cfuncdesc}
1938
1939\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
1940 This function exists for internal use by the interpreter. Sets the
1941 \member{softspace} attribute of \var{p} to \var{newflag} and
1942 \withsubitem{(file attribute)}{\ttindex{softspace}}returns the
1943 previous value. \var{p} does not have to be a file object for this
1944 function to work properly; any object is supported (thought its only
1945 interesting if the \member{softspace} attribute can be set). This
1946 function clears any errors, and will return \code{0} as the previous
1947 value if the attribute either does not exist or if there were errors
1948 in retrieving it. There is no way to detect errors from this
1949 function, but doing so should not be needed.
1950\end{cfuncdesc}
1951
1952\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
1953 int flags}
1954 Writes object \var{obj} to file object \var{p}. The only supported
1955 flag for \var{flags} is
1956 \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW}; if given, the
1957 \function{str()} of the object is written instead of the
1958 \function{repr()}. Returns \code{0} on success or \code{-1} on
1959 failure; the appropriate exception will be set.
1960\end{cfuncdesc}
1961
Fred Drake454af892001-11-29 22:42:59 +00001962\begin{cfuncdesc}{int}{PyFile_WriteString}{const char *s, PyFileObject *p}
Fred Drake3adf79e2001-10-12 19:01:43 +00001963 Writes string \var{s} to file object \var{p}. Returns \code{0} on
1964 success or \code{-1} on failure; the appropriate exception will be
1965 set.
1966\end{cfuncdesc}
1967
1968
1969\subsection{Instance Objects \label{instanceObjects}}
1970
1971\obindex{instance}
1972There are very few functions specific to instance objects.
1973
1974\begin{cvardesc}{PyTypeObject}{PyInstance_Type}
1975 Type object for class instances.
1976\end{cvardesc}
1977
1978\begin{cfuncdesc}{int}{PyInstance_Check}{PyObject *obj}
1979 Returns true if \var{obj} is an instance.
1980\end{cfuncdesc}
1981
1982\begin{cfuncdesc}{PyObject*}{PyInstance_New}{PyObject *class,
1983 PyObject *arg,
1984 PyObject *kw}
1985 Create a new instance of a specific class. The parameters \var{arg}
1986 and \var{kw} are used as the positional and keyword parameters to
1987 the object's constructor.
1988\end{cfuncdesc}
1989
1990\begin{cfuncdesc}{PyObject*}{PyInstance_NewRaw}{PyObject *class,
1991 PyObject *dict}
1992 Create a new instance of a specific class without calling it's
1993 constructor. \var{class} is the class of new object. The
1994 \var{dict} parameter will be used as the object's \member{__dict__};
1995 if \NULL, a new dictionary will be created for the instance.
1996\end{cfuncdesc}
1997
1998
1999\subsection{Method Objects \label{method-objects}}
2000
2001\obindex{method}
2002There are some useful functions that are useful for working with
2003method objects.
2004
2005\begin{cvardesc}{PyTypeObject}{PyMethod_Type}
2006 This instance of \ctype{PyTypeObject} represents the Python method
2007 type. This is exposed to Python programs as \code{types.MethodType}.
2008 \withsubitem{(in module types)}{\ttindex{MethodType}}
2009\end{cvardesc}
2010
2011\begin{cfuncdesc}{int}{PyMethod_Check}{PyObject *o}
2012 Return true if \var{o} is a method object (has type
2013 \cdata{PyMethod_Type}). The parameter must not be \NULL.
2014\end{cfuncdesc}
2015
2016\begin{cfuncdesc}{PyObject*}{PyMethod_New}{PyObject *func.
2017 PyObject *self, PyObject *class}
2018 Return a new method object, with \var{func} being any callable
2019 object; this is the function that will be called when the method is
2020 called. If this method should be bound to an instance, \var{self}
2021 should be the instance and \var{class} should be the class of
2022 \var{self}, otherwise \var{self} should be \NULL{} and \var{class}
2023 should be the class which provides the unbound method..
2024\end{cfuncdesc}
2025
2026\begin{cfuncdesc}{PyObject*}{PyMethod_Class}{PyObject *meth}
2027 Return the class object from which the method \var{meth} was
2028 created; if this was created from an instance, it will be the class
2029 of the instance.
2030\end{cfuncdesc}
2031
2032\begin{cfuncdesc}{PyObject*}{PyMethod_GET_CLASS}{PyObject *meth}
2033 Macro version of \cfunction{PyMethod_Class()} which avoids error
2034 checking.
2035\end{cfuncdesc}
2036
2037\begin{cfuncdesc}{PyObject*}{PyMethod_Function}{PyObject *meth}
2038 Return the function object associated with the method \var{meth}.
2039\end{cfuncdesc}
2040
2041\begin{cfuncdesc}{PyObject*}{PyMethod_GET_FUNCTION}{PyObject *meth}
2042 Macro version of \cfunction{PyMethod_Function()} which avoids error
2043 checking.
2044\end{cfuncdesc}
2045
2046\begin{cfuncdesc}{PyObject*}{PyMethod_Self}{PyObject *meth}
2047 Return the instance associated with the method \var{meth} if it is
2048 bound, otherwise return \NULL.
2049\end{cfuncdesc}
2050
2051\begin{cfuncdesc}{PyObject*}{PyMethod_GET_SELF}{PyObject *meth}
2052 Macro version of \cfunction{PyMethod_Self()} which avoids error
2053 checking.
2054\end{cfuncdesc}
2055
2056
2057\subsection{Module Objects \label{moduleObjects}}
2058
2059\obindex{module}
2060There are only a few functions special to module objects.
2061
2062\begin{cvardesc}{PyTypeObject}{PyModule_Type}
2063 This instance of \ctype{PyTypeObject} represents the Python module
2064 type. This is exposed to Python programs as
2065 \code{types.ModuleType}.
2066 \withsubitem{(in module types)}{\ttindex{ModuleType}}
2067\end{cvardesc}
2068
2069\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
2070 Returns true if \var{p} is a module object, or a subtype of a module
2071 object.
2072 \versionchanged[Allowed subtypes to be accepted]{2.2}
2073\end{cfuncdesc}
2074
2075\begin{cfuncdesc}{int}{PyModule_CheckExact}{PyObject *p}
2076 Returns true if \var{p} is a module object, but not a subtype of
2077 \cdata{PyModule_Type}.
2078 \versionadded{2.2}
2079\end{cfuncdesc}
2080
2081\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
2082 Return a new module object with the \member{__name__} attribute set
2083 to \var{name}. Only the module's \member{__doc__} and
2084 \member{__name__} attributes are filled in; the caller is
2085 responsible for providing a \member{__file__} attribute.
2086 \withsubitem{(module attribute)}{
2087 \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
2088\end{cfuncdesc}
2089
2090\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
2091 Return the dictionary object that implements \var{module}'s
2092 namespace; this object is the same as the \member{__dict__}
2093 attribute of the module object. This function never fails.
2094 \withsubitem{(module attribute)}{\ttindex{__dict__}}
2095\end{cfuncdesc}
2096
2097\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
2098 Return \var{module}'s \member{__name__} value. If the module does
2099 not provide one, or if it is not a string, \exception{SystemError}
2100 is raised and \NULL{} is returned.
2101 \withsubitem{(module attribute)}{\ttindex{__name__}}
2102 \withsubitem{(built-in exception)}{\ttindex{SystemError}}
2103\end{cfuncdesc}
2104
2105\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
2106 Return the name of the file from which \var{module} was loaded using
2107 \var{module}'s \member{__file__} attribute. If this is not defined,
2108 or if it is not a string, raise \exception{SystemError} and return
2109 \NULL.
2110 \withsubitem{(module attribute)}{\ttindex{__file__}}
2111 \withsubitem{(built-in exception)}{\ttindex{SystemError}}
2112\end{cfuncdesc}
2113
2114\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
2115 char *name, PyObject *value}
2116 Add an object to \var{module} as \var{name}. This is a convenience
2117 function which can be used from the module's initialization
2118 function. This steals a reference to \var{value}. Returns
2119 \code{-1} on error, \code{0} on success.
2120 \versionadded{2.0}
2121\end{cfuncdesc}
2122
2123\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
2124 char *name, int value}
2125 Add an integer constant to \var{module} as \var{name}. This
2126 convenience function can be used from the module's initialization
2127 function. Returns \code{-1} on error, \code{0} on success.
2128 \versionadded{2.0}
2129\end{cfuncdesc}
2130
2131\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
2132 char *name, char *value}
2133 Add a string constant to \var{module} as \var{name}. This
2134 convenience function can be used from the module's initialization
2135 function. The string \var{value} must be null-terminated. Returns
2136 \code{-1} on error, \code{0} on success.
2137 \versionadded{2.0}
2138\end{cfuncdesc}
2139
2140
2141\subsection{Iterator Objects \label{iterator-objects}}
2142
2143Python provides two general-purpose iterator objects. The first, a
2144sequence iterator, works with an arbitrary sequence supporting the
2145\method{__getitem__()} method. The second works with a callable
2146object and a sentinel value, calling the callable for each item in the
2147sequence, and ending the iteration when the sentinel value is
2148returned.
2149
2150\begin{cvardesc}{PyTypeObject}{PySeqIter_Type}
2151 Type object for iterator objects returned by
2152 \cfunction{PySeqIter_New()} and the one-argument form of the
2153 \function{iter()} built-in function for built-in sequence types.
2154 \versionadded{2.2}
2155\end{cvardesc}
2156
2157\begin{cfuncdesc}{int}{PySeqIter_Check}{op}
2158 Return true if the type of \var{op} is \cdata{PySeqIter_Type}.
2159 \versionadded{2.2}
2160\end{cfuncdesc}
2161
2162\begin{cfuncdesc}{PyObject*}{PySeqIter_New}{PyObject *seq}
2163 Return an iterator that works with a general sequence object,
2164 \var{seq}. The iteration ends when the sequence raises
2165 \exception{IndexError} for the subscripting operation.
2166 \versionadded{2.2}
2167\end{cfuncdesc}
2168
2169\begin{cvardesc}{PyTypeObject}{PyCallIter_Type}
2170 Type object for iterator objects returned by
2171 \cfunction{PyCallIter_New()} and the two-argument form of the
2172 \function{iter()} built-in function.
2173 \versionadded{2.2}
2174\end{cvardesc}
2175
2176\begin{cfuncdesc}{int}{PyCallIter_Check}{op}
2177 Return true if the type of \var{op} is \cdata{PyCallIter_Type}.
2178 \versionadded{2.2}
2179\end{cfuncdesc}
2180
2181\begin{cfuncdesc}{PyObject*}{PyCallIter_New}{PyObject *callable,
2182 PyObject *sentinel}
2183 Return a new iterator. The first parameter, \var{callable}, can be
2184 any Python callable object that can be called with no parameters;
2185 each call to it should return the next item in the iteration. When
2186 \var{callable} returns a value equal to \var{sentinel}, the
2187 iteration will be terminated.
2188 \versionadded{2.2}
2189\end{cfuncdesc}
2190
2191
2192\subsection{Descriptor Objects \label{descriptor-objects}}
2193
Fred Drake54e62942001-12-11 19:40:16 +00002194``Descriptors'' are objects that describe some attribute of an object.
2195They are found in the dictionary of type objects.
2196
Fred Drake3adf79e2001-10-12 19:01:43 +00002197\begin{cvardesc}{PyTypeObject}{PyProperty_Type}
Fred Drake54e62942001-12-11 19:40:16 +00002198 The type object for the built-in descriptor types.
Fred Drake3adf79e2001-10-12 19:01:43 +00002199 \versionadded{2.2}
2200\end{cvardesc}
2201
2202\begin{cfuncdesc}{PyObject*}{PyDescr_NewGetSet}{PyTypeObject *type,
2203 PyGetSetDef *getset}
2204 \versionadded{2.2}
2205\end{cfuncdesc}
2206
2207\begin{cfuncdesc}{PyObject*}{PyDescr_NewMember}{PyTypeObject *type,
2208 PyMemberDef *meth}
2209 \versionadded{2.2}
2210\end{cfuncdesc}
2211
2212\begin{cfuncdesc}{PyObject*}{PyDescr_NewMethod}{PyTypeObject *type,
2213 PyMethodDef *meth}
2214 \versionadded{2.2}
2215\end{cfuncdesc}
2216
2217\begin{cfuncdesc}{PyObject*}{PyDescr_NewWrapper}{PyTypeObject *type,
2218 struct wrapperbase *wrapper,
2219 void *wrapped}
2220 \versionadded{2.2}
2221\end{cfuncdesc}
2222
2223\begin{cfuncdesc}{int}{PyDescr_IsData}{PyObject *descr}
2224 Returns true if the descriptor objects \var{descr} describes a data
2225 attribute, or false if it describes a method. \var{descr} must be a
2226 descriptor object; there is no error checking.
2227 \versionadded{2.2}
2228\end{cfuncdesc}
2229
2230\begin{cfuncdesc}{PyObject*}{PyWrapper_New}{PyObject *, PyObject *}
2231 \versionadded{2.2}
2232\end{cfuncdesc}
2233
2234
2235\subsection{Slice Objects \label{slice-objects}}
2236
2237\begin{cvardesc}{PyTypeObject}{PySlice_Type}
2238 The type object for slice objects. This is the same as
2239 \code{types.SliceType}.
2240 \withsubitem{(in module types)}{\ttindex{SliceType}}
2241\end{cvardesc}
2242
2243\begin{cfuncdesc}{int}{PySlice_Check}{PyObject *ob}
2244 Returns true if \var{ob} is a slice object; \var{ob} must not be
2245 \NULL.
2246\end{cfuncdesc}
2247
2248\begin{cfuncdesc}{PyObject*}{PySlice_New}{PyObject *start, PyObject *stop,
2249 PyObject *step}
2250 Return a new slice object with the given values. The \var{start},
2251 \var{stop}, and \var{step} parameters are used as the values of the
2252 slice object attributes of the same names. Any of the values may be
2253 \NULL, in which case the \code{None} will be used for the
2254 corresponding attribute. Returns \NULL{} if the new object could
2255 not be allocated.
2256\end{cfuncdesc}
2257
2258\begin{cfuncdesc}{int}{PySlice_GetIndices}{PySliceObject *slice, int length,
2259 int *start, int *stop, int *step}
2260\end{cfuncdesc}
2261
2262
2263\subsection{Weak Reference Objects \label{weakref-objects}}
2264
2265Python supports \emph{weak references} as first-class objects. There
2266are two specific object types which directly implement weak
2267references. The first is a simple reference object, and the second
2268acts as a proxy for the original object as much as it can.
2269
2270\begin{cfuncdesc}{int}{PyWeakref_Check}{ob}
2271 Return true if \var{ob} is either a reference or proxy object.
2272 \versionadded{2.2}
2273\end{cfuncdesc}
2274
2275\begin{cfuncdesc}{int}{PyWeakref_CheckRef}{ob}
2276 Return true if \var{ob} is a reference object.
2277 \versionadded{2.2}
2278\end{cfuncdesc}
2279
2280\begin{cfuncdesc}{int}{PyWeakref_CheckProxy}{ob}
2281 Return true if \var{ob} is a proxy object.
2282 \versionadded{2.2}
2283\end{cfuncdesc}
2284
2285\begin{cfuncdesc}{PyObject*}{PyWeakref_NewRef}{PyObject *ob,
2286 PyObject *callback}
2287 Return a weak reference object for the object \var{ob}. This will
2288 always return a new reference, but is not guaranteed to create a new
2289 object; an existing reference object may be returned. The second
2290 parameter, \var{callback}, can be a callable object that receives
2291 notification when \var{ob} is garbage collected; it should accept a
2292 single paramter, which will be the weak reference object itself.
2293 \var{callback} may also be \code{None} or \NULL. If \var{ob}
2294 is not a weakly-referencable object, or if \var{callback} is not
2295 callable, \code{None}, or \NULL, this will return \NULL{} and
2296 raise \exception{TypeError}.
2297 \versionadded{2.2}
2298\end{cfuncdesc}
2299
2300\begin{cfuncdesc}{PyObject*}{PyWeakref_NewProxy}{PyObject *ob,
2301 PyObject *callback}
2302 Return a weak reference proxy object for the object \var{ob}. This
2303 will always return a new reference, but is not guaranteed to create
2304 a new object; an existing proxy object may be returned. The second
2305 parameter, \var{callback}, can be a callable object that receives
2306 notification when \var{ob} is garbage collected; it should accept a
2307 single paramter, which will be the weak reference object itself.
2308 \var{callback} may also be \code{None} or \NULL. If \var{ob} is not
2309 a weakly-referencable object, or if \var{callback} is not callable,
2310 \code{None}, or \NULL, this will return \NULL{} and raise
2311 \exception{TypeError}.
2312 \versionadded{2.2}
2313\end{cfuncdesc}
2314
2315\begin{cfuncdesc}{PyObject*}{PyWeakref_GetObject}{PyObject *ref}
2316 Returns the referenced object from a weak reference, \var{ref}. If
2317 the referent is no longer live, returns \NULL.
2318 \versionadded{2.2}
2319\end{cfuncdesc}
2320
2321\begin{cfuncdesc}{PyObject*}{PyWeakref_GET_OBJECT}{PyObject *ref}
2322 Similar to \cfunction{PyWeakref_GetObject()}, but implemented as a
2323 macro that does no error checking.
2324 \versionadded{2.2}
2325\end{cfuncdesc}
2326
2327
2328\subsection{CObjects \label{cObjects}}
2329
2330\obindex{CObject}
2331Refer to \emph{Extending and Embedding the Python Interpreter},
Fred Drake54e62942001-12-11 19:40:16 +00002332section~1.12, ``Providing a C API for an Extension Module,'' for more
Fred Drake3adf79e2001-10-12 19:01:43 +00002333information on using these objects.
2334
2335
2336\begin{ctypedesc}{PyCObject}
2337 This subtype of \ctype{PyObject} represents an opaque value, useful
2338 for C extension modules who need to pass an opaque value (as a
2339 \ctype{void*} pointer) through Python code to other C code. It is
2340 often used to make a C function pointer defined in one module
2341 available to other modules, so the regular import mechanism can be
2342 used to access C APIs defined in dynamically loaded modules.
2343\end{ctypedesc}
2344
2345\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
2346 Returns true if its argument is a \ctype{PyCObject}.
2347\end{cfuncdesc}
2348
Tim Petersf582b822001-12-11 18:51:08 +00002349\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
Fred Drake54e62942001-12-11 19:40:16 +00002350 void (*destr)(void *)}
Fred Drake3adf79e2001-10-12 19:01:43 +00002351 Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
2352 \var{destr} function will be called when the object is reclaimed,
2353 unless it is \NULL.
2354\end{cfuncdesc}
2355
2356\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
2357 void* desc, void (*destr)(void *, void *)}
2358 Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
2359 \var{destr} function will be called when the object is reclaimed.
2360 The \var{desc} argument can be used to pass extra callback data for
2361 the destructor function.
2362\end{cfuncdesc}
2363
2364\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
2365 Returns the object \ctype{void *} that the \ctype{PyCObject}
2366 \var{self} was created with.
2367\end{cfuncdesc}
2368
2369\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
2370 Returns the description \ctype{void *} that the \ctype{PyCObject}
2371 \var{self} was created with.
2372\end{cfuncdesc}
Fred Drakecd8474e2001-11-26 21:29:17 +00002373
2374
2375\subsection{Cell Objects \label{cell-objects}}
2376
2377``Cell'' objects are used to implement variables referenced by
2378multiple scopes. For each such variable, a cell object is created to
2379store the value; the local variables of each stack frame that
2380references the value contains a reference to the cells from outer
2381scopes which also use that variable. When the value is accessed, the
2382value contained in the cell is used instead of the cell object
2383itself. This de-referencing of the cell object requires support from
2384the generated byte-code; these are not automatically de-referenced
2385when accessed. Cell objects are not likely to be useful elsewhere.
2386
Fred Drake54e62942001-12-11 19:40:16 +00002387\begin{ctypedesc}{PyCellObject}
2388 The C structure used for cell objects.
2389\end{ctypedesc}
2390
Fred Drakecd8474e2001-11-26 21:29:17 +00002391\begin{cvardesc}{PyTypeObject}{PyCell_Type}
2392 The type object corresponding to cell objects
2393\end{cvardesc}
2394
2395\begin{cfuncdesc}{int}{PyCell_Check}{ob}
2396 Return true if \var{ob} is a cell object; \var{ob} must not be
2397 \NULL.
2398\end{cfuncdesc}
2399
2400\begin{cfuncdesc}{PyObject*}{PyCell_New}{PyObject *ob}
2401 Create and return a new cell object containing the value \var{ob}.
2402 The parameter may be \NULL.
2403\end{cfuncdesc}
2404
2405\begin{cfuncdesc}{PyObject*}{PyCell_Get}{PyObject *cell}
2406 Return the contents of the cell \var{cell}.
2407\end{cfuncdesc}
2408
2409\begin{cfuncdesc}{PyObject*}{PyCell_GET}{PyObject *cell}
2410 Return the contents of the cell \var{cell}, but without checking
2411 that \var{cell} is non-\NULL{} and a call object.
2412\end{cfuncdesc}
2413
2414\begin{cfuncdesc}{int}{PyCell_Set}{PyObject *cell, PyObject *value}
2415 Set the contents of the cell object \var{cell} to \var{value}. This
2416 releases the reference to any current content of the cell.
2417 \var{value} may be \NULL. \var{cell} must be non-\NULL; if it is
2418 not a cell object, \code{-1} will be returned. On success, \code{0}
2419 will be returned.
2420\end{cfuncdesc}
2421
2422\begin{cfuncdesc}{void}{PyCell_SET}{PyObject *cell, PyObject *value}
2423 Sets the value of the cell object \var{cell} to \var{value}. No
2424 reference counts are adjusted, and no checks are made for safety;
2425 \var{cell} must be non-\NULL{} and must be a cell object.
2426\end{cfuncdesc}