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