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