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